From ben at dadsetan.com Thu Jul 3 16:21:14 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Thu, 03 Jul 2003 21:21:14 +0100 Subject: Python Code Snippets References: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> Message-ID: <3F04903A.8080009@dadsetan.com> Guyon Mor?e wrote: > You're gonna love this :) > > http://aspn.activestate.com/ASPN/Cookbook/Python > > > "Aur?lien G?ron" wrote in message > news:be1hs0$111s$1 at biggoron.nerim.net... > >>Hi, >> >>Does anyone know where I can find a lot of Python code snippets? >> Or you might want to just look around here. In this newsgroup/mailing-list one gets to see really lots of nice code. One that I would nominate as the best test for measuring a hard-core python programmer would be to explain the following code without the context :) Karl Scalet wrote: > there are very likely easier ways, but at least > > s = 'C6 H12 O6' > print [' '.join(xx) for xx in apply( > zip,[(x[0],x[1:]) for x in s.split()])] > > gives some results, > > Karl Once I understood the above, I beleive I will write python in my Resume... What was this about "One simple obvious way doing it"? ;) From andy at wild-flower.co.uk Sun Jul 13 17:33:59 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sun, 13 Jul 2003 22:33:59 +0100 Subject: Reloading nested modules Message-ID: <200307132233.59555.andy@wild-flower.co.uk> Does anyone know of a way to dynamically reload all the imported modules of a client module? I'm writing a program that I have broken down into quite a few submodules, and the 'configuration' is done with modules too. As I am developing the app, I need to test bits and pieces here and there. This is what I currently do: In each module, I have a section, just after the main imports like so: -----------8<----------- # normal imports: from ooby import squibble,dibble import dooby import doo # reloads for debugging import ooby # create a reference to ooby so we can reload it reload(ooby) reload(dooby) reload(doo) # main module code begins... -----------8<----------- The debugging imports of course will be dropped when the program is stable. I also often find myself doing similar stuff from the command-line, like: reload(ooby.oojar); reload(ooby.dibble); reload(ooby); ooby.somefunc(.....) I just wondered if anyone had develped a better 'spell' or even a small script that uses some clever intorspecton hack, before I go and start trying to reinvent the wheel... -andyj From ben at dadsetan.com Thu Jul 10 02:53:44 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Thu, 10 Jul 2003 08:53:44 +0200 Subject: Deleting specific characters from a string In-Reply-To: <38ec68a6.0307092151.21ba077a@posting.google.com> References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> <38ec68a6.0307092151.21ba077a@posting.google.com> Message-ID: Asun Friere wrote: > Behrang Dadsetan wrote in message news:<3F0C8AC3.5010304 at dadsetan.com>... > > >>def isAcceptableChar(character): >> return charachter in "@&" >> >>str = filter(isAcceptableChar, str) >> >>is going to finally be what I am going to use. > > > Might 'return character not in "@&"' work better? ahem... yes of course... From MK at foo.com Sun Jul 20 16:24:41 2003 From: MK at foo.com (MK) Date: Sun, 20 Jul 2003 22:24:41 +0200 Subject: Importing WMI module into Python CGI script fails References: <3F1A9A07.F71D274D@engcorp.com> <3F1AEA34.5072FADE@engcorp.com> Message-ID: "Peter Hansen" wrote [...] > I'd suggest you (a) learn more about Python, since you don't seem > to know how to interpret error tracebacks, and (b) describe in more > detail what you are trying to accomplish, because the problem is > not with the "wmi" module per se, but at a lower level, and appears > to be related to your not having the correct user permissions for > the object you are accessing. Fair enough. Thanks for suggestions! I will keep digging. MK From daniel.nouri at con-fuse.org Fri Jul 4 17:58:51 2003 From: daniel.nouri at con-fuse.org (Daniel Nouri) Date: Fri, 04 Jul 2003 21:58:51 GMT Subject: 'self' disappearing References: Message-ID: Answering my own question: Only a class attribute that is of FunctionType will be automatically converted into a bound method by the Python interpreter. If I wanted more control, I would have to do it through metaclasses. However, my (working) approach now is to return a function instead of a class instance, using this simple closure: def make_funwrapper(fun): def funwrapper(*args, **kwds): print 'Calling', fun.__name__ fun(*args, **kwds) return funwrapper Note that this requires Python 2.2 or 'from __future__ import nested_scopes' because I'm using 'fun' in the nested function. From bokr at oz.net Sat Jul 12 18:47:03 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 22:47:03 GMT Subject: Newbie with sort text file question References: <86d2ca4.0307121146.3deb854a@posting.google.com> Message-ID: On 12 Jul 2003 12:46:51 -0700, stuart_clemons at us.ibm.com (stuartc) wrote: >Hi: > >I'm not a total newbie, but I'm pretty green. I need to sort a text >file and then get a total for the number of occurances for a part of >the string. Hopefully, this will explain it better: > >Here's the text file: > >banana_c \\yellow >apple_a \\green >orange_b \\yellow >banana_d \\green >orange_a \\orange >apple_w \\yellow >banana_e \\green >orange_x \\yellow >orange_y \\orange > >I would like two output files: > >1) Sorted like this, by the fruit name (the name before the dash) > >apple_a \\green >apple_w \\yellow >banana_c \\yellow >banana_d \\green >banana_e \\green >orange_a \\orange >orange_b \\yellow >orange_x \\yellow >orange_y \\orange > >2) Then summarized like this, ordered with the highest occurances >first: > >orange occurs 4 >banana occurs 3 >apple occurs 2 > >Total occurances is 9 > >Thanks for any help ! ===< stuartc.py >======================================================== import StringIO textf = StringIO.StringIO(r""" banana_c \\yellow apple_a \\green orange_b \\yellow banana_d \\green orange_a \\orange apple_w \\yellow banana_e \\green orange_x \\yellow orange_y \\orange """) # I would like two output files: # (actually two files ?? Ok) # 1) Sorted like this, by the fruit name (the name before the dash) fruitlist = [line.split('_',1) for line in textf if line.strip()] fruitlist.sort() # apple_a \\green # apple_w \\yellow # banana_c \\yellow # banana_d \\green # banana_e \\green # orange_a \\orange # orange_b \\yellow # orange_x \\yellow # orange_y \\orange outfile_1 = StringIO.StringIO() outfile_1.write(''.join(['_'.join(pair) for pair in fruitlist])) # 2) Then summarized like this, ordered with the highest occurances # first: # orange occurs 4 # banana occurs 3 # apple occurs 2 outfile_2 = StringIO.StringIO() fruitfreq = {} for fruit, dummyvar in fruitlist: fruitfreq[fruit] = fruitfreq.get(fruit, 0)+1 fruitfreqlist = [(occ,name) for name,occ in fruitfreq.items()] fruitfreqlist.sort() fruitfreqlist.reverse() outfile_2.write('\n'.join(['%s occurs %s'%(name,occ) for occ,name in fruitfreqlist]+[''])) # Total occurances is 9 print >> outfile_2,"Total occurances [sic] is [sic] %s" % reduce(int.__add__, fruitfreq.values()) ## show results print '\nFile 1:\n------------\n%s------------' % outfile_1.getvalue() print '\nFile 2:\n------------\n%s------------' % outfile_2.getvalue() ========================================================================= executed: [15:52] C:\pywk\clp>stuartc.py File 1: ------------ apple_a \\green apple_w \\yellow banana_c \\yellow banana_d \\green banana_e \\green orange_a \\orange orange_b \\yellow orange_x \\yellow orange_y \\orange ------------ File 2: ------------ orange occurs 4 banana occurs 3 apple occurs 2 Total occurances [sic] is [sic] 9 ------------ Is that what you wanted? Regards, Bengt Richter From cookedm+news at physics.mcmaster.ca Wed Jul 9 17:46:28 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 09 Jul 2003 17:46:28 -0400 Subject: Shared vs static link performance hit --and Windows? References: <6ee58e07.0307091112.4931c31b@posting.google.com> Message-ID: At some point, llothar at web.de (Lothar Scholz) wrote: > Christos "TZOTZIOY" Georgiou wrote in message news:... >> Last night I was compiling the latest python snapshot at my home Linux >> system (a K6-III @420 --the extra 20 Hz is overclocking :); then I tried >> building a shared version of the interpreter. I did some speed >> comparisons, and pystone reported ~6090 pystones for the shared and >> ~7680 pystones for the (default) static build. >> > > Yes, today i recommend to not use the -fPIC option for certain > libraries when compiling a .so library. If you use it you get one more > indirection and this can be very bad on systems with long CPU > pipelines (PIV systems). If you don't use -fPIC then the shared > library will be patched and is only shared on disk but not in memory. On PowerPC Linux (or any PPC Unix using ELF), AFAIK, compiling shared libraries *without* -fPIC will run you into trouble. This is espically true if you then link to a library that was compiled with -fPIC. You'll get errors like 'R_PPC_REL24 relocation ...'. I certainly see problems with bad code that doesn't use -fPIC that runs on x86, but not on PPC. x86 has a different way of doing things from PPC that doesn't bite you on the ass when you compile without -fPIC. You especially run into trouble when you mix non-fPIC code with -fPIC code. [while we're on the subject, I'll point out that -fpic and -fPIC are not equivalent. -fpic can run out of space in the global offset table, while -fPIC avoids that. x86 doesn't have that limit, so I see people using -fpic where they should be using -fPIC.] -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From domma at procoders.net Mon Jul 21 12:07:14 2003 From: domma at procoders.net (Achim Domma) Date: Mon, 21 Jul 2003 18:07:14 +0200 Subject: COM interface to the Python interpreter References: Message-ID: Hi Christian, > under Win32 it is possible to use Python as a scripting language inside ASP > pages (win32lib package), so there must be a COM interface to the Python > interpreter. > > I like to use this interface instead of writing my own COM server to invoke > Python scripts from COM aware languages, unfortunately i can not find the > type-library for this interface. I think you are mixing something. To be available as scripting language inside ASP, there has to be a special interface, but it's not a 'simple' IDispatch based interface. You can look at the documentation of the Windows Scripting Host on how to use it in your own apps. Then you can automate your App with all installed scripting languages. If you would give us more details about what you want to do, one could answer more helpfully. regards, Achim From http Fri Jul 11 01:24:33 2003 From: http (Paul Rubin) Date: 10 Jul 2003 22:24:33 -0700 Subject: Securing 'pickle' References: Message-ID: <7x3chdfxf2.fsf@ruckus.brouhaha.com> Dave Cole writes: > def pickle_sign(self, text): > m = md5.new() > m.update(self.__secret) > m.update(text) > text = m.digest() + text > return text Use instead: def pickle_sign(self, text): m = hmac.new(self.__secret) m.update(text) text = m.digest() + text return text def pickle_unsign(self, text): digest = text[:16] text = text[16:] m = hmac.new(self.__secret) m.update(self.__secret) m.update(text) if m.digest() == digest: return text raise CookieError # or something like that Differences are: 1) use hmac instead of md5, to prevent appending attack 2) raise an exception if authentication fails, and handle it of course. The null string might be a valid cookie value and returning it on authentication failure lets attacker force return of a null string. There's another issue, mentioned in other post: if you have several pickles in separate cookies, you should sign them all together, not use an independent signature for each pickle like your class does. Say session 1 sets pickles A and B, and session 2 sets pickles C and D. With independent signatures, an attacker controlling both sessions can send back A and C, or B and D, with results that might confuse the application. From gsmatthew at ozemail.com.au Fri Jul 18 17:28:08 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Sat, 19 Jul 2003 07:28:08 +1000 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: Aahz Thanks, ive actually been using your OSCON slides which have helped a lot. So it technically correct that all worker threads in a thread pool are either doing some work or polling the queue to find out if there is a job to process ? eg: (pseudocodish :-)) def run(self): while 1: self.lock.acquire() if QueueManager.HasJob: job = QueueManager.GetFreeJob() __processJob(job) self.lock.release() def __processJob(self): blah blah blah ..... many thanks ...... "Aahz" wrote in message news:bf8ri5$cs7$1 at panix1.panix.com... > In article <0tRRa.212$vD1.8077 at nnrp1.ozemail.com.au>, > Graeme Matthew wrote: > > > >I just cannot seem to find any documentation that shows an example of > >using the factory method Event() in threads. I have a thread pool and > >if there are no jobs in a Queue I want them to wait for something to > >be inserted. When a job is inserted I want to send an Event, the first > >thread that picks it up runs with the job the rest wait for another > >insert Event. > > Given that you're already using a Queue, there is no, repeat NO, reason > for using an Event. Just have your threads block on the Queue. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > A: No. > Q: Is top-posting okay? From gh at ghaering.de Wed Jul 2 16:54:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 02 Jul 2003 22:54:52 +0200 Subject: undo tab In-Reply-To: <3F02ECF0.105@gmx.net> References: <3F02E7D5.4060401@gmx.net> <3F02ECF0.105@gmx.net> Message-ID: <3F03469C.4030508@ghaering.de> Tom wrote: > [how to (un)tabify] > > it doesn't work with any editor that I tried. The one I use on a regular > basis is the standard python IDLE. Sometimes I also use the editor of > pythonwin and Boa-Constructor. IDLE: Mark block. Menu: Edit/Indent Region Edit/Dedent Region. There are shortcuts for this. Which ones you can see in the Edit menu. PythonWin: mark block, press Tab or Shift-Tab. Works For Me [tm]. -- Gerhard From duncan at NOSPAMrcp.co.uk Wed Jul 16 05:04:18 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 09:04:18 +0000 (UTC) Subject: hex check References: Message-ID: Ruslan Spivak wrote in news:mailman.1058340712.8247.python-list at python.org: > Does anybody have a hint how to check if input hex number is in correct > hex format? > Use 'int' to convert it to a number, catch the exception if it isn't a valid format: >>> int('aa',16) 170 >>> int('0xaa',16) 170 >>> int('ag',16) Traceback (most recent call last): File "", line 1, in ? int('ag',16) ValueError: invalid literal for int(): ag >>> -- 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 tyler at scalegen.com Fri Jul 4 00:22:34 2003 From: tyler at scalegen.com (Tyler Eaves) Date: Fri, 04 Jul 2003 00:22:34 -0400 Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F04E609.2010500@dadsetan.com> Message-ID: On Fri, 04 Jul 2003 03:27:21 +0100, Behrang Dadsetan wrote: > A bit a pitty the message board system is php based.. > Ben. Why? Right tool for the job and all that... From jon+usenet at unequivocal.co.uk Thu Jul 10 19:33:12 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 10 Jul 2003 23:33:12 GMT Subject: Sample Web application References: Message-ID: In article , Ian Bicking wrote: > Well, it wasn't Quixote I was talking about. It was more things like > jonpy (with wt templates, specifically) Well, the way 'wt' works requires you to put 2 lines of mod_rewrite rules in your .htaccess or httpd.conf, there's no getting around that. I don't see it as a big hardship though. It's kind've fundamental to they way 'wt' templates work and 2 lines of work in advance means a lot of work saving later on. If you don't like the 'wt' templates then just use the rest of jonpy without them... From leo.broska at NOSPAM.isys.com.au Wed Jul 2 02:46:38 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Wed, 2 Jul 2003 16:46:38 +1000 Subject: arbitrary long integer aritmetics Message-ID: hi all is there a python module around allow using arbitrary long integers? i.e. the result of an integer operation is as long as necessary, so that a*b never produces an overflow error. (but rather an out of memory error ;-) ) thanks, leo From tebeka at cs.bgu.ac.il Thu Jul 17 06:05:31 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Jul 2003 03:05:31 -0700 Subject: hex to signed integer References: Message-ID: <33803989.0307170205.6cc6ffe@posting.google.com> Hello Tom, > I want to convert a string of hexadecimal characters to the signed > integer they would have been before the statement converted > them. How do I do this in such a way that is compatible with Python > versions 1.5.2 through 2.4, and not machine-dependent? eval? e.g.: >>> eval("0x%s" % "FF") 255 HTH. Miki From mwh at python.net Fri Jul 18 07:43:48 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jul 2003 11:43:48 GMT Subject: [development doc updates] References: <20030715221007.07C7A18F01B@grendel.zope.com> Message-ID: <7h38yqw12yn.fsf@pc150.maths.bris.ac.uk> Andy Jewell writes: > Does the following still hold true? I thought it had all changed - > do the new resolution rules only apply to "New Style Classes" ? Yes. Cheers, M. -- You owe the Oracle a star-spangled dunce cap. -- Internet Oracularity Internet Oracularity #1299-08 From russelllear at earthlink.net Wed Jul 2 23:26:33 2003 From: russelllear at earthlink.net (Russell Lear) Date: Thu, 03 Jul 2003 03:26:33 GMT Subject: Copying files in Python Message-ID: A simple question from a python beginner: How do I do 'cp -p source destination' where source could be a list of files and destination could be a file or directory (I could break the operation up if it must be file to file)? Perserving file creation time is important. Platform independence also nice. Clearly I could open the source file for reading and a destination file for writing and copy the bits over, but that might not preserve the file creation time. Right now I'm running Python 2.2.2 on SuSE Linux 8.2 I'll probably find the answer to this 30 minutes after posting this (isn't that always the way?) but any help would be appreciated. Thanks, Russell. From timr at probo.com Sat Jul 19 21:22:15 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 19 Jul 2003 18:22:15 -0700 Subject: Jerry Pournelle, Byte, Python, and Python in a Nutshell References: <3ebfb0c2$0$2616$a1866201@newsreader.visi.com> Message-ID: >On 12 May 2003 16:13:11 GMT, bokr at oz.net (Bengt Richter) wrote: > >>[OT] Are old mags and journals worth anything? I have tons (almost literally ;-) >>of old Bytes, DrDobbs, ACM Communications, SigPlan, SigOps, IEEE Computer, etc. etc. >>which I'd like to dispose of without feeling like I've thrown away money or >>something of value to someone. I have every Byte ever printed. I was a charter subscriber back in September, 1975 (first tag line: "Computers: The World's Greatest Toys!"), and I kept the subscription until they collapsed. I keep thinking they'll be worth money some day, but I suspect I'm dreaming. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jon+usenet at unequivocal.co.uk Tue Jul 8 12:02:48 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 8 Jul 2003 16:02:48 GMT Subject: Python vs PHP References: Message-ID: In article , Afanasiy wrote: > A couple other slight issues : > > * catch-all error handling not as flexible or non-existent > * no equivalent to php_value auto_prepend_file "_header.php" > * no equivalent to php_value auto_append_file "_footer.php" > * not as intelligent form value handling > * white space sensitivity is a unique problem when embedding Try jonpy (http://jonpy.sf.net/), it solves all of the above. Also you may find FastCGI (which jonpy supports) helps with your "safe mode" problem, although it might require a bit of hackery. From jdhunter at ace.bsd.uchicago.edu Mon Jul 7 22:57:56 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 07 Jul 2003 21:57:56 -0500 Subject: getting a submatrix of all true In-Reply-To: (bokr@oz.net's message of "8 Jul 2003 00:48:21 GMT") References: <52fe159d.0307041016.4dcb4a5c@posting.google.com> Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> Curiousness: what do your observations represent? By day, I do research in neurology and neurobiology. By night, stock market analysis: academia doesn't pay! I have written several modules to parse the Yahoo Finance pages, eg, http://biz.yahoo.com/z/a/x/xoma.html and http://biz.yahoo.com/p/x/xoma.html. The 2 fields which you identified as missing on all but 2 observations are Revenue Estimates: "Year Ago Sales" and "Sales Growth" for This Year, both of which are N/A for almost all tickers. Jon> Interesting problem! Bengt> Yes. So many, so little time ... ;-/ Exactly. JDH From kericks272 at earthlink.net Thu Jul 24 11:06:29 2003 From: kericks272 at earthlink.net (ken) Date: Thu, 24 Jul 2003 15:06:29 GMT Subject: python 2.2 string conversion ? References: Message-ID: It wasn't clear to me when I read the docs - I inferred that the long() built-in only took 1 parameter. Thanks everybody. "Gary Herron" wrote in message news:mailman.1059027097.828.python-list at python.org... > > > > >>> x="e10ea210" > > >>> y=long(x) > > > > Traceback (most recent call last): > > File "", line 1, in ? > > y=long(x) > > ValueError: invalid literal for long(): e10ea210 > > > What am I doing wrong? > > You didn't specify what you are trying to do here, but I'll make a > wild *guess* that the string in x is a hexadecimal (i.e., base 16) > value. However, Python can't go around making such a guess, so you > have to explicitly specify your radix (radix being another term for > base) like this: > > >>> print long("e10ea210",16) > 3775832592 > > or tell it to infer the radix from a '0x' prefix: > > >>> print long("0xe10ea210",0) > 3775832592 > > Here are the relevant portions of the manual: > > long(x[, radix]) > > Convert a string or number to a long integer. If the argument is a > string, it must contain a possibly signed number of arbitrary size, > possibly embedded in whitespace; this behaves identical to > string.atol(x). The radix argument is interpreted in the same way as > for int(), and may only be given when x is a string. Otherwise, the > argument may be a plain or long integer or a floating point number, > and a long integer with the same value is returned. Conversion of > floating point numbers to integers truncates (towards zero). > > > int(x[, radix]) > > Convert a string or number to a plain integer. If the argument is a > string, it must contain a possibly signed decimal number > representable as a Python integer, possibly embedded in whitespace; > this behaves identical to string.atoi(x[, radix]). The radix > parameter gives the base for the conversion and may be any integer > in the range [2, 36], or zero. If radix is zero, the proper radix is > guessed based on the contents of string; the interpretation is the > same as for integer literals. If radix is specified and x is not a > string, TypeError is raised. Otherwise, the argument may be a plain > or long integer or a floating point number. Conversion of floating > point numbers to integers truncates (towards zero). If the argument > is outside the integer range a long object will be returned instead. > > > Gary Herron > > > > From theller at python.net Thu Jul 17 12:47:02 2003 From: theller at python.net (Thomas Heller) Date: Thu, 17 Jul 2003 18:47:02 +0200 Subject: Unicode question References: Message-ID: <65m1yubd.fsf@python.net> Gerhard H?ring writes: > >>> u"???" > u'\x84\x94\x81' > > (Python 2.2.3/2.3b2; sys.getdefaultencoding() == "ascii") > > Why does this work? > > Does Python guess which encoding I mean? I thought Python should > refuse to guess :-) I stumbled over this yesterday, and it seems it is (at least) partially answered by PEP 263: In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals. I have the impression that this is undocumented on purpose, because you should not write unescaped non-ansi characters into the source file (with 'unknown' encoding). Thomas From lists at gregfortune.com Fri Jul 11 09:31:23 2003 From: lists at gregfortune.com (Greg Fortune) Date: Fri, 11 Jul 2003 06:31:23 -0700 Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: Because sorts works in place and the sort fuction returns None rather than a copy of the list. Try import sys temp = sys.modules.keys() temp.sort() print temp Greg Steve Pinard wrote: > (Got a comm error trying to post first time, sorry if this > is a duplicate) > > New to Python, so please bear with me. > >>>> import sys >>>> print sys.modules.keys() # works fine > ['code', ...snip... ] >>>> print sys.modules.keys().sort() # returns None, why? > None > > According to my reference (Nutshell), keys() returns a > "copy" of the dict keys as a list, so I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? > > TIA, > - Steve From wolfson at uchicago.edu Sat Jul 5 21:15:14 2003 From: wolfson at uchicago.edu (Ben Wolfson) Date: Sun, 06 Jul 2003 01:15:14 GMT Subject: problems with sf cvs server? Message-ID: Is anyone else experiencing trouble checking the python source tree out of the sf cvs server? I hang forever here: cvs server: Updating python/nondist/src/Compiler/tests/output -- BTR The Glass Marble, mistaking the No. 37 Penpoint for the Four-Holed Button, pushed it into the Yawning Chasm. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 19:40:16 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 31 Jul 2003 01:40:16 +0200 Subject: Convert a number to it name... In-Reply-To: References: Message-ID: <3f285760$0$49111$e4fe514c@news.xs4all.nl> Mauro Baraldi wrote: > Someone can help how to convert a number to it name. Well I'll explain... Ben suggested the pynum2word project, but you might also want to take a look at my 'number.py' that is part of Snakelets (as an example). It works with data files for over 70 languages. http://tinyurl.com/ikim Don't pay attention to the code style-- it's ugly as sin, because it is a straight port from some very old C code. --Irmen From Kepes.Krisztian at peto.hu Mon Jul 28 03:16:55 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Mon, 28 Jul 2003 09:16:55 +0200 Subject: The protection of resources Message-ID: Hi ! In this time I use the Lock() for thread synchronization, and resource protection. But in the new project I must reorganize this thing. The program must be run in lin/win, so I cannot use the winapi. I need to protect resources from concurrent r/w. Possible that the modules are not threads but are tasks. In the Delphi and WinAPI I use the Mutex, that is a simple, opsystem protected thing to signaling. It is a simple signal (1/0). I search for this in python, but I see only mutex with "procedure queue". I cannot see a signal like thing. I want to only signaling: the resource are taken or not. I don't want to wait for the non used state (not block !). So these my questions: - 1. How to use the py mutex object ? Please send an example to me ! - 2. Have the py an signal object ? (platform !!!) - 3. Is any solution is a file locking. Have the py a possibility of exclusive file opening ? Thx: KK From tim.one at comcast.net Wed Jul 16 10:52:56 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 16 Jul 2003 10:52:56 -0400 Subject: <> and != In-Reply-To: <3F155B6D.8000205@hotmail.com> Message-ID: [hokiegal99, on <> vs !=] > What's the reason for having two symbols mean the same thing? Hysterical raisins. Python originally used only "<>". C programmers whined about that, so Python added "!=" too. But Python code already used "<>", so it was too late to get rid of that one. "<>" was deprecated instead. That's a computer science term usually meaning it's like a mentally disturbed uncle: we won't kill it, but we won't talk about it either . The good news is that Guido has become more hardened to whining over the centures since then. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 08:32:12 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 14:32:12 +0200 Subject: RELEASED Python 2.3 (final) In-Reply-To: References: Message-ID: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> Barry A. Warsaw wrote: > On behalf of the Python development team and the Python community, I'm > happy to announce the release of Python 2.3 (final). kudo 1 : AWARD, HONOR 2 : COMPLIMENT, PRAISE (M-W) --Irmen de Jong From intentionally at blank.co.uk Sun Jul 13 17:20:33 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 22:20:33 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: On 13 Jul 2003 15:05:38 -0500, Ian Bicking wrote: >On Sun, 2003-07-13 at 14:39, Stephen Horne wrote: >> The fact is that 'assignment' has a common meaning separate from the >> choice of programming language, > >This just isn't true. The C++ assignment operator is not at all like >the Python assignment statement. Python variables are not like C++ >variables, no surprise assignment is different too. If you used >languages outside of C++ and its like (e.g., Pascal), you would find >Python's behavior common. Think again. When I say "'assignment' has a common meaning separate from the choice of programming language" I assumed you would get the hint. I'm not referring to some specific other programming language, of which I have used many - and not all of them imperative. I am referring to the definitions in computer theory, which do not relate to any specific programming language but actually apply to all of them, irrespective of paradigm and everything else. Of course, if you really believe that pointer/reference behaviour should be arbitrarily tied to mutability then you can claim that I am wrong, but you still can't claim the high ground as this is still an arbitrary and bizarre thing to do. The ability to change part or all of a value in-place has nothing to do with whether that value is referenced using a pointer or whatever in computer theory - any link between pointers/references and mutability should be related to the implementation of the language - not the semantics. So much for dropping out of the discussion, but I hate it when people make false claims about my beliefs, making me out to be ignorant, when it is *not* *me* who is missing the point. From afriere at yahoo.co.uk Wed Jul 30 22:28:57 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 30 Jul 2003 19:28:57 -0700 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> Message-ID: <38ec68a6.0307301828.7310e01b@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > John Machin wrote: > > > >So ... could we please change that to "much kudos"? > > Nope. Kudos is a mass noun, but it's a discrete mass noun. So you need > to say "many kudos". I believe it is customary to use the construction 'great kudos,' which, in any case, you all deserve. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 29 18:07:32 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 00:07:32 +0200 Subject: Showing IP address of a user... In-Reply-To: References: <7b454334.0307291005.53ee8c07@posting.google.com> Message-ID: <3f26f026$0$49117$e4fe514c@news.xs4all.nl> Jeremy Yallop wrote: > os.environ['REMOTE_ADDR'] Ofcourse, this is only available when you're in a CGI-like environment. When running inside mod_python, or something else, I doubt that this environment variable is available. In those cases, there is usually a specific way of obtaining the client's address, either directly or via the socket that represents the network connection. But this depends on what you're running! --Irmen From 2002 at weholt.org Mon Jul 7 07:34:41 2003 From: 2002 at weholt.org (Thomas Weholt ( PRIVAT )) Date: Mon, 7 Jul 2003 13:34:41 +0200 Subject: Python vs PHP References: Message-ID: Replace PHP ? They're rather different animals, but as Web programming languages go I think there is little you can do in PHP that you cannot do in Python some way or another. Python has good support MySQL. Search for Mysql and python on www.sourceforge.net. The docs contain examples on how to connect to the database too. General tutorials on Python are available at www.python.org, but more web specific docs depends on what you want to do, how and where ( platform etc ). Give a bit more details. Thomas "Catalin" wrote in message news:mailman.1057574470.1750.python-list at python.org... > Can Python replace PHP? > Can I use a python program to make an interface to a mysql 4.X database? > If that's possible where can I find a tutorial? > > From pablo at bogus.domain.org Sat Jul 19 16:48:16 2003 From: pablo at bogus.domain.org (Pablo) Date: Sat, 19 Jul 2003 22:48:16 +0200 Subject: classes References: Message-ID: I am sorry my post was sent twice. From CNDESMTP03OUServersOUKGaAOHENKEL at henkel.com Wed Jul 9 14:00:16 2003 From: CNDESMTP03OUServersOUKGaAOHENKEL at henkel.com (CNDESMTP03OUServersOUKGaAOHENKEL at henkel.com) Date: Wed, 09 Jul 2003 19:00:16 +0100 Subject: Report to Sender Message-ID: Incident Information:- Database: E:/Notes/Data/mail.box Originator: python-list at python.org Recipients: HR.Department at cognis.com Subject: Re: Application Date/Time: 07/09/2003 07:00:04 PM The file attachment your_details.zip you sent to the recipients listed above was infected with the W32/Sobig.e at MM virus and was deleted. From mis6 at pitt.edu Thu Jul 17 13:25:45 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 17 Jul 2003 10:25:45 -0700 Subject: Co-routines References: Message-ID: <2259b0e2.0307170925.5e876d1f@posting.google.com> wrote in message news:... > (I recall the malevolent and wicked ternary operator example that was > posted here which fiddled with function source code in the metaclass... I'm > still picking up pieces of my brain from the floor) > Oops! ;-) To make ammend, I send you this solution: def f1(): for i in range(1,4): print "1-%s" % i; yield i def f2(): for i in f1(): print "2-%s" % i f2() This print 1-1 2-1 1-2 2-2 1-3 2-3 However I am not sure I understand correctly what you have in mind, so this solution may well be not relevant at all! Michele From staschuk at telusplanet.net Wed Jul 16 22:02:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 20:02:02 -0600 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? In-Reply-To: <3f15ca92@shknews01>; from lol@lolmc.com on Wed, Jul 16, 2003 at 10:57:16PM +0100 References: <3f15ca92@shknews01> Message-ID: <20030716200202.B656@tibia.amotlpaa.bogus> Quoth Rogue9: > draw = 1 > while 1: > if draw == 792: > break > b1 = someOtherList[draw-1] > r1 = b1[draw] > draw = draw+1 > > However,the item I expect is not being retrieved i.e. a zero is the result > of the retrieval rather than the integer in the list I was expecting. > Furthermore,when I substitute an integer for draw e.g. r1 = b1[12],I > do get the expected result. Bizarre. What is the value of someOtherList? (And, as a side note, why not use a for loop, e.g., for draw in range(1, 793): r1 = someOtherList[draw-1][draw] # and then, I assume, you actually do something with r1 ?) -- Steven Taschuk staschuk at telusplanet.net Every public frenzy produces legislation purporting to address it. (Kinsley's Law) From akaihola at ambi-spam-me-not-tone.com Fri Jul 18 17:58:13 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Sat, 19 Jul 2003 00:58:13 +0300 Subject: Open MS Excel Spreadsheet with Python In-Reply-To: <1c057c8e.0307171643.486e9678@posting.google.com> References: <1c057c8e.0307171643.486e9678@posting.google.com> Message-ID: There's an excellent utility called xlhtml, which converts XLS spreadsheets to HTML files, available at http://chicago.sourceforge.net/xlhtml/ I made a simple Python wrapper, which uses xlhtml and parses the converted spreadsheet into a Python Numeric array. As I didn't need to do any calculations with the data, you only get cell contents as string objects at this time. Note that using this method you only need freely available tools, no excel or windows. Also, it isn't necessary to open and save the spreadsheet as a CSV or XML file, which is nice if you need to batch process lots of spreadsheets. Take a look at akaihola.iki.fi/comp/python and drop me a note if you make improvements to the code. Antti From geoff at gerrietts.net Mon Jul 7 14:05:09 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Mon, 7 Jul 2003 11:05:09 -0700 Subject: python scripting game The Temple Of Elemental Evil update In-Reply-To: References: <82ff1d8b.0307061540.5da32ae@posting.google.com> Message-ID: <20030707180509.GB26862@thoth.homegain.com> Quoting Bengt Richter (bokr at oz.net): > I'm wondering what "the scripting" does in the above. I.e., who writes the scripts, > and what aspect of the games do they implement? When are they executed, and by what? > > (Apologies, too lazy/tired right now to pursue it via the links on this page ;-) Not trying to pursue this too far, and not trying to claim authority, but most RPG-style games that use an embedded scripting environment, use it more or less as the means of expressing content. It's almost like the programmers build a Lego set out of C, C++, and image files; then the game designers assemble the Legos using Python. With a little more specificity, most of the games I have seen that use this approach (which is a pretty large number of games) build a graphics engine, a rules engine, and a collection of library routines as primitives. These primitives are exposed into the scripting language. The story itself is largely told through the scripting language, by using the API to manage dialogue options, build quests, etcetera. I can't speak for the Temple of Elemental Evil in particular, but this pattern holds true in dozens of similar titles. If they're doing something different, they're doing something really very different. --G. -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From adechert at earthlink.net Mon Jul 21 20:27:29 2003 From: adechert at earthlink.net (Alan Dechert) Date: Tue, 22 Jul 2003 00:27:29 GMT Subject: Voting Project Needs Python People References: <5ab0af73.0307211623.6e12f807@posting.google.com> Message-ID: "Matt Shomphe" wrote in message news:5ab0af73.0307211623.6e12f807 at posting.google.com... > "Alan Dechert" wrote in message news:... > > > We have an excellent team together. We're looking for a few good Python > > coders willing to volunteer for this free open source project. It will be > > on sourceforge.net later today. > > Are there any prerequisites for joining the team? > It would be nice if you know some Python. Do you? BTW, I'm told it will take a day or two to get the project going on sourceforge.net. Alan Dechert From peter at engcorp.com Wed Jul 9 20:35:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 20:35:57 -0400 Subject: SNMP support for Python under Windows References: <538fc8e.0307091027.1825b454@posting.google.com> <3F0C65FB.1B86A0C2@engcorp.com> <538fc8e.0307091335.70526148@posting.google.com> Message-ID: <3F0CB4ED.C195374F@engcorp.com> WIWA wrote: > > I did two things, both unsuccessfull: > > 1) If I install the pySNMP modules under lib/site-packages and then > type sth like: > from pysnmp import session it gives the error message "ImportError: No > module named pysnmp". The same happens if I unstall pySNMP directly > under the lib directory. Installs in this context means 'copy paste' > the *.py files of the pySNMP distribution. I misled you the first time, but have since taken another look at the installation to see how it works. In order to import anything from a package (roughly, a set of .py files that includes an __init__.py file), you need to put those files in a directory which is named for the package (e.g. pysnmp in this case) _and_ which is available in sys.path. (Do "import sys" and "sys.path" to see the list. You probably have lib/site-packages in that list, so just put all the PySNMP files under it in a folder called pysnmp.) > - Do I need to explicitly mention in my script where pySNMP is > installed? Not if it's in a folder called pysnmp that is itself in one of the sys.path folders, or under the current folder. > 2) I installed distutils 1.0.2 for Windows and it installed into the > Python directory. So ar so good, I think... Distutils is included in Python so you probably didn't need to do that, and maybe shouldn't have. I'm not sure whether that will have broken the standard distutils. It's repairable if it did. On my Python 2.2.1 setup here, the standard distutils is v1.0.3. > I go to DOS prompt and go to the directory where disutils is installed > and type in python setup.py install, but DOS replies: > 'Python is not recognized as an internal or external command, program > or batchfile". Now that's a different problem. You need python.exe to be findable from the DOS PATH. The simplest approach might be to check the FAQ entry at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp As a test of the pysnmp installation, without having to change PATH at all, change to the Python directory ("cd \python" or whatever) and run the interactive interpreter ("python") and just type "import pysnmp" to see if it works. > System coordinates are Windows XP. Python version is 2.2.2 and pySNMP > is version 3.0.0. Should all be no problem, although I suspect instructions in that FAQ entry may be a little light on XP advice. Let us know if you see any area that could be improved so others can benefit from this exchange... -Peter From sac at noreply.com Wed Jul 9 12:07:00 2003 From: sac at noreply.com (Sac) Date: Wed, 09 Jul 2003 09:07:00 -0700 Subject: Python 2.2 build problems on AIX References: Message-ID: edadk wrote: > Hi > > I building Python on AIX using > > make > > However, I get some errors when building > > readline > gdbm > > and > > -ltermcap > > is missing. See below. Can those problems be fixed? > > Erling > > building 'readline' extension > cc_r -DNDEBUG -O -I. > -I/mnt/mds/metawrk/edanders/Python-2.2.3/./Include > -I/usr/local/include -I/mnt/mds/metawrk/edanders/Pytho > 2.2.3/Include -I/mnt/mds/metawrk/edanders/Python-2.2.3 -c > /mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c -o build/t ...(Lines Deleted) Greetings, You may wish to grab some of these tools and utilities from IBM. Many Open Source packages are available. Project heading is Linux Toolbox for AIX. Source and binaries are available from the following IBM website: ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox Installation instructions are available from ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/README.txt Cheers... From max at alcyone.com Tue Jul 15 20:35:38 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Jul 2003 17:35:38 -0700 Subject: md5 consistent across platforms/Python versions? References: Message-ID: <3F149DDA.EDA010EC@alcyone.com> Gary Robinson wrote: > I know that hash functions are often platform-dependent for efficiency > reasons. From what I understand, this includes Python's hash(), which > I have > read is not guaranteed to return the same result across platforms or > even > across Python versions. Yes. > Can someone tell me whether an MD5 hash using Python's MD5 library IS > guaranteed to return the same results for the same input string, > across > platforms and Python versions? Yes. MD5 hashes and Python's internal hash function are unrelated. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Nine worlds I remember. \__/ Icelandic Edda of Snorri Sturluson From peter at engcorp.com Sat Jul 19 10:10:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jul 2003 10:10:56 -0400 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> <9j3Sa.319$vD1.15038@nnrp1.ozemail.com.au> Message-ID: <3F195170.E60FB1A6@engcorp.com> Graeme Matthew wrote: > > ok so code like this is perfectly safe > > def run(self): > > while 1: > > job = queue.get() > > __processjob() It's almost like you aren't even seeing Aahz' replies. ;-) The above is certainly safe, but can't be terminated easily. Just use the loop Aahz showed, which is the above plus the ability to terminate. -Peter From evotrain at gmx.net Wed Jul 9 05:22:08 2003 From: evotrain at gmx.net (Thomas Kwapich) Date: Wed, 09 Jul 2003 09:22:08 GMT Subject: pythonw freezes with print output Message-ID: <20030709.9220899@tomsbook.internedomain.loc> Hi, I'm developing a wxpython application under windows 2000. If I start it with pythonw.exe (without dos window) it freezes after some time depending on the amount of print output it generates. On the other hand if I start it with python.exe (the dos window is shown) it is stable. Reducing the print output to zero makes it even stable when started with pythonw. (I tried to debug it with SciTe but it doesn't crash with it altough SciTe starts it with pythonw) Any ideas why this happens? Best regards Thomas From jepler at unpythonic.net Sun Jul 13 16:40:38 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 13 Jul 2003 15:40:38 -0500 Subject: How to crash Python in 1 easy step (python 2.2.2) In-Reply-To: <2e363c08.0307130944.4c470bc3@posting.google.com> References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <20030713204037.GE32319@unpythonic.net> On Sun, Jul 13, 2003 at 10:44:41AM -0700, Paul Miller wrote: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is Doesn't happen here. What terminal (xterm, kterm, gnome-terminal, console?) and what LANG is set in your environment? If you run 'od -c' at the shell, then hit ctrl-shift-enter then ctrl-d, what does it show? I'd expect to see something very much like this: $ od -c 0000000 \n 0000001 that is, even with the modifier keys, the program only sees a normal newline character. What happens if you type ctrl-shift-enter to another readline-linked program (for instance 'bc', an infix calculator)? Do you get the same crash? Does the behavior change if you run 'cat | python' and then press ctrl-shift-enter? This will avoid importing readline (and another side-effect is to suppress the normal ">>>" prompt of the interative interpreter) Jeff From giles_brown at hotmail.com Sat Jul 5 14:41:27 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 5 Jul 2003 11:41:27 -0700 Subject: Question about "exec in globals, locals" References: <57de9986.0307040041.553ff329@posting.google.com> Message-ID: <57de9986.0307051041.1292a0ec@posting.google.com> Adrien Di Mascio wrote in message news:... > Hi, > > source = """ > > class FirstClass: > > pass > > class SecondClass: > > References = [FirstClass] > > """ > > > When you specify both locals() and globals(), here's what happen : > > """ > class FirstClass: > pass > > ## ---------> Here, your locals() dict have been updated, but not your > ## globals() one. > ## But, here, you can do : References = [FirstClass] since your > ## locals() > ## know about 'FirstClass' > > class SecondClass: > ## ---------> Here, your locals() dict is a new one since you've > just > ## entered a new scope. So, 'FirstClass' is neither defined in > ## 'locals()' nor in 'globals()', that's why you have your > NameError > """ > > I'm not quite sure of my explanation, but that could explain your > problem. Sorry if I've made any Python mistake. Hmmm. You might be right, but wouldn't you expect the scope of SecondClass to be nested within the scope of the passed in locals()? I find this quite confusing, which unusual for a Python ;-) Thanks, Giles Brown From evan at 4-am.com Wed Jul 16 15:40:01 2003 From: evan at 4-am.com (Evan Simpson) Date: Wed, 16 Jul 2003 14:40:01 -0500 Subject: Replacing rexec In-Reply-To: <1058378060.5034.13.camel@redwall.ofsloans.com> References: <1058378060.5034.13.camel@redwall.ofsloans.com> Message-ID: <3F15AA11.1000705@4-am.com> Tim Gerla wrote: > Given a bit more assurance that a replacement would be useful and > possible, we potentially have the resources to do so. Having a working > and trusted plpython is valuable to both my own organization and, IMHO, > the Python world itself. Zope has a trusted Python implementation based on Python 2.2+'s compiler package. It would need to be substantially adapted for use in plpython, but it could be done. Among other things, it controls imports and builtins, forbids the use of exec and eval, redirects print statements, and prevents access to names starting with '_'. Cheers, Evan @ 4-am From FBatista at uniFON.com.ar Mon Jul 28 09:52:31 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 28 Jul 2003 10:52:31 -0300 Subject: Standard behaviour of a getSomething method Message-ID: #- >> Considering that this attribute is always another object #- (everything #- >> is an object in Python), what should getMyAttrib do? #- >> #- >> 1) Return the object #- >> 2) Return a copy of the object #- #- Because returning a copy is seldom needed, I prefer returning the #- object itself. If it's an immutable object, the difference doesn't #- matter, anyway. If it's a mutable object, you should note the access #- semantics in the docstring, as someone else pointed out. Here it's the very point. I don't want to anybody to access the class attribute from outside. Beyond the get/set interface mechanism, if I return the object (a mutable one), this object can be modified from outside. Shouldn't I return a copy of the object in this case? Thanks. . Facundo From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 15 07:10:53 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 11:10:53 GMT Subject: FCNTL module deprecation warning References: Message-ID: Meyer, Tony enlightened us with: > C:\Program Files\Python23\lib\fcntl.py:7: DeprecationWarning: the > FCNTL module is deprecated; please use fcntl Seems you're using windoze. > It seems to be saying that I shouldn't use "import FCNTL" (which gives > the same warning), but "import fcntl", but that's what I _am_ doing. Windoze has a case insensitive filesystem, and thus it can't see the difference between FCNTL and fcntl. Try removing the depricated FCNTL from your harddisk, or rename it to FCNTL-dep.py. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From richiez_1 at yahoo.com Fri Jul 25 01:43:13 2003 From: richiez_1 at yahoo.com (BrianZ) Date: 24 Jul 2003 22:43:13 -0700 Subject: Problem with pyOpenSSL and Python2.3c References: Message-ID: "Stephen C. Waterbury" wrote in message news:... > I'm trying to get pyOpenSSL to work with Python 2.3c on > Red Hat 9, but there seems to be a Python C API incompatibility. > I assume this just means that a new version of pyOpenSSL is > needed for Python 2.3 -- is that correct? > > - Steve. Do you need pyOpenSSL specifically? If you're just trying to get SSL support the Python 2.3 socket module has it built in. From dhostetler at sopris.net Mon Jul 14 14:33:33 2003 From: dhostetler at sopris.net (.d.hos) Date: 14 Jul 2003 11:33:33 -0700 Subject: parsing flat file to mssql (odbc) References: <8db020b9.0307081101.23325bd@posting.google.com> Message-ID: <8db020b9.0307140644.6d7a8beb@posting.google.com> > > Strange error message you have there... > > Have you tried using mxODBC at this ? I'd bet you get much better > results. > > -- > Marc-Andre Lemburg > eGenix.com Mark, thanks for your suggestion, it seems to be working w/ mxODBC. From skodela at lithium.com Wed Jul 30 18:28:02 2003 From: skodela at lithium.com (sreekant) Date: Wed, 30 Jul 2003 22:28:02 +0000 (UTC) Subject: reading in lines from a file -FAST! In-Reply-To: References: Message-ID: Why not use s=openfile.read() s=string.split(s,'\n') just a thought sree From skip at pobox.com Sun Jul 27 11:48:15 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 27 Jul 2003 10:48:15 -0500 Subject: emacs python-mode questions: C-c C-c and broken docstring fill In-Reply-To: <87ptjwre0x.fsf@pobox.com> References: <87ptjwre0x.fsf@pobox.com> Message-ID: <16163.62527.778966.448916@montanaro.dyndns.org> John> 1. Why do I get this in my minibuffer when I do C-c C-c in a John> python-mode buffer containing the following valid Python code? John> Wrong type argument: sequencep, cpython It looks like a bug in py-execute-region. It sets the shell variable like so: (setq shell (or (py-choose-shell-by-shebang) (py-choose-shell-by-import) py-which-shell)))) which gives it the value (quote cpython). Later on it tries to concatenate it: (let ((cmd (concat shell (if (string-equal py-which-bufname "JPython") " -" "")))) which fails because shell is not a string (strictly speaking, a sequence) at that point. I'm not sure what the correct fix is. John> 2. A while ago I 'upgraded' to a version of python-mode (from John> somewhere on sourceforge, I think -- perhaps Python CVS, don't John> remember) which somebody here claimed was able to fill comments John> without needing blank lines before and after the comment. It does John> do that, but the new version also breaks filling text in John> docstrings (under particular circumstances which I haven't figured John> out, but which occurs very frequently). I get something like: John> "The parameter start is not the beginning of a python string". John> Where does the latest python-mode live, and is this fill bug with John> docstrings fixed? Can you file a bug report with a small failing example? Assign it to me (montanaro). Skip From jdhunter at ace.bsd.uchicago.edu Wed Jul 2 15:16:57 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 02 Jul 2003 14:16:57 -0500 Subject: getting a submatrix of all true Message-ID: I have a largish data set (1000 observations x 100 floating point variables), and some of the of the data are missing. I want to try a variety of clustering, neural network, etc, algorithms on the data, and to keep life simple I want to reduce the dimensions of the matrix so that I have no missing values, since not all the algorithms are able to handle them and there is sufficient redundancy in the variables that I can afford to lose some. I am currently using a hack that works, but it makes me wonder if there is an optimal solution. I define optimal as the removal of rows and columns such that there are no missing values and max(numRows*numCols). My current approach is to drop rows (observations) that have more than some prespecified number of missing variables, and then drop the columns (variables) of the reduced data set that have any missing values. I chose the threshold for dropping a row by eyeballing the distribution of number of missing variables per observation, pick a number on the low end of the distribution, and dropping the rows that exceed the threshold. Another way of formulating the question: for a sparse boolean matrix (sparse on True), what is the optimal way to remove rows and columns so that the total number of elements in the matrix is maximal and there are no True values left. Example: 0 0 0 0 0 0 candidate sub matrix has 12 elements 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 candidate submatrix has 15 elements 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 candidate submatrix has 8 elements 0 0 0 0 I want to programatically extract the 15 element matrix Following the approach described above, I get the desired answer in the example below, though this is a hack solution and I have the feeling there is a better one. from Numeric import nonzero, array, take, sum X = array([[1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0]]) goodObsInd = nonzero(sum(X,1)<2) # observations with < 2 missing variables X = take(X, goodObsInd) # drop the bad goodVarInd = nonzero(sum(X)==0) # variables with no missing data X = take(X, goodVarInd, 1 ) # drop the bad variables print X John Hunter From bokr at oz.net Thu Jul 17 16:05:28 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 20:05:28 GMT Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> <3f16bb84@shknews01> Message-ID: On Thu, 17 Jul 2003 16:05:15 +0100, "Rogue9" wrote: >After reviewing my question I realised that I should have posted the short >piece of real code I'm working on and not tried to write some pseudo-code >to illustrate the problem I'm having.Therefore I have printed the listing >below which is quite short and hopefully won't annoy too many peopleabout >the length of my post. > >To reiterate: >The masterList holds the results for the UK lottery in the form >[[1,'1994-10-19',3,14,16,23,34,43,2,3,'ARTHUR',234]...] and there are 792 >results in the list. The skipFreqList holds the count of skipped draws >between when a certain ball was drawn i.e if ball one was drawn in draw >one and then not again till draw 10 the list would look like this >[['Ball1',0,1,2,3,4,5,6,7,8,9,0......],['Ball2,1,2,0,1,2,3,4,5,0,0]....['Ball49',1,0,1,2,3,4,5,6,7,8]].Each >item in the skipFreqList will be 1 item longer than the masterList length >as each one starts with a string descriptor. I don't understand what skipFreqList really is. Do the zeroes signify that the ball was picked as the first ball in that draw and numbers n mean it was drawn in that draw as the (n+1)th ball? (if so why have a 9, since 8 is all the balls taken for a given draw?) IMO a more straight-forward encoding of that info would be just the pick order of the ball for a given draw: 1-8 for picked first-last, and zero for not picked at all. If you use 0-7 for pick order and call it skips, and then have 8 mean skip altogether, that might be what's happening? But then your 9 is a typo ;-) If that's it, you'd expect to get zero about 1 in 8, but not always. Why not just load the data interactively by typing (or maybe you can just copy this and run it as something.py for starters to see what we get (untested! but you should be able to fix it ;-) ====< something.py >=========================================== import cPickle f=open('/home/lol/disk/python/lotto/dat/masterList.lb','r') masterList = cPickle.load(f) f.close() f=open('/home/lol/disk/python/lotto/dat/skipFreqList.lb','r') skipFreqList = cPickle.load(f) f.close() #and then interactively looking at the data step by step the way you #think the program should be looking at it. #You can also make little interactive loops to show specific items from all the draws, #e.g., (untested!) def getSkip(draw, pick): # ok, index draw from 1, and picks also 1-8 drawresult = masterList[draw-1] # draw starts with 0 from xrange ball = drawresult[pick+1] # picked ball skip = skipFreqList[ball-1][draw] # past ball name return (ball, skip) # since we are talking about the first ball here, the skip is always 0? print 'pick #1' for draw in xrange(1,20): # or xrange(1,len(masterList)+1): for the whole thing print getSkip(draw, 1), # first ball pick in any draw should get skip of 0, right?? print # now try second pick print 'pick #2' for draw in xrange(1,20): # or xrange(1,len(masterList)+1): for the whole thing print getSkip(draw, 2), # 2nd ball pick in any draw should get skip of 1, right?? print #Or what does skipFreqList mean? # =================================================================== HTH Regards, Bengt Richter From tylere at hotpop.com Wed Jul 2 22:13:32 2003 From: tylere at hotpop.com (Tyler Eaves) Date: Wed, 02 Jul 2003 22:13:32 -0400 Subject: anything like a "pointer" in python? References: Message-ID: On Thu, 03 Jul 2003 09:41:05 +0800, stevenswan wrote: > I want to open a file in python and read something and process the file in c++ moduel, but there is no "pointer" in python, > so how can I pass the arg(file buffer) between python and c++ modules? > > > ______________________________________ > > =================================================================== Is there any reason you just can't give the C module the filename and let it handle the fopen? From gh at ghaering.de Fri Jul 11 20:23:32 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 02:23:32 +0200 Subject: The "intellectual property" misnomer In-Reply-To: References: Message-ID: <3F0F5504.5080700@ghaering.de> Ben Finney wrote: > On Fri, 11 Jul 2003 15:13:43 -0400, Guido van Rossum wrote: > >>The PSF holds the intellectual property rights for Python > > > Ugh. Please don't propagate this ridiculous, meaningless term. It's > used to refer to a wide range of greatly disparate legal concepts; to > use it as a single term implies that there's some unifying "intellectual > property" principle joining them together, which is a falsehood. > > If the PSF holds the copyright to Python, please say that. > > If the PSF holds patents which cover Python, please say that. > > If the PSF owns the trademark for Python, please say that. > > If the PSF has trade secrets in Python, please say that. > > But please *don't* muddy the water by saying the PSF holds "the > intellectual property rights" for Python. That says nothing useful -- > it doesn't help determine which of the above fields of law are > applicable -- and only promotes the idea that all these different fields > of law are part of a whole, which they are definitely not. > > It also encourages another falsehood: that of considering intellectual > objects as property. This is something which many people who use Python > would disagree with strongly. > > Well said. -- Gerhard From paulpaterson at users.sourceforge.net Fri Jul 25 12:10:09 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Fri, 25 Jul 2003 16:10:09 GMT Subject: How safe is modifying locals()? Message-ID: I am trying to find a way to mimic by-reference argument passing for immutables in Python. I need to do this because I am writing an automated VB to Python converter. Here's an example of the VB code: Sub Change(ByVal x, ByRef y) x = x+1 y = y+1 End Sub x = 0: y = 0 Change x, y ' Now x should be 0 and y should be 1 One approach that has been suggested is to use locals() and indirect references to the immutable via the resulting dictionary, def change(x, y, refs): x = x + 1 refs[y] = refs[y] + 1 x = 0; y = 0; change(x, 'y', locals()) The Python documentation gives a warning that modifying the contents of locals() may not affect local values. Despite the warning, the code seems to work as desired, at least on Python 2.2. Does anyone know how safe this approach is, particularly in a multithreaded environment? Will this work on Jython? Does anyone have any alternative strategies for trying to achieve the objective? A "Pythonic" approach such as, def change(x, y): x = x + 1 y = y + 1 return y x = 0; y = 0 y = change(x, y) Works in a single threaded environment but, because the value of 'y' changes at the wrong time, with multiple threads there is a possibility that two users of 'y' could dissagree on its value. Paul Paul Paterson (paulpaterson at users.sourceforge.net) vb2py :: A Visual Basic to Python Conversion Toolkit http://vb2py.sourceforge.net From intentionally at blank.co.uk Wed Jul 16 17:38:30 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 22:38:30 +0100 Subject: anything like C++ references? References: <1058377188.3f158de4a3a51@mcherm.com> Message-ID: <47gbhvg0i58nkkph3k6a7bpikaabgm4b47@4ax.com> On 16 Jul 2003 17:51:20 -0000, Moshe Zadka wrote: >On Wed, 16 Jul 2003, Michael Chermside wrote: > >> stuff[i] = newComplexObject(i++, "name", "fred") > >I'm not entirely sure that C code is not undefined. I think it >is, but it could be that I'm mistaken and that "=" is a "sequence point". >It's a variant on the old > >a[i]=i++ I think you're right. The old 'when does the postincrement happen' issue. I missed that on the first read - though admittedly not a real debugging-mode read - but it still shows that it doesn't stand out as obvious when you need to find the problem. But - though I'm not sure - I think it might not be an issue in C++ rather than C. With user defined objects and stuff, the postincrement is done immediately when the 'i++' is evaluated - a result of using a member function to implement it. The behaviour of integers and pointers may have been redefined to fit the same pattern. But don't quote me on it, and certainly don't depend on it - it's an obvious thing for many compilers to have an optimisation option for, perhaps buried in a badly defined strict-or-optimised option. It's going to bug me now, though. I tend to dislike expression side effects in part because these little mistakes are so easy. In this case... stuff[i] = newComplexObject(i, "name", "fred"); ++i; ... ...is no problem (or Adams 'len' solution, of course). From andy47 at halfcooked.com Thu Jul 3 05:31:05 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Thu, 03 Jul 2003 10:31:05 +0100 Subject: Remote db connections possible with DCOracle2? In-Reply-To: <16131.24584.242446.711276@montanaro.dyndns.org> References: <16131.19186.190625.679324@montanaro.dyndns.org> <200307021518.22410.dave@pythonapocrypha.com> <16131.24584.242446.711276@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Dave> Use this style of connection string (all one line if it wraps): > > Dave> user/password@(description=(address=(host=10.20.30.40)(protocol=tcp)(port=1521))(connect_data=(sid=dbsid))) > > Thanks. The example or two I saw indicated something like > > user/password at dbname > > where I presume "dbname" is looked up in tnsnames.ora. > > Skip > The 'correct' way to connect to an Oracle database is, as you say, through a service name that you have configured and which is stored in the local tnsnames.ora file. In later versions of Oracle (8.1 and above) it is strongly recommended that you configure your connectivity through the supplied tools (Net8 Assistant or Oracle Net Manager). Editing tnsnames.ora files by hand is somewhat frowned upon. Having said that the format and syntax hasn't changed (much) since the days of SQL*Net so if you know what you are doing it isn't too scary. Practically, if you can connect to a database from SQL*Plus then DCOracle2 won't have a problem either. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From bokr at oz.net Wed Jul 23 05:14:29 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Jul 2003 09:14:29 GMT Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: On Wed, 23 Jul 2003 08:06:17 +0000 (UTC), Duncan Booth wrote: >bokr at oz.net (Bengt Richter) wrote in news:bfjokm$kbc$0 at 216.39.172.122: > >>>'all_false(...)' is simply 'not any_true(...)' >>>'any_false(...)' is 'not all_true(...)' >>> >>>So you could get by with just two of these functions, in which case >>>'any_of', and 'all_of' might be suitable names. >>> >> I don't think they're equivalent if they do short-circuiting. >> > >any_true short circuits as soon as it finds one that is true. >all_false short circuits as soon as it find one that is true. > >all_true short circuits as soon as it finds on that is false. >any_false ditto. > >Why aren't they equivalent? > Oops, d'oh ... well, they're not spelled the same ;-) Regards, Bengt Richter From newsgroups at jhrothjr.com Wed Jul 30 15:52:59 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 30 Jul 2003 15:52:59 -0400 Subject: Upgrading python References: Message-ID: "Bengt Richter" wrote in message news:bg93pm$72v$0 at 216.39.172.122... > On 30 Jul 2003 06:43:22 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: > > >Stephen Boulet writes: > > > >> When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3? > > > >If you want to, you can have both 2.2 and 2.3 installed, side-by-side. > >If you want to replace 2.2, you should uninstall it first. > > > How do I know what will happen to file extension associations and the system path search > that takes unadorned python and finds some/path/to/python23.exe? > > And how does the old python22 find what it needs? Do I need to go through a .cmd file that > sets up its environment before running? How do I know everything it needs? > > IOW, how do you set up a clean way to run both 2.2.3 and 2.3 "side by side" but separately, > with default "python" going to 2.3? I am being lazy in not reading the install docs yet, > but does it cover the question fully? If so, the answer to this post can just be "yes" ;-) As with most things having to do with installation, the answer is a bit complicated. On Windows, Python keeps its information in separate keys by major release, so there's a different key for Python 2.2 and Python 2.3. That's compiled into the executable, so anything that's in the registry is kept nice and separate. So you can have two or more major releases side by side. You can't have two minor releases, though, because they use the same registry key. The keys aren't secret, so any outboard programs that need a specific version of Python can go right to it. Where the difficulty lies is that other things, such as the system path for finding executables and the file name associations don't have the same facility. So if I wanted to just be able to doubleclick on a .py or .pyc file and have it find the correct executable, I'm out of luck unless I do some arcane system programming. (That is, associate them with a program that figures out from the directories or the "magic number" which version of python is wanted, and then invokes it.) If all you want is for the default to be 2.3, then just make certain that the system path goes to the proper directory. All your file name associations will tag along as long as the command keys didn't include full paths. And I find that .cmd files are my friends. I use them to set the Pythonpath so I don't have to figure out a path that's going to work for everything, now and forever. And they work very well for drag and drop targets for those little utilities that operate on one file... John Roth > > Regards, > Bengt Richter From david at fielden.com.au Wed Jul 9 03:54:52 2003 From: david at fielden.com.au (DG) Date: Wed, 9 Jul 2003 17:54:52 +1000 Subject: Deleting specific characters from a string In-Reply-To: Message-ID: <007801c345ef$62137b10$9501a8c0@borg.fielden.com.au> >>> import string >>> str = 'You are ben at orange?enter&your&code' >>> print string.replace(string.replace(str, '@', ''), '&', '') You are benorange?enteryourcode >>> Rowdy > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Behrang Dadsetan > Sent: Wednesday, 9 July 2003 5:12 PM > To: python-list at python.org > Subject: Deleting specific characters from a string > > > Hi all, > > I would like deleting specific characters from a string. > As an example, I would like to delete all of the '@' '&' in > the string > 'You are ben at orange?enter&your&code' so that it becomes > 'benorange?enteryourcode'. > > So far I have been doing it like: > str = 'You are ben at orange?enter&your&code' > str = ''.join([ c for c in str if c not in ('@', '&')]) > > but that looks so ugly.. I am hoping to see nicer examples to acheive > the above.. > > Thanks. > Ben. > > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at v.loewis.de Thu Jul 17 18:33:38 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 18 Jul 2003 00:33:38 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: <3F172442.2040907@v.loewis.de> Alan Kennedy wrote: > For anybody who has MS Internet Explorer 5+, Netscape 6+, Mozilla 1+, > i.e. any browser that supports XML, simply save this to a disk file > and open it in your chosen browser. [...] > So, the challenge to the ASCII proponents is: put the greek word > "gignooskoo" on everybody's screen, originating from a usenet message, > in the original greek, where "oo" -> greek letter omega. [...] > I expect you won't find it as simple as the XML above, although I'm > also completely prepared to be proven wrong (Alan tries to cover his > a** in advance ;-). So what do you think about this message?: ???????? Look Ma, no markup. And not every character uses two bytes, either. And I can use Umlauts (???) and Arabic (???.????) if I want to. I don't know for whom this renders well, but I guess MSIE5+, NS6+ and Mozilla 1+ are good candidates - without the need for saving things into files. Regards, Martin From jcazier at decode.is Wed Jul 23 07:33:55 2003 From: jcazier at decode.is (jean-Baptiste Cazier) Date: 23 Jul 2003 04:33:55 -0700 Subject: Transparency with PIL and paste ? Message-ID: S?l ! I am trying to rotate some text and paste it into a larger PIL Image. ( cannot use PyFT for some reasons) However I have a problem of transparency and my new images in a box shape are overlapping eventhough the test itself does not overlap. I would like to avoid that problem using the transparency of the image but without much success so far Below is my code for Python2 Any help would be appreciated Thanks Jean-Baptiste #!/usr/bin/python import sys,math sys.path.append("/home/stat/Pygtk/PIL/") sys.path.append("/home/stat/Pygtk") import Image,ImageDraw,ImageFont def rotat(text,angle=70): """ Rotation routine returns the image and its size """ color=(220,120,010) pangle=float(angle)*math.pi/180.0 [x,y]=my_font.getsize(text) xy=x+y timage=Image.new("RGBA", (2*xy,2*xy),(255,255,255,0)) draw=ImageDraw.Draw(timage) draw.text((xy, xy-y), text,font=my_font,fill=color) timage2=timage.rotate(angle) X0=int(xy-math.sin(pangle)*y) Y0=int(xy-x*math.sin(pangle)-y*math.cos(pangle)) X1=int(xy+math.cos(pangle)*x) Y1=int(xy) t3=timage2.crop((X0,Y0,X1,Y1)) return t3,X1-X0,Y1-Y0 my_font=ImageFont.load('/home/stat/Pygtk/PIL/Fonts/helvR12-ISO8859-1.pil') #Create 2 new images im,x_im,y_im=rotat("Mest the Test with M",45) im2,x_im2,y_im2=rotat("new Test with T",20) # Create an empy image empty_image=Image.new("RGB", (500,300) ,(155,255,255)) empty_draw=ImageDraw.Draw(empty_image) xs=0 xs2=xs+30 ys=0 # Paste new images empty_image.paste(im,(xs,ys,xs+x_im,ys+y_im)) empty_image.paste(im2,(xs2,ys,xs2+x_im2,ys+y_im2)) empty_image.show() From http Wed Jul 9 18:24:40 2003 From: http (Paul Rubin) Date: 09 Jul 2003 15:24:40 -0700 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: <7xhe5vmj87.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > The Java Pet Store was suggested, but it was pointed out that it's a very > large application, requiring too much effort for an author to do in their > spare time. Heh, the point of doing it in Python is it should take much less time than doing it in Java :). > * Should be implementable in a few evenings Good > * Should exercise a reasonable set of features. > * HTML generation (duh!) > * Accepting a form Accepting a very long form (i.e. megabytes of POST data) > * Returning non-HTML files (generating a GIF, say) > * Sessions > * Uploading a file > * RDBMS access? (That's more a function of the DB-API module you're > using, but a framework might provide support for pooling > connections or something similar.) Yes, this should be included, lack of a standard DB API module is a serious Python deficiency and any DB-using app needs to work around the deficiency somehow. > * Other suggestions? > > Possibilities: > * A Wiki? > * A multiple-user weblog? > * A Slashdot-like discussion board? > * A simple content manager -- upload files, set permissions on them, > control access to them, and download them again. > * A simple browse-a-catalog-and-buy-things store? > * Other suggestions? Webmail client From bhahn at spam-spam.g0-away.com Tue Jul 15 16:15:28 2003 From: bhahn at spam-spam.g0-away.com (Brendan Hahn) Date: Tue, 15 Jul 2003 20:15:28 GMT Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> Message-ID: duncan at rcp.co.uk wrote: >"Colin S. Miller" wrote: >To "take someone in" means to trick or deceive them. "take in" can also mean to observe. -- brendan DOT hahn AT hp DOT com From hans at deragon.biz Sat Jul 19 22:45:52 2003 From: hans at deragon.biz (Hans Deragon) Date: Sat, 19 Jul 2003 22:45:52 -0400 Subject: How to detect user activity - for a screensaver for example. Message-ID: Greetings. If I want to write a screensaver for Linux using Python, how can I detect that the user has not touched the keyboard or mouse for the last 5 mins? Sincerely, Hans Deragon -- Deragon Informatique inc. Open source: http://www.deragon.biz http://swtmvcwrapper.sourceforge.net mailto://hans at deragon.biz http://autopoweroff.sourceforge.net From alanmk at hotmail.com Thu Jul 17 06:28:29 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 11:28:29 +0100 Subject: Jython classpath question References: Message-ID: <3F167A4D.CCF59244@hotmail.com> Tennessee James Leeuwenburg wrote: > Is it > correct that Jython can only access Java classes which are inside JAR > archives in the JYTHON_HOME directory? No. Here is an example of accessing java classes in a jar that is at some non-jython location. #-- Commands should be same for all platforms, 'cept maybe 'copy'->'cp' C:\>cd temp C:\temp>mkdir classpathtest C:\temp>cd classpathtest C:\temp\classpathtest>copy C:\jars\oro206\oro206.jar . 1 file(s) copied. C:\temp\classpathtest>set CLASSPATH=./oro206.jar; C:\temp\classpathtest>jython *sys-package-mgr*: processing new jar, 'C:\temp\classpathtest\oro206.jar' Jython 2.1 on java1.4.2 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import org.apache.oro as oro >>> dir (oro) ['__name__', 'io', 'text', 'util'] >>> And here is an example of compiling a java class in the local directory, and using it from within jython. #--- file SayHi.java starts here public class SayHi { public SayHi() { System.out.println("Hello World!"); } } #--- file SayHi.java ends here Save the above into SayHi.java, then compile it C:\temp\classpathtest>javac SayHi.java C:\temp\classpathtest>echo %CLASSPATH% ./oro206.jar; C:\temp\classpathtest>jython Jython 2.1 on java1.4.2 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import SayHi >>> newobj = SayHi() Hello World! >>> > I have a working directory where all my code lives, and because my app is > under rapid development, I would prefer to avoid creating a JAR file > every time I want to do some Python scripting? Examples above should show you the way. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From tomas at fancy.org Mon Jul 7 21:59:06 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 07 Jul 2003 18:59:06 -0700 Subject: looking for UDP package, network programming guidance References: Message-ID: Tom Plunket wrote: > ...now the stumbling block comes up that Python doesn't seem to > have any UDP handling built into its distribution. Thanks a lot for the pointers, gang. Hopefully I can get something up and running in the next couple of days (or rather, the next time I have a couple of uninterrupted hours for this task), so these pointers will send me in the right direction. I definitely like the idea of a lower level solution, so this is nice. For whatever reason, my web search turned up info related only to win32all, so I assumed... :) Anyway, off to get this going. :) -tom! From paddy3118 at netscape.netNOTthisBIT Sun Jul 6 09:12:17 2003 From: paddy3118 at netscape.netNOTthisBIT (Donald 'Paddy' McCarthy) Date: Sun, 06 Jul 2003 14:12:17 +0100 Subject: Collective memory In-Reply-To: References: Message-ID: <3F082031.3010503@netscape.netNOTthisBIT> Charles Shannon Hendrix wrote: > The problem with Python is that its use of indentation is not the same > as COBOL or FORTRAN. Apples and Oranges. > > Python uses it for actually determining the logic in your program, which > IMHO is dangerous. > > if > > > > > Is part of the if statement, or did someone with different > tab settings from the author make a mistake and align it accidentally? Well, no matter WHAT the language, I find tabs are evil little things that introduce special cases and the need for code to handle them. That said though, I find python block structure (sans tabs), just fine thanks. It would be nice if tabs as indentation for Python was deprecated but failing that, If you don't use tabs, its wonderful. If you do try python, try not to indent with tabs, and please try it, I did and look at me now :-) Cheers, Pad. From writeson at earthlink.net Tue Jul 8 13:25:38 2003 From: writeson at earthlink.net (Doug Farrell) Date: 8 Jul 2003 10:25:38 -0700 Subject: re module substitution confusion References: <88bc63c6.0307071326.3eb60848@posting.google.com> Message-ID: <88bc63c6.0307080925.4352ca63@posting.google.com> Hi all, I got a direct email from someone (who I can't remember right now) who suggested that I wasn't very clear about what I was trying to do and what was wrong. In an attempt to clarify I'm adding this post. :) I'm trying to create a little Python CGI program that will read in a HTML template file that has Python code embedded in it between ... tags. So I'd like to use the re module to find the following pattern: pattern = re.compile("()(.*?)()", re.DOTALL) Doing a search with this pattern like this: match = re.search(pattern, text) where text equals the HTML template file in string form, will find all the code segments. I then pull out the code segment and pass it to exec() to execute it. I can capture the output of the exec() call by redirecting sys.stdout to a StringIO object. The problem is that this; I can match the ... segments no problem. But I only want to replace each one in turn with the results of the exec() call. If I do this: text = re.sub(pattern, ".. exec() output..", text) it replaces all the code segments, not just the one that was matched. I need to substitute in the output of the exec() (which is a string when I'm done) into the one place it came from. Hope this clears up any confusion. I didn't include the whole program in my first post as it's kind of long. I thought the sections I included above were enough information to follow what I'm trying to do, at least I hope so. Thanks again in advance for your help, Doug From pushpin at media.mit.edu Wed Jul 30 13:41:37 2003 From: pushpin at media.mit.edu (Josh) Date: 30 Jul 2003 10:41:37 -0700 Subject: tkinter menu bars, assigning children to parents, and grid/pack managers Message-ID: <8bf5dfd1.0307300941.f068138@posting.google.com> Caution, newbie approaching... I'm trying to come up with a very simple Tkinter test application that consists of a window with a drop-down menu bar at the top and a grid of colored rectangles filling the remainder of the window. Mind you, this is a contrived test application to help me understand Tkinter and Python, not an actual application yet. I've trivially subclassed Tkinter.Canvas into ColorCanvas, added a bunch of ColorCanvases to a trivial subclass of Tkinter.Frame called MultiColor, and then tried adding a MultiColor and a subclass of Tkinter.Frame called MultiColorMenu to a root window. The problem is that the menu bar is overlaid on top of the MultiColor gridded frame, instead of above it. I think the problem is that I don't know how to assign a widget as a child to a parent widget. The code I'm talking about is copied below. Any ideas? Thanks, josh ## Begin code. import Tkinter class ColorCanvas(Tkinter.Canvas): "This class is simply a colored rectangle." def __init__(self, background, numXPixels=300, numYPixels=100, master=None): ## Initialize variables. if master is None: master = self self.numXPixels = numXPixels self.numYPixels = numYPixels Tkinter.Canvas.__init__(master, background=background, width=self.numXPixels, height=self.numYPixels, borderwidth=0) class MultiColor(Tkinter.Frame): "This class is a grid of colored rectangles." def __init__(self, numOfColors, master=None): Tkinter.Frame.__init__(self, master) self.colors = [] for i in range(numOfColors): self.colors.append(ColorCanvas(background='purple')) self.colors[i].grid(row=i/3, column=i%3) class MultiColorMenu(Tkinter.Frame): "This class is a bar of drop-down menus for manipulating a grid of colored rectangles." def __init__(self, master=None): Tkinter.Frame.__init__(self, master) self.tk_menuBar(self.help_menu()) def help_menu(self): help_btn = Tkinter.Menubutton(self, text='Help', underline=0) help_btn.pack(side=Tkinter.LEFT, padx="2m") help_btn.menu = Tkinter.Menu(help_btn) help_btn.menu.add_command(label="How To", underline=0, command=self.helpFoo) help_btn.menu.add_command(label="About", underline=0, command=self.helpFoo) help_btn['menu'] = help_btn.menu return help_btn def helpFoo(self): print 'Heelllppppp!!!' def main(): root = Tkinter.Tk() root.title('Lifton\'s Fabulous Color Canvases') mc = MultiColor(numOfColors=22, master=root) #mc.pack(fill=Tkinter.BOTH, side=Tkinter.BOTTOM) mc.grid(row=1, column=0) mc_menus = MultiColorMenu(master=root) #mc_menus.pack(fill=Tkinter.X, side=Tkinter.TOP) mc_menus.grid(row=0, column=1) root.mainloop() main() ## End code. From iamshady at rediffmail.com Thu Jul 3 05:27:52 2003 From: iamshady at rediffmail.com (Jim Shady) Date: 3 Jul 2003 02:27:52 -0700 Subject: wxPython mouse controls Message-ID: <9afd3f36.0307030127.2abc37a1@posting.google.com> Hi, I am looking at the feasibility in using wxPython on a project our company needs. I intend to show a bar graph in a frame. I can either generate an image and show it in a panel, or maybe draw it on a canvas (?). Either case, the vital feature that we need is the ability to choose parts of the bar by clicking and dragging on it. The selected portion will then be zoomed into again by the software, generating a new bar graph. Is this possible using wxPython? Thanks, Jim From tjreedy at udel.edu Wed Jul 9 16:10:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jul 2003 16:10:23 -0400 Subject: .join() question References: Message-ID: "drs" wrote in message news:eo_Oa.14415$BM.4645038 at newssrv26.news.prodigy.com... > why does > > >>> ''.join(lst) > > not automatically do > > >>> ''.join([str(i) for i in lst]) > > ? That is, is there ever a time when one does not want .join to make > everything into a string? This seems like reasonable default behavior, but > maybe I'm missing something? If the members of lst are already str strings, this would be a waste of time. If they are unicode strings, this would be the wrong thing to do. Auto conversions are not Python's style. Terry J. Reedy From aahz at pythoncraft.com Wed Jul 2 00:04:02 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Jul 2003 00:04:02 -0400 Subject: __del__ not working with cyclic reference? References: Message-ID: In article , Jane Austine wrote: > >I have some code using singleton pattern. The singleton instance >is shared as a class variable. The problem is that the singleton >instance is not cleared automatically. > >Following is a simplified version that shows the problem: > >-------- >#foobar.py >class FooBar: > def __del__(self): > print "FooBar removed" > >FooBar.foobar=FooBar() >-------- > >Why is this so? Due to the cyclic reference? Isn't python's gc >supposed to treat it? What singleton idiom is recommended >otherwise? There are two issues that you'll run into with this: gc doesn't work on classes that define __del__(), and prior to Python 2.3, gc doesn't run on exit. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 14 19:49:58 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 14 Jul 2003 23:49:58 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <3F132103.4D18759F@engcorp.com> Message-ID: Tim Gerla enlightened us with: > Anyway, does that mean that the Qt parser has a bug? If it wants to be HTML-compliant: yes. If it wants to use HTML-like codes for markup: no Al least, that's the way I see it. I dont't know Trolltech's intentions. I'll check out the docs. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From trash at kjn-law.de Tue Jul 8 04:40:34 2003 From: trash at kjn-law.de (Theodor Rash) Date: Tue, 08 Jul 2003 10:40:34 +0200 Subject: Building Python - how to set include and lib paths? References: <2003Jul4.102150@ukwit01> Message-ID: <2lcqt-p45.ln1@newsgate.kjn.lan> Lack Mr G M wrote: > ... My problem occurs when I am *building* python > itself. There seem to be no way that I can tell it where to look for > header files and libraries for other packages/utilities (eg: SSL) that I > have previously installed or how to add these to compilation and linking > options.. It hard-wires /usr/local/{include,lib} for these. > That's right. I had to patch setup.py to make it find Tcl/Tk which resides under /opt in my system. Theo From danb_83 at yahoo.com Fri Jul 4 20:54:18 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Jul 2003 17:54:18 -0700 Subject: strings problem References: Message-ID: "Jimmy verma" wrote in message news:... > Hello *.* > > Can you please tell me how can i have the output in no's, instead of string > from this program: > ... > print t > > The output is > > Token: 50 > Token: 800 > \275\371\264 > > Instead of this i want the output should be in no's like this: > bdF9B4 >>> print repr(t) '\xbd\xf9\xb4' >>> print ''.join(['%02X' % ord(c) for c in t]) BDF9B4 From usenet_spam at janc.invalid Tue Jul 15 16:42:40 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 15 Jul 2003 20:42:40 GMT Subject: anything like C++ references? References: <3f67hvgi36s7rmtn59rajj2gpir8hhfiph@4ax.com> <3F13ADDD.57BF2969@alcyone.com> Message-ID: aahz at pythoncraft.com (Aahz) schreef: > What's the value of a file object? I think in a > very real sense, a file object doesn't have a "value". You could try > arguing that the file contents are the value, but that value is not > contained within the object -- the object is a proxy. IANACS[*] but I would think the combination of all the file's properties is the value of a file object: the file contents, the filename, any associated metadata, the seek pointer, the ability to read from and write to the contents, etc. The fact that parts of the object, e.g. the contents, are stored on "external memory" instead of in "internal memory" is an irrelevant implementation detail IMHO... I think of an object's "value" as the whole set of "properties" (the real world term, not the often limited programming term) that makes it have some "worth". [*] I Am Not A Computer Scientist ;) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From manish.j at gmx.net Fri Jul 25 16:43:33 2003 From: manish.j at gmx.net (Manish Jethani) Date: Sat, 26 Jul 2003 02:13:33 +0530 Subject: decimal to binary In-Reply-To: References: <200307250653.18754.gherron@islandtraining.com> Message-ID: manuel wrote: > This is the first time that I try to handle > binary file. > > I read a tga file, and store all bytes in a list: > > --------------------------------------- > #LETTURA DEL FILE TGA > listByte = [] > try: > f = open(filename,'rb') > except IOError,(errno,strerror): > msgstring = "I/O error(%s): %s" % (errno, strerror); Draw() > return > fileReaded = f.read(); > msgstring = "Parsing tga..."; Draw() > for i in range(len(fileReaded)): > listByte.append(ord(fileReaded[i])) > f.close() > ------------------------------------------ > > I use ord() to convert the value of byte in > integer, if I don't make this, I've the ASCII > symbol... You CAN store the byte as it is, in a string. So, for example, you can store 'a(*@' instead of [97, 40, 42, 64] But it depends on your requirements. > But, for listByte[17], I must read the sequence > of 0 and 1, because I must know the 4? and 5? bit: > this bits specify the image origin. This function returns the binary representation as a string: def foo(i): b = '' while i > 0: j = i & 1 b = str(j) + b i >>= 1 return b bin = foo(listByte[17]) bin[-4] # 4th (3rd) bit bin[-5] # 5th (4th) bit You have to check for IndexError, or check the length of the string. BUT! But you don't need to do this in order to get the value of the 4th (3rd) bit. Just do this: if listByte[17] & (1 << 3): else: For the 5th (4th) bit, change '<< 3' to '<< 4'; and so on. -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From ulope at gmx.de Sun Jul 20 18:54:34 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 21 Jul 2003 00:54:34 +0200 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: "Alan Dechert" schrieb im Newsbeitrag news:P9DSa.111436$Io.9552373 at newsread2.prod.itd.earthlink.net... Sorry but why on earth you dont just print that on paper and let people make their crosses where they want? From runeb at [remove].eyeone.com Thu Jul 31 05:49:38 2003 From: runeb at [remove].eyeone.com (Rune Braathen) Date: Thu, 31 Jul 2003 11:49:38 +0200 Subject: SGI + SUN = OpenGL for Jython In-Reply-To: <3a838998.0307301803.4e247823@posting.google.com> References: <3a838998.0307301803.4e247823@posting.google.com> Message-ID: Buckshot wrote: [ ... ] > Sweet! Now we'll be able to use OpenGL with Jython! It's been possible to use the various other OpenGL-bindings for java through jython for years. But it is nevertheless a good thing that SUN finally decided on making a more 'official' binding. Anyway, I'm sure it won't hold a candle to PyOpenGL. -- runeb From evan at 4-am.com Thu Jul 10 12:13:47 2003 From: evan at 4-am.com (Evan Simpson) Date: Thu, 10 Jul 2003 11:13:47 -0500 Subject: Business model for Open Source - advice wanted In-Reply-To: <246a4e07.0307100613.fc2fc50@posting.google.com> References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <3F0D90BB.7080000@4-am.com> Frank Millman wrote: > I am busy developing an accounting package, using Python and wxPython, > together with PostgreSQL on a Unix platform or SQL Server on a Windows > platform. I am a qualified accountant and have been developing > accounting software, mostly customised, for over 20 years. I know very little about accounting, or software to support it, but this paragraph seems to imply that there is a significant market for customizations to such software. Is this correct? If so, you may want to consider the business model that made Zope Corp. a success. > The essence of a business model must be that the source code may be > free, but you have to pay for support. I believe that accounting > systems more than most systems need support, and that a sensible > company looking for accounting software would not consider anything > that was not supported. While Zope Corp. sells support, they make most of their money by selling their expertise as Zope custom solution providers. This *only* works because Zope is Free -- instead of being the sole vendor pushing a proprietary solution, they are merely the most prominent and knowledgable developers for a widely-used platform. So, if you can create an accounting package that is so good that everyone wants to use it, yet allowing substantial demand for customization, you can promote yourself as the best provider of such services, as well as support. "I wrote it, so I know it inside and out. I can provide your business with a totally customized accounting solution, plus support, for less than you would pay in licensing fees for a boxed product." Cheers, Evan @ 4-am From tim.one at comcast.net Tue Jul 22 14:17:28 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 22 Jul 2003 14:17:28 -0400 Subject: python startup on XP very slow In-Reply-To: Message-ID: [christof hoeke] > for some days now i have problems with python taking a lot of time to > start up or run programs. What did you change on your system some days ago? That is, things were fine, at some point they got worse, and what changed between those two times? > today i installed the python 2.3rc1 but still the same problem. That's just more evidence that it's got nothing in particular to do with Python. > e.g. starting pythonwin 1.53 on winXP (athlon 1200 with 512MB) which > normally took only a few seconds now takes at least 15-20 seconds. > > has anybody had a similar problem or knows where the delay comes from? I don't, and don't know. Common culprits for things "like this" include updates to virus scanners and firewall software -- anything that sticks its nose into other processes' business. So you can try killing other processes, one at a time, and see how that affects Python startup time. From aahz at pythoncraft.com Sun Jul 20 09:39:51 2003 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2003 09:39:51 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: In article , Mike C. Fletcher wrote: > > * finally, stores the value > o tries to do what would have been done if there were no > descriptor (with the new, coerced value) > o does *not* create new names in the object's namespace (all > names are documented w/ descriptors, there's not a lot of > '_' prefixed names cluttering the namespace) > o does *not* require a new dictionary/storage-object attribute > for the object (the descriptor works like any other > descriptor, a *stand-alone* object that replaces a regular > attribute) But this is a recipe for name clashes. If you follow the first bullet, it's a normal attribute, but everything else says you want a property. Properties are themselves objects that are attached to names in an object. You can't have the same name bound to two different objects. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From tgerla at outsourcefinancial.com Mon Jul 14 18:09:38 2003 From: tgerla at outsourcefinancial.com (Tim Gerla) Date: 14 Jul 2003 15:09:38 -0700 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser In-Reply-To: <3F132103.4D18759F@engcorp.com> References: <3F132103.4D18759F@engcorp.com> Message-ID: <1058220577.5035.4.camel@redwall.ofsloans.com> On Mon, 2003-07-14 at 14:30, Peter Hansen wrote: > Tim Gerla wrote: > > > > Very fun stuff. Someday I hope to have a Zaurus or similar device to > > toy with. Anyway, to actually be on topic, "proper" HTML (XHTML 1.0, > > and maybe HTML 4.0? I don't recall...) requires double-quotes to be > > used. Single quotes are illegal. > > Are you certain about that? It seems very unlikely that it would > outlaw use of single quotes when it is supposed to be XML-compatible, > and XML explicitly allows either single or double quotes around attributes. You're right--I was under the wrong impression about single & double quotes. For some reason I recall reading somewhere (can't trust everything you read online) that XML only allowed double quotes, and I never bothered to verify it. Anyway, does that mean that the Qt parser has a bug? -Tim From manish.j at gmx.net Wed Jul 2 19:15:19 2003 From: manish.j at gmx.net (Manish Jethani) Date: Thu, 03 Jul 2003 04:45:19 +0530 Subject: 'For' loop symmetry with list comprehensions. In-Reply-To: <840592e1.0307021036.508d7d7d@posting.google.com> References: <840592e1.0307021036.508d7d7d@posting.google.com> Message-ID: <9QJMa.12$eD3.406@news.oracle.com> Hannu Kankaanp?? wrote: > One can currently say this with list comprehensions: > > [x.lower() for x in words if x.startswith('foo')] > > Wouldn't it be better if the normal 'for' syntax was symmetrical > with the notation used in list comprehensions? To be more specific, > it lacks the 'if' part. I.e. this should be possible: > > for x in words if x.startswith('foo'): > print x To some extent, yes: for x in words: if x.startswith('foo'): print x You saved one level of indent. -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From tim_one at email.msn.com Wed Jul 23 00:24:52 2003 From: tim_one at email.msn.com (Tim Peters) Date: Wed, 23 Jul 2003 00:24:52 -0400 Subject: Python and VS.Net In-Reply-To: Message-ID: [Ravi] > Has anyone tried building Python with VC++.NET? Does it work or fail > horribly like I think it will. Yes, several people have built it that way, and it works fine. You can get into obscure kinds of trouble if you try to mix code compiled with VC6 and VC7, though, because the C runtime systems are distinct (so, e.g., malloc()ing memory in one runtime and free()ing it in another, or passing FILE* thingies across them, can lead to subtle-- or instantly catastrophic --problems). Note that all current Windows installers from PythonLabs install code compiled with VC6, and the same will be true for 2.3 final (due out next week). It also seems that 3rd-party extension modules compiled with VC7 are still hard to come by. > My boss seems to think it is good to have programs that are in managed > code because it is more 'portable'. Not that there's another complete > .NET runtime besides Microsoft's but he does not understand that. If you're younger than him, you can reasonably hope to outlive him . alas-it's-not-a-strategy-that-works-your-whole-career-ly y'rs - tim From whatsupg21 at hotmail.com Thu Jul 10 13:38:48 2003 From: whatsupg21 at hotmail.com (Michael) Date: 10 Jul 2003 10:38:48 -0700 Subject: Parsing Message-ID: I have been assigned a project to parse a webpage for data using Python. I have finished only basic tutorials. Any suggestions as to where I should go from here? Thanks in advance. From sybrenUSE at YOURthirdtower.imagination.com Wed Jul 16 11:14:27 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 16 Jul 2003 15:14:27 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: Message-ID: Greg Fortune enlightened us with: > Are you intended on releasing the source for this? If so, dump > something up there so we can play ;o) Yes, I am going to release the source for this ;-) I'll post it on http://zaurus.thirdtower.com/ when I'm a bit further in the building process. I'll let the group know when I do that! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From jjl at pobox.com Sun Jul 27 20:23:18 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:23:18 +0100 Subject: looping through a file References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> <3f21903c$0$27898$626a54ce@news.free.fr> <87llukrdow.fsf@pobox.com> Message-ID: <87u197a495.fsf@pobox.com> bokr at oz.net (Bengt Richter) writes: > On 27 Jul 2003 01:55:11 +0100, jjl at pobox.com (John J. Lee) wrote: [...] > >I recall that in an old Python you could get into an awful mess (as I > >did) with this by having several 'for line in file' blocks in a row: > > > >for line in f: > > if not line.startswith("magic"): continue # skip header > > > >for line in f: > > ...process data... [my example should have been: for line in f: if line.startswith("magic"): break # skip header for line in f: ...process data... ] > What mess was that? (unless you meant to re-open the file to read > from the beginning) That example creates (used to, anyway) two iterators -- one for each 'for line in f'. The first reads chunks (not just one line at a time) and caches the read data. The second one knows nothing about that and innocently starts reading from the seek position that the first happened to stop at -- ie., at some random point further on than the point where you thought you'd finished up at the break in the first loop. http://www.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3C6D73DE.3090201%40wi.mit.edu&rnum=3 > >I gathered from a recent thread that this has changed -- the file is > >its own iterator now. Was the old behaviour ever released in 2.2, or > >was it just part of a 2.3 beta? > > > Curious what was changed ... I'm not certain it has changed -- haven't tested. John From imbosol at aerojockey.com Thu Jul 31 03:54:59 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 31 Jul 2003 07:54:59 GMT Subject: Exceptions as New Style Classes References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: Steven Taschuk wrote: > Quoth Carl Banks: >> Steven Taschuk wrote: >> > At the moment the dominant idea for solving these problems is to >> > make inheritance from Exception mandatory for exception types; see > [...] >> Why not give exceptions their own metaclass? So if type(x) is >> ExceptionMetaclass, it's a class. If type(type(x)) is >> ExceptionMetaclass, it's an instance. Otherwise, it's illegal to >> raise it. > > That seems workable. (I'd prefer, though, to test > isinstance(type(x), ExceptionMetaclass) > and likewise for the second case.) > > I'm not sure what it gains us, though, over the idea of mandatory > inheritance from Exception. Am I missing something? Probably not much, unless you think you want to raise exceptions that aren't subclasses of Exception. -- CARL BANKS From paddy3118 at netscape.netNOTthisBIT Mon Jul 14 20:09:25 2003 From: paddy3118 at netscape.netNOTthisBIT (Donald 'Paddy' McCarthy) Date: Tue, 15 Jul 2003 01:09:25 +0100 Subject: anything like C++ references? In-Reply-To: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <0BHQa.982$mS2.152@news-binary.blueyonder.co.uk> Tom Plunket wrote: > I want to do something along the lines of the following C++ code: > > void change(int& i) > { > i++; > } > > > Is there any way to do references like this in Python? It'd be > like this, though clearly this doesn't change the thing I want it > to change: > > def change(val): > val += 1 > > v = 0 > change(v) > > # v == 1 now. > > thanks. > > I can see that maybe if I passed in a list of one integer I could > change that, but that seems circuitous to me. > > > -tom! Hi Tom, Welcome to Python. I guess the first thing to remember is that Python is not any other language. It has its own ways of doing things, and its own nomenclature, that while in some cases may use the same term or phrase as another language, or symbols used in Mathematics - It puts a Python meaning on them. Python does things its own way. I found that I got much more productive when I learnt enough to let go of the C idioms in my case that I had initially. I guess I was helped in that I was a good programmer in C, didn't like C++ or Java and was looking for another language that would be more productive. I could do the C pointer wizardry but in no way did I think that it was ideal. It sometimes helps to have an understanding of what Python is doing 'under the hood', but I don't solve my Python problems by translating solutions expressed in C pointer terms. Other mails have gone into the minutia of trying to answer the question. I would just like to add that if you look up scope rules or the global keyword you will find ways of accessing variables defined outside of a function definition. From dave at pythonapocrypha.com Wed Jul 2 18:25:13 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 2 Jul 2003 15:25:13 -0700 Subject: Remote db connections possible with DCOracle2? In-Reply-To: <200307021518.22410.dave@pythonapocrypha.com> References: <16131.19186.190625.679324@montanaro.dyndns.org> <200307021518.22410.dave@pythonapocrypha.com> Message-ID: <200307021525.13908.dave@pythonapocrypha.com> On Wednesday 02 July 2003 03:18 pm, Dave Brueck wrote: > On Wednesday 02 July 2003 02:13 pm, Skip Montanaro wrote: > > Connections to remote Oracle databases doesn't seem possible with > > DCOracle2. I have no problem making remote connections using Perl's > > DBI::Oracle package, so I know it's possible in theory. Is this > > capability available in DCOracle2 but just not documented perhaps? > > Actually, I've never used a _local_ database with DCOracle2, so it's very > possible but, IMO, very underdocumented too. :) > > Use this style of connection string (all one line if it wraps): > > user/password@(description=(address=(host=10.20.30.40)(protocol=tcp)(port=1 >521))(connect_data=(sid=dbsid))) > > (changing the values of user, password, 10.20.30.40, and dbsid of course). Replying to myself here because I forgot to mention that the benefit of the hideous connection string is that it requires no modification to your TNSNAMES.ORA file (I believe the normal way of connecting to a remote DB is to specify a certain name that you've configured in TNSNAMES.ORA). The above is particularly important if you don't have a true Oracle client installation (IIRC last year I posted a list of just the files you need to make DCOracle2 work without doing a full Oracle client install - on Linux, at least for me, the Oracle client install was massive, scary, and flaky). -Dave From tjreedy at udel.edu Sun Jul 13 15:07:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2003 15:07:23 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: "David McNab" wrote in message news:pan.2003.07.13.10.58.11.376531 at 127.0.0.1... > In Python, basic types like strings and numbers are a weird exception to > the 'everything is an object' rule. In Java perhaps, but NOT in Python. This is WRONG, WRONG, WRONG. Please do not muddy the waters like this. In Python, most builtin types are immutable. The two mutable builtin types are lists and dicts. Instances of user-defined classes are also mutable by default. >When you pass any other object in a function, >But when you pass a string or numeric object, [incorrect statement clipped] In Python, everything is 'passed' to functions the same way: first, the argument expressions are evaluated one at a time, left to right. In the typical case (number of argument expressions == number of positional parameters), the resulting objects are then bound to the corresponding parameter names, left to right, in the local namespace of the function. (Or, if you prefer, the names are bound ...) The type of the argument objects is not looked at. How a particular interpreter performs name binding is its own business, as long as the specified semantics are implemented. What CPython does may or may not be the same as Jython or any other actual or potential computer implementation. What any computer does is probably significantly different from what human interpreters do. Terry J. Reedy From tzot at sil-tec.gr Tue Jul 22 13:19:30 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 20:19:30 +0300 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3f15b04b$0$49114$e4fe514c@news.xs4all.nl> Message-ID: On Wed, 16 Jul 2003 22:06:36 +0200, rumours say that Irmen de Jong might have written: >You should really add a comma at the right place, otherwise even Dutch >people themselves tend to get confused rather quickly too: > >"Als achter vliegen vliegen vliegen, vliegen vliegen vliegen achterna." ...and the meaning is? -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From tbonemp3 at yahoo.com Mon Jul 21 18:23:25 2003 From: tbonemp3 at yahoo.com (Ted Weatherly) Date: 21 Jul 2003 15:23:25 -0700 Subject: Automatically filling in answers to interactive shell command questions Message-ID: Is it possible to use python to automatically fill in the answers to interactive shell command questions? For example, I am using a shell command addperson that behaves as follows: > addperson First Name: Ted Birthday: 12/08/1977 Height: 6'0" Location: San Francisco, CA > I am prompted for "First Name: " and I enter "Ted". I am prompted for "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 people or more...it gets tiresome. Assuming I can't change the addperson command to read data from a file, is there any way to use python to fill in the data for the expected questions? Perhaps a different language would be better? -Ted From maxm at mxm.dk Sun Jul 13 13:51:35 2003 From: maxm at mxm.dk (Max M) Date: Sun, 13 Jul 2003 19:51:35 +0200 Subject: The definition of an object in Python In-Reply-To: <94af9c5a.0307130919.1ab63400@posting.google.com> References: <94af9c5a.0307130919.1ab63400@posting.google.com> Message-ID: <3F119C27.3050806@mxm.dk> Avi Kak wrote: > But when I do the following > > mystring = 'hello' > > print mystring.id() > > print mystring.type() > > Python complains that mystring does not possess the attributes > id and type. mystring = 'hello' print id(mystring) print type(mystring) >>> 8985424 >>> id and type are built in functions. Not methods on objects. Wich imho is a good thing. This means that you can have methods on objects called id and type, without loosing the ablity to use these functions. regards Max N From shalehperry at comcast.net Mon Jul 14 21:23:10 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Mon, 14 Jul 2003 18:23:10 -0700 Subject: www.python.org hacked? In-Reply-To: References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> Message-ID: <200307141823.10360.shalehperry@comcast.net> On Monday 14 July 2003 13:22, Aahz wrote: > In article <3F12FA18.B04B400E at engcorp.com>, > > Peter Hansen wrote: > >Have we been hacked, or is this human error during maintenance? > > Yes to both. :-( We were actually hacked a while ago, then failed to > do a complete cleanup. When we got the disk full problem, I attempted > to update the main page so people would know what was going on; I > thought that vi was capable of managing the re-write inplace. I was > wrong. We're back on the air, with special thanks to Thomas Wouters for > interrupting his post-OSCON snooze. both vim and nvi have options you can pass them so that they do not make copies of the file. nvi is -F and I forget what the vim option is. From jane.doe at acme.com Fri Jul 25 13:59:12 2003 From: jane.doe at acme.com (Jane Doe) Date: Fri, 25 Jul 2003 19:59:12 +0200 Subject: [newbie] MySQL : How to check if no row returned? References: <5ua0ivcl3loh45cq6pnoimsoa86nt0q4db@4ax.com> Message-ID: On Thu, 24 Jul 2003 21:05:13 GMT, "Steve Holden" wrote: >Alternatively, you can observer that the fetchall() method will return an >empty list, and use > > if not rows: > # empty set returned Thx to you both. That did it :-) JD. From mwh at python.net Tue Jul 29 14:15:25 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jul 2003 18:15:25 GMT Subject: Debugging Python ? References: <3c91a864.0307282013.2acb2d1f@posting.google.com> <84fc4588.0307290453.52671e11@posting.google.com> Message-ID: <7h365llci8u.fsf@pc150.maths.bris.ac.uk> pythonguy at Hotpop.com (Anand Pillai) writes: > It would be nice if you could give a name > to your email address, i.e if you are not > that paranoid as it seems. I know his name, and I bet a bit of work with google will find it for you too, if you care -- though I can't see why you would. Cheers, mwh -- 3. Syntactic sugar causes cancer of the semicolon. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From just at xs4all.nl Tue Jul 8 04:17:16 2003 From: just at xs4all.nl (Just) Date: Tue, 08 Jul 2003 10:17:16 +0200 Subject: path module References: Message-ID: In article , Ian Bicking wrote: > I think Jason Orendorff's path module is really nice: > http://www.jorendorff.com/articles/python/path/ > > Beats the hell out of os.path, which is an ugly thing indeed. The OO > interface means you could use the interface nicely to implement other > things, like URLs. The problem? It's just some module. The various os > functions (of which path replaces quite a few) have become idiomatic to > me, and I'm sure others as well. I find myself reluctant to use it in > code that's not essentially private, because it's changing something > small and seemingly trivial, and people won't be familiar with it. > > The solution? It should be a builtin! Or, if not a builtin, included > in the os module. But I actually like the idea of it being a builtin -- > if open is a builtin, path stands right up there too. It would get rid > of 90% of the use of the os module. > > Thoughts? Reactions? I would greatly appreaciate such a module in the std library, but while Jason's module has some very cool features, to my taste it goes a bit too far with overloading operators. I really don't like overloading a/b to mean os.path.join(a, b) and I don't think the default iterator should do a listdir (although list(mypath) is indeed cute). If it were toned down a bit in this area I think we may be able to make a good case for including it in the std library. Just From adalke at mindspring.com Mon Jul 21 16:17:53 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 21 Jul 2003 14:17:53 -0600 Subject: Voting Project Needs Python People References: Message-ID: Harry George: > Is the intent to do opensource all the way to commodity chips? Else a > proprietary BIOS could be the weak link. In which way? There resulting code should be runnable on a wide number of platforms, so there isn't a single source issue, and the actual vote is on voter verifiable paper, so corruption of the BIOS won't be able to affect anything other than the number of "something's wrong - this isn't what I voted for" complaints. Perhaps you were thinking of a pure electronic version? Andrew dalke at dalkescientific.com From ivlenin at gmx.co.uk Mon Jul 14 08:56:06 2003 From: ivlenin at gmx.co.uk (I V) Date: Mon, 14 Jul 2003 12:56:06 GMT Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <3f12a45b.6171268@news.freeserve.com> On Sun, 13 Jul 2003 20:39:56 +0100, Stephen Horne wrote: >The fact is that 'assignment' has a common meaning separate from the >choice of programming language, and that the way Python handles name Yes. >binding means that meaning is not respected by Python for mutable >objects. No. Assignment takes a name and binds it to a different value, whatever programming language you use. Python does this for both immutable and mutable types. The same is true of Lisp, and of C++ (although, in C++, you can provide an implementation of operator= which does something else, just as you can provide an implementation of operator+ which doesn't add, but in both cases to do so is a mistake). >Python, however, does not respect this meaning. It uses an arbitrary >distinction based on whether or not the object has internals that can >be usefully in-place modified, and uses that distinction to vary the No, it doesn't. x = (1, 2) binds the name 'x' to a tuple entity with the value '(1, 2)'. x = [1, 2] binds the name 'x' to a list entity with the value '[1, 2]'. There's no distinction here, arbitary or otherwise. There is an exposed implementation detail as regards the identity of immutable and mutable entities, but this doesn't effect the semantics of their values. -- "Mr I V Lenin, the Lenin of love" From tl_news at nexgo.de Thu Jul 31 13:00:46 2003 From: tl_news at nexgo.de (Tino Lange) Date: Thu, 31 Jul 2003 19:00:46 +0200 Subject: .setdefault() References: Message-ID: <4jiiivoph0jr20dvfmp1mn5ii4m3ouusje@4ax.com> On Thu, 31 Jul 2003 16:54:46 +0000 (UTC), Alexandre Fayolle wrote: >> I just realized that .setdefault *always* executes the second >> argument - even if it's not necessary, because the requested item in >> the first argument exists. > method and function arguments are always evaluated before the >method is called. Yep. You're right. Of course it's like that. Anyway - that's not what I expected in the first thought. It shows that less code is not always the best code... Thanks! Tino From lamar_air at hotmail.com Thu Jul 10 11:11:03 2003 From: lamar_air at hotmail.com (lamar_air) Date: 10 Jul 2003 08:11:03 -0700 Subject: delete file from python cgi Message-ID: <2c6431ab.0307100711.780a65ad@posting.google.com> I have a python script and i want to delete a file on my computer c:\....\...\.. .txt what's the script to do this? I know how to write to files but i also need to know how to delete a file. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jul 27 07:48:55 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 27 Jul 2003 13:48:55 +0200 Subject: Tools for reading Dr Dobb's Python-URL In-Reply-To: References: Message-ID: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> Egbert Bouwman wrote: > What is _the_ tool for reading Dr. Dobb's Python-URL, > I mean not only seeing the url's, but opening them as well ? > > I have made a python-script which handles it reasonably well, > but someone must have invented a better wheel before me. Open the message in your news reader. Click on an URL in the message. Sorry, couldn't resist. I'm not sure what you want to do, really? You can also read Python-URL online (as a web page): http://www.ddj.com/topics/pythonurl/ --Irmen From usenet_spam at janc.invalid Tue Jul 15 23:02:02 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 03:02:02 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> <3f1444bc$0$49100$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong schreef: >> Cons: It's vi. That means a pretty steep learning curve until you've >> gotten used to modal editing, where you go into "insert mode" to type >> text and go back into "command mode" (by hitting ESC) to move the >> cursor, copy and paste text, do searches, move text around, etc. Many >> people try vi and give up in disgust after five minutes. > > Actually, moving the cursor around, erasing characters (del, bs) and > perhaps some other frequent actions *don't* require you to switch to > command mode in Vim... > So perhaps it is a lot less painful to start using Vim (compared > to a 'true' vi). And when using "gVim Easy" (aka "evim" or "gvim -y") you almost never need command mode. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From news at garthy.com Thu Jul 24 17:36:55 2003 From: news at garthy.com (Garth) Date: Thu, 24 Jul 2003 22:36:55 +0100 Subject: possible error in socketmodule / asyncore on win32 In-Reply-To: References: Message-ID: <2iYTa.56897$Df6.39614@news-binary.blueyonder.co.uk> Garth wrote: > Hi, > > I think there's an error in ther socketmodule.c code > under windows. The code in internal connect should test > exceptfds to check for connecttion refused. If this is so it > should call getsockopt(SOL_SOCKET, SO_ERROR,..) to get the error > status. (Source microsoft Platform SDK) > > If this isn't then the asynccore module fails on windows and never > returns connection refused. > > The code should probably look something like this (untested) > > if (s->sock_timeout > 0.0) { > if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) { > /* This is a mess. Best solution: trust select */ > fd_set exfds; > struct timeval tv; > tv.tv_sec = (int)s->sock_timeout; > tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); > FD_ZERO(&exfds); > FD_SET(s->sock_fd, &exfds); > /* Platform SDK says so */ > res = select(s->sock_fd+1, NULL, NULL, &exfds, &tv); /* CORRECTION! */ if (res > 0) > { > if( FD_ISSET( &exfds ) ) > { > /* Get the real reason */ > > getsockopt(s->sock_fd,SOL_SOCKET,SO_ERROR,(char*)&res,sizeof(res)); > } > else > { > res = 0; > } > } /* CORRECTION */ else if( res == 0 ) { res = WSAEWOULDBLOCK; } else { /* Not sure we should return the erro from select? */ res = WSAGetLastError() } > } > } else if (res < 0) > res = WSAGetLastError(); The first code I wrote left in writefd testmaybe I should have left it in. I'll have to wait till I get to work to test it but looking at the platform sdk on select should explain what my code is trying to do. ;-) Laters Garth From jdhunter at ace.bsd.uchicago.edu Mon Jul 14 11:39:15 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 14 Jul 2003 10:39:15 -0500 Subject: Expressing time. In-Reply-To: ("Sean"'s message of "Mon, 14 Jul 2003 10:18:53 -0500") References: Message-ID: >>>>> "Sean" == Sean writes: Sean> Is there any python facilities to make this an easier chore Sean> (aka time.localtime()+months(3))? (I included months as it Sean> is a special case in that you can't just arbitrarily Sean> calculate months in seconds without being relative to a Sean> particular month). The mx.DateTime package does what you need: Eg, from mx.DateTime import now, RelativeDateTime, DateTime date2 = now() date1 = date2 + RelativeDateTime(days=-7) # 7 days ago From hst at empolis.co.uk Tue Jul 15 12:06:57 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 15 Jul 2003 17:06:57 +0100 Subject: [OT] sentances with two meanings Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4D9@hendrix.empolisuk.com> Syver Enstad > roy at panix.com (Roy Smith) writes: > > > Harvey Thomas wrote: > > > Also 'I was unknown to you and you deceived me'. Slightly > colloquial > > > > > > Given the biblical meaning of "known", this could have even > more than > > two meanings :-) > > Does "to know" in english also mean to feel someone? In my > own language > the direct translation of the english know also means to feel. I could > say (translated) "I know the cold", meaning I feel the cold > weather. > Not really. The sense Roy is referring to is in the King James (Authorised Version) of the bible, "know" is often used in the sense "to know sexually" i.e. to have sex with. It's archaic now, so if you asked someone "Do you know Guido van Rossum", no-one would think you were asking "Have you had sex with GvR" _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From bokr at oz.net Sat Jul 5 17:24:31 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Jul 2003 21:24:31 GMT Subject: A possible bug in python threading/time module? References: Message-ID: On 5 Jul 2003 09:56:35 -0700, vm_usenet at yahoo.com (vm_usenet) wrote: >"Tim Peters" wrote in message news:... >> [Tim] [...] > >I hope to see more mature people working on the Python project than >Tim. > LOL ;-) Regards, Bengt Richter From andrew.gregory at npl.co.uk Wed Jul 30 07:34:58 2003 From: andrew.gregory at npl.co.uk (Andrew Gregory) Date: 30 Jul 2003 04:34:58 -0700 Subject: Python 2.3 distutils with Mingw C++ Message-ID: <2830c89c.0307300334.4a365a81@posting.google.com> In Python 2.2, I compiled some C++ code on Windows (MinGW compiler) to create an extension using distutils and the following setup.py file: from distutils.core import setup, Extension setup (name = "_pysimple", version = "1.0", maintainer = "AG", maintainer_email = "xxx at xx.co.uk", description = "Sample Python C++ DLL", ext_modules = [Extension('_pysimple', extra_compile_args=['-O2','-march=i586','-malign-double'], extra_link_args=['-mthread'], library_dirs=['C:\\mingw\\lib'], libraries=['supc++'], # if using iostreams etc. use stdc++ sources=['pysimple_wrap.cxx'])]) Provided that certain C++ features such as templates were not used, this would build ok using the gcc compiler (not g++), as supc++ is linked to. Command used is: python setup.py build --compiler=mingw32 In Python 2.3, distutils recognises the .cxx extension as C++ and tries to compile with cc -mno-cygwin -shared etc. resulting in "cc not found" error message. It should compile with c:\mingw\bin\gcc -mno-cygwin -shared etc. or *much* better c:\mingw\bin\g++ -mno-cygwin -shared etc. The quick fix is to copy the old distutils subdirectory from Python22 into Python23. Andrew. From max at alcyone.com Wed Jul 2 18:16:04 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 15:16:04 -0700 Subject: Good code patterns in Python References: <3F0285F0.EDF697E3@alcyone.com> <6qllvh9oi3.fsf@salmakis.intevation.de> Message-ID: <3F0359A4.3F0BE933@alcyone.com> Bernhard Herzog wrote: > Guido broke his silence at EuroPython: The ternary operator will not > be > added to Python. As I said, it's hardly a big surprise. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Divorces are made in Heaven. \__/ Oscar Wilde From hokiegal99 at hotmail.com Thu Jul 10 20:52:07 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Thu, 10 Jul 2003 20:52:07 -0400 Subject: more regexp Message-ID: I can replace all spaces in filenames and directory names with this bit of code: (thanks to all who helped me get this!) > fspaces = re.compile('[ ]') > > for root, dirs, files in os.walk('/test/dir'): > for file in files: > badchars = fspaces.findall(file) #find spaces > newfile = '' > for badchar in badchars: > newfile = file.replace(badchar,'%') > if newfile: > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,file) > os.rename(oldpath,newpath) > dspaces = re.compile('[ ]') > > for root, dirs, files in os.walk('/test/dir'): > for dir in dirs: > badchars = dspaces.findall(dir) #find spaces > newdir = '' > for badchar in badchars: > newdir = dir.replace(badchar,'%') > if newdir: > newpath = os.path.join(root,newdir) > oldpath = os.path.join(root,dir) > os.rename(oldpath,newpath) Now, I'd like to be able to search for the '%' character at the begining and the ending of filenames and dirs and remove them entirely. Could someone suggest a way to do this? Any tips are welcomed! From tim.one at comcast.net Sun Jul 6 23:54:48 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 6 Jul 2003 23:54:48 -0400 Subject: PEP idea. ( removing __slots__ ) In-Reply-To: <3f08984c$1_3@news1.vip.uk.com> Message-ID: [Martin v. L?wis] >> No. Some classes have slots for efficiency, and their subclasses >> have dictionaries for generality. >> >> Likewise, some classes have slots to save the dictionary for most >> instances, but some instances may need additional attributes, in >> which case Python creates the dictionary on-the-fly. [simon place] > I know subclasses can add a __dict__, but i really thought a class > with __slots__ could not have a __dict__, It can, but if you want that (I have a hard time imagining why ...), you have to give it a __dict__ explicitly. > doesn't the script below show this behavior? It shows that a class with __slots__ won't grow a __dict__ by magic (although a subclass of a class with __slots__ can grow a __dict__ by magic, provided that the subclass doesn't itself define __slots__). > PythonWin 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit > (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) > - see 'Help/About PythonWin' for further copyright information. > >>> class A(object): > ... __slots__=['a'] > ... > >>> b=A() > >>> b > <__main__.A object at 0x00EFABF0> > >>> b.__dict__ > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'A' object has no attribute '__dict__' > >>> b.a > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: a > >>> b.a=1 > >>> b.a > 1 > >>> b.b=1 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'A' object has no attribute 'b' Constrast with: >>> class A(object): ... __slots__ = 'a', '__dict__' # NOTE: __dict__ explicitly given ... >>> b = A() >>> b <__main__.A object at 0x006AD730> >>> b.__dict__ {} >>> b.a Traceback (most recent call last): File "", line 1, in ? AttributeError: a >>> b.a = 1 >>> b.a 1 >>> b.b = 1 >>> b.b 1 >>> From martin at v.loewis.de Fri Jul 25 01:17:07 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 25 Jul 2003 07:17:07 +0200 Subject: Python 2.3C1 Fails to build ? References: Message-ID: "Holden Caulfield" writes: > The integer operation result is out of range. > > PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) [...] > Any ideas what is going on? I'd say there is a bug in the compiler. PT(0) is PTA(0), PTA(0), which is ((poolp )((uchar *)&(usedpools[2*(0)]) - 2*sizeof(block *))) Assuming that "2*(0)*" and "2*sizeof(block*)" are all not out of range, abouth the only remaining operation is the subtraction, which is of type "uchar* - size_t". This is, however, not an integer operation, but a pointer operation. You might want to try similar expressions in a separate program, to narrow down the problem further. Regards, Martin From NAIVS-CAPETOWNZACAPEX01 at verisign.com Mon Jul 7 04:40:59 2003 From: NAIVS-CAPETOWNZACAPEX01 at verisign.com (GroupShield for Exchange (ZACAPEX01)) Date: Mon, 7 Jul 2003 10:40:59 +0200 Subject: ALERT - GroupShield ticket number OA1571_1057567254_ZACAPEX01_3 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: ispsales at thawte.com From: python-list at python.org Sent: 1941043072,29574243 Subject: Re: Application Attachment Details:- Attachment Name: your_details.zip File: your_details.zip Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1920 bytes Desc: not available URL: From akhleung at earthlink.net Thu Jul 31 14:40:33 2003 From: akhleung at earthlink.net (Aaron Leung) Date: 31 Jul 2003 11:40:33 -0700 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <96dcb58a.0307311040.7fb17890@posting.google.com> It seems to me that a big compromise/feature is that all kinds of namespaces are usually represented by dictionaries, and that Python exposes this fact to the programmer. This would seem to limit the possible optimizations that can easily be performed by a compiler. BTW, I have only read about Python out of interest, and haven't actually used it for anything, so I hope my remark isn't ignorant. Best regards, Aaron From jason.orendorff at lumigent.com Mon Jul 21 14:16:57 2003 From: jason.orendorff at lumigent.com (Jason Orendorff) Date: 21 Jul 2003 11:16:57 -0700 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> Message-ID: <11234c14.0307211016.344d40bc@posting.google.com> I wrote the 'path' module at: http://www.jorendorff.com/articles/python/path There was some discussion on it here: http://groups.google.com/groups?th=42ab4db337b60ce3 Just a few comments: Ian and Holger wondered why 'path' should subclass 'str'. It's because a path is a string. Benefit: you can pass 'path' objects to functions that expect strings (like functions in 'win32file'). I find this really useful in practice. I agree with Just that 'path' shouldn't override '__iter__()'. I'll change this eventually. I think Just is the first to argue that 'path / filename' is confusing. I find it intuitive. Other people have chosen / for this purpose, independently: see the O'Reilly book _Python Cookbook_ [1], recipe 4.17, and the Boost path object [2]. I do believe 'path' should be in the standard library (if not builtin). I enjoy it and I use it all the time. My perception is that the Python core dev team doesn't see any particular need for it. If anyone wants me to, I'll write the PEP. for f in path('/music').walkfiles('*.mp3'): play_mp3(f) Cheers, Jason [1] http://safari.oreilly.com/?xmlid=0-596-00167-3 [2] http://www.boost.org/libs/filesystem/doc/path.htm#operator_slash From shangius at yahoo.com Fri Jul 25 06:45:03 2003 From: shangius at yahoo.com (Sami Hangaslammi) Date: 25 Jul 2003 03:45:03 -0700 Subject: generator function within a generator function doesn't execute? References: <20030724190941.18070.00000520@mb-m17.aol.com> Message-ID: <6298355.0307250245.530c5656@posting.google.com> thedustbustr at aol.com (TheDustbustr) wrote in message news:<20030724190941.18070.00000520 at mb-m17.aol.com>... > > > However, when run, the sleep function doesn't execute. It doesn't even print > "In Sleep". It never gets called, even though I say sleep(1.5) in cutscene(). > Run it for yourself if you don't believe me. Calling sleep(2.5) isn't supposed to run anything. It just creates a generator object. Calling it from within another generator makes no difference. You need to manually unwind the sleep generator to your scheduler, so instead of sleep(2.5) do for x in sleep(2.5): yield x From bokr at oz.net Mon Jul 28 15:36:21 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 19:36:21 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> <7x65lmzf20.fsf@ruckus.brouhaha.com> Message-ID: On 28 Jul 2003 11:23:03 -0700, Paul Rubin wrote: >Carl Banks writes: >> In the interests of practicality beats purity, when you're >> interpolating (instead of stepping as in range) you should include the >> final endpoint. In my experience, when when you divide a segment into >> intervals, you almost always want to include both endpoints. > >I think you're right about this, but it goes against the Python notion >of a "range" function, so an frange that includes both endpoints >should be called something different, maybe "fstep" or something like >that. For what I was doing, the frange that I posted did the job. > >I see now that that the problem is subtle enough that IMO, a fully >worked out solution should be written and included in the Python >library or at least the Python cookbook. How about if we indicate the kind of interval, e.g., >>> def interiter(start, stop, n_intervals, ends='[]'): ... fn=float(n_intervals) ... for i in xrange(ends[0]=='(', n_intervals+(ends[1]==']')): ... yield ((n_intervals-i)/fn)*start + (i/fn)*stop ... >>> >>> for f in interiter(0, 8, 8): print f, ... 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 >>> for f in interiter(0, 8, 8, ends='[)'): print f, ... 1.0 2.0 3.0 4.0 5.0 6.0 7.0 >>> for f in interiter(0, 8, 8, ends='(]'): print f, ... 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 >>> for f in interiter(0, 8, 8, ends='()'): print f, ... 1.0 2.0 3.0 4.0 5.0 6.0 7.0 >>> for f in interiter(0, 8, 8, ends='[]'): print f, ... 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 Regards, Bengt Richter From Juha.Autero at iki.fi Thu Jul 31 03:18:43 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Thu, 31 Jul 2003 10:18:43 +0300 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <87smon88q4.fsf@jautero.no-ip.org> kylotan at hotmail.com (Kylotan) writes: > PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S %Y')' as a > reverse-asctime(), and was surprised that I couldn't find this wrapped > in a function in any of the modules. Maybe such a function would be > considered for future addition? That's probably because it's easier to do it with time.strptime(). From documentation: The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime() Which means that time.strptime() without format parameter acts as reverse-asctime(). Maybe documentation should state "which matches the formatting returned by ctime() and asctime()" since both functions use the same formatting. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From rganesan at myrealbox.com Tue Jul 29 08:20:44 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Tue, 29 Jul 2003 17:50:44 +0530 Subject: How to detect typos in Python programs References: <3F214977.AEB088C8@engcorp.com> <877k64c0qo.fsf@pobox.com> <3F26597F.9B589160@engcorp.com> Message-ID: >>>>> "Peter" == Peter Hansen writes: > You don't understand the dynamic nature of Python if you > think this is something that is either easy or 100% reliable. > Very contrived but instructive example: > def func(x): > pass > import sys > setattr(sys, 'ab' + 'ost', func) > stick-that-in-your-static-analyzer-and-smoke-it-ly y'rs The dynamic nature of Python is definitely a problem but there are some obvious workarounds. For example a static analyzer can take an option that says "assume standard modules are not modified". This is probably good enough for 90% of the cases. Ganesan -- Ganesan R From eger at cc.gatech.edu Tue Jul 15 15:51:20 2003 From: eger at cc.gatech.edu (Modular Forms Boy) Date: 15 Jul 2003 19:51:20 GMT Subject: PyErr_SetString() != raise ? References: <94974e1a.0307150937.5999593f@posting.google.com> Message-ID: David Eger wrote: :> My exception disappears! to which Paul Simmonds replied: : This part should work fine. Try looking back through the function : calls, layer by layer, making sure each function in turn tests for a : NULL return, and propagates it back to the interpreter. Without a : little more code it's tough to say exactly what's wrong. I've found the place where my exception gets swallowed. Thanks for the pointer! The problem is in the SWIG wrappers: I'm taking discussion to that list: swig at cs.uchicago.edu. -Eger David From peter at engcorp.com Tue Jul 15 17:18:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 17:18:30 -0400 Subject: Thread suddenly stops in NT Service References: <4150f6c8.0307151133.7dab4b25@posting.google.com> Message-ID: <3F146FA6.17C0DE7A@engcorp.com> Matt Rapoport wrote: > > I'm running an NT service with a thread. The thread performs a > calculation every so often and appends the number to a text file. > Every so often the thread just stops - or so it seems. The text file > stops getting numbers added to it but the service is still running and > no errors have been thrown. I'm quite sure that the code would catch > an error and post it to the event viewer if one were arising. > > The only other relevant points I can think of are that the thread runs > a while 1: loop and is set to run as a Daemon. The service waits only > for the stop command. It doesn't seem to be operating system specific > (happens on both XP and 2000). It doesn't seem to be file size > specific, it stops at various file sizes ranging from 5K - 50K. It > doesn't seem to be time specific - sometimes it'll stop after about a > day. Sometimes it'll stop after two days. Is there any evidence to counter the theory that the thread is simply throwing an exception, terminating, and the main thread is continuing to run, unaware of the problem? -Peter From printers at sendme.cz Thu Jul 3 16:39:32 2003 From: printers at sendme.cz (A) Date: Thu, 03 Jul 2003 22:39:32 +0200 Subject: CGI script is in plain text Message-ID: <3F04B0A4.32692.3596CD0@localhost> I have a webhosting account with one company. They have Apache running. When I start CGI script from a web browser, the result is plain text( the copy of that script) I can not access httpd.conf file so I changed .htaccess file. I put into it Options +ExecCGI Sethandler /usr/bin/python.exe .py but the result is the same, plain text Can you please help? Thanks Ladislav From http Mon Jul 28 14:23:03 2003 From: http (Paul Rubin) Date: 28 Jul 2003 11:23:03 -0700 Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Message-ID: <7x65lmzf20.fsf@ruckus.brouhaha.com> Carl Banks writes: > In the interests of practicality beats purity, when you're > interpolating (instead of stepping as in range) you should include the > final endpoint. In my experience, when when you divide a segment into > intervals, you almost always want to include both endpoints. I think you're right about this, but it goes against the Python notion of a "range" function, so an frange that includes both endpoints should be called something different, maybe "fstep" or something like that. For what I was doing, the frange that I posted did the job. I see now that that the problem is subtle enough that IMO, a fully worked out solution should be written and included in the Python library or at least the Python cookbook. From nav+posts at bandersnatch.org Tue Jul 8 11:14:37 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Jul 2003 11:14:37 -0400 Subject: path module References: Message-ID: Just van Rossum writes: > (Did I mention that / usually means divide in Python? ;-) I believe you did... But doesn't % usually mean modulo in Python? :^) Nick -- # sigmask | 0.2 | 2003-01-07 | public domain | feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','') From theller at python.net Tue Jul 29 14:10:06 2003 From: theller at python.net (Thomas Heller) Date: Tue, 29 Jul 2003 20:10:06 +0200 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> <467c9d67.0307290640.4f7d87b1@posting.google.com> Message-ID: <1xw9dx1d.fsf@python.net> "Jordan Tucker" writes: > A fix that seems to work (at least it lets DllRegisterServer succeed) > is inserting the following before the aforementioned line: > > scriptDir = None > if hasattr(sys, 'argv'): > scriptDir = os.path.split(sys.argv[0])[0] > > This allows registration, but now when I try to instantiate one of the > objects defined in my dll from the interpreter, I get the following > error: > > Fatal Python error: PyThreadState_Get: no current thread > > This also happens with the server example included. Do I have to use > something other than win32com.client.Dispatch to connect to an inproc > server from a dll? I think I've used it before to do the same thing > with non-py2exe dlls. I don't know anything about the first error you get (the argv not set problem), but the second is a known bug: You cannot use the python dll com server from a Python client (at least if the client uses the same Python version). This is because of the difficulties managing the threadstate correctly. I hope Mark or I will be able to fix this bug soon (in 2.3, with the help of PEP 311 it should be possible). In the sample zip there's a VB script included to test the server, run it in a console window with cscript.exe like this: 'cscript test_interp.vbs'. Thomas From andymac at bullseye.apana.org.au Sat Jul 12 05:12:18 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 12 Jul 2003 19:12:18 +1000 (EST) Subject: Accessing and updating global variables among several modules In-Reply-To: References: Message-ID: <20030712190624.Y4962@bullseye.apana.org.au> [posted & mailed] On Sat, 11 Jul 2003, Fuming Wang wrote: > However, when I modify these global variables in one module, the other > modules would not see the changes. Any one has any suggestions? ( I > don't want to use from A import *) Use a container, and change the container's contents, eg make the global "variable" a dictionary, and access the different "global variables" via the dictionary's keys. What you're seeing is due to Python's variables being references to values, rather than actual values. With the container approach, all the references will still point to the container, even though the contents change. In fact, Python itself does pretty much all name lookup through dictionaries. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bokr at oz.net Fri Jul 18 14:35:42 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 18:35:42 GMT Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: On 18 Jul 2003 09:30:32 +0200, Hallvard B Furuseth wrote: >Oren Tirosh wrote: >>On Fri, Jul 18, 2003 at 03:11:56AM +0000, Bengt Richter wrote: > >>> > >Needs to be charset=utf-8. iso-8859-7 has no character number 947. You're right. I think the iso-8859-7 just served as a font hint, in effect. You can't leave out the >>>

γ(...) > >> Actually, you don't need the "CHARSET=iso-8859-7". It would be >> required if you used the bytes 227, 223, 227, 237, 249, 243, 234, 249 >> to represent the characters. With numeric character references you can >> embed any character from the UCS repertoire regardless of the charset >> used. > >&#; seems to mean character number NUM in the current character >set, not in UCS. At least on NS 4.79. That seems to be confirmed by the Cyrillic experiment above, now at least for NS4.5 and NS4.79. Regards, Bengt Richter From Vincent.Raaijmakers at ge.com Thu Jul 31 10:08:14 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 31 Jul 2003 09:08:14 -0500 Subject: SQL2000 database vs python Message-ID: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> Ok I was too happy. mssqldb doesn't help me to connect my python app on a linux OS to a sql2000 (windows os) database. I can't even compile the package, I guess it is missing sybase stuff (sybdb.h and sybfront.h), which is correct because I don't have that database. Also, mssqldb supports ms sql server 7.0, my hope is that that won't be a problem in using ms sql 2000. Pfew, there goes my hope. Vincent -----Original Message----- From: Gerhard H?ring [mailto:gh at ghaering.de] Sent: Thursday, July 31, 2003 8:53 AM To: Raaijmakers, Vincent (IndSys, GE Interlogix) Cc: python-list at python.org Subject: Re: SQL2000 database vs python Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Can someone tell me if there is a module out for using a sql2000 database within python? > My python application (runs on Linux) already uses mysql but now I need also to talk to a sql2000 database on another machine. > > Any suggestions? www.python.org, google couldn't help me. http://www.object-craft.com.au/projects/mssql/ -- Gerhard From cookedm+news at physics.mcmaster.ca Sun Jul 20 23:08:57 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 20 Jul 2003 23:08:57 -0400 Subject: distutils.core not in Debian python2.2 package References: Message-ID: At some point, Kent Tenney wrote: > David M. Cooke wrote: >> At some point, Kent Tenney wrote: >> >>>Howdy, >>> >>>I did; >>># apt-get install python2.2 >>> >>># python >>>Python 2.2.1 >>>... >>> >>> >>> >>>then checked docutils out of CVS >>>and did; >>> >>>docutils# python ./setup.py install >>> >>>ImportError: No module named distutils.core >>> >>>How do I install distutils? >> Install the python2.2-dev package. > > It surprises me to find distutils in a package described as: > > "Header files and a static library for Python (v2.2)" > > Kent Except in the extended description, where it says """ Includes the python distutils, which were in a separate package up to version 1.5.2. """ In general, if you need to compile, or develop, you need the corresponding *-dev packages. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From milkchug89 at hotmail.com Wed Jul 30 16:20:46 2003 From: milkchug89 at hotmail.com (Michael Sampson) Date: Wed, 30 Jul 2003 15:20:46 -0500 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> Message-ID: <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> How does the IDLE that comes with the latest release of python handle this? When it automaticly indents does it do it with spaces or tabs? If you hit tab in the IDLE will it just put 5 spaces in for you? "Gisle Vanem" wrote in message news:3f27f0e3$1 at news.broadpark.no... > I'm a .py newbie and fascinated by the simplicity of formatting. > No need for {} as in Perl etc. But the misuse of that many > .py writers do makes it hard to understand how a script operates. > > E.g. > > def main(): > terminate = 0 > def foo(): > line = sys.stdin.readline() > try: > bar() > except: > terminate = 1 > > main() > > Now, with an editor with different tab-settings it's difficult to see where > the try statement belongs. In 'def main()' or in 'def foo()' ? > I'm confused, please enlighten me. > > --gv > > From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 18:24:30 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 31 Jul 2003 00:24:30 +0200 Subject: funny slashdot quote regarding python 2.3 release In-Reply-To: References: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> <3f27b0a9$0$49104$e4fe514c@news.xs4all.nl> Message-ID: <3f28459f$0$49105$e4fe514c@news.xs4all.nl> John Hunter wrote: >>>>>>"Irmen" == Irmen de Jong writes: I don't know where that came from but that is most definately not my email address... > processing. I found that the Numeric version was about 20% faster > than the FORTRAN, in part because there were some inefficiencies in > his hand coded FORTRAN routines. > > Which emphasizes that it's often better to use a well tested, > optimized extension than to code it yourself in a compiled language. If it's available, and can do the job, I agree 100% with you. This will also, in the end, very likely result in a shorter development time because you are not writing from scratch. --Irmen From intentionally at blank.co.uk Sun Jul 13 10:55:27 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 15:55:27 +0100 Subject: removing spaces from front and end of filenames References: Message-ID: <34r2hvgiq1oe662ummbqrhn25vlfekbc50@4ax.com> On Sat, 12 Jul 2003 21:42:56 -0400, hokiegal99 wrote: >This script works as I expect, except for the last section. I want the >last section to actually remove all spaces from the front and/or end of >filenames. For example, a file that was named " test " would be >renamed "test" (the 2 spaces before and after the filename removed). Any >suggestions on how to do this? ... > for file in files: > fname = (file) > fname = fname.strip( ) > print fname The indentation here looks suspicious. It is a very bad idea to indent some lines with tabs and others with spaces - use one method or the other. Also, you are not saving the stripped versions of the strings anywhere. BTW - the strip method doesn't change the object in place, so I don't see the point of the 'fname = (file)' line. I certainly don't understand the brackets. In fact, why not just... files = [i.strip() for i in files] My best guess is that you expected the 'file' variable to reference into the list, but this won't happen - its one of those things that depends on whether the values are mutable or immutable, and with for loops it's the type of the items within the list (ie the strings) that is important. Strings are immutable. Yes, this mutable/immutable thing is a pain :-( Anyway, if you don't like list comprehensions, you'll need to loop through the indices using something like... for i in range(len(files)) : files[i] = files[i].strip () Hope this helps. From hwlgw at hotmail.com Thu Jul 3 17:46:42 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 3 Jul 2003 14:46:42 -0700 Subject: XML Validation with Python References: <3F042045.C5CB0248@hotmail.com> <3F0474F5.FD7E57F3@hotmail.com> Message-ID: > [Alan Kennedy] > ... interesting links and comments ... > Are you sure that XML validation-parsing is the right solution for > your problem? There may be simpler ways. We have defined a new XML vocabulary with a DTD. I offered to make a webservice so everybody can validate their XML files based on this DTD. For this I use CGI with Python 2.1.1 and I have no web master privileges. The idea of web applications is nice in that you do not have to code GUIs anymore: you can do pretty much everything with (X)HTML. Sometimes you have to rethink your UI so it is possible to give every user state a URI. A big plus is that everybody can now use your application. And you can do more than I thought before, for example users can send files from their computer with type=FILE fields in forms. And for development you can just download Apache and install it on your laptop and configure it such that everything is exactly the same as on the target website (#!/usr/bin/python...means install their python version in C:\usr\bin on you laptop :-) The big problem with web applications is all the permissions you need to install, compile, configure, etc. For Python CGI this means you are stuck with some Python version and you realize how important the Python Standard Library is. -- Experience is what allows you to recognize a mistake the second time you make it. From bokr at oz.net Sun Jul 27 13:36:17 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2003 17:36:17 GMT Subject: Seeing next character in an file References: Message-ID: On Sun, 27 Jul 2003 02:58:13 GMT, "Keith Jones" wrote: >On Sun, 27 Jul 2003 01:09:54 +0000, Grumfish wrote: > >> Is there a way to see the next character of an input file object without >> advancing the position in the file? > > >To do this, you can do the following: > >fin = file('myfile') > >... > >char = fin.read(1) >fin.seek(-1,1) # set the file's current position back a character > Warning, though: this is very iffy on windows unless you have opened the file in binary. E.g., >>> print >> file('ends_in_windows_EOL.txt','w'), 'Ends in windows EOL here:' Look at it in binary: >>> file('ends_in_windows_EOL.txt','rb').read() 'Ends in windows EOL here:\r\n' Cooked: >>> file('ends_in_windows_EOL.txt','r').read() 'Ends in windows EOL here:\n' Now try to seek back past the apparent \n single character and one more (2) so we can read the ':' >>> f = file('ends_in_windows_EOL.txt') >>> f.seek(-2, 2) >>> f.read() '\n' Hm. That's a representation of reading the last two characters in cooked mode. Apparently the seek positioned us to read '\r\n', not a cooked ':\n' Look at the same in binary: >>> f = file('ends_in_windows_EOL.txt', 'rb') >>> f.seek(-2, 2) >>> f.read() '\r\n' The last two are the windows EOL. Seeking -2 in cooked mode is not positioning at ':\n' as we can see in the binary: >>> f.seek(-3, 2) >>> f.read() ':\r\n' [...] So if you're going to seek/tell, best to do it in binary, and deal with the platform dependent EOLs. Regards, Bengt Richter From jdhunter at ace.bsd.uchicago.edu Wed Jul 30 17:10:30 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 30 Jul 2003 16:10:30 -0500 Subject: Syntax: pointers versus value In-Reply-To: <3F27F673.3000801@mathstat.concordia.ca> (Danny Castonguay's message of "Wed, 30 Jul 2003 12:46:43 -0400") References: <3F27F673.3000801@mathstat.concordia.ca> Message-ID: >>>>> "Danny" == Danny Castonguay writes: Danny> I want to avoid listA's value to change. There are several ways listB = listA[:] listB = [x for x in listA] import copy listB = copy.copy(listA) listB = copy.deepcopy(listA) These don't all do the same thing, but all satisfy the example you posted, eg >>> listA = [1 ,2] >>> listB = listA[:] >>> listB.append(3) >>> listA [1, 2] So far so good, but consider this case >>> listA = [[],1] >>> listB = listA[:] >>> listB[0].append(12) # changing the list at listB[0] >>> listB [[12], 1] >>> listA [[12], 1] Sneaky, eh? So the 'listB = listA[:]' made a copy of the list, but not of the elements of the list. This is a shallow copy, and you should get the same behavior from copy.copy. Note that this is related to mutable and immutable objects in python. In the example above, I didn't replace the first item of the list, I changed it. Since both listA and listB contained the same object as their first element, changing one changes the other. If I had replaced that object in listB, nothing would have happened to listA >>> listA = [[],1] >>> listB = listA[:] >>> listB[0] = 12 # replacing the object, not changing it >>> listB [12, 1] >>> listA [[], 1] If you want to avoid this, use deepcopy. >>> import copy >>> listA = [[],1] >>> listB = copy.deepcopy(listA) >>> listB[0].append(12) >>> listB [[12], 1] >>> listA [[], 1] The behavior of mutable objects bites everyone a few times when they begin learning python, so welcome to the club! John Hunter From barry at python.org Thu Jul 24 23:01:05 2003 From: barry at python.org (Barry Warsaw) Date: 24 Jul 2003 23:01:05 -0400 Subject: RELEASED Python 2.3c2 Message-ID: <1059102065.12996.22.camel@anthem> Python 2.3c2 is the second and last release candidate for Python 2.3. There have been a bunch of bug fixes and memory leak plugs since the first release candidate, but no new features. As described in PEP 283, Python 2.3 final will be released before the end of July 2003. We are planning for Tuesday 29-Jul-2003 if everything looks good. We highly encourage everyone to rigorously test this release candidate. Only critical bug fixes will be allowed from here to the final release, but we want this release to be as stable as possible. Highlights since rc1 include: - It is now possible to import from zipfiles containing additional data bytes before the zip compatible archive. Zipfiles containing a comment at the end are still unsupported. - Fixed leaks in pyexpat and locale, and a long standing bug in the parser module. - The MacOSX build is now built with -mno-fused-madd to fix test_coercion on Panther (OSX 10.3). For more highlights, see http://www.python.org/2.3/highlights.html Other new stuff since Python 2.2: - Many new and improved library modules, e.g. sets, heapq, datetime, textwrap, optparse, logging, bsddb, bz2, tarfile, ossaudiodev, and a new random number generator based on the highly acclaimed Mersenne Twister algorithm (with a period of 2**19937-1!). - New builtin enumerate(): an iterator yielding (index, item) pairs. - Extended slices, e.g. "hello"[::-1] returns "olleh". - Universal newlines mode for reading files (converts \r, \n and \r\n all into \n). - Source code encoding declarations. (PEP 263) - Import from zip files. (PEP 273 and PEP 302) - FutureWarning issued for "unsigned" operations on ints. (PEP 237) - Faster list.sort() is now stable. - Unicode filenames on Windows. - Karatsuba long multiplication (running time O(N**1.58) instead of O(N**2)). To report problems, use the SourceForge bug tracker: http://sourceforge.net/tracker/?group_id=5470&atid=105470 brought-to-you-by-the-letter-'D'-for-drifty-ly y'rs, -Barry From utopia_2020 at hotmail.com Tue Jul 1 12:31:39 2003 From: utopia_2020 at hotmail.com (Ram) Date: 1 Jul 2003 09:31:39 -0700 Subject: threads and os.spawnlp on Linux References: Message-ID: Some more info to add on ... the problem seems that if some system call fails (or times out) in the os.system or os.spawnlp, then it never returns back the execution context. The following also causes similar results as before if the IP address pinged is unreachable, but if it is a reachable IP, it returns correctly. The problem occurs only if the os.system is inside the thread class. import os import threading import time class Child(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # Pinging some unreachable IP os.system("ping -c 2 192.168.1.55") print "done" if __name__ == '__main__': t = Child() t.start() Thanks Ram From ulope at gmx.de Tue Jul 15 18:29:04 2003 From: ulope at gmx.de (Ulrich Petri) Date: Wed, 16 Jul 2003 00:29:04 +0200 Subject: Accessing an instance's __init__ args from outside the class References: Message-ID: "Alexander Eberts" schrieb im Newsbeitrag news:RKCQa.27757$O55.714325 at wagner.videotron.net... > Duncan, > > Thanks for your response - much appreciated. Do you know how the python > interpreter handles *args and **kwargs passed to a class's __init__ method? > (maybe the better question is "what section in the python docs describes how > class args are handled" :) > They are handled exactly as they would be in any other method. It seems you have a bit of a misconception on how the __init__ method works!? Ciao Ulrich PS: To post an answer above the aswered text is not exactly liked on the (use)net. From alanmk at hotmail.com Sun Jul 6 15:05:56 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 20:05:56 +0100 Subject: absolute beginners question about API documentation References: Message-ID: <3F087314.D8F79BC6@hotmail.com> Dave Kuhlman wrote: > If you are asking about the *Python* API, then look here: > > http://www.python.org/doc/current/lib/typesmapping.html > > If you are asking about the C API (which is less likely but > possible), then look here: > > http://www.python.org/doc/current/api/dictObjects.html I think that for completeness, and given the OPs java background, it's probably worth mentioning the Java API to the jython interpreter as well http://www.jython.org/docs/javadoc/index.html -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From http Mon Jul 21 19:26:52 2003 From: http (Paul Rubin) Date: 21 Jul 2003 16:26:52 -0700 Subject: Voting Project Needs Python People References: Message-ID: <7x65lv31hf.fsf@ruckus.brouhaha.com> "Alan Dechert" writes: > > 1. Software chooses 1% of votes to change (big enough to have an > > effect, small enough to maybe go unnoticed). > > > I don't think this is a possible scenario. However, it brings up an > interesting test for our full blown study (keep in mind, we're trying to > focus on getting the demo done even though people want to jump ahead to > speculate on every possible detail). But something like that seems to have happened in Escambia County, Florida, in 2000. Out of 21,500 absentee ballots cast, 296 (1.5% of the total) were overvotes with three or more presidential candidates checked. ZERO were overvotes with exactly two candidates checked. Ballot tampering after the ballots were received is the most plausible explanation. You said that in your system the paper ballots are supposed to take priority over the electronic count if there is a dispute (that's the whole point of having the paper ballots). So it doesn't matter if the paper and electronic results don't match, and the tampering doesn't have to happen while the voter can still see the ballot. Reference: http://www.failureisimpossible.com/essays/escambia.htm Note: Paul Lukasiak, the main author of that article, did some of the most thorough analysis of the Florida debacle that I've seen. I hope you will read a lot of his stuff in designing your real system, so you'll be able to say how your system deals with the problems that he identified in Florida. From skip at pobox.com Wed Jul 23 17:44:32 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jul 2003 16:44:32 -0500 Subject: lists and files question In-Reply-To: References: <3F1DCF52.7040607@hotmail.com> Message-ID: <16159.448.677068.670308@montanaro.dyndns.org> Jumping in late, and not meaning to step on John's toes: >> 2) The reason to use re.compile is for efficiency. There is no need >> to call it inside the loop, since you're just recompiling the same >> regex over and over again. Instead, compile the regex outside the >> loop >> >> >>> rgx = re.compile('[A-Z]+') >> >>> for some_text in some_list: >> ... m = rgx.match(some_text) This usually doesn't buy you much because both regular expression modules delivered with Python (sre via re, and pre if you choose it explicitly) cache regular expression objects they compiles from strings. Details are in sre.py:_compile and pre.py:_cachecompile. Skip From bogal2 at comcast.net Mon Jul 14 10:30:18 2003 From: bogal2 at comcast.net (BogAl) Date: Mon, 14 Jul 2003 09:30:18 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: Thanks for the reply, Dave.... > Try putting the .pyd in C:\Python22\Lib\site-packages Unfortunately, I'm still getting the error message. :( From tjreedy at udel.edu Thu Jul 17 20:33:42 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 20:33:42 -0400 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> Message-ID: "Rogue9" wrote in message news:3f15ca92 at shknews01... > Hi, > I?m trying to retrieve an item from a list using a reference called > ?draw?' (which is an integer from 1 to 792 in a while loop) using:- 'draw' is a name (or maybe a variable) bound to a succession of integers. Calling it a reference is not generally helpful and may someday mislead you. > draw = 1 > while 1: > if draw == 792: > break > b1 = someOtherList[draw-1] > r1 = b1[draw] > draw = draw+1 For newsgroup postings, spaces generally work better than tabs. To make it easier to answer such questions, make your lists short enough (say len() == 3) to post. Make sure you copy and paste the actual code executed. Then copy and past the actual result and explain what you wanted or expected that would be different. Terry J. Reedy From tim.one at comcast.net Fri Jul 18 22:25:11 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 18 Jul 2003 22:25:11 -0400 Subject: Threading Pool Event() In-Reply-To: Message-ID: [Graeme Matthew] > ok still a bit confused sorry .... first attempt at a thread pool > > Am I correct in saying that each thread runs in a continious loop That's a usual way to write this, yes. > each thread calls queue.get. Right. > The get method will block and not return anything until an item is > placed into it. Until an item is placed into the Queue object, via a Queue.put() call made in some other thread. > When an item is placed into it, one of the threads will get assinged a > job i.e the first one that happens to be in use during the cycle ? *Some* thread's .get() call will return then. Nothing is defined about *which* thread. > The job is returned to the thread, it runs with the job and does all > the processing then returns and calls queue.get again and waits for a > job to become available ? Right. > When placing a job via Queue.put() one must acquire a lock place it > and then release it No. Work is put on the Queue by calling Queue.put(), and removed from the Queue by calling Queue.get(). There is no need for you to do any locking; all necessary synchronization is performed for you, by the methods of the Queue class. > Am i aslo correct in saying that queue is actually doing the blocking Yes. > and controls which thread gets the job ? No -- that's up to the vagaries of your operating system's and/or platform C library's thread implementation, which Python calls. > Lastly, sorry for all the questions, surely the CPU usage is the same > when the queue is waiting for jobs and when the threads are polling > as theyre all in one process anyway No, blocking on a Queue.get() consumes no (or essentially no ) CPU time on reasonable platforms. Blocking is passive. Polling is active. The Queue class doesn't poll. From sketerpot at chase3000.com Fri Jul 11 13:28:15 2003 From: sketerpot at chase3000.com (Peter Scott) Date: 11 Jul 2003 10:28:15 -0700 Subject: Python extension on Windows References: Message-ID: <659f82ff.0307110928.658965ee@posting.google.com> David Isal wrote in message news:... > i read that it is mandatory to use Micro$oft visual c++ to build any > extensions on windows beacuse it's the same compiler used to build > python for windows. > does anybody has advices about that? > i would rather use cygwin/g++ but i don't know if it's possible or how > to fix this error message. I don't know what's causing your particular problem (since I got free MSVC++ from a Microsoft promotional gimmick), but if you download the python 2.2.3 source and compile that with Cygwin, that should eliminate any possible incompatibilities between compilers. The source tarball is at . From faizan at jaredweb.com Sun Jul 27 15:34:26 2003 From: faizan at jaredweb.com (Fazer) Date: 27 Jul 2003 12:34:26 -0700 Subject: GET/POST Data Array in Python? Message-ID: <7b454334.0307271134.771de1ce@posting.google.com> Hello Everyone! I am making a simple Pythong CGI script that collects data from a form. When the Python CGI Script is called, I wish to gather all the POST variables and display all their values. So, I was wondering if all the POST data is collected in an array like in PHP where I just go through all keys and display their values? Thanks, From glenfant at NOSPAM.bigfoot.com Fri Jul 4 18:04:11 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Sat, 5 Jul 2003 00:04:11 +0200 Subject: How to get CGI request-URL References: Message-ID: "Hallvard B Furuseth" a ?crit dans le message de news: HBF.20030704ty6d at bombur.uio.no... > How can I get the URL the user typed (except the part after '?') with > the cgi module? > > I expect the 'Host:' HTTP header + os.environ['SCRIPT_NAME'] would do > it, but I don't see how to find the Host header. The www server has > several names, so I can't just use the default host name. > > -- > Hallvard Don't remember but... There's a test() function in the cgi module that shows the special data available from a CGI script. --Gilles From pinard at iro.umontreal.ca Tue Jul 22 17:07:06 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 22 Jul 2003 17:07:06 -0400 Subject: Search for a string in binary files In-Reply-To: References: Message-ID: [hokieghal99] > One last question: does grep actually open files when it searches them? I did not look at `grep' sources for a good while, I might not remember correctly, read me with caution. `grep' might be trying to `mmap' the files if the file (and the underlying system) allows this, and there is system overhead associated with that function, just like `open'. > And, would it be more efficent (faster) to just call grep from python to > do the searching? No doubt to me that it is more efficient calling `grep' _instead_ of Python. However, if Python is already started, it is more efficient doing the work from within Python than launching an external program as `grep', as there is non-negligible system overhead in doing so. (Yet for only a few files, launching `grep' is fast enough that the user would not notice it anyway.) Still, there are special cases, unusual in practice, when `grep' might be faster despite the overhead of calling it. When the file is long enough, and the string to be searched for meets some special conditions, the Buyer-Moore algorithm (not sure of spelling) might progressively beat the likely more simple-minded search technique used within `string.find'. Yet if Python's `string.find' relies on `strstr' in GNU `libc', it might be quite fast already. The implementation of such basic routines in `libc' varied over time, they at least once used to be extremely well implemented for speed, cleverly using bits of assembler here and there. For `strstr' in particular, there was once some good code from Stephen van den Berg. I do not know what `libc' uses nowadays, nor if Python takes advantage of it. Finally, for huge files, proper reading in Python has to be done in chunks, and the string to be searched for may happen to span chunks. Doing it properly might require some more care than one might think at first. But in practice, on the big average, for reasonable files, staying in Python wins. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tzot at sil-tec.gr Mon Jul 21 22:03:03 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 05:03:03 +0300 Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: On Tue, 15 Jul 2003 07:03:11 +0100, rumours say that Stephen Horne might have written: >You could make a very strong case for references being a distinct >datatype from pointers I think you were correct to say that references act as pointers *and* syntactic sugar. Simply put, a declaration of a reference: int &c; could be interpreted as: int *__c; #define c (*__c) with a corresponding #undef at the end of the block. This explains stuff like why one uses . instead of -> with a reference. Anyway, this is how *I* interpreted C++ references once I met them, and it kind of stuck in my mind. I could be missing something, though... I'm more of a plain-C person. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From gh at ghaering.de Wed Jul 23 17:39:05 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Jul 2003 23:39:05 +0200 Subject: How to do raw Ethernet under Win32? In-Reply-To: <3f1ee77f$0$160$a1866201@newsreader.visi.com> References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> <3f1ee77f$0$160$a1866201@newsreader.visi.com> Message-ID: <3F1F0079.90705@ghaering.de> Grant Edwards wrote: > It looks like I can _almost_ do what I want with the python > wrapper around the windows pcap lib. Where's PyLibpCap for Windows available? -- Gerhard From peter at engcorp.com Sat Jul 12 05:33:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Jul 2003 05:33:10 -0400 Subject: The "intellectual property" misnomer References: Message-ID: <3F0FD5D6.EC69DB89@engcorp.com> Ben Finney wrote: > > On Sat, 12 Jul 2003 04:29:04 GMT, Raymond Hettinger wrote: > > In layman's terms, it means exactly what Guido said. > > The layman's understanding of "intellectual property" is confused, > doesn't relate to reality, and is harmful. Please avoid use of that > term. You've already stated clearly your belief (Are you a lawyer? No? So it's merely a belief, right? a personal opinion.) that the term "intellectual property" has no legal meaning, therefore "layman's" in the above is redundant. The result is that you are saying in effect that the term "intellectual property" is wrong for everyone on the planet and that no one can have a useful meaning for it and therefore must avoid its use. One might almost expect you to claim copyright on the phrase and refuse to license its reproduction to the rest of us. ;-) As far as I'm concerned, "intellectual property" *has* a useful meaning, though an ambiguous one (as intended, no doubt), and Guido used it in a way which communicated *to me* (as he intended it to communicate to people like me) certain information. There's no need in non-legal documents to avoid ambiguity and in fact there's a lot of advantage in using it. Think of it as a Pythonic approach to communication: it's not rigorously defined, yet it works! You may not like the term, but I got something useful out of that use of it, as was intended, and I might feel somewhat offended by your telling me and everyone else on the planet that we should avoid it when *we* believe it communicates something useful, and effectively. -Peter From davecook at nowhere.net Fri Jul 18 03:04:01 2003 From: davecook at nowhere.net (David M. Cook) Date: Fri, 18 Jul 2003 07:04:01 GMT Subject: gui References: Message-ID: In article , Linkages wrote: > a good GUI for linux ? I like pygtk together with glade for doing layout: FAQ: http://www.async.com.br/faq/pygtk/index.py?req=all Tutorial: http://www.moeraki.com/pygtktutorial/pygtk2tutorial/index.html Reference: http://www.moeraki.com/pygtkreference/pygtk2reference/ There are also wxpython, pyqt, foxpy, and good old tkinter (which is what comes with the standard library.) Dave Cook From intentionally at blank.co.uk Mon Jul 14 18:55:41 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 23:55:41 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> On 14 Jul 2003 10:26:36 -0400, aahz at pythoncraft.com (Aahz) wrote: >>>That's why I (and others) prefer to use "name" and "target" instead of >>>"variable". Would that assuage your ire? >> >>Not really, for reasons defined elsewhere. The problem isn't >>theoretical - it is practical, as shown by the fact that people do >>trip over it time and time again. I'm just saying that the problem >>arises out of peoples intuition of how variables should work - an >>intuition that matches very well with theory. > >People trip over pointers, too, even when they're explicit. Heck, >people have problem with the simple > > a = a + 1 > >no matter *what* programming language is used if they can't get past >their high school algebra and understand that "=" is a *command* in this >context. The question is not whether newcomers get tripped up, but the >extent to which the language can be easily defined in a consistent and >rigorous manner. Python passes that test quite handily, IMO. Ah - but this is also Pythons fault. It has arbitrarily redefined the meaning of a mathematics operator - presumably simply because C, C++, Java, Basic and others have done this in the past. C's rationale for this still amuses me. It was because there are more assignments in a typical program than tests for equality. It was an argument about numbers of keypresses! Frankly, this is another thing that should not be done in a 'very high level language'. In BASIC, the operator is a shorthand for what was originally written with a 'LET' command. Annoying, but at least the original form made the point. Personally, though, I'd go with Pascal on this one. Similarly, if Pythons binding of variables to objects was used to correctly implement a binding of variables to values - as happens in mathematics - there'd be no confusion. In another thread, hokiegal99 made a mistake where she expected the string.strip method to literally change the name of a file on disk. But was she being irrational? I don't think so. She had no doubt been told, in effect, that Python variables bind to objects rather than values. The object she was changing was 'the name of a file'. If Python variables bind to objects rather than values, then that os.walk method should be providing literally a list of the names of the files - objects which literally refer back to the on disk file names. It doesn't. It provides a list of representations of the names at a point in time. Of course in this case, binding to the object itself (or something that implements a binding to that object) would be complex and inefficient. I guess Python is just doing what is convenient for the implementation. From jdhunter at ace.bsd.uchicago.edu Thu Jul 10 13:50:37 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 10 Jul 2003 12:50:37 -0500 Subject: replace value of a specific position In-Reply-To: (Tom's message of "Thu, 10 Jul 2003 19:36:16 +0200") References: Message-ID: >>>>> "Tom" == Tom writes: Tom> Hi, I want to replace a specific part of a string. I tried Tom> replace but this doesn't work the way I want it, because it Tom> checks and replaces all values and not the position (index). Tom> t = '010010101001001110100101010111' t = t.replace(t[5], '2') strings are immutable and cannot be changed. You can represent a string as a list, change the list, and then convert back to a string. If you need to make lots of changes, keep it as a list until you are done and need the string back t = '010010101001001110100101010111' l = list(t) l[5] = '2' print l # now convert back to string tnew = ''.join(l) print tnew JDH From hokiegal99 at hotmail.com Sun Jul 13 12:43:46 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 13 Jul 2003 09:43:46 -0700 Subject: removing spaces from front and end of filenames References: Message-ID: <93f5c5e9.0307130843.3e3e3daa@posting.google.com> Ha!! Fixed it with this bit of code: for root, dirs, files in os.walk('/home/BradTill/python'): for file in files: fname = (file) fname = fname.strip( ) newfile = fname if newfile: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) print oldpath print newpath Below is a sample of how the script acts on filenames: --- Remove '%2f' From Filenames --- /home/BradTill/python/ %2fbad%2fmac%2ffile> /home/BradTill/python/ -bad-mac-file> /home/BradTill/python/-target1-/ %2fbad%2fmac%2ffile| /home/BradTill/python/-target1-/ -bad-mac-file| /home/BradTill/python/-target1-/-target2-/ %2fbad%2fmac%2ffile? /home/BradTill/python/-target1-/-target2-/ -bad-mac-file? /home/BradTill/python/-target1-/-target2-/-target3-/ %2fbad%2fmac%2ffile\ /home/BradTill/python/-target1-/-target2-/-target3-/ -bad-mac-file\ --- Done --- --- Remove Bad Characters From Filenames --- /home/BradTill/python/ -bad-mac-file> /home/BradTill/python/ -bad-mac-file- /home/BradTill/python/-target1-/ -bad-mac-file| /home/BradTill/python/-target1-/ -bad-mac-file- /home/BradTill/python/-target1-/-target2-/ -bad-mac-file? /home/BradTill/python/-target1-/-target2-/ -bad-mac-file- /home/BradTill/python/-target1-/-target2-/-target3-/ -bad-mac-file\ /home/BradTill/python/-target1-/-target2-/-target3-/ -bad-mac-file- --- Done --- --- Remove Spaces From Filenames --- /home/BradTill/python/fix_files.py /home/BradTill/python/fix_files.py /home/BradTill/python/fix_dirs.py /home/BradTill/python/fix_dirs.py /home/BradTill/python/files /home/BradTill/python/files /home/BradTill/python/ -bad-mac-file- /home/BradTill/python/-bad-mac-file- /home/BradTill/python/-target1-/ -bad-mac-file- /home/BradTill/python/-target1-/-bad-mac-file- /home/BradTill/python/-target1-/-target2-/ -bad-mac-file- /home/BradTill/python/-target1-/-target2-/-bad-mac-file- /home/BradTill/python/-target1-/-target2-/-target3-/ -bad-mac-file- /home/BradTill/python/-target1-/-target2-/-target3-/-bad-mac-file- --- Done --- Works well on dirs too, except that the path changes when a fix is made to a parent dir so the script has to be run over and over until all sub dirs are fixed. From gsmatthew at ozemail.com.au Sun Jul 6 08:08:35 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Sun, 6 Jul 2003 22:08:35 +1000 Subject: Python is a gem, you need to keep pushing it .... References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: <9jUNa.625$kY2.37246@nnrp1.ozemail.com.au> sorry guys, i was just praising python not trying to cause a theoretical bitch fight, for my purposes it the best language out there, if you need to write device driver fine use C ... "Graeme Matthew" wrote in message news:0gVMa.126$a%1.9289 at nnrp1.ozemail.com.au... > Hi all, I just wanted to tell someone :-) > > I was previously a perl programmer and have been a visual basic frustrated > developer for a number of years, only for the reason that corporates are so > obsessed with using proprietary marketing focused computer languages and not > using true computer science oriented solutions written by computer science > engineers and not a marketing panel. The amount of frustration I have > experienced using visual basic is unbelievable and most of these programs > could have been easily written in python and solved in half the time. I > looked at ruby, it is a beautiful language too but there are still too many > scarce libraries compared to python. Perl, I still like perl but its syntax > requires a photographic memory when coming back to some old code. > > I have now taken on a large project outside of work for another company, > initially they, yes wait for it, wanted a VB client / server solution. It > took me lot of hard motivation and they have now totally changed their > focus, a web based python solution it now is ! who said one cannot market > linux, python and mysql ? I hope to have the project completed in 6 months > and I am looking forward to adding it to one of python's success stories. > > So the whole point of this email is that if a lot of you are hitting the > same frustration as myself where managers (and people who think Microsoft > invented everything well except a watch you need to recharge every 2 days > :-) keep on insisting on developing in the basket case Microsoft Languages > such as VB (I am not mentioning C or C++ as it does not fall into this > bracket) then dont give up, keep up the evangelism, as someday they will > give in .... and let you prove it too them > > Cheers > > > > From alanmk at hotmail.com Thu Jul 24 15:24:07 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 24 Jul 2003 20:24:07 +0100 Subject: Tokenize References: <8%VTa.133$313.72262@news.uswest.net> Message-ID: <3F203257.AD0A4B30@hotmail.com> Ken Fettig wrote: > Does Python have an equivelent to the Java StringTokenizer? If so, > what is it and how do you implement it? Is this the kind of thing that you mean? Python 2.3b1 (#40, Apr 25 2003, 19:06:24) Type "help", "copyright", "credits" or "license" for more information. >>> s = "This is a string to be tokenised" >>> s.split() ['This', 'is', 'a', 'string', 'to', 'be', 'tokenised'] >>> s = "This:is:a:string:to:be:tokenised" >>> s.split(':') ['This', 'is', 'a', 'string', 'to', 'be', 'tokenised'] >>> s.split(':', 2) ['This', 'is', 'a:string:to:be:tokenised'] >>> Or maybe you have something more specific in mind? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From martin at v.loewis.de Wed Jul 9 15:36:24 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jul 2003 21:36:24 +0200 Subject: Possible to install from CD using distutils? References: Message-ID: "Simon Wittber (Maptek)" writes: > Try this command. It will let you write to a CD drive. > > mount -o rw /dev/cdrom /mnt/cdrom Did you try this? You can't mount a cdrom rw - the hardware just does not support writing to a CD-*ROM* (Read-Only Memory). Regards, Martin From glenfant at NOSPAM.bigfoot.com Thu Jul 10 11:40:25 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Thu, 10 Jul 2003 17:40:25 +0200 Subject: delete file from python cgi References: <2c6431ab.0307100711.780a65ad@posting.google.com> Message-ID: No direct connection with cgi... import os os.remove("/path/to/your/file.txt") --Gilles From Aaron.Hawley at uvm.edu Sun Jul 27 17:13:08 2003 From: Aaron.Hawley at uvm.edu (Aaron S. Hawley) Date: Sun, 27 Jul 2003 17:13:08 -0400 Subject: Inheriting (subclass) of dict data attribute (copying) Message-ID: Would be the most obvious (best in idiom) to overwrite the dictionary of my derived dict class? The old school way is obvious to me. TIA, /a #!/usr/bin/env python from UserDict import UserDict class Old_Chickens(UserDict): ## old school def __init__(self, chickens): self.set_chickens(chickens) def set_chickens(self, chickens): self.data = chickens class New_Chickens(dict): ## new school def __init__(self, chickens): self.set_chickens(chickens) def set_chickens(self, chickens): self = dict.__init__(self, chickens) new_chickens = New_Chickens({'white': 12, 'brown': 8}) print new_chickens['white'] old_chickens = Old_Chickens({'white': 12, 'brown': 8}) print old_chickens['white'] -- PINE 4.55 Mailer - www.washington.edu/pine/ source-included, proprietary, gratis, text-based, console email client From lorenb2 at bezeqint.net Sun Jul 20 15:28:54 2003 From: lorenb2 at bezeqint.net (Bobbie) Date: Sun, 20 Jul 2003 21:28:54 +0200 Subject: httplib\urllib attributes problem Message-ID: <001c01c34ef5$2804e7b0$6700a8c0@inet43> hello ppl, While trying to build a web client I've encountered problems using both httplib and urllib2. The problem with httplib is that the "Accept-Encoding: Identity" HTTP header is always sent by the library with no regard to my headers configuration. in case I setup an "Accept-Encoding" header of my own it just sends them both... The problem with urllib2 is that a "User-agent: Python-urllib/2.0a1" is, again, sent by default. in case I setup a "User-Agent" attribute of my own it just, again, sends them both. Note the lower-case 'a' letter in the former user-agent automatically sent by the library. I can't even overrun it because of that. I'll be happy for any kind of help, suggestion,... thanks Bob. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jul 9 05:59:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 05:59:34 -0400 Subject: Executables under Win32 References: <5vkngvs2epq6rv0a3rodeb839k5ls8bafj@4ax.com> <3F0BE70A.165B5274@engcorp.com> Message-ID: <3F0BE786.E0EB043E@engcorp.com> Peter Hansen wrote: > > Fuzzyman wrote: > > > > IS there a tool to make Python Executables (binaries) under Win32... > > or must people have a distribution of Python to use any scripts I > > write ? > > > > I don't need to hide my source code - but would liek to make it easy > > for a newbie to use my scripts. > > (Excellently asked question! We get this one often, but rarely so > clearly. :-) Of course, having written this, I should have stopped myself from answering as I did and directed you to the FAQ! http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.028.htp From abelikov72 at hotmail.com Wed Jul 9 00:59:20 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Wed, 09 Jul 2003 04:59:20 GMT Subject: Python vs PHP References: Message-ID: <998ngvs89fa45iap2ummvvmnlohagfipvd@4ax.com> On Tue, 08 Jul 2003 20:46:53 -0500, "A.M. Kuchling" wrote: >On 8 Jul 2003 17:59:12 GMT, > Jon Ribbens wrote: >> I don't understand why you keep saying "CGI is not an option" when >> nobody has suggested that you use it. > >Jon, there's no point in debating Afanasiy about CGI. He's convinced >packages for Python web programming support are inadequate (*all* of them), >is unable to explain what the problem is or what his requirements are, and >doesn't seem to really understand the subject (e.g. thinking FastCGI is >basically the same as regular CGI). Ignoring him is the best course. Read. From max at alcyone.com Fri Jul 18 01:37:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 22:37:07 -0700 Subject: scanf string in python References: Message-ID: <3F178783.41DCA40F@alcyone.com> lehrig wrote: > I have a string which is returned by a C extension. > > mystring = '(1,2,3)' > > HOW can I read the numbers in python ? re.findall seems the safest and easiest solution: >>> re.findall(r'(\d+)', '(1, 2, 3)') ['1', '2', '3'] >>> map(int, re.findall(r'(\d+)', '(1, 2, 3)')) [1, 2, 3] Flavor to taste. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You can buy any kind of love, but you can't buy love deluxe. \__/ Sade Adu From LogiplexSoftware at earthlink.net Thu Jul 3 18:23:34 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 03 Jul 2003 15:23:34 -0700 Subject: A story about Python... sort of In-Reply-To: References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <1057271014.16862.34.camel@software1.logiplex.internal> On Thu, 2003-07-03 at 06:50, Max Khesin wrote: > import flame.* > import sorry.* > Ok, with all my respect to python, the stuff about C++ is a bunch of hooey. > Compilation time is the problem? Give me a break. It is *a* problem. I'll agree that it's one of the least. > 1) separate compilation? > 2) precompiled headers? > 3) tools that allow cluster compilation? > 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ > project. letter-envelope idiom to help compilation...etc. > Anyway, if you are coding so fast that compilation time becomes a serious > problem you are either > a) the smartest and fastest programmer on earth > b) are not thinking enough Or making simple typos. > c++ is great when execution speed and memory efficiency is a must. It is > hard to learn, but there are great benefits, and do you really want halfwits > (who can't learn it) involved on your project? It also (by design) makes > previous C programmers productive very fast. I won't disagree that there is a place for languages like C++. Developing entire applications isn't it. > Empirically - just look at all the C++ projects on SF! And what percentage of those are incomplete, abandoned, or simply unusable? -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From alanmk at hotmail.com Thu Jul 3 14:24:53 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 03 Jul 2003 19:24:53 +0100 Subject: XML Validation with Python References: <3F042045.C5CB0248@hotmail.com> Message-ID: <3F0474F5.FD7E57F3@hotmail.com> Will Stuyvesant wrote: > Because I want to use it from a cgi script written in Python. And I > am not allowed to install 3rd party stuff on the webserver. Even if I > was it would not be a solution since it has to be easy to put it on > another webserver. But of course: if there is a validating parser > written completely in Python then I can use it too! If it runs under > Python 2.1.1, that is (that is what they have at the website). I will > investigate this www.garshol.priv.no link you gave me, thank you. Glad to be of help. There is a comment on Lars site, which is vaguely worrying, which says: "Note that it is recommended to use xmlproc through the SAX API rather than directly, since this provides much greater freedom in the choice of parsers. (For example, you can switch to using Pyexpat which is written in C without changing your code.)" Which seems to indicate to me that the author is encouraging the user not to rely on xmlproc too much. Perhaps performance might be an issue? One more thing: There are alternative validation methods, which may or not be suitable, based on your requirements. For example, there is a python implementation of James Clark's Tree Regular EXpressions (TREX), written in pure python, and which uses the inbuilt C parser, written by James Tauber and called pytrex. I personally find trex and pytrex a very natural, and thus easy to learn, way to check structures in a tree, including data validation. Pytrex is not complete, and is no longer maintained, but what's there is good code, and with nice little features, such as the ability to define your own datatype validation functions, which are called at match time. http://pytrex.sourceforge.net/ Pytrex is unlikely to be ever completed, because James Clark has abandoned TREX in favour of RELAX-NG, for which I haven't seen any python implementation. http://www.relaxng.org/ There is a python implementation of XML-Schema, xsv, written by Henry Thompson, which I think was kept fairly up-to-date with the XML-Schema spec as it evolved. However, given the complexity of XML-Schema, and having never tried to use xsv, I have no idea of its stability. http://www.ltg.ed.ac.uk/~ht/xsv-status.html I note that the author also maintains a web service for validating documents. Are you sure that XML validation-parsing is the right solution for your problem? There may be simpler ways. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jepler at unpythonic.net Sun Jul 20 23:15:56 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 20 Jul 2003 22:15:56 -0500 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) In-Reply-To: References: Message-ID: <20030721031556.GA4990@unpythonic.net> Earlier, I [Jeff] wrote: > > In fact, I wonder why slices *aren't* hashable. > On Mon, Jul 21, 2003 at 04:49:55PM +0950, Ben Finney wrote: > How would you store the resulting key; how would you expect it to be > returned from keys() ? ??? Here's something that "works" today: >>>class C: __getitem__ = lambda self, idx: idx ... >>> C()[:] slice(0, 2147483647, None) But this doesn't work: >>> d = {} >>> s = C()[:] >>> d[s] = None TypeError: unhashable type Here's what "should" happen: >>> d[s] = None >>> print d[s] None >>> print d {slice(0, 2147483647, None): None} I don't see what's problematic about letting slices be hashable: they don't appear to be mutable, for instance. >>> s.start 0 >>> s.start = -1 TypeError: readonly attribute ... it may merely be an oversight. Hashing them as hash((s.start,s.stop,s.step)) might be a reasonable definition. Jeff From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 07:48:56 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 13:48:56 +0200 Subject: funny slashdot quote regarding python 2.3 release In-Reply-To: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> References: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> Message-ID: <3f27b0a9$0$49104$e4fe514c@news.xs4all.nl> Guyon Mor?e wrote: > suspect that most time-critical code is not written in python. > > Depends on which time is critical: CPU time, or programmer time? > > -jcr Not only funny, but also a very *sound* question. From your development company's point of view: the programmer time. From the customer's point of view: depends. Usually CPU time. But programmer's time means longer realization times and usually higher cost (unless the project is fixed-price). And let's not forget that time-critical code can very well be written in a high-performance C extension module. --Irmen From adechert at earthlink.net Mon Jul 21 03:32:28 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 07:32:28 GMT Subject: Electronic voting with free software References: Message-ID: "Ben Finney" wrote in message news:slrnbhma55.si4.bignose-hates-spam at iris.polar.local... > On Mon, 21 Jul 2003 00:54:34 +0200, Ulrich Petri wrote: > > > > Sorry but why on earth you dont just print that on paper and let > > people make their crosses where they want? > > To give benefits that paper ballots can't provide. E.g. allowing people > to vote over the Internet who can't get to voting booths, removing the > human element of transposing ballots to a database, possibly reducing > double-voting, etc. > Several studies concluded that remote unattended Internet voting poses some very thorny problems (especially voter identity). However, these studies have also said there is no reason attended Internet voting could not work. Our project incorporates a proposal for Remote Attended Internet Voting to replace the various existing absentee voting methods employed today. > The FREE project was developing GNU.FREE software for electronic voting; > development has since halted, but they have a lot of articles resulting > from the development activity: > Kitkat, underestimated the size of the problem on the technical side. He never started to look at the politcal one which is much larger. It is axiomatic that everyone that jumps in to solve the problem underestimates it. The team I am putting together is getting a handle on the technical side as well as the political side. We have a ways to go yet. Alan Dechert From peter at engcorp.com Fri Jul 25 09:01:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jul 2003 09:01:10 -0400 Subject: decimal to binary References: Message-ID: <3F212A16.A8A57532@engcorp.com> manuel wrote: > > How to convert a decimal to binary ? No builtin function, but you could likely find lots of previous questions like this, and answers. If you don't feel like searching, can you post an example of what you want in and what you want out? Some people asking this kind of question are confused about representations of numbers and how data is really stored in computers, and they don't really want what they thing they want. A quick Google groups search with "convert decimal binary" reveals answers that would probably work for you. -Peter From andymac at bullseye.apana.org.au Tue Jul 15 06:27:18 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 15 Jul 2003 20:27:18 +1000 (EST) Subject: FCNTL module deprecation warning In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1302644325@its-xchg4.massey.ac.nz> References: <1ED4ECF91CDED24C8D012BCF2B034F1302644325@its-xchg4.massey.ac.nz> Message-ID: <20030715201604.E39137@bullseye.apana.org.au> On Tue, 15 Jul 2003, Meyer, Tony wrote: > (I did try to google for an answer to this, but couldn't find anything, > although plenty of instances of the warning). > > I don't understand this warning: > >>> import fcntl > C:\Program Files\Python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL > module is deprecated; please use fcntl > DeprecationWarning) > >>> > > It seems to be saying that I shouldn't use "import FCNTL" (which gives > the same warning), but "import fcntl", but that's what I _am_ doing. > > (I don't actually even import fnctl, but httplib does, and causes this > all over the place. > > Any light shedding would be appreciated. You don't state your exact platform, but the filename quoted is a MS-DOSish form. Python natively is case-sensitive. Windows 9x and later, and OS/2 with HPFS file systems, are case-insensitive but case-preserving. So Python relies on the case preservation when trying to match a filename to a module name. This behaviour can be turned off with the PYTHONCASEOK environment variable. I would hazard a guess that either:- a) you have the PYTHONCASEOK environment variable set when you shouldn't; or b) you have Python installed on a non-case-preserving file system (like FAT12 or FAT16); or c) you installed Python with tools that didn't preserve the case of the files in the Python library. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From peter at engcorp.com Sun Jul 20 15:15:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 15:15:00 -0400 Subject: Importing WMI module into Python CGI script fails References: <3F1A9A07.F71D274D@engcorp.com> Message-ID: <3F1AEA34.5072FADE@engcorp.com> MK wrote: > > This is what I get back in browser's window: Browser? What are you trying to do, that runs Python code in the browser window? Try running your code directly instead of through CGI and see what happens. It's easier to debug that way. > C:\python\lib\site-packages\win32com\client\__init__.py in > Moniker(Pathname='winmgmts:', clsctx=23) > > com_error: (-2147217405, 'OLE error 0x80041003', None, None) The above two snippets suggest that you are trying to access some COM object called "winmgmts:" but don't have permission. I have no idea about COM/ActiveX so I can't help, but perhaps someone else can. Searching on Google for the above error code gives lots of results, including: In the call to pWbemServices->GetObject an error of 0x80041003 is returned which according to MSDN documentation is WBEM_E_ACCESS_DENIED The current user does not have permission to perform the action I'd suggest you (a) learn more about Python, since you don't seem to know how to interpret error tracebacks, and (b) describe in more detail what you are trying to accomplish, because the problem is not with the "wmi" module per se, but at a lower level, and appears to be related to your not having the correct user permissions for the object you are accessing. Sorry I can't help more. -Peter From gbhsaint at aol.com Sun Jul 27 07:27:42 2003 From: gbhsaint at aol.com (Gbhsaint) Date: 27 Jul 2003 11:27:42 GMT Subject: Del's "except"ional PEP Rejection References: <20030727031348.05032.00000554@mb-m26.aol.com> Message-ID: <20030727072742.00688.00000811@mb-m25.aol.com> Man, I can't believe that I spelled yield wrong. what a bone head. Well at least this construct is an exception at the very first word and it never gets this far. From piet at cs.uu.nl Tue Jul 8 16:29:25 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 08 Jul 2003 22:29:25 +0200 Subject: A story about Python... sort of References: Message-ID: >>>>> "Russell Reagan" (RR) wrote: RR> "Bob Gailer" wrote >> Physically impossible? or impractical. If it can be solved by Turing >> machine computation then it is physically possible, even though it might >> take more time/resources than anyone cares to expend. The Turing machine will only use a finite part of it, otherwise the computation will not finish. However, you don't always now how big that part will be. RR> Or more time and resources than anyone has, which would make it impossible, RR> for now. Both problems can be solved by stopping when space is exhausted, waiting until technique has evolved enough to upload the state of the computation to the new extended hardware etc. Of course this still stops it when you (or your successors) have used up the whole universe or have reached the end of the universe. In that sense it could be physically impossible. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From bokr at oz.net Sat Jul 26 18:03:59 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 22:03:59 GMT Subject: How safe is modifying locals()? References: Message-ID: On Sat, 26 Jul 2003 15:20:24 GMT, Paul Paterson wrote: >Stefan Schwarzer wrote: > >> Hi Paul >> >> Paul Paterson wrote: >> >>> This is a very interesting (and Pythonic) approach, thanks for >>> suggesting it! This is certainly what I would try to do if I were >>> writing the code from scratch. It may be possible to construct a >>> "namespace" type object which gets passed to the function. >> >> >> I think the most common way to make a namespace in Python is > > > >Thanks, the bare namespace class is essentially what I am going to try. > >> >> Of course, if you have a better name for your container, that's even >> better. Think of Ian's Point example. :-) > >I think you may have missed my original post; I am writing a generic VB >to Python converter so generating good names based on code intent would >be pretty tough! Perhaps in v2.0 ;) > >My current thinking is (for the orignal example of changing one >variable, 'y' but not another, 'x'), > >class Namespace: pas > ># ByVal arguments passed directly, ByRef via a namespace >def change(x, byrefs): > x = x + 1 > byrefs.y = byrefs.y + 1 > >ns = Namespace() # The local namespace >ns.x = 0 >ns.y = 0 >change(ns.x, ns) ># Now ns.x = 0, ns.y = 1 > This looks readable, to me ;-) But it is not pointer semantics, since you have to know the name for y inside change. It will be nice and fast if you can use the above, but if not, in some cases, class NSP below will let you use it just like Namespace above, though with pointer features if you need them. I just wanted to throw in here that the namespace approach will also let you use properties (there's a handy builtin to create them from accessor methods, or you can instantiate them from your own descriptor classes) as your byrefs "variables" if you like. You just have to mane the NameSpace class inherit from object, to make it a new-style class. Then you can add properties either right in the class definition or later by setting class attributes , e.g., >>> class Namespace(object): pass ... >>> ns = Namespace() >>> ns.x = 123 >>> Namespace.p = property(lambda self:'Read is only access function specified here') Note that the above was *not* setting an instance attribute with ns.p = property(...) >>> ns.x 123 >>> ns.p 'Read is only access function specified here' >>> ns.x = 456 >>> ns.p = 789 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute >>> del ns.p Traceback (most recent call last): File "", line 1, in ? AttributeError: can't delete attribute So you can define a kind of constant, or have any side effect you want for setting, getting, and deleting. Note that normal class attributes are shadowed by instance attributes, e.g., >>> ns.x # from last assignment 456 >>> Namespace.x = '456000' >>> ns.x 456 >>> del ns.x # deletes ordinary instance attribute >>> ns.x # and if instance attribute is absent, it will be looked for in class '456000' Actually it is a little more complicated than that, since it has to be determined that there is not a data descriptor/property in the class overriding the instance variable access. That's why I said "normal" ;-) A namespace for variables also gives you the potential to define methods for the name space itself. Here is an example with a name space that has an internal pointer class and lets you create "pointers" to the "variables" in the namespace, using ns[vname] syntax, which goes to the __getitem__ method of the class to make a "pointer" (__slots__ hopefully just makes pointer instances better optimized): >>> class NSP(object): ... """NSP defines name space with "pointer" creation via p = ns[vname]""" ... class Ptr(object): ... """Ptr instance holds ns ref and vname for access to ns.vname""" ... __slots__ = 'ns', 'vname' ... def __init__(self, ns, vname): self.ns=ns; self.vname=vname ... def __getitem__(self, i): ... """typical: x=p[:]""" ... return getattr(self.ns, self.vname) ... def __setitem__(self, i, v): ... """Typical: p[:] = x""" ... setattr(self.ns, self.vname, v) ... def __delitem__(self, i): ... """Typical: del p[:] # deletes what's pointed to""" ... delattr(self.ns, self.vname) ... def __getitem__(self, name): ... """Make "pointer." Typical: p2x = ns['x']; p2x[:] => ns.x""" ... return self.Ptr(self, name) ... >>> ns = NSP() >>> ns.x = 123 >>> ns.y = 456 >>> def change(x, py): ... x = 'new x?' ... py[:] = 'new via py[:]' ... >>> ns.x 123 >>> ns.y 456 >>> change(ns.x, ns['y']) # on the fly &y >>> ns.x 123 >>> ns.y 'new via py[:]' >>> You can also save a "pointer" and use it later, or pass it around: >>> px = ns['x'] >>> px[:] 123 ( [:] is just sugar, since the arg is ignored. [0] will run faster, since no slice object is needed) >>> px[0] 123 >>> px[0] = 'new x value' >>> ns.x 'new x value' >>> Establish some new values: >>> ns.x = 123; ns.y = 456 >>> ns.x, ns.y (123, 456) An important distinction from using explicit byref attribute names (e.g. byref.y) in change(): >>> change('byvalue', px) # note we are passing px in the py parameter position >>> ns.x, ns.y ('new via py[:]', 456) I.e., change was passed a "pointer" it thought of as pointing to y (i.e., was named "py" by the programmer to suggest the meaning), but it pointed to x, and so x changed when py[:] was assigned to. Changes to 'byvalue' were just local to change, as expected. We can also delete an attribute via the pointer: >>> del px[0] >>> ns.x Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NSP' object has no attribute 'x' which doesn't affect the "pointer" itself: >>> px[0]='an x again' >>> ns.x 'an x again' but of course deleting the pointer itself as opposed to px[0] will: >>> del px >>> ns.x 'an x again' >>> px Traceback (most recent call last): File "", line 1, in ? NameError: name 'px' is not defined i.e., the pointer got deleted, not the thing pointed to. I'm not necessarily recommending any of the above, but I thought it might give you some ideas. There is definitely a performance hit in px[:] (or better, px[0]) vs byref.x to consider. Anyway, I thought properties and descriptors might also come in handy somewhere in your quest ;-) Raymond Hettinger has written a nice "How-To Guide for Descriptors": http://users.rcn.com/python/download/Descriptor.htm and for properties (follow Table Of Contents link in below page) and much more there is http://www.python.org/2.2/descrintro.html HTH Regards, Bengt Richter From cybersamurai at mac.com Tue Jul 8 15:49:30 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Tue, 08 Jul 2003 16:49:30 -0300 Subject: id = -1 in wxpython Message-ID: <3F0B204A.20004@mac.com> id -1 for some object mean that this object have a default id, but how I can work with this kind of id? From alan.gauld at btinternet.com Mon Jul 21 03:24:02 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Jul 2003 07:24:02 GMT Subject: Newbie Questions? References: <504413fa.0307200626.3fceb85a@posting.google.com> <9a410299.0307201513.7ba29781@posting.google.com> Message-ID: <3f1b94b1.432205849@news.blueyonder.co.uk> On 20 Jul 2003 16:13:15 -0700, klappnase at freenet.de (klappnase) wrote: > KodeKruncherDude at aol.com (Adam Petrosh) wrote in message news:<504413fa.0307200626.3fceb85a at posting.google.com>... > > Hail all. Are newbie questions allowed here, or is there a different > > Newsgroup for that? Thanks. > > I think you may ask whatever you want, seems like you are not the only > one around here. But its worth also giving a plug to the python-tutor mailing list which is specifically for newbie questions... :-) Join via the python web site - communities - mailing lists. Alan g Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From donn at drizzle.com Sun Jul 13 23:40:05 2003 From: donn at drizzle.com (Donn Cave) Date: Mon, 14 Jul 2003 03:40:05 -0000 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <1058154004.286325@yasure> On Sun, 2003-07-13 at 20:32, Aahz wrote: > In article , |> Ian Bicking wrote: |>> |>> (Admittedly, some confusion may occur because these very different |>> operations use the same syntax: |>> |>> x = 10 |>> x[0] = 10 |>> obj.x = 10 |>> |>> The second and third are entirely different from the first.) |> |> No, they aren't. They are precisely the same; they just have different |> assignment targets. | | Sure they are different. The first is a primitive operation binding the | variable x. The second gets x, and calls x.__setitem__(0, 10), and the | third is equivalent to setattr(obj, 'x', 10). I wonder if this is a good example of a mutability thing that really is kind of missing to the detriment of Python. If you want to support user-implemented sequences (as Python does) but make Aahz's ``precisely the same'' assertion true in the sense you're taking it - then I think the user-implemented indexing function would have to return a reference to the index location. class UserArray: ... def __item__(self, index): return &self.internal_array[index] userArray[5] = 1 (python internal) loc = UserArray.__item__(userArray, 5) *loc = 1 if userArray[6] == (python internal) loc = UserArray.__item__(userArray, 6) return *loc There are other places where instead we use some kludge with a mutable container type, but in this case I don't think there's a way to get around it. So whether we like the idea or not, assignment to a user-implemented sequence doesn't have to involve any assignment at all, because Python lacks the "pointer" type (or "target" type, if you prefer) that would be required to implement that. Donn Cave, donn at drizzle.com From mcfletch at rogers.com Sun Jul 20 06:54:18 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 20 Jul 2003 06:54:18 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: <3F1A74DA.6000703@rogers.com> Beni Cherniavsky wrote: >Mike C. Fletcher wrote on 2003-07-19: > > > >> * finally, stores the value >> o tries to do what would have been done if there were no >> descriptor (with the new, coerced value) >> o does *not* create new names in the object's namespace (all >> names are documented w/ descriptors, there's not a lot of >> '_' prefixed names cluttering the namespace) >> o does *not* require a new dictionary/storage-object attribute >> for the object (the descriptor works like any other >> descriptor, a *stand-alone* object that replaces a regular >> attribute) >> >>It's that last part that I'd like to have a function/method to >>accomplish. That is, store (and obviously retrieve as well) attribute >>values for objects, instances, types, classes, __slot__'d instances, >>etceteras under a given name without triggering any of the __setattr__ >>machinery which defers to the __set__ method of the associated descriptor. >> >>I can work around the problem by violating either of those two bullet >>points under "finally, stores the value", but I'm looking for something >>that *doesn't* violate them. See below for responses to particular >>points... >> >> >> >I didn't grasp your precise problem but I've been having some similar >problems (without metaclasses however). Two tricks: > >- Insert a dummy class into you heirarchy between object (or whatever > other superclass that doesn't have the properties yet and the class > where you install the properties. Then you might be able to use > this class to access the underliying class dict without being > intercepted by the properties. [I recall some problems with > properties vs. super, didn't follow them closely]. > This violates the "does *not* require a new dictionary/storage-object attribute" constraint. The super-class is just another way of spelling "special place to store data" within the class instance, albeit a nicely evil one :) . I'm looking for something that doesn't require modifying classes to be property-aware just to add the properties, that is, a stand-alone property object should be able to do this stuff w/out requiring that the client objects know about the properties at all. >- If you use __slots__, they are also implemented as properties. So > if you define properties with the same name in the same class, you > lose all access to the raw slots. The solution is similar: define > __slots__ in a superclass, hide them with properties in a sublass. > See http://www.technion.ac.il/~cben/python/streams.py for an > example. > Will look it up. Basically, I'm not too worried about slotted instances yet. I just think it should be part of whatever general solution Guido figures is best. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tomas at fancy.org Fri Jul 4 19:25:23 2003 From: tomas at fancy.org (Tom Plunket) Date: Fri, 04 Jul 2003 16:25:23 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: <3b2cgvkod9cgnpm5a3noglm3qtp166t0re@4ax.com> Jack Diederich wrote: > I would make countdown dumber, and make the call more explicit > > def countdown(thismany) > for (i) in range(thismany): > yield False > yield True > while True: > yield False Hmm. What's the yield doing here? I can't find anything on it in the PQR which has pretty much become my reference of choice for Python. I can guess at its function from what I know about other languages, but ... hmmm. Doesn't seem like what I want really, and how would I restart it? I'm guessing that yield is akin to return here but the next time the function is called, program flow resumes at the yield, but... Yeah, I'm not really sure how this solves my problem. > But I'm not sure if this is what you really want, the countdown() > keeps going even after it has fired. Hence the 'While True: > yield False' Right- maybe a similar solution (three return values) that would allow me to pop the "finished" countdowns off of a stack or something. thanks for your help. -tom! From jjl at pobox.com Thu Jul 10 21:26:53 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Jul 2003 02:26:53 +0100 Subject: for in sequence problem... possible new operator to add to python References: <3F0DE61E.1F38C291@engcorp.com> Message-ID: <87d6ghhmzm.fsf@pobox.com> Peter Hansen writes: > sismex01 at hebmex.com wrote: > > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > When you iterate over a dict in recent versions of Python, you [...] > Sorry, perhaps I should stop using the term "iterate" for its > more widely known generic meaning of visiting each item in a > sequence one at a time, and restrict my usage only to those > cases where in Python I'm talking about an actual "iterator" > object. > > ("Iterate" was a very general term... it would be a shame if > one could no longer use it as such.) I think you're correct even in the strict Python sense of the word 'iteration'. Objects (eg. dicts and lists) that are not themselves iterators can still support iteration. Section 2.2.5 from the 2.2 library reference: Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. ... John From theller at python.net Wed Jul 23 13:45:07 2003 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jul 2003 19:45:07 +0200 Subject: XML parser and py2exe References: <84fc4588.0307200721.970b9d9@posting.google.com> Message-ID: <4r1dkuho.fsf@python.net> pythonguy at Hotpop.com (Anand Pillai) writes: > I am using the expat parser in the 'xml.parsers.expat' module in > my code. The code works well as source, but the py2exe executable created > using it does not. I get the following traceback. > > Traceback (most recent call last): > File "", line 146, in ? > File "imputil.pyo", line 103, in _import_hook > File "", line 52, in _import_top_module > File "imputil.pyo", line 216, in import_top > File "imputil.pyo", line 271, in _import_one > File "", line 128, in _process_result > File "HarvestManConfig.pyo", line 110, in ? > File "imputil.pyo", line 103, in _import_hook > File "", line 52, in _import_top_module > File "imputil.pyo", line 216, in import_top > File "imputil.pyo", line 271, in _import_one > File "", line 128, in _process_result > File "HarvestManXMLParser.pyo", line 12, in ? > File "imputil.pyo", line 132, in _import_hook > File "", line 70, in _finish_import > File "imputil.pyo", line 318, in _load_tail > ImportError: No module named _xmlplus.parsers The released version of py2exe isn't able to handle PyXML correctly. Although the current CVS version can do it. If you can build it yourself, you should try it. I'm hesitating to make a new release at the moment because I hope to solve the Python 2.3 problems, and also I have got a patch from Mark Hammond for inproc com servers, which I would like to integrate. Thomas From jjl at pobox.com Thu Jul 10 08:51:22 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Jul 2003 13:51:22 +0100 Subject: A story about Python... sort of References: <3F0A0655.99823E25@alcyone.com> <87smphp2in.fsf@pobox.com> <2259b0e2.0307091344.73040406@posting.google.com> Message-ID: <874r1u5yut.fsf@pobox.com> mis6 at pitt.edu (Michele Simionato) writes: [...] > Why do you disagree? I would think Erik is right. Off-list, please! (yeah, I'm a hypocrite) John From staschuk at telusplanet.net Thu Jul 31 02:06:59 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 00:06:59 -0600 Subject: time, calendar, datetime, etc In-Reply-To: <153fa67.0307300326.45a29380@posting.google.com>; from kylotan@hotmail.com on Wed, Jul 30, 2003 at 04:26:39AM -0700 References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <20030731000659.B2806@tibia.amotlpaa.bogus> Quoth Kylotan: [...] > And does datetime.timetuple() actually return something equivalent to > a struct_time as used by the time module? At first glance this looks > to be true, but it isn't clearly documented as such. Isn't it? timetuple() Return a 9-element tuple of the form returned by time.localtime(). > Personally I think 2 separate modules (1 high level, 1 low level > corresponding to the C api) would suffice, or even to combine it all > into one coherent module. Is there any benefit to the status quo that > I am missing? The bulk of the calendar module deals with creating and printing strings and arrays representing calendar months. Hardly general-purpose; I wouldn't want to see such things in the datetime module. The exception, as you noted, is calendar.timegm(), which, indeed, the docs describe as "unrelated but handy". > PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S %Y')' as a > reverse-asctime(), and was surprised that I couldn't find this wrapped > in a function in any of the modules. Maybe such a function would be > considered for future addition? Maybe indeed. One consideration here is that the time module is, I think, intended simply as a wrapper over the underlying C API. Afaik that API doesn't have convenience inverses of gmtime or asctime. -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jul 5 06:57:24 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 05 Jul 2003 12:57:24 +0200 Subject: Collective memory In-Reply-To: References: Message-ID: <3f06af11$0$49113$e4fe514c@news.xs4all.nl> Charles Shannon Hendrix wrote: > Python uses it for actually determining the logic in your program, which > IMHO is dangerous. > > if > > > > > Is part of the if statement, or did someone with different > tab settings from the author make a mistake and align it accidentally? To catch such mistakes, Python has the -tt command line option: -t : issue warnings about inconsistent tab usage (-tt: issue errors) There's also tabnanny.py in the standard library to check things before executing code. I'm not sure, but I suspect that PyChecker also checks this. --Irmen From staschuk at telusplanet.net Sun Jul 20 14:04:20 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 20 Jul 2003 12:04:20 -0600 Subject: classes In-Reply-To: ; from pablo@bogus.domain.org on Sun, Jul 20, 2003 at 02:30:11PM +0200 References: Message-ID: <20030720120420.A438@tibia.amotlpaa.bogus> Quoth Pablo: > [cut] > >> 2) how to declare a static method > > > > class HasStaticMethod: > > def method(arg0, arg1): # note the lack of "self" > > # do something with arg0 and arg1 > > method = staticmethod(method) > > That's not exactly what I wanted. [...] > but Python does not allow to invoke any class method without providing an > instance of the class object Sure it does. Allowing that is the purpose of the "staticmethod" call in Dan's example. Try it yourself: >>> class HasStaticMethod(object): ... def mystaticmethod(x, y): ... print x, y ... mystaticmethod = staticmethod(mystaticmethod) ... >>> HasStaticMethod.mystaticmethod(3, 4) 3 4 No instance of HasStaticMethod exists here. [...] > So my problem would be solved if I could create a class which would be > seen only in its module (something like private class). Then I could > create an object and simply use it across my application. [...] > Is it possible to create a class and forbid its use outside its module? No, not really. (There's a philosophical reason: Java encourages the attitude that other programmers can't be trusted to use your code correctly, while Python encourages the attitude that other programmers know what they're doing. Thus there's not a lot of mechanisms in Python to forbid other programmers from doing things with your code.) For the particular problem you're interested in -- singletons -- here are a few approaches: First, use __new__ trickery: _the_instance = None class MySingleton(object): def __new__(self): global _the_instance if _the_instance is None: _the_instance = object.__new__(self) return _the_instance Example use: >>> x = MySingleton() >>> y = MySingleton() >>> x is y # same object! True In this approach, users create instances of MySingleton as they would for any other class (rather than by calling a getInstance classmethod) -- that action just happens to return the same object always. One gotcha with this approach can be observed by adding def __init__(self): print 'running __init__ on instance %s' % id(self) Then we see >>> x = MySingleton() running __init__ on instance 1075795852 >>> y = MySingleton() running __init__ on instance 1075795852 >>> x is y True As shown, each "instantiation" runs __init__ on the single instance again. If you have initialization which should occur only when the single instance is actually created: _the_instance = None class MySingleton(object): def __new__(self): global _the_instance if _the_instance is None: _the_instance = object.__new__(self) _the_instance._my_init() return _the_instance def _my_init(self): pass # one-time initialization here (Another possible issue with this approach arises when subclassing MySingleton. Details left as an exercise.) Second approach: Use a metaclass. See Third: forget about singletons and use a Borg. See (With Borgs, multiple instances may exist, but they share state.) Fourth: rethink the idea that a database connection should be a singleton. See and linked pages for discussion on the merits of singletons. -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From peter at engcorp.com Mon Jul 14 14:35:19 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 14:35:19 -0400 Subject: Using xml.xpath question. References: <23891c90.0307110057.bbe91e3@posting.google.com> <23891c90.0307140145.8d9ff70@posting.google.com> Message-ID: <3F12F7E7.1DFB98BA@engcorp.com> Paul Boddie wrote: > > hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > > > > A very nice and helpful Paul Boddie in action on c.l.p. > > Glad to be of some help. ;-) > > > But OMFG! > > Object Management F Group? First words are "Oh My", while last word references one's personal deity. The F word is left to personal choice as well. ;-) -Peter From aahz at pythoncraft.com Sun Jul 13 10:37:01 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 10:37:01 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: In article , Stephen Horne wrote: > >One of the few things I hate about Python is that mutable objects are >implicitly shared using a reference system whereas immutable objects >are not. Well, that's incorrect. *ALL* Python objects are implicitly shared with bindings. The difference is whether updating the value referenced by a target requires *re*binding the target or simply updating an object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From FBatista at uniFON.com.ar Fri Jul 4 11:01:38 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 4 Jul 2003 12:01:38 -0300 Subject: sys.setedefaultencoding() Message-ID: Very strange (never happende to me before): Learning (and needing it) Unicode, in Dive Into Python found the sys.setedefaultencoding() method. Very nice, but in the documentation of the 2.2.1 version, says that this method is new in 2.0 version. I've got installed Python 2.1.1 and when I do dir(sys), don't get that method!! Strange. And ugly, :( So, two questions: - Why this happens? - How can I, by a different method, set the default encoding? Thanks a lot. Facundo Batista Gesti?n de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 From tl_news at nexgo.de Wed Jul 30 13:03:49 2003 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 30 Jul 2003 19:03:49 +0200 Subject: Syntax: pointers versus value References: <3F27F673.3000801@mathstat.concordia.ca> Message-ID: On Wed, 30 Jul 2003 12:46:43 -0400, Danny Castonguay wrote: Hi! > Clearly, "listB = listA" >creates the problem. listB and listA become two pointers to the same >object. Exactly. > How then, do I duplicate the two objects; ie make a copy of the > object that listA is pointing to and have listB point to that object. Use: listB = listA[:] Cheers, Tino From hokiegal99 at hotmail.com Sun Jul 6 16:32:37 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sun, 06 Jul 2003 16:32:37 -0400 Subject: Using Loops to track user input Message-ID: I don't understand how to use a loop to keep track of user input. Could someone show me how to do what the program below does with a loop? Thnaks! ---------------------------- #Write a program that reads 10 numbers from the user and prints out the sum of those numbers. num0 = input("Enter a number: ") num1 = input("Enter a number: ") num2 = input("Enter a number: ") num3 = input("Enter a number: ") num4 = input("Enter a number: ") num5 = input("Enter a number: ") num6 = input("Enter a number: ") num7 = input("Enter a number: ") num8 = input("Enter a number: ") num9 = input("Enter a number: ") num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9 print num ---------------------------------- From Scott.Daniels at Acm.Org Sat Jul 19 14:07:14 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 19 Jul 2003 11:07:14 -0700 Subject: compiling mysql-python for python 2.3 on windows In-Reply-To: References: Message-ID: <3f197727$1@nntp0.pdx.net> Achim Domma wrote: > Hello, > > I need mysql-python for python 2.3 on windows. I downloaded the source and > tried to build it myself, but I get linker errors: > > mysqlclient.lib(password.obj) : error LNK2001: unresolved external symbol > __ftol2 > > The problem seems to be, that the mysql lib is build with VC7, but distutils > tries to compile with VC6 (which are both on my machine). Can I force > distutils to use VC7? Or has somebody prebuild binaries for windows? Or has > somebody another hint on how to get it working on windows? I have also mingw > 3.2 installed, if it would be helpfull!? > > regards, > Achim At least by rc1, 2.3 distutils supports VC 7.1. Perhaps that fix will allow VC7, and perhaps not. Check the newest distutils docs anway. -Scott David Daniels Scott.Daniels at Acm.Org From intentionally at blank.co.uk Mon Jul 14 01:10:03 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 06:10:03 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> On 13 Jul 2003 21:03:59 -0700, owski at hotmail.com (Adam Ruth) wrote: >I don't see the arbitrary change. Python has one type of variable: A >pointer that cannot itself be dereferenced. It's much more consistent >then having 3 types of variables (in C++). I answered most of these arguments elsewhere (significantly with an admission of stupidity) but your assertion here about C++ is wrong. C++ has precisely one type of variable. That variable is a placeholder for a value of a datatype which is specified in the declaration. The datatype may be a pointer datatype, but so what? Pointer datatypes are not treated any differently than other datatype except that they, like all datatypes, they have their own set of functionality. C++ references are tellingly also called self-dereferencing pointers. They are not a distinct concept - they are syntactic sugar. I suspect they mainly arise out of the modern desire to disguise pointers and fantasize that they're not there, though they certainly work very well in certain contexts. >> One way or the other, Python is currently choosing not to respect the >> computer science definition of those terms. It may have historic and >> backward-compatability reasons, but that does not change the facts. >> This deviation from computer science definitions, whatever the excuse, >> is arbitrary, confusing and error prone. That is my problem. > >It's not respecting the static language definitions of those terms, >but it shouldn't even try. There are different meanings for those >words in mathematics, but you wouldn't try to express those >definitions in terms of C, it would be equally frustrating. The >static definitions are merely abstractions of the mathematic meanings, >and the dynamic meanings are also abstract, but in a different >direction. Funny thing. When I use algebra, the variables I define don't end up referring to different values, functions or whatever unless I explicitly redefine them. When I write a definition on one piece of paper, the things I wrote earlier on another sheet don't change. Seems to me that the math equivalent of assignment (defining named things) works very much like the 'static language definitions' as you put it. From jon+usenet at unequivocal.co.uk Fri Jul 11 05:07:21 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 11 Jul 2003 09:07:21 GMT Subject: Sample Web application References: Message-ID: In article , Ian Bicking wrote: > FWIW, I spent a lot of time trying to get those two lines to work, > ultimately failing (it was a while ago, so I'm afraid I can't expand). > It's entirely possible I was trying too hard and making it more > complicated than it was... but configuring Apache in general is a pain, > because diagnostics for that sort of configuration are largely > nonexistent, you simply get incorrect behavior. Or maybe I got Apache > right, but the file layout wrong. Whichever. Certainly mod_rewrite can be difficult to get right. The redeeming feature is RewriteLog which if you set it up to level 9 temporarily while debugging means it is usually pretty clear what to do. > My problems with FastCGI have been largely the same. It shouldn't be > complicated, but somehow manages to be so anyway. The multitudes of > FastCGI-reimplementors can't all be wrong, can they? ;) I've definitely never found it complicated, there's a lot of server options you can tweak but I've never needed to change any of them. It's 1 line in the httpd.conf to say when to use the fastcgi handler. Mind you, I have a habit of finding problems in things hundreds of thousands of people have used without trouble also, so YMMV ;-) From kth at srv.net Mon Jul 7 18:16:22 2003 From: kth at srv.net (Kevin Handy) Date: Mon, 07 Jul 2003 16:16:22 -0600 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: <3F09F136.6060000@srv.net> Cameron Laird wrote: > In article , > Bob Gailer wrote: > . > . > . > >>This brings back the good old days of FORTRAN IV which had a >>single-statement IF and no ELSE. Thus: >> C = VALUE1 >> IF ( A .EQ. B) C = VALUE2 >>Notice the indentation. Cols 1-5 were reserved for line # and col 6 for the >>continuation code. So Python is not the only indentation dependent >>language. Nor is it the first to use indentation to convey structure. > FORTRAN isn't indentation dependent, it is position dependent. There is a big difference between the two. In FORTRAN, certial columns were allocated to specific purposes. 1-5 for the line number, 6 for comment/continuation, 7-75 for the program line, 76-80 for sequence numbers. [iirc] If you want a language that was even more position dependent than fortran, look at RPG-II. You used printed forms for programming to get the columns correct. One character in the wrong column would change the meaning of that line. In PYTHON, it is the indentation itself that matters, not the actual column position. > . > . > . > Maybe youngsters don't realize this. > > One monotonous but unremitting argument that Python inspires > is about the wisdom of its white-space-significance (WSS). > Modern programmers might not realize how strongly old-timers > associate WSS with early FORTRAN and COBOL (as we capitalized > them then), and how unpleasant some of those memories are. > *That*, I assume, is why WSS discussions become as heated as > they do. From trash at kjn-law.de Thu Jul 3 04:46:05 2003 From: trash at kjn-law.de (Theodor Rash) Date: Thu, 03 Jul 2003 10:46:05 +0200 Subject: Good code patterns in Python References: <3f027b11$0$97204$edfadb0f@dread12.news.tele.dk> Message-ID: Andrew Bennetts wrote: > > if cond: > x = special_val > else: > x = some_val > > can be "read" more-or-less directly into English: "if the condition is > true, then 'x' is set to 'special_val'; otherwise, 'x' is set to > 'some_val'". > Saying "'x' is set to 'some_val'. Now, if some condition is true, 'x' is > set to 'special_val'" is counter-intuitive to my way of thinking. > > That said, I can readily recognise both idioms (despite having a slight > preference for one form), so it's really a non-issue... > ACK, but I'd like to add an additional aspect: If the if-statement should work as a real switch, that is: one branch or the other of two equivalent branches, than it should be coded in a way that the reader recognizes the switch at first glance, with if/else. If the condition is brought into the code to fit some rare exception, for example to meet some hardware requirements that might get obsolete and thrown out again in a later stage of maintenance, then the form 'x' is set to 'special_val' is the right way, IMHO. But it should be accompanied with a comment that indicates the purpose of that piece of code. Anyway, instead of speculating about how some other programmer might perhaps interpret the code that I wrote, I give him an explicit comment and I'm done. (Saw this sig somewhere: 'Comment my code?? Why do you think they call it code?') Theo From borcis at users.ch Thu Jul 31 11:31:36 2003 From: borcis at users.ch (Borcis) Date: Thu, 31 Jul 2003 17:31:36 +0200 Subject: Announcing issue 2 of The Agile Developer's Life free eZine References: Message-ID: <3F293658.3030609@users.ch> DevCoach wrote: > I have just published the second issue of The Agile Developer's Life > (formerly called The Agile Life) How much of Rumsfeld's special vocab does it port to computer programming ? From ee01b092 at ee.iitm.ernet.in Wed Jul 16 23:53:18 2003 From: ee01b092 at ee.iitm.ernet.in (Vinoo Vasudevan) Date: 16 Jul 2003 20:53:18 -0700 Subject: Securing the Pyton Interpreter? References: Message-ID: <45f7ff62.0307161953.1e33bb1@posting.google.com> Stephen VanDahm wrote in message news:... > I'm looking for a way to install Python on a UNIX machine in a way such > that any user on the system can use it, but only to execute scripts that > are located in a certain directory. I do not have root access on the > machine that will be running Python, so my options are limited. I thought > about hacking the Python interpreter itself so that it will examine the > argument array and exit with an error if the script to be executed isn't > in the appropriate directory, but this seems pretty risky. The module > 'site.py' is imported automatically upon initialization -- I've thought of > adding the check there instead. I don't think either of these solutions > are very elegant. Is there a better way? > > Thanks for your time, > > Steve VanDahm > vandahm at norge.freeshell.org Hi, Hacking the interpreter seems like overkill. Why not just set up a shell script containing the names of the allowed python scripts, and execute it from there. for example: #!/usr/bin/sh if "$1" in myscript1.py myscript2.py ....; then . /usr/bin/env python "$1" else echo "You can't execute that script." fi My shell scripting is a little rusty so there may be some errors, but I hope you get the general idea. Hope it's useful, Vinoo From skip at pobox.com Mon Jul 28 09:51:27 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 08:51:27 -0500 Subject: How to get success/failure in case of thread In-Reply-To: <20030728175542.A23857@cs.unipune.ernet.in> References: <20030728175542.A23857@cs.unipune.ernet.in> Message-ID: <16165.10847.483917.787182@montanaro.dyndns.org> vivek> import thread vivek> thread.start_new_thread(my_func,(args,)) vivek> here my_func will return true/1 on success and false/0 on vivek> failure. How can I check whether the function failed/succeeded vivek> ??? Have the function (or a wrapper function) put() the return value on a Queue object, then get() it from there. Skip From bgailer at alum.rpi.edu Thu Jul 24 15:26:23 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 24 Jul 2003 13:26:23 -0600 Subject: Mystery Theater New Style Classes In-Reply-To: References: Message-ID: <5.2.1.1.0.20030724132523.01d6d398@66.28.54.253> At 02:26 PM 7/24/2003 -0400, Terry Reedy wrote: >"Bob Gailer" wrote in message >news:mailman.1059062857.29503.python-list at python.org... > > Predict the output: > > > > class A(int): > > classval = 99 > > def __init__(self, val = 0): > > if val: > > self = val > > else: > > self = A.classval > >I am not sure what the point is. However, > >1. Rebinding the local variable 'self' (or any other local variable) >only affects further code within the function, which there is not any. >So the above conditional is equivalent to 'pass'. > >2. Because ints are immutable, the value of a new int is set within >int.__new__, which is not overwritten. Thus, the above __init__ is >irrelevant. In particular, the value of an A object has nothing to do >with the defaulted parameter 'val=0'. > > > a=A(3) > >3. This is equivalent to a=int(3). No surprises. > > > b=A() > >4. This is equivalent to b = int(). I thought this might raise an >exception. But after seeing the result (0). I remember Guido's >decision (and a recent PyDev discussion thereof) that callable builtin >types should, if possible, return a null value when getting a null >input. Hence > > >>> int(), long(), float(), tuple(), list(), dict() >(0, 0L, 0.0, (), [], {}) > > > print a,b >3,0 > >5. Result is same if 'val=0' is changed to 'val=9' or anything else. > > > [from OP's self followup] The question this leads to is: how does >one access the value of such a class within a class method? > >Since there is no class method presented, this make not much sense. >Bob: were you aware of 4.) above when you posted this? There's a lot I was not aware of. Your reply and Bengt's have givem me what I needed. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From marc.engel at recif.com Wed Jul 30 09:59:47 2003 From: marc.engel at recif.com (Marc ENGEL) Date: 30 Jul 2003 06:59:47 -0700 Subject: pythoncom: STA python COM server randomly does not receive event from other objects : deadlock References: <6411841c.0307300119.46bc0159@posting.google.com> Message-ID: <6411841c.0307300559.74557d9a@posting.google.com> I'd like to add that just setting the Python COM object to Inproc instead of Local server makes the all thing work properly. But I need a Local server... It works without modifying a line of code! Marc marc.engel at recif.com (Marc ENGEL) wrote in message news:<6411841c.0307300119.46bc0159 at posting.google.com>... > Hi all, > > I coded a python COM object that runs in a pythonw local server as a > STA. > > This object creates and advises a VC++ COM object to receive its > event. Those events are sent by worker threads. > > The VC++ object is free threaded. As a consequence call between my STA > python object and apartment are marshalled through proxy. > > The python COM object regularly calls a blocking method on the VC++ > object to synchronize. But, as it is a cross apartment call, during > the call it can gets the event handler called thanks to the message > pump operated by COM. > > But sometimes events are no received and it seems that I enter a > deadlock. > When I attach to the VC+ object, I can see that the thread that made > the Fire_XX is still waiting for the call to end. > > Does somedy know the reason? > > Does the COM message pump may be different from the pythoncom message > pump located in localserver.py : pythoncom.PumpMessages ? > > Thanks in advance for any hint, because this is a very blocking issue > for my project. > > Marc From staschuk at telusplanet.net Thu Jul 17 20:04:13 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 17 Jul 2003 18:04:13 -0600 Subject: Recursion in compile() In-Reply-To: <781faf41.0307171037.142956f6@posting.google.com>; from naren@trillium.com on Thu, Jul 17, 2003 at 11:37:11AM -0700 References: <781faf41.0307161629.6295618b@posting.google.com> <781faf41.0307171037.142956f6@posting.google.com> Message-ID: <20030717180413.B931@tibia.amotlpaa.bogus> Quoth Narendra C. Tulpule: [...] > I was trying something like > cobj = compile('eval(src_code)', ...) > eval(cobj) > And that complains about syntax error (because I am trying to define a > function within eval string?) That would do it -- with a string argument, eval only does expressions, not statements (and so in particular, not def statements). Try compile('exec src_code') instead. -- Steven Taschuk staschuk at telusplanet.net Every public frenzy produces legislation purporting to address it. (Kinsley's Law) From intentionally at blank.co.uk Thu Jul 17 14:11:13 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 17 Jul 2003 19:11:13 +0100 Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> <20030716160013839-0600@news.xmission.com> <20030716180329385-0600@news.xmission.com> Message-ID: <7lmdhv4id47rfluluvbbl70s0obfk18prc@4ax.com> On Thu, 17 Jul 2003 00:03:38 +0000 (UTC), Adam Ruth wrote: >Anyway, glad we cleared that up. Sorry about misrepresenting you, I >really thought you were talking about Python. In retrospect, my >metaphor wasn't very clear. And in restrospect, I appologise too - of course the disguising pointers thing was about Python and the fact that people *do* fake pointers. But the "when you really can't avoid pointers" had no place being carried over as in Python you can avoid pointers (including faked pointers). I should have though about that before replying - what I didn't state, I certainly did imply and wrongly. Sorry again. >I don't see it as a side effect, I see it as the core design. >References are a very concrete type, they happen to be implemented as >pointers in C. In Java they're not implemented as pointers, I'm not >sure what they're implemented with, but it isn't pointers. In that case >it must pass by reference (ala Java), but the semantics in Python of >passing references by value is maintained. The terms 'pointer' and 'reference' are actually different names for essentially the same thing - an indirect way of accessing something else. The distinction between the terms is somewhat artificial, and the meanings vary according to your background. For example, the ML 'reference' would probably be called a pointer by a C++ programmer as it requires explicit dereferencing using a dereference operator. But note the word 'reference' embedded within 'dereference', even when applied to a pointer. Different name, different syntactic quirks, but basically the same thing. It's just that references (as in things that don't need explicit dereferencing) tend to limit errors simply by limiting the ways you can use them. I just got tired of typing 'pointer/reference'. At some point, however, there must be some kind of manipulation of hardware addresses - maybe in the implementation of the language, maybe in the next layer down, or whatever. Even if you use a C fixed-size array, the implementation in assembler is using essentially pointer math to implement it. That pointer math is so exposed in C, actually, that in most cases you can treat a pointer as an array and visa versa (sizeof being the only exception I can think of off the top of my head). Anyway, this kind of thing is not what I want from a high level language. What I would want (in the alternate universe I mentioned elsewhere) is actually a simpler version of what we already have - a mutable container that always holds exactly one item. That would do the important jobs of a pointer, but being explicitly meant the job it would cause less confusion and would have less potential for errors. Even if it were dereferenced using '[0]' that is still doing the job of a pointer. I'd simply like to see it dereferenced in a way that doesn't suggest a '[1]' or '[2]' might be used. And in some contexts, implicit dereferencing might well be the way to go. Variable parameters being an important example. >> No, my background isn't just in C - that is a long way from being the >> first language I used, and I've used Python regularly longer than C++. > >I wasn't referring to you, but to the people that come to the newsgroup >and ask questions about it. OK - sorry for taking that personally, then. From Scott.Daniels at Acm.Org Thu Jul 24 02:49:37 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jul 2003 23:49:37 -0700 Subject: python 2.2 string conversion ? In-Reply-To: References: Message-ID: <3f1f8181@nntp0.pdx.net> ken wrote: > I've been looking for a solution to a string to long conversion problem that > I've run into >>>>x = 'e10ea210' >>>>print x > e10ea210 >>>>y=long(x) > How about: y = long(x, 16) From vm_usenet at yahoo.com Wed Jul 2 04:39:40 2003 From: vm_usenet at yahoo.com (vm_usenet) Date: 2 Jul 2003 01:39:40 -0700 Subject: A possible bug in python threading/time module? Message-ID: Hi everyone, I've been running this segment of code (slightly simplified to emphasize the main part): ----START of Script---- import time import threading sem = threading.Semaphore(2048) class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) sem.acquire() def run(self): j = 0 for i in range(1000): j = j+1 time.sleep(60) sem.release() #main for i in range(4096): MyThread().start() ----END of Script---- I ran it on python 2.2.2 and python 2.3b1, and on both all of the threads started successfully, acquiring the semaphore until 0 resources were left. However, about 10-20 threads remain active after a while (and the semaphore is lacking resources, respectively). I waited for about two hours, and nothing changed - it appears to be hanging. Did anyone encounter this behaviour before? Am I the only one who ran into this situation? Is this a bug? Thanx in advance vm From allisonb at terralogicgis.com Thu Jul 17 20:43:44 2003 From: allisonb at terralogicgis.com (A.Bailey) Date: 17 Jul 2003 17:43:44 -0700 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <1c057c8e.0307171643.486e9678@posting.google.com> "Allison Bailey" wrote in message news:... > Hi Folks, > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. > > Then, I get errors when I try the following: > sh = wb.worksheets(1) > Thanks to everyone for suggestions, hints, and code, particularly the ideas about where to find more information. I know that MS Excel is not every Open Source-er's idea of a good time, but my plan is to get my data out of there as fast as I can and do the fun stuff in Python! It turns out, as some people pointed out, that after running the makepy utility, the methods become case-sensitive, so it should have read: sh = wb.Worksheets(1) and everything would have gone smooth as silk! And yes, I would love to preview Excel/Python code if you would like to pass it along to me. Allison From max at nospam.com Wed Jul 30 13:25:05 2003 From: max at nospam.com (max) Date: Wed, 30 Jul 2003 17:25:05 GMT Subject: Misuse of In-Reply-To: References: <3f27f0e3$1@news.broadpark.no> Message-ID: > You're quite right - mixing spaces and tabs when indenting is > not the thing to do. In fact, it's warned against in a number of > places. The recommended practice is to use spaces, and > avoid tabs completely. > > I think you'll find that all the modules in the standard library > use spaces exclusively. The problem with spaces is that you need to do 5 times the work of a tab to get decent-looking indentation :). From sschwarzer at sschwarzer.net Sat Jul 26 08:49:41 2003 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 26 Jul 2003 14:49:41 +0200 Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Hi Paul Paul Paterson wrote: > This is a very interesting (and Pythonic) approach, thanks for > suggesting it! This is certainly what I would try to do if I were > writing the code from scratch. It may be possible to construct a > "namespace" type object which gets passed to the function. I think the most common way to make a namespace in Python is class my_namespace: pass ... my_namespace.a = 'foo' my_namespace.b = 'bar' Such namespaces are very similar to dictionaries: my_namespace = {} ... my_namespace['a'] = 'foo' my_namespace['b'] = 'bar' but the first approach is a bit more readable. If you need many containers, you could use: class Container: pass c1 = Container() c2 = Container() ... c1.foo = 'foo' c2.foo = 'bar' Of course, if you have a better name for your container, that's even better. Think of Ian's Point example. :-) Stefan From peter at engcorp.com Wed Jul 16 11:49:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jul 2003 11:49:15 -0400 Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> <3f156c23$0$166$a1866201@newsreader.visi.com> Message-ID: <3F1573FB.8ADBE587@engcorp.com> Grant Edwards wrote: > > Though I was recently surprised > that the remove() method for lists uses "==" and not "is" to > determine what to remove. It's documented that it works that > way. But, it wasn't what I excpected, and it took me a while to > figure out that it was using my class's __cmp__ method rather > than the object ID. Probably a very good thing, considering what would happen if you were trying to remove strings from the list, rather than simple things like integers... -Peter From bokr at oz.net Wed Jul 2 16:09:47 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Jul 2003 20:09:47 GMT Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: On Wed, 2 Jul 2003 08:21:57 -0600, Steven Taschuk wrote: >Quoth Bengt Richter: > [...suggests a := b equivalent to a.__update__(b)...] >> I guess it's a matter of what kind of sugar you like ;-) > >Quite. > > [...syntactic support for Currency objects...] >> I'm not sure what that would mean. > >I meant a language like Python but with a Currency literal syntax. >With syntax such as, say, > 123.45$ equivalent to Currency(123.45) >(except, perhaps, for decimal vs binary exactness issues), the >users could type > a = 7$ > # ... > a = 6$ >which is less onerous than writing Currency(7), Currency(6). > >This idea is well-suited to the scenario in which the users make >pervasive use of objects of this type, and the main problem is >having to type "Currency" over and over again. Hm, it just occurred to me that one could have yet another form of sugar [ It's now later, and I think this may be more than sugar ;-) ] to help with this, by treating the dot operator slightly more symmetrically, like, e.g., '+'. Example, then explanation: a = 7 .USD # (using symbols from http://www.xe.com/iso4217.htm by convention, no hard defs) # ... a = 6 .USD This example uses the fact that int has no methods with plain names, so 6 .__getattribute__('USD') will fail. Normally that would be the AttributeError end of it, but if '.' were like '+', we could look for the r-version of __getattribute__ on the other object, analogous to __radd__. Thus 6 .USD # => USD.__rgetattribute__(6) (note necessary disambiguating space here is not necessary in unambiguous contexts) could return a specific currency object, e.g., if USD were defined something like e.g., (untested sketch !!) -- class XXX_Currency(FixedPoint): def __init__(self, symbol, *valprec): FixedPoint.__init__(self, *valprec) self.symbol = symbol def __rgetattribute__(self, other): return self.__class__(self.symbol, other, self.get_precision()) USD = XXX_Currency('USD') -- Alternatively, perhaps USD could be a class from a factory instead of an instance, and have __rgetattribute__ as a class method. BTW, num = 6 num = num.USD would do the expected. I.e., this would be a dynamic mechanism, not a tweaked literal syntax. Obviously this could be used for other quantity units than currencies, e.g., distance_to_moon = 384467 .km # avg dist I.e., the mechanism is conceived in terms of an __rgetattribute__ method analogous to __radd__, where you look for a compatible method in the other if the left arg can't handle it. This could then allow a general mechanism for all types, not just numerics, yet constrain it to special methods, to avoid accidental connections. Thus for an int, 6 . USD # => USD.__rgetattr__(6) but also, this kind of binary-op attribute computation could supply missing methods, e.g., for simple file objects. Thus f.readlines() would effectively become readlines.__rgetattribute__(f)() if there were no readlines method on f, and this could wrap f on the fly to provide the missing readlines method. Am I being a troublemaker? ;-) Regards, Bengt Richter From intentionally at blank.co.uk Sun Jul 13 13:51:47 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 18:51:47 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: On 13 Jul 2003 12:19:08 -0400, aahz at pythoncraft.com (Aahz) wrote: >Whether one can mutate a specific object is simply an >attribute of that object, rather than requiring a different syntax. >Trying to focus on the mutable/immutable distinction is what causes the >mental blowup -- keep your eye on the objects and bindings and you're >fine. That's exactly it - you have to focus on whether an object is mutable or immutable for that exact reason. While I admit I'm not sure, I believe that in early versions of Python immutable values literally were copied. Mutable types were made mutable because of efficiency concerns about copying overheads that would occur otherwise. If an object is large enough that it is worthwhile modifying items within it in-place then it tends to be worthwhile trying to avoid copying overheads, even though these two aspects of 'mutability' are actually quite distinct in principle. Actually, I'm convinced there are some flaws in Guidos own logic *unless* this is the case. Take for instance this... http://www.python.org/search/hypermail/python-1992/0292.html """ They serve different purposes. Lists can get quite long, they are generally built incrementally, and therefore have to be mutable. Tuples on the other hand are generally short and created at once. Then why can't tuples be mutable and serve both purposes? Imagine a graphics class that stores coordinates of graphical objects as tuples. It may also store rectangles as a tuple of points, etc. If tuples were mutable, the class would have to store copies of all points and rectangles it receives, since otherwise a caller who creates a point variable, passes its value to the graphics class, and later changes the point for its own use (e.g., to create another graphical object with slightly different coordinates) might violate the internal consistency of the graphics class. Note that most callers woouldn't modify the points, but the graphics class has no way to tell, so it has to make the copies anyway. (And now imaging the software is actually layered in such a way that coordinates are passed down several levels deep...) """ So what? As things are, the points could be stored using a list of tuples, with each tuple representing a point. When you store a new point in the list, you don't immediately make a copy (so if the supplier of the point immediately discards it, no copying is needed at all except for pointers) so it is efficient - yet you are still guarenteed that external processing will not mutate the value you hold in your list. Fine. But that can be achieved equally well by applying a copy-on-write system to *all* types, without a distinction between mutable and immutable for this purpose. Equally, you could use the same rationale for storing items which Python classes as mutable instead of these point tuples. If you have an object which stores class instances or dictionaries or lists for you, you need to store copies as - just as Guido recognised for the tuple case - your object doesn't know for sure what the caller is going to do with those objects after passing them in as parameters. This makes no sense to me *unless* there were other reasons for the mutable/immutable distinction. If lists had copy-on-write semantics, they could still be mutable (ie support in-place modification) yet there would be no need to make early copies. Tuples would be redundant as their only distinctive feature would be their lack of support for in-place modifications. It only makes sense if the copy-on-write for immutable values hadn't been implemented when the distinction was created - if immutables did not use references, but were always copied immediately on assignment - so that the referencing mechanism need never worry about copy-on-write at all. But it is worse than just being an arbitrary and pointless distinction... Back when PEP238 was being 'debated', a major argument in favor of the change was that there is no legitimate case where a function would need to either do 'true' division or integer division depending on the argument type. The type of division needed depends on the purpose of the function, and behaviour shouldn't change just because someone passes an integer into a function that expects a real or visa versa. Apply the same logic to mutable and immutable types. Tell me one case where it is sensible for a function to behave such that whether the caller sees a change in a variable it passed as its argument should depend on the type. Tell me one case where an object storing values should care about callers mutating values it holds *only* for certain types. I doubt you can. This is an arbitrary distinction created for historic reasons that have long since vanished (apart, of course, from backward compatibility and psychological inertia), given that copy-on-write is implemented for immutable objects anyway. And the fact that immutable values do an excellent job of implementing the common semantics of most imperitive languages (i.e. assignment sets the LHS to something that can be treated as a distinct copy) whereas mutable types behave in a fundamentally different way is quite simply a wart - inconsistent, confusing and error-prone behaviour. From alanmk at hotmail.com Tue Jul 1 08:34:55 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 01 Jul 2003 13:34:55 +0100 Subject: Python hosting? References: Message-ID: <3F017FEF.D499AA5B@hotmail.com> MK wrote: > Can anybody recommend a good hosting package > for Python? Must be cheap, that is max. $5 per month. > > If the solution offers Java+MySQL as well, that would > be great! Check out the Python Hosting Wiki, which is the most authoritative list I've come across. http://www.python.org/cgi-bin/moinmoin/PythonHosting HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mhammond at skippinet.com.au Wed Jul 23 19:44:12 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 24 Jul 2003 09:44:12 +1000 Subject: Newbie question about Python & W2K Admin In-Reply-To: <86d2ca4.0307231125.70ee3f57@posting.google.com> References: <86d2ca4.0307231125.70ee3f57@posting.google.com> Message-ID: stuartc wrote: > Hi all: > > I need to change a few Local Security Settings on a number of W2K > machines. An example of a Security Setting I need to change is the > "Minimum password length" setting, which is under Account Policies, > Password Policy. > > Instead of doing this manually on each machine, I would like to have > an automated way to do this. Can Python be used for this ? > > Any direction on how to automate this using Python or some other tool > will be greatly appreciated. Look into the win32net module - you can change all sorts of things there. "Python Programming on Win32" has some good examples. Mark From yvan_charpentier at hotmail.com Fri Jul 11 15:59:07 2003 From: yvan_charpentier at hotmail.com (yvan) Date: 11 Jul 2003 12:59:07 -0700 Subject: Create another Excel instance References: <9ee55987.0307101339.701965a7@posting.google.com> Message-ID: <9ee55987.0307111159.6978676e@posting.google.com> "Cy Edmunds" wrote in message news:... > "yvan" wrote in message > news:9ee55987.0307101339.701965a7 at posting.google.com... > > I am using Excel to save data. > > Everything works as i intend it to if no other instance of Excel is > running. > > If another instance is running, it will do the job, but also close that > instance. > > How can i prevent that from happening? > > > > Here is the code that creates and deletes the instance: > > class CExcel: > > def __init__(self, bVisible = 0): > > import sys > > import pythoncom > > sys.coinit_flags = 0 > > pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) > > import win32com.client.dynamic > > self.xlApp = win32com.client.dynamic.Dispatch("Excel.Application") > > self.xlApp.Visible = bVisible > > self.xlBook = self.xlApp.Workbooks.Add() > > self.xlSheet = self.xlApp.ActiveSheet > > > > def __del__(self): > > import pythoncom > > if self.xlSheet != None: > > del(self.xlSheet) > > if self.xlBook != None: > > self.xlBook.Close(0) > > del(self.xlBook) > > if self.xlApp != None: > > self.xlApp.Quit() > > del(self.xlApp) > > pythoncom.CoUninitialize() > > > > Thank for your help, > > > > -Yvan > > I haven't tried this myself but maybe... > > if self.xlApp != None: > nbook = self.xlApp.Workbooks.Count # number of open workbooks > if nbook == 0: > self.xlApp.Quit() > > Let us know how you made out. It looks like that would work if 'Visible' was set to 1. Unfortunately mine has to be 0. Thanks for the suggestion. Basically, my problem is that the object uses the same process if an instance of Excel already exists. How can i create the new instance in a different process? From gh at ghaering.de Wed Jul 9 06:13:14 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Jul 2003 12:13:14 +0200 Subject: format discs. In-Reply-To: References: Message-ID: <3F0BEABA.1090003@ghaering.de> Flanagan wrote: > hello to all > > somebody can say to me whereupon I modulate of python I can format > discs. You probably mean creating a filesystem on a partition. In Windoze-speak that's stupidly called "to format". The easiest solution for Windows is to just call format.exe with the appropriate parameters. This can be done in various ways from Pythno, the simplest one being os.system. Other options are the commands and popen2 modules, depending on wether you need to read the output of format.exe. Similarly on *nix, call mkfs. -- Gerhard From peter at engcorp.com Mon Jul 14 21:33:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 21:33:23 -0400 Subject: Next meeting of Toronto Python User Group: Tue July 29 8pm Message-ID: The next regular meeting of the Greater Toronto Area Python User Group (aka PyGTA) will occur on Tuesday July 29 at 8pm in the usual location. See the wiki page at http://web.engcorp.com/pygta/wiki/NextMeeting for details. There are as of yet no offers of presentations, but the last two meetings seemed to be well received so maybe we'll continue the impromptu-presentation-with-laptop-with-broken-keyboard style of meetings... ;-) A projector should be available for use *if* requested in advance. See you there! -Ian Garmaise, Peter Hansen, PyGTA organizers From Vincent.Raaijmakers at ge.com Thu Jul 31 16:19:01 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 31 Jul 2003 15:19:01 -0500 Subject: Solved: SQL2000 database vs python, using mssqldb and Pyro Message-ID: <55939F05720D954E9602518B77F6127F02F873F6@FTWMLVEM01.e2k.ad.ge.com> Problem solved!! Forgot to put the owner in front of the table name. so: vincent.my_table instead of my_table. Thanks guys! -----Original Message----- From: Raaijmakers, Vincent (IndSys, GE Interlogix) Sent: Thursday, July 31, 2003 2:47 PM To: python-list at python.org Subject: SQL2000 database vs python, using mssqldb First of all, thanks for all the help guys! Until now, lots of install problems on all the recommended packages/modules. For now, my best option was to make use of my existing Pyro framework (thanks Irmen!) I already build a MSSQL (Pyro/server)service on the windows box using mssqldb. My linux app will talk to this service. This at least has been installed successful and my service can already connect to the database. So far so good: Now, I can't find the API of MSSQL. Not on the website nor in the installed folders. So, I tried to use the examples and only the connections seems successful. When I try a select on a table, it tells me that the table name is an invalid object name. Just tried a kind of a hello world example... import mssqldb import MSSQL db = MSSQL.connect('my_db_server', 'user', 'password', 'my_database') ## so far, so good c = db.cursor() c.execute('select * from my_table') ## boom, error c.fetchall() c.nextset() The ms sql enterprise manager shows me that the database and table is there. Unfortunately, in python the error tells me: Invalid object name 'my_table' Anyone with experience? Where are the API's? Vincent -- http://mail.python.org/mailman/listinfo/python-list From maney at pobox.com Sun Jul 13 01:15:01 2003 From: maney at pobox.com (Martin Maney) Date: Sun, 13 Jul 2003 05:15:01 +0000 (UTC) Subject: Nice presentation of Dana Moore on Oscon References: <3F0E63AA.4000107@embeddedsystems.nl> Message-ID: Aahz wrote: > Unfortunately, Bruce Eckel has been perpetuating that terminology. I'm > in the process of writing a rebuttal. > http://www.artima.com/intv/typing.html In this it sounds as though Mr. Eckel is coming around to the right view. In the first part he seems to be using "latent", and only says at one point "...latent typing, sometimes called weak typing...". And he repeatedly uses the phrase "strong static type checking" for what is supposed to be the strength of C++ and Java, and notes that "Strong static type checking forces the programmer to do a lot of extra work." So I get the impression that he is making that journey of discovery that we know so well. Or, anyway, I know it - maybe you didn't go through the same wringer that made B&D static type checking seem like a pretty good idea in contrast to what came before? I used to think C++ was the best thing since the symbolic assembler, or maybe object [code] linking... I don't know that I care much for "latent typing", although it has a certain attraction. If nothing else, it's shorter than "strong dynamic typing", the first word of which seems necessary these days. :-( But whether or not Mr. Eckel is still contributing to it, I can attest that there is a general confusion about this among programmers, perhaps especially java programmers. Just the other day I whacked one upside the head (virtually; we were chatting on IRC) with the distinction between "strong" and "static" typing and had the pleasure of watching his eyes light up. Well, I imagine they lit up. But that was only one, so if you'd get cracking on that paper... :-) -- Passport brilliantly combines the kludgey and unstable nature of NIS+ with the insecurity of the trusted hosts concept to produce a nine-step process with obvious opportunities for security and other abuses. -- Paul Murphy From db3l at fitlinxx.com Thu Jul 10 11:38:33 2003 From: db3l at fitlinxx.com (David Bolen) Date: 10 Jul 2003 11:38:33 -0400 Subject: mx.DateTime.Parser.DateFromString('crap') References: Message-ID: Koczian writes: > This doesn't raise an exception but returns the current date. I know > the comment in the notes for the Parser submodule: "The Parser > submodule ... will try very hard to come up with a reasonable output > given a valid input." But this is no valid input, so I'd prefer an > exception or at least not a valid DateTime object. Double check that you're using a recent version of the egenix base package (probably 2.0.3 or later). The parser module functions such as DateFromString were augmented to accept an optional list of parsers to try, which allows you to override the default. The default does include an "unknown" parser which will default to the current date as in prior versions, but if you exclude that you'll get a ValueError exception if none of the other parsers match. For example: >>> import mx.DateTime >>> print mx.DateTime.Parser._date_formats ('euro', 'us', 'altus', 'iso', 'altiso', 'lit', 'altlit', 'eurlit', 'unknown') >>> print mx.DateTime.Parser.DateFromString('crap') 2003-07-10 00:00:00.00 >>> myformats=mx.DateTime.Parser._date_formats[:-1] >>> print myformats ('euro', 'us', 'altus', 'iso', 'altiso', 'lit', 'altlit', 'eurlit') >>> print mx.DateTime.Parser.DateFromString('crap',formats=myformats) Traceback (most recent call last): File "", line 1, in ? <...snip...> ValueError: unknown date format: "crap" -- David From postmaster at NCSNAHUB1.JNJ.com Tue Jul 1 04:52:07 2003 From: postmaster at NCSNAHUB1.JNJ.com (System Administrator) Date: Tue, 1 Jul 2003 04:52:07 -0400 Subject: Undeliverable: Re: Movie Message-ID: <599C6453A1B8D41189320008C7E620572F0B7DFC@ncsusraexims1.rar.ncsus.jnj.com> Your message To: pdale at lifescan.com Subject: Re: Movie Sent: Tue, 1 Jul 2003 04:57:02 -0400 did not reach the following recipient(s): pdale at lifescan.com on Tue, 1 Jul 2003 04:51:49 -0400 The recipient name is not recognized The MTS-ID of the original message is: c=us;a=attmail;p=wwjjprmd;l=NCSUSRAEXIMS10307010851MVD0HFY8 MSEXCH:IMS:JNJ:NCSNAHUB1:NCSUSRAEXIMS1 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Movie Date: Tue, 1 Jul 2003 04:57:02 -0400 Size: 898 URL: From sismex01 at hebmex.com Thu Jul 10 13:07:20 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 10 Jul 2003 12:07:20 -0500 Subject: for in sequence problem... possible new operator to add to py thon Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > Sent: Jueves, 10 de Julio de 2003 11:36 a.m. > > Adam Gent wrote: > > [..snippage..] > > [..more.snippage..] > > When you iterate over a dict in recent versions of Python, you > are by definition iterating over the keys in the dict. If you > want the values, you use .values(), and if you want both keys > and values, you use .items(). See the docs for more. > > -Peter > Actually, .keys(), .values() and .items() return their respective lists, in arbitrary order. If you wish to use an iterator, use .iterkeys() , .itervalues() or .iteritems() ; very helpful in the case of big dictionaries, since you don't need to create and then destroy big lists. Adam: If you wish to iterate through the items by default, have you tried something like this? class NewDict(dict): def __iter__(self): return super(NewDict,self).itervalues() That should, by default (like "for x in nd:") iterate through the values of a dictionary, instead of it's keys. I haven't tested it though, so caveat emptor. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From peter at engcorp.com Thu Jul 10 12:35:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 12:35:50 -0400 Subject: for in sequence problem... possible new operator to add to python References: <3a8fc6c5.0307100816.634c83a3@posting.google.com> Message-ID: <3F0D95E6.3BC763D3@engcorp.com> Adam Gent wrote: > > I was fooling around subclassing a dictionary object and noticed that > when > I do the standard "for in :" that I have no > control on how python gets that sequence. > > For example: > > class Blah(dict): > pass > > bl = Blah() > > for b in bl: > #b will be a key and not a value > #no matter how I subclass Blah > > However I want b to be the values with out doing: > for b in bl.values() Why do you want that? That is not how Python works. This is sort of like saying "when I'm in my car and I push on the gas pedal, the car moves. However I want to make it move without pushing on the gas pedal." When you iterate over a dict in recent versions of Python, you are by definition iterating over the keys in the dict. If you want the values, you use .values(), and if you want both keys and values, you use .items(). See the docs for more. -Peter From t.leeuwenburg at nothing.bom.gov.au Fri Jul 18 00:32:10 2003 From: t.leeuwenburg at nothing.bom.gov.au (Tennessee James Leeuwenburg) Date: Fri, 18 Jul 2003 14:32:10 +1000 Subject: null pointer exceptions Message-ID: It seems to be the case that there are some null pointer exceptions which Java can handle, but Jython can't. Which doesn't make sense to me, as with Jython, it is Java which is doing the work. Are there any good guides to this? I have a class which includes adding an ImageIcon. If the required graphic resource isn't present, there is a NullPointerException. Java doesn't care - the straight Java program handles it internally and gets on with life. But when I include it from Python, it explodes. It may be because the resource is specified using a relative pathname. When Jython executes, it may be not using the current directory as its' base for relative paths, but could be using JYTHON_HOME, which could lead to this behaviour. Can anyone tell me what Jython uses for its' relative path base? Can anyone describe how Jython handles exceptions that is different from Java? Thanks, -Tennessee From vze4rx4y at verizon.net Sat Jul 26 20:01:57 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 27 Jul 2003 00:01:57 GMT Subject: How do I get info on an exception ? References: Message-ID: [Raymond] > >The part that could be improved is where it talks about returning a > >message or a tuple, as if either one but not both could occur at any > >time. It would be more accurate to say, that in all cases an exception > >instance is returned; the instance has a __str__ method so it can be > >printed as if it were a string; the instance has an attribute "args" which > >is the tuple (errno, errmsg); and the instance has a __getitem__ method > >so the args tuple can be directly unpacked as if the instance had been > >the tuple itself. [Frank] > After checking that the input is a string, I try calling > gethostbyname/addr depending on whether the first char is numeric and > catch: > "except socket.error, err:" > Will this catch all possible errors? I've tried feeding various > errors into my def and caught them all so far. Input might come from > users at the keyboard, and crashing the program is not an option, no > matter what is typed in. Yes, that will catch all errors. You have bound the instance to "err". As I said earlier, the part of the docs that some folks may find confusing is that part about returning a string or a tuple. In fact, it always returns an instance that can be printed like a string *and* unpacked like a tuple. I'll modify the docs to make this more clear. If you're in an experimental frame of mind, it is straight-forward to learn exactly what is going on by adding a few print statements: except socket.error, inst: print 'Caught a', type(inst) # show that an exception instance was recd print 'The inst can be printed like a string:', inst errno, errmsg = inst # show the exception can be unpacked print 'It contains a tuple with', errno, 'and', errmsg print 'Its methods are', dir(inst) print 'The data is kept in inst.args', inst.args print 'It prints because of the __str__ method:', inst.__str__() print 'That is my story and I am sticking with it!' Raymond Hettinger Raymond Hettinger From maney at pobox.com Wed Jul 2 01:51:50 2003 From: maney at pobox.com (Martin Maney) Date: Wed, 2 Jul 2003 05:51:50 +0000 (UTC) Subject: new to python - looking for a good book References: <9d5509fa.0306301704.3234d552@posting.google.com> Message-ID: Peter Ballard wrote: > Why should I buy any of these books when I've got the (free) official > Python documentation downloaded, and always just a click or two away? Because some of them - the Cookbook comes forcefully to mind for me - cover material that the regular docs don't touch on; the difference between what the language allows and how best to use those facilities. Others, even the so-called "Bible" which I found wanting in its thoroughness of coverage, can illuminate the features and libraries with well-crafted small examples that are rarely present in the more reference-like documentation. And even books that are not at first glance much more than a printed version of the online docs (although _Essential Reference_ always seemed more useful to me, especially back when I was working with its first edition and Python 1.5) have some portability and usability advantages if one is not attached to his computer at the waist. :-) At least those are the sorts of reasons that come to my mind. -- We reject kings, presidents, and voting. We believe in rough consensus and running code. -- David Clarke From news at 92tr.freeserve.co.uk Tue Jul 29 04:27:27 2003 From: news at 92tr.freeserve.co.uk (ddoc) Date: Tue, 29 Jul 2003 08:27:27 +0000 Subject: small CDs? References: Message-ID: Kevin Altis wrote: > it would be handy to be able to > run Python on machines that don't already have Python installed. ... > CD-ROM is not very effective because the media is read-only and too big to > carry in your pocket. Read-only, yes, but you can get small CD-Rs that hold a reasonable amount of information in either a proper round shape, or one with corners that makes it conference badge/credit card sized. Probably easiest to set up the system you burn on the pocketable CD so that it uses the USB device you carry in the other pocket to store anything that needs to change or be retained after a session. -- A From aahz at pythoncraft.com Fri Jul 25 18:41:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 25 Jul 2003 18:41:15 -0400 Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: In article , Shane Hathaway wrote: > >Well, here's a pattern I've been trying out for this purpose: use assert >statements at the top of the function. > >def foo(bar, baz): > assert isinstance(bar, int) > assert isinstance(baz, str) > >I'm quite happy with the pattern, although there are a couple of >negative points that I can think of: > >- It's a bit verbose, although that verbosity enables you to perform >bounds checking and operate with other type systems like Zope's interfaces. > >- You can't specify the type of the return values this way. You skipped the crucial negative: it breaks Python's name-based polymorphism. If someone creates a class that works just like a string but doesn't derive from the str class, your program breaks for no good reason. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From kmj9907 at cs.rit.edu Thu Jul 31 18:20:59 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Thu, 31 Jul 2003 22:20:59 GMT Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <38ec68a6.0307301841.dfb951a@posting.google.com> Message-ID: > If you use vim remember to put 'set expandtab' (or if you wanna be fancy > 'au BufRead,BufNewFile *.py set expandtab' ) into your .vimrc (or .exrc) > file. This way you can use '[Ctrl]-[T]' and '[Ctrl]-[D]' to in- and > un-dent in insert mode, as well as '>>' and '<<' in command mode, > without fear of hard tabs being inserted. (Though the way vi(m) mixes > tabs and spaces is consistent enough that you wouldn't usually get into > any trouble with it.) Oh, yeah, forgot to mention expandtab; I did not know about >>, <<, Ctrl+T, and Ctrl+D, however; so thanks for those. I had mapped and to : s/^/ / and : s/^ / for command mode, which I guess I won't have to use anymore. I noticed in visual mode, you can just use '>' or '<' to tab or untab multiple lines, though sadly the visual mode disappears. This leads to the question: what python specific entries people have in their .vimrc's? I've got the following: " smart indenting is necessary of course autocmd FileType python set autoindent smartindent et sts=4 \ cinwords=class,def,elif,else,except,finally,for,if,try,while " I hate that vim puts # at the beggining of the line if it's the " first character, so this prevents that autocmd FileType python inoremap # X# " as described above, insert or remove tabs (works with visual, to) autocmd FileType python map : s/^/ / autocmd FileType python map : s/^ // " These move to the top of the next or previous class or function autocmd FileType python map [[ ?^\s*class\s autocmd FileType python map ]]/^\s*class\s autocmd FileType python map [] ?^\s*def\s autocmd FileType python map ][ /^\s*def\s " find some of my stupid mistakes autocmd FileType python map :w:!pychecker % " comment or uncomment multiple lines in visual mode autocmd FileType python vmap # : s/^/#/ autocmd FileType python vmap @ : s/^#*// I should just put all those commands in a vim file and source it. From member32239 at dbforums.com Tue Jul 1 04:08:36 2003 From: member32239 at dbforums.com (Mike Medland) Date: Tue, 01 Jul 2003 08:08:36 +0000 Subject: Mod_python xml parsing problem Message-ID: <3061157.1057046916@dbforums.com> Hi, I am currently using Python 2.2.3, apache 1.3.27 and mod_python 2.7.8. Under Solaris 8 on a sun. The configuration appears to be working fine but, the problem that i am having is in parsing xml files, when i do for example: xmlfile = minidom.parse(file) root = xmlfile.childNodes It creates a dom instance but it contains nothing at all, and root returns a 'nonetype'. I believe that it may be an encoding problem but i dont know how to fix it. When i tried the same code using cgi instead of mod_python it worked fine. Any suggestions would be greatly appreciated. -- Posted via http://dbforums.com From furliz at libero.it Thu Jul 31 10:05:01 2003 From: furliz at libero.it (furliz) Date: Thu, 31 Jul 2003 16:05:01 +0200 Subject: tkinter menu bars, assigning children to parents, and grid/pack managers In-Reply-To: <8bf5dfd1.0307300941.f068138@posting.google.com> References: <8bf5dfd1.0307300941.f068138@posting.google.com> Message-ID: Josh wrote: > Caution, newbie approaching... well... newbie vs newbie :)) > > I'm trying to come up with a very simple Tkinter test application that > consists of a window with a drop-down menu bar at the top and a grid > of colored rectangles filling the remainder of the window. It seems you'd like to obtain a standard window with a standard menubar attached at the top.... is it right? Perhaps I'm not the best person for your problem resolution, but I hope I'll could give you a contribute :) > class MultiColorMenu(Tkinter.Frame): > "This class is a bar of drop-down menus for manipulating a grid of > colored rectangles." > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master) > self.tk_menuBar(self.help_menu()) > > def help_menu(self): > help_btn = Tkinter.Menubutton(self, text='Help', underline=0) > help_btn.pack(side=Tkinter.LEFT, padx="2m") > help_btn.menu = Tkinter.Menu(help_btn) > help_btn.menu.add_command(label="How To", underline=0, > command=self.helpFoo) > help_btn.menu.add_command(label="About", underline=0, > command=self.helpFoo) > help_btn['menu'] = help_btn.menu > return help_btn > > def helpFoo(self): > print 'Heelllppppp!!!' > For my knowledge (..very small on python, yet) you should use the Tkinter.Menu widget rather than creating an extension of the Tkinter.Frame like you did in your MultiColorMenu class. Just copy&paste this simple example, so you see if it is what you're looking for. #begin code from Tkinter import * root = Tk() root.title("Menu demo") root.geometry("300x300") # -- barra menu masterMenu = Menu(root) # -- menu tipo di ricerca menutiporicerca = Menu(masterMenu,tearoff=0) menutiporicerca.add_command(label="Ricerca directory") menutiporicerca.add_command(label="Ricerca file") menutiporicerca.add_command(label="Ricerca dentro file") # -- menu ricerche menuricerca = Menu(masterMenu,tearoff=0) menuricerca.add_cascade(label="Nuova ricerca...",menu=menutiporicerca) menuricerca.add_command(label="Salva ricerca") menuricerca.add_separator() menuricerca.add_command(label="Esci") masterMenu.add_cascade(label="Ricerca",menu=menuricerca) # -- menu info menuinfo = Menu(masterMenu,tearoff=0) menuinfo.add_command(label="Info") menuinfo.add_separator() menuinfo.add_command(label="About..") masterMenu.add_cascade(label="?",menu=menuinfo) #setta barra menu root.config(menu=masterMenu) root.mainloop() #end code hope this help you. Bye. From peter at engcorp.com Mon Jul 7 08:43:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 08:43:08 -0400 Subject: anything new on the ternary operator? References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> <3F09235B.6F7DE56@alcyone.com> Message-ID: <3F096ADC.1E4D6232@engcorp.com> Erik Max Francis wrote: > > Mind you, such discussion will not be very constructive, but just > saying, "Welp, it's not going to be added, nobody talk about it ever > again" is not going to be very effective when new people come in all the > time and, one must admit, at least some segment of the user community > would have liked the feature. At least by then the FAQ will be updated to point to the updated PEP, which will, as originally intended, clearly explain the background, the discussion, the vote, and the "final" decision. -Peter From sjmachin at lexicon.net Thu Jul 17 16:25:31 2003 From: sjmachin at lexicon.net (John Machin) Date: 17 Jul 2003 13:25:31 -0700 Subject: python.dll References: <3f169c26$1@newspilot.put.poznan.pl> Message-ID: Gerhard H?ring wrote in message news:... > Jacek Potrymaj o wrote: > > I installed this version of python software, but when I > > try to install software which use Python I have an error - incorrect ve > rsion > > of python.dll is installed. [...] > > Is that the exact error message you get? If not, please tell us the > exact error message. > > You wonder why I don't believe that this is the exact error message? > There is no such thing as a python.dll on Windows. The Python DLLs > always carry the major and minor version numbers, like python21.dll or > python22.dll. Gerhard is correct, as far back as Python 1.5 (determined by searching for python*.dll on my machine). Jacek, ignore any suggestions to the contrary. Not sure what's going on there; either (a) inappropriate use of the time machine or (b) bot rot or (c) the bot has been hacked ... From tim.one at comcast.net Tue Jul 15 21:27:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 15 Jul 2003 21:27:01 -0400 Subject: FCNTL module deprecation warning In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1318CF26@its-xchg4.massey.ac.nz> Message-ID: [Tony Meyer] > Strange. I get the warning on 2.2.3 and 2.3b2, except in 2.3b2 IDLE, > which successfully imports fcntl (odd). (long cut'n'pastes below). Not in my 2.3b2 IDLE (installed from the released binary installer): Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. IDLE 1.0b2 >>> import fcntl Traceback (most recent call last): File "", line 1, in -toplevel- import fcntl ImportError: No module named fcntl >>> > Do you have the PYTHONCASEOK envar set? Absolutely not. That envar is for desperate backward compatibility problems on junk systems, where the user doesn't care about portable import semantics. > (This doesn't seem to make any difference to me, but from the > explanation I didn't think it would). To the contrary, setting PYTHONCASEOK radically changes behavior here! Indeed, it's the only explanation I can think of for this: > Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl c:\progra~1\python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is dep recated; please use fcntl DeprecationWarning) There isn't (or at least shouldn't be) any file named fcntl.py anywhere in your Python installation. FCNTL.py, yes, but not fcntl.py (or .dll, or .pyd, etc). The deprecation warning you showed there comes from FCNTL.py (open it up and look at line 7): warnings.warn("the FCNTL module is deprecated; please use fcntl", DeprecationWarning) Therefore, when you did "import fcntl", it actually opened FCNTL.py. That's what happens if you set PYTHONCASEOK -- case distinctions are ignored on Windows then, violating Python's intended behavior. The reason the later from fcntl import * in FCNTL.py doesn't cause infinite recursion then is subtle, but intended behavior. Note that this module doesn't blow up with infinite recursion either if you import it: C:\Code\python\PCbuild>type fooey.py print "a bunch of junk" import fooey C:\Code\python\PCbuild> The short course is that Python arranges for recursive imports "to work", so that circular imports are possible (for the careful). Here: C:\Python23>set PYTHONCASEOK=1 C:\Python23>python Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl C:\PYTHON23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> print fcntl.__file__ C:\PYTHON23\lib\fcntl.pyc >>> fcntl.__file__ gives the name of the file Python believes the .pyc file was compiled from. Because PYTHONCASEOK is set, the case given in the import statement was believed (bit ignored for purposes of searching for it). There certainly isn't any file named fcntl.py here, though: C:\Python23>dir/b lib\fc* FCNTL.py FCNTL.pyc C:\Python23> Python works as designed if that envar is left unset: C:\Python23>set PYTHONCASEOK= C:\Python23>python Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fcntl >>> From claird at lairds.com Wed Jul 30 07:30:32 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 30 Jul 2003 11:30:32 -0000 Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: In article , Andrew Dalke wrote: >Rick: >> But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal >> papers in the history of Python in the opinion of members of this >> newgroups? > > - Lutz Prechelt's paper comparing C, C++, Perl, Java, Tcl, Python, and > a couple more languages, all on the same non-trivial task > > - Greg Stein's paper at the San Jose conference (1998), on how his > company used Python to make a commercial web app then sold it > to Microsoft - helped convince me people could make money doing Python > > - not really a paper, but reading through the tutorial and the library >docs > back in 1997 were what convinced me that Python was the language for >me. > It still took 2 years before I could use it -- too much preexisting Tcl >and Perl > code. . . . Somewhere between academic papers and Usenet discussions, examples of each of which have already been recommended to you, are magazine articles. Last millenium, I wrote several that *still* appear to attract readers, to my surprise. If my e-mail is an apt indication, "Python as a First Language" www.oreillynet.com/pub/a/network/2000/06/02/magazine/python_first_language.html "Getting Started With Python" web.archive.org/web/20010201170400/http://www.sunworld.com/sunworldonline/swol-02-1998/swol-02-python.html "Batteries Included" web.archive.org/web/20001013152452/http://sunworld.com/swol-12-1998/swol-12-regex.html are among those influential out of proportion to their artistic merit. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From intentionally at blank.co.uk Mon Jul 14 23:34:01 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 04:34:01 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> Message-ID: On Mon, 14 Jul 2003 17:06:17 -0700, Tom Plunket wrote: >>>> a = 5 >>>> b = ref_to(5) >>>> a = 3 >>>> print b >3 > >This would require a new built-in probably, and any time you >(accidentally?) did 'b = c', then you'd lose that reference, >but... hmm, I wonder if it'd be handy. > >Probably not enough to justify the expense. :) True - but the problem doesn't arise if you need to explicitly dereference pointers to access the objects they point to. >>> a = 5 >>> b = &a >>> a = 3 >>> *b 3 >>> *b = 7 # note - not 'b = c' >>> a 7 Providing the pointers aren't low level store addresses or fuzzy concepts vaguely related to arrays as in C, the principle would work just fine. From alanmk at hotmail.com Sun Jul 6 08:54:40 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 13:54:40 +0100 Subject: Frustration with spurious posts. References: <3F06FD11.967D8D8A@hotmail.com> Message-ID: <3F081C10.8CF6B57@hotmail.com> Alan Kennedy: >> Bringing an end to the problem would probably involve a fairly >> substantial admin effort on the part of the python.org admins. JanC wrote: > No, it's the admins that run an antivirus on their mail server or the > users that use broken anti-virus/anti-spam tools that should fix their > system. Ah but, we all know that is never going to happen. There are just too many admins out there who either don't know how or are unwilling to deal with this problem. There are two ways to sort the problem out 1. Get *all* of the admins to configure their setups to stop bouncing virus emails. 2. Sort it out at the python-list/Usenet gateway. Since #1 is unlikely to ever happen in practice, #2 is the only viable option available. Hence my statement. > It's plain stupid and irresponsible to bounce or send a mail back to a > *forged* and often randomly shuffled "From:" address, doubling or > tripling the mail traffic generated by the virus itself. :-( Yes, it can be indeed thoroughly silly, especially if the from address is forged. But if an email is sent from an individual to an individual, then such "you sent me a virus!" emails can be very useful information. It's only when an email address is associated with lots of subscribers that it becomes a problem. Or, as you pointed out, when the from address is forged. Is there some sort of mail header that these virus checking gateways could examine, to see if the email is from a list, rather than an individual, before it sends these emails? Maybe we need to invent one, e.g. X-Dont-Send-Me-Virus-Reports: YES > "Be strict when sending and tolerant when receiving." > RFC 1958 - Architectural Principles of the Internet - section 3.9 Do this mean we should quietly tolerate the "you sent me a virus!" emails? ;-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From skip at pobox.com Sat Jul 19 12:04:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 19 Jul 2003 11:04:55 -0500 Subject: List of declared variables in interactive Python session? In-Reply-To: References: Message-ID: <16153.27687.462239.251885@montanaro.dyndns.org> Fredrik> Is there a way to list all the declared variables in an Fredrik> interactive Python session? >>> i = 1 >>> a = "abc" >>> b = a >>> print globals().keys() ['dirall', 'completion', 'b', '__builtins__', '__file__', 'titan', 'xmlrpclib', 'configpath', 'dirpat', 'buildinfo', 'sys', 'i', 'xmlrequest', 'manatee', 'a', 'x', '__name__', 'dxp', 'os', '__doc__', 'dir'] >>> print globals() {'dirall': , 'completion': , 'b': 'abc', '__builtins__': , '__file__': '/Users/skip/.python.py', 'titan': , 'xmlrpclib': , 'configpath': , 'dirpat': , 'buildinfo': , 'sys': , 'i': 1, 'xmlrequest': , 'manatee': , 'a': 'abc', 'x': Type help() for interactive help, or help(object) for help about object., '__name__': '__main__', 'dxp': , 'os': , '__doc__': None, 'dir': } Note that it picks up anything defined in your PYTHONSTARTUP file as well. Skip From cneal92 at lycos.com Sun Jul 6 19:40:28 2003 From: cneal92 at lycos.com (O'Neal Computer Programmer) Date: 6 Jul 2003 16:40:28 -0700 Subject: python scripting game The Temple Of Elemental Evil update Message-ID: <82ff1d8b.0307061540.5da32ae@posting.google.com> I was reading here: http://groups.google.com/groups?q=elemental+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&selm=mailman.1044572235.32593.python-list%40python.org&rnum=3 that a game The Temple Of Elemental Evil is going to be using python as its scripting language. It says that on the FAQ which you can read about here http://mywebpages.comcast.net/ibnobody/troika.html Q. What language are you writing the gamecode in? A. (S.M. 2/6) The renderer is written in C, the animation player is in C++, the game logic and user interface is also written in C, and most of the scripting is done in Python (thanks Guido). Anyway, this game also has a forum at http://ina-community.com/forums/forumdisplay.php?s=&forumid=286 and also one that you have to pay for at http://vnboards.ign.com/board.asp?brd=22335 with more info about the game. From ebolonev at rol.ru Fri Jul 4 05:48:35 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 20:48:35 +1100 Subject: Question about "exec in globals, locals" References: <57de9986.0307040041.553ff329@posting.google.com> Message-ID: Hello, Giles! You wrote on 4 Jul 2003 01:41:36 -0700: [Snipped] GB> # Case - 2 GB> myglobals = {'__builtins__' : None, '__name__': None} GB> mylocals = {} GB> exec source in myglobals, mylocals exec source in mylocals exec source in myglobals And it work with no errors. But I'm not sure you wish this. GB> print "Global names are:", myglobals.keys() GB> print "Local names are:", mylocals.keys() With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From adalke at mindspring.com Wed Jul 30 15:52:11 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 30 Jul 2003 13:52:11 -0600 Subject: while (assignment): References: Message-ID: Me: > Again, don't this in real code. Evil. But cute. Tim Delaney: > I would say it's actually rude, rather than evil. Ehh, you're right. So it's no longer part of the axis of evil? Andrew dalke at dalkescientific.com From ianb at colorstudy.com Wed Jul 16 20:11:13 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Jul 2003 19:11:13 -0500 Subject: list() coercion Message-ID: <1058400673.19233.1088.camel@lothlorien> I have an iterable object. It supports many list-like methods, specifically __len__. These methods are rather expensive (they result in database calls, COUNT(*) to be specific), but cheaper than iterating over the object. Sometimes it is useful to create a list from the iterator, using list(). However, list() seems to call the object's __len__, I imagine to pre-allocate space. This is a problem, as pre-allocation saves much less than is spent doing __len__. Is there a way I can keep this from happening? Maybe something list() tries first that I can make fail. (I notice list() catches any exceptions in __len__ and then will just skip that step) Ian From paulpaterson at users.sourceforge.net Fri Jul 25 13:28:22 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Fri, 25 Jul 2003 17:28:22 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Paul Paterson" wrote in message >> >>The Python documentation gives a warning that modifying the contents > > of > >>locals() may not affect local values. Despite the warning, the code >>seems to work as desired, at least on Python 2.2. > > > At module scope, locals() == globals(). Within a function, locals() > currently is a *copy* of the function's local namespace. So above > only works because you made the call from the global (module) context > and would not if you tested by making call from within a function. > Thanks Terry! I adjusted my tests and now see this behaviour exactly. The function itself works but the changes do not propogate out to the calling scope. So this approach of using locals() appears to be dead. Are there any other approaches? Paul From bignose-hates-spam at and-zip-does-too.com.au Sat Jul 12 02:44:00 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 12 Jul 2003 16:34:00 +0950 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: Message-ID: On Sat, 12 Jul 2003 06:56:52 GMT, Raymond Hettinger wrote: > For your amusement and edification, I'm working on a series of Python > puzzles designed to highlight areas of the language known only to > those who have read the docs more than once. Excellent stuff! Any plans to put these online, perhaps with collation of the responses? How many episodes are currently planned? I imagine that some of the "blindingly obvious" explanations would be welcome in the docs :-) -- \ "I wish a robot would get elected president. That way, when he | `\ came to town, we could all take a shot at him and not feel too | _o__) bad." -- Jack Handey | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From manish.j at gmx.net Fri Jul 25 09:35:01 2003 From: manish.j at gmx.net (Manish Jethani) Date: Fri, 25 Jul 2003 19:05:01 +0530 Subject: data conversion question (binary string to 'real string') In-Reply-To: <3F212EB3.7020600@stacom-software.de> References: <3F212EB3.7020600@stacom-software.de> Message-ID: <3waUa.5$gZ.161@news.oracle.com> Alexander Eisenhuth wrote: > This two lines converts 0.5 to a string in binary > representation > > >>>from struct import * from binascii import hexlify > >>>bin_str = pack('!f', 0.5) > > now bin_str is '?\x00\x00\x00', wich is the representation > of 0.5 in the memory. I need now to convert this binary > string to "3F000000", where '3F' is the hex value of the '?' > in ascii - table. > > Any ideas ?? foo = hexlify(bin_str) print foo -Manish PS: You posted the same message thrice, by mistake. -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From andersjm at dancontrol.dk Fri Jul 25 06:30:58 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Fri, 25 Jul 2003 12:30:58 +0200 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> Message-ID: <3f210717$0$76049$edfadb0f@dread11.news.tele.dk> "Ben Finney" wrote: > On 25 Jul 2003 07:18:15 +0200, Martin v. L?wis wrote: > > rimbalaya at yahoo.com (Rim) writes: > >> So what problem is the new.instancemethod() trying to solve? > > > > It has no side effects on the class it is an instancemethod of. > > So what side effects (i.e. what problem) is the new.instancemethod() > trying to solve? Assigning to the class changes the behaviour of all instances of that class. new.instancemethod can be used to add a method to an individual instance. >>> class A: pass ... >>> a1 = A(); a2 = A() >>> a1.f = new.instancemethod(lambda self: "hi", a1, A) >>> a2.f() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'f' >>> a1.f() 'hi' - Anders From max at alcyone.com Mon Jul 21 00:01:45 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2003 21:01:45 -0700 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: <3F1B65A9.839A79E8@alcyone.com> Ben Finney wrote: > You're not requesting to slice a dict; you're requesting to reference > an > element of a dict with : as the key. No he's not, that would be {}[':'] Here's the proof; actually, the error has nothing to do with assignment, it just has to do with slicing: >>> {}[:] Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type What this really does is build a slice object and try that: >>> {}[slice(0)] Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type So the complaint is that the index it's trying to lookup can't be hashed. And that's because slices aren't hashable: >>> hash(slice(0)) Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type Though there's no doubt at all that's a confusing error. But slicing is a feature of a _sequence_ type, not a _mapping_ type. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It is much safer to obey than to rule. \__/ Thomas a Kempis From tug at wilson.co.uk Wed Jul 16 12:23:33 2003 From: tug at wilson.co.uk (John Wilson) Date: Wed, 16 Jul 2003 17:23:33 +0100 Subject: XML <=> Database References: <20030716152600.A1315@cs.unipune.ernet.in> Message-ID: <0f2401c34bb6$9af47930$640a0b0a@handel> vivek at cs.unipune.ernet.in wrote: > Hi all, > > Is there any module available which does the same work as the XML > Integrator > in Java. Actually I am working in an educational institute, there > somebody asked me to teach Java as a part of a Database course. As I > am not very good in Java so I asked for the type of assignments they > want to give to students. So here is what they told me: > > There will be a three tier architechture. One web application, Web > Server, > one Application Server and the Database backend. The Web server will > get the > data as a XML document. This will be passed to the application server > that > will parse the document and will insert/Update/Delete the data in the > database > Server. Similarly the data will be retrieved from the database and > will be > converted in a XML document by the application server and will be > send to the > user's browser through the web server. Can you define the format of the XML document or is it fixed? If you can define the format of the document then you could make it an XML-RPC call. The data from the document would be marshalled automatically by the XML-RPC implementation and you would have very little code to write to perform ythe database access. Likewise the result of a database query would be converted into XMl by the XML-RPC implementation. Using XML-RPC would have the advantage that you could make Python and Java implementations and compare the ease of development and performance between the two approaches. John Wilson The Wilson Partnership http://www.wilson.co.uk From vze4rx4y at verizon.net Tue Jul 29 18:59:14 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 29 Jul 2003 22:59:14 GMT Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> Message-ID: <6%CVa.59$cI2.38@nwrdny01.gnilink.net> > >> In other words, the the inverse of the built-in zip function? > > > > When used with the * operator, zip() is its own inverse: > > > > This (obviously) doesn't work when z has length 0 or 2. > I don't quite understand why zip is overloaded ... > > Oh, hang on, it does work for length 2! that's neat-o, > and perhaps that's why zip was extended. Is it a functional programming > convention, i wonder. > > Simon. There is no special extension to zip(). It just happens to be one of those functions like int.__neg__() that is closely related to its own inverse. * or apply() serve only to break a list into individual arguments. So, transpose() can be defined like this: def transpose(mat): return zip(*mat) The transpose() is its own inverse for rectangular matrices represented as lists of tuples. Raymond Hettinger From postmaster at 127.0.0.1 Thu Jul 10 21:20:48 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Fri, 11 Jul 2003 13:20:48 +1200 Subject: Securing 'pickle' Message-ID: Hi, I'm writing a web app framework which stores pickles in client cookies. The obvious security risk is that some 5cr1p7 X1ddi35 will inevitably try tampering with the cookie and malforming it in an attempt to get the server-side python code to run arbitrary code, or something similarly undesirable. To protect against this, I've subclassed pickle.Unpickler, and added overrides of the methods load_global, load_inst, load_obj and find_class. My override methods simply raise exceptions unconditionally, which causes any unpickle to fail if the pickle tries to unpack anything even resembling code or an object. I did this in preference to using the reputable 'bencode' module from BitTorrent, because bencode doesn't support floats. My question - have I done enough, or are there still ways where my hobbled unpickler could be subverted by a malformed cookie? Cheers David From ianb at colorstudy.com Mon Jul 14 08:36:17 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 14 Jul 2003 07:36:17 -0500 Subject: path module In-Reply-To: References: Message-ID: <1058186176.28457.701.camel@lothlorien> On Mon, 2003-07-14 at 06:44, Hallvard B Furuseth wrote: > Ian Bicking wrote: > >On Tue, 2003-07-08 at 09:52, Hallvard B Furuseth wrote: > >> If there is going to be a New Wonderful Path module, I suggest you give > >> some thought to paths on systems that don't fit the simple Unix/Windows > >> path model. A path to a filename may e.g. looks different from a path > >> to a directory. (...) > > > Interesting, but I think a bad idea. (...) If someone was using VMS > > paths, I would assume they would subclass path for that OS, adding the > > portions that applied. > > It would be pointless to include _data structures_ for components that > are not supported on any system Python is ported to, but for subclassing > to make sense, some of the _interface_ would have to be in place. Like > the possibility of usin path.joindir() vs. path.joinfile() or something > depending on whether the result should be a file or directory path. And > just path.join() for people who don't care. Assuming there will be a > join method, of course. Since *no one* will ever use joindir or joinfile, why would it be helpful? Modern systems just don't make that distinction, and people aren't going to make that distinction in their code. > Also, you may need some special handling of 'device:' on Windows. Yes, and the network portion as well (\\server\...). However, it would still be handled textually. I.e., path(r'\\server') would happen to create this network path, and path(r'\something_else') wouldn't. The Windows implementation of path would presumably have an attribute to get at "server" (.unc or something), while you'd get an AttributeError on Posix systems. > > I think it's unreasonable to expect people programming on normal > > platforms to pay attention to components like version, so even > > including it in a structured manner is asking for trouble. > > I dunno. People have already mentioned coming systems where versions > will be availbale. But we have no idea what it will look like, or how it may be represented in a filename (if at all!) -- so implementing something based on that would be a little optimistic. You're likely to create an interface that won't make sense. Better to leave it unspecified until there's an actual system you want to support, at which point the interface will seem much clearer. Predictive design is a very bad idea. Ian From tim at lesher.ws Wed Jul 16 22:17:47 2003 From: tim at lesher.ws (Tim Lesher) Date: 16 Jul 2003 19:17:47 -0700 Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: Doug Tolton wrote in message news:<215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>... > This solution strikes me as inelegant and ugly. Is there a cleaner > way of accomplishing this? The problem is this: performing addition of tuples is concatenation, not addition of the elements. If you try to decompose the augmented addition into an addition and an assignment, you get a tuple that is (in your case) the concatenation of the two 3-tuples, or a 6-tuple, which can't unpack into a 3-tuple. That said, for some definition of "cleaner", you could do: def accumulate(i,j): return map(int.__add__, i, j) // loop i,j,k = accumulate((i,j,k), fn()) From scasjos at mixmail.com Thu Jul 10 08:41:28 2003 From: scasjos at mixmail.com (jose maria) Date: 10 Jul 2003 05:41:28 -0700 Subject: Executing a remote process via WMI in Win32. References: Message-ID: <99071af2.0307100441.1f8c9b66@posting.google.com> "Sean" wrote in message news:... > I can connect to a machine remotely with no problems but I'm having trouble > trying to create a process remotely. Initially this was a perl and VB > script which I'm converting to python. Its entire purpose is to start a > process remotely. The problem initially was that the perl script could not > 'see' any mapped drives as it would alway return 'access denied' so I'm > trying to not only rewrite the script but fix this problem and my idea was > to connect with the Administrator account. > > Now the following script sort of works. I can get the set of running > processes but it dies out when I try to create one. > > ## being ## > import win32com.client > wmi = win32com.client.Dispatch('wbemscripting.swbemlocator') > remote_machine = > wmi.ConnectServer('','root\\cimv2',Administrator','') > > process = remote_machine.InstancesOf("Win32_Process") > for proc in process: > size = int(proc.WorkingSetSize)/1024 > print proc.Caption, size,"kb" > # test to see if we can 'see' what's on a mapped drive. > # doesn't seem to go. > process.Create("cmd.exe /K dir w:\\") > ## END ## > > The script will print out all the processes fine but once it get's to > 'Create' it dies out with and error message I don't understand. > > NOTEPAD.EXE 80 kb > Traceback (most recent call last): > File "C:\Documents and Settings\scody\test.py", line 14, in ? > process.Create("cmd.exe /K dir w:\\") > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, > in > __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: InstancesOf.Create > > The process method should only have the one parameter as defined at: > http://userpages.umbc.edu/~kbradl1/wsz/ref/WMIref.html#process > > I just tried using the 'Terminate' process but that didn't work either.... > > So I'm going to assume that the WMI objects are not instantiated as python > classes (hence why the methods are not working). Am I completely off base > here (meaning it is a syntax problem)? > > Any suggestions or pointers to the right direction would be creately > appriciated... Hi Sean I?m now work in a module that create several kind of methods to manage process using wmi take one example: I?m use ActiveState Python 2.2.1 firts you have it?s that python know of existencie of WMI for instance you must use COMMakepy utility now Python *knows* about the 'WMI Scripting' typelibrary. Note:this part of script its tested in windows 2000 and its functional except in windows 2000 with SP2 that failed and I don?t know why Example create process: (After Use Makepy) import win32com.client wmi = win32com.client.Dispatch('wbemscripting.swbemlocator') remote_machine = wmi.ConnectServer('','root\\cimv2',Administrator','') strProcess=("cmd.exe /K & dir w:\\") #this is very important you must put & objprocess = remote_machine.Get('Win32_Process') Method = objProcess.Methods_('Create') InParameters = Method.InParameters.SpawnInstance_() InParameters.Properties_.Item('CommandLine').Value=strProcess try: OutParameters = objProcess.ExecMethod_ ('Create',InParameters) ReturnValue = OutParameters.Properties_.Item('ReturnValue').Value ProcessID = OutParameters.Properties_.Item('ProcessId').Value except pythoncom.com_error, (hr,msg,exc,arg): ExceptionHandler(hr,msg,exc,arg) def ExceptionHandler (self,hr,msg,exc,arg): print 'COM call failed: %s' % msg if exc is not None: wcode, source, text, helpFile, helpID, scode = exc print 'Error source:',source print text print 'See also: %s (id=%d)' % (helpFile,helpID) Example kill process: strPid="'yourpid'" # In this form else not work sql="SELECT * FROM Win32_Process WHERE ProcessId=%s" %strPid objProc=objprocess.ExecQuery(sql) if objProc.Count==0: print "Pid strPid Not Found" else: for process in objProc: strmeth = process.Methods_('Terminate') strparms=strmeth.InParameters strparms.Properties_('Reason').Value=0 process.ExecMethod_('Terminate',strparms) Sorry Sean for my bad Enghlis I hope help you From usenet_spam at janc.invalid Tue Jul 15 22:24:33 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 02:24:33 GMT Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3F12CE17.76A0A5@hotmail.com> <16146.53798.759651.430032@montanaro.dyndns.org> Message-ID: Francois Pinard schreef: > "The firm driver is carrying her." Which is a nice example of something that could be misunderstood in English. ;-) (Is the driver strong or does he work for a firm?) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter at engcorp.com Tue Jul 15 12:26:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 12:26:57 -0400 Subject: Stop Python from exiting upon error in Windows References: <3F136BEA.5B56562@engcorp.com> Message-ID: <3F142B51.94C898BC@engcorp.com> Robert at AbilitySys.com wrote: > > Ok, I figured out the IDLE block indent (duh - RTFMenu), and now it works > great in DOS. Again, thanks to all who helped. > > However, I'd still like to know how to determine what environment I'm > running under inside my code. Any suggestions? I doubt if there's any particular way to do it consistently. In principle one could write a cute module which would be able to check the "signature" of the environment to figure it all out. Check if certain modules are in __builtins__ to see if you are running inside an application that uses Python for scripting, check for sys.argv[0] to learn whether you were launched in a way that suggests running as a script with python.exe, etc. It's probably not a great idea to write anything which depends on this however, and it sounds like more time than it's worth. -Peter From fredrik at pythonware.com Fri Jul 4 11:23:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Jul 2003 17:23:07 +0200 Subject: sys.setedefaultencoding() References: Message-ID: Facundo Batista: > Learning (and needing it) Unicode, in Dive Into Python found the > sys.setedefaultencoding() method. Very nice, but in the documentation of the > 2.2.1 version, says that this method is new in 2.0 version. > > I've got installed Python 2.1.1 and when I do dir(sys), don't get that > method!! Strange. And ugly, :( sys.setdefaultencoding() shouldn't be used by application programs; it was added for test purposes only. if you really need to change the encoding, tweak site or sitecustomize, and be aware that 1) python programs you write may not work on other systems, and 2) extensions may not work properly on your system. > - Why this happens? site.py removes the function. > - How can I, by a different method, set the default encoding? the default encoding is ASCII, and shouldn't be changed. good practice is to decode data on the way in, use Unicode strings on the inside, and encode data on the way out. (see the codecs module for information on how to created encoded streams). From bokr at oz.net Sat Jul 12 23:59:53 2003 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2003 03:59:53 GMT Subject: Python - if/else statements References: Message-ID: On Sun, 13 Jul 2003 12:30:52 +1200, dmbkiwi wrote: >On Sat, 12 Jul 2003 23:11:20 +0000, Bengt Richter wrote: > >> On Sat, 12 Jul 2003 14:27:33 +1200, dmbkiwi wrote: >> >>>On Sat, 12 Jul 2003 01:58:13 +0000, Bengt Richter wrote: >>> >> [...] >>>> If that is really happening, I wonder if you are somehow executing code from a different version >>>> or have some kind of mixed-up installation. Or are using incompatible extension modules? >>>> Do you have multiple versions installed? what are your versions, and what sym links are there? >>>> And what are the #! lines of your script(s)? >>> >>>One point that I may not have made clear is that I'm not experiencing this >>>behaviour personally with my set up. It is other people using this script >> Is it a single .py file? BTW, since you uploaded it, is there an URL for it? > >Yes, although it imports a module called karamba (see my original post - >this is a theme run through a theme engine called superkaramba). > Unfortunately that makes me imagine an engine in a theme park, maybe in Argentina ;-P IOW I know nothing about theme engines ;-) >> >>>who are reporting this behaviour. The difficulty I'm having is that it's >>>very hard to debug a problem you're not having. I've sent versions of the >>>script to these people, with print statements at appropriate points to >>>ensure that the script is doing what I think it's doing (in terms of going >>>wrong for them), and from the output they send back, the interpreter is >>>definitely ignoring the else statement and ploughing through them, even >>>though, it's also executed the corresponding if statement. >>> >> I wonder if your script is executed directly by Python. Perhaps it is "sanitized" >> for security reasons before being executed in some context, and it gets glitched, >> in the sanitizing process. If so, could you ask them to put a debug print to >> show what's actually being executed? And ask them how it's being executed >> (ie, exec vs exec in somedir vs execfile vs import and invoke vs whatever they do). > >It is being executed through the superkaramba engine (written in c++ I >believe). Not sure if I, or my users have enough gumption to do the >debugging you are referring to. I have asked them to execute the script >which contains a number of print statements to verify that it is ignoring >the else statement. Is there other debugging info that I should be >printing when running the script? Maybe write a little test of if/else that doesn't depend on any data that you don't control right in the test. E.g., since most of your tests test for == 1 or 0, >>> for testval in (0, 1, None, (), [], '', 'x'): ... if testval == 0: print '%r==0?'%(testval,), ... else: print 'not %r==0?'%(testval,), ... if testval == 1: print '%r==1?'%(testval,), ... else: print 'not %r==1?'%(testval,), ... if testval: print 'if %r?'%(testval,), ... else: print 'not if %r?'%(testval,), ... print ... 0==0? not 0==1? not if 0? not 1==0? 1==1? if 1? not None==0? not None==1? not if None? not ()==0? not ()==1? not if ()? not []==0? not []==1? not if []? not ''==0? not ''==1? not if ''? not 'x'==0? not 'x'==1? if 'x'? Everything should be true (with not prefixes considered). If the if/else tests are not working right for local variables, maybe the results will be glitched. Also declare a global _with the rest, not a separate line_, say g_testval, and do another loop like the above with testval changed to g_testval everywhere. If either of these glitch, I'd bet on the global one, but I actually expect them both to work. It would make another data point though. And just FTHOI, give them a version with 100% space indenting. Then the question would be, if these tests work, why don't the tests in the original code. We could also ask users to run these tests in some simpler context -- what if they just run the above loops in a def test(): (so there's a difference between local and global) with nothing more in the script than test() to invoke it? That must work from the console command line python, or they are totally FUBAR. But it's a data point on the no-errors side of the fence. We could then break down the code into painfully primitive steps, and print (where does printing go, BTW? is stdout captured for you in a file?) the results of each step. Again if something is parsing and potentially modifying the code before executing, giving it something dead simple to parse might help. Can someone say if the code is given to the interpreter completely unmodified, so we can put that to rest? In the meanwhile, if most users have no problem, maybe you have to make a table of user configurations -- versions of linux, bsd, python (multiversion? how last upgraded?), libraries? gcc stuff? etc. until a pattern emerges as to who has the problems and how they are different. Maybe make a little script to capture all that info and make it easy for folks to give it to you. (I wouldn't try to make it automatically send an email without their informed consent, though ;-) Regards, Bengt Richter From tjreedy at udel.edu Sun Jul 27 20:44:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2003 20:44:11 -0400 Subject: changing the List's behaviour? References: Message-ID: > > i want to change the List so that it returns None if the index for > > accesssing list elements is out of bound. Slicing always 'works' (does not raise exception), so seq[i:i+1] returns empty slice rather than length 1 slice if i too large. This is a standard idiom for getting, for instance, first element of list if there is one when there might not be. So slice and condition off length and if 1, extract element. This has advantage over idea above that [] is different from [None] (which you would get is seq[i]==None). Terry J. Reedy From bogus at antispam.com Tue Jul 22 22:20:59 2003 From: bogus at antispam.com (Alex) Date: Tue, 22 Jul 2003 22:20:59 -0400 Subject: Stopping a loop with user input. in curses References: <20030722045203.23831.00000293@mb-m27.aol.com> Message-ID: > Ray says >> Hi Alex > > You got your answer to the second part of the problem from-- > > From: "Dr. Peer Griebel" griebel at konzept-is.de > > Credit where credit is due ! > I certainly didn't want to take anything away from the good doctor. He not only helped me solve the problem, but pointed me towards a very interesting module that I might have otherwise overlooked. I've got to say that the amount of modules in Python is completely mind-boggling. I'm sure many people have written convoluted functions that could probably have been replaced by simple "from module import function" command. I guess python isn't only about learning the proper syntax and such, it's also about learning about all of the modules out there. ... Lord, what have I gotten myself into... :) Thank the gods that there are places like this newsgroup and the [Tutor] mailing list. I have to say that I'm super impressed with the sort of community the Python programming language has. Everyone is really very helpful. ...and I was simply confused earlier when I said I had posted to another Ray. For some reason, one of your posts showed up as "author: Chatralias". Alex From edreamleo at charter.net Thu Jul 31 12:47:08 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 31 Jul 2003 11:47:08 -0500 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: > What to you think python largest compromises are? There aren't any. You want to base significant projects on the highest level, most dynamic tools available (Python), then use Python as a wrapper to hide static inflexibilities and inferiorities when descending to lower levels for whatever (usually spurious) reasons. For example, there is a huge difference between using wxWindows and wxPython, but the performance difference between wxWindows and wxPython is insignificant. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jon+usenet at unequivocal.co.uk Tue Jul 8 13:59:12 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 8 Jul 2003 17:59:12 GMT Subject: Python vs PHP References: Message-ID: In article , Afanasiy wrote: > CGI, FastCGI, SCGI are not faster than mod_python in my experience and > straightforward benchmark. In the case of CGI, yes of course. In the case of FastCGI, your experience contradicts my own. > That's all I can really say about it. CGI is not an option for me. I don't understand why you keep saying "CGI is not an option" when nobody has suggested that you use it. From jim_938 at hotmail.com Mon Jul 7 04:23:15 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon, 07 Jul 2003 13:53:15 +0530 Subject: strings problem Message-ID: ... print t The output is Token: 50 Token: 800 \275\371\264 Instead of this i want the output should be in no's like this: bdF9B4 print repr(t) '\xbd\xf9\xb4' print ''.join(['%02X' % ord(c) for c in t]) BDF9B4 yeah that solved the problem. Can you please tell me sthing more regarding what you have suggested here: print ' ' .join([' 02X' % ord(c) for c in t]) Thanks again. regards, _________________________________________________________________ Dress up your desktop! Get the best wallpapers. http://server1.msn.co.in/msnchannels/Entertainment/wallpaperhome.asp Just click here! From Scott.Daniels at Acm.Org Sun Jul 27 16:29:38 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 27 Jul 2003 13:29:38 -0700 Subject: multithreading-problem In-Reply-To: References: Message-ID: <3f243632$1@nntp0.pdx.net> Diez B. Roggisch wrote: > ... > for i in xrange(4): > thread = threading.Thread(target=lambda : foo(i)) > thread.start() > ... So it appears that the curried lambda passed as target is > somehow a reference equal for all four invocations.... This is why the "curry" recipe dances more jig than you have. the lambda-expression that you've passed in did not do any value-capture. The smallest fix is: > ... > for i in xrange(4): > thread = threading.Thread(target=lambda v=i: foo(v)) > thread.start() > ... With curry from the Python Cookbook (or as below), I'd write: > ... > for i in xrange(4): > thread = threading.Thread(target=curry(foo, i)) > thread.start() > ... The problem is that your lambda expression looks up "i" at function evaluation time (when target is called), not when you assign the target function for the thread. -Scott David Daniels Scott.Daniels at Acm.Org ============================= for 2.2 I define curry as: from __future__ import nested_scopes def curry(*_args, **_kwargs): """curry(f,)() == f(, ) (roughly). keyword args in the curry call can be overridden by keyword args in the later call; curry can be used to change defaults. """ def result(*__args, **__kwargs): if _kwargs and __kwargs: kwargs = _kwargs.copy() kwargs.update(__kwargs) else: kwargs = _kwargs or __kwargs return _args[0](*(_args[1:]+__args), **kwargs) return result From belred1 at yahoo.com Sun Jul 13 18:42:21 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 13 Jul 2003 22:42:21 GMT Subject: anything like C++ references? References: Message-ID: > 3. Why is there no way to reference an immutable object via a > pointer, other than stuffing it into a mutable object designed for > some purpose other than simple pointer behaviour? > >>> a = (1, 2, 3) >>> b = a >>> id(a) 15471760 >>> id(b) 15471760 >>> print b[1] 2 >>> i just referenced an immutable object via a "pointer" and i __did_not__ stuff it into a mutable object as you say. a and b "point" to the same object. bryan From skip at pobox.com Wed Jul 30 15:22:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jul 2003 14:22:29 -0500 Subject: time, calendar, datetime, etc In-Reply-To: <153fa67.0307300326.45a29380@posting.google.com> References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <16168.6901.829996.304197@montanaro.dyndns.org> kylotan> Is there any chance of these modules becoming somewhat combined kylotan> in the future? Maybe. Perhaps you would like to write a PEP? kylotan> Right now it seems a little awkward to find the function you kylotan> want. The main culprit is 'timegm' which is the only thing I kylotan> need from the calendar module but which should probably be in kylotan> the time module. I've never used it, but it looks like you're right. It's the GMT/UTC equivalent of time.mktime(), right? kylotan> PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S %Y')' as a kylotan> reverse-asctime(), and was surprised that I couldn't find this kylotan> wrapped in a function in any of the modules. Maybe such a kylotan> function would be considered for future addition? Seems simple enough to not be needed. What makes asctime() all that special? Skip From csad7 at yahoo.com Sun Jul 20 09:14:18 2003 From: csad7 at yahoo.com (christof hoeke) Date: Sun, 20 Jul 2003 15:14:18 +0200 Subject: xml processing and sys.setdefaultencoding Message-ID: hi, i wrote a small application which extracts a javadoc similar documentation for xslt stylesheets using python, xslt and pyana. using non-ascii characters was a problem. so i set the defaultending to UTF-8 and now everything works (at least it seems so, need to do more testing though). it may not be the most elegant solution (according to python in a nutshell) but it almost seems when doing xml processing it is mandatory to set the default encoding. xml processing should almost only work with unicode strings and this seems the easiest solution. any comments on this? better ways to work thanks chris From codepunk at codepunk.com Wed Jul 23 02:18:26 2003 From: codepunk at codepunk.com (Codepunk) Date: 22 Jul 2003 23:18:26 -0700 Subject: Cluster Node Auto Discovery Message-ID: Hi Everyone, I have written a specialized server in python and now I wish to look at making it scalable. To do this I wish to include automatic discovery of peer nodes operating on my network. Can anyone provide me a pointer as to how I do such a thing? By how to do it I mean how does something like that work at the network level? ping scan the ip range? some sort of broadcast packet? udp request to entire ip range? I am not asking for code just how is something like that typically done? From theller at python.net Wed Jul 9 07:55:42 2003 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jul 2003 13:55:42 +0200 Subject: pythonw freezes with print output References: <20030709.9220899@tomsbook.internedomain.loc> Message-ID: <4r1vsym9.fsf@python.net> Thomas Kwapich writes: > Hi, > > I'm developing a wxpython application under windows 2000. > If I start it with pythonw.exe (without dos window) it freezes > after some time depending on the amount of print output it generates. > On the other hand if I start it with python.exe (the dos window is shown) > it is stable. > Reducing the print output to zero makes it even stable when started with > pythonw. > > (I tried to debug it with SciTe but it doesn't crash with it altough > SciTe starts it with pythonw) > > Any ideas why this happens? It is my experience (with Win2k and XP, and Python 2.2 at least) that you get an IOError after writing 4096 bytes (or so) to sys.stdout. You should probably redirect sys.stdout and sys.stderr to a file, or a file-like object, otherwise you won't see any output or any tracebacks. (It may work in SciTe because SciTe catches the output of the program itself?) Thomas From webmaster at beyond-thoughts.com Tue Jul 29 18:20:28 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Wed, 30 Jul 2003 00:20:28 +0200 Subject: memory leak troubleshooting techniques In-Reply-To: References: Message-ID: <3F26F32C.9060609@beyond-thoughts.com> Adam Deutsch wrote: > I would like to ask some advice about tracking down memory leaks in Python > code. > > We have a python application running on Python 2.0.1 in an embedded Linux > environment (kernel version 2.4.7). We have recently detected a memory leak > that we can see from "ps aux" is attributable to the Python processes. > Running Sam Rushing's (http://www.nightmare.com/medusa/memory-leaks.html) > get_refcounts() function does not yield any smoking guns: the reference > counts for all classes remain stable even as memory use climbs. > > Is there any systematic method of determining how Python is using its > allocated memory? > > Thanks. > There might be one more readon for a memory-leak -- besides an increasing refcount. Have you thought about a growing string? (or an similar object) In Python a string can have 80 MB without problems / not "hurting" python. Of course the refount won't get higher as there's just one string -- but this one might be getting *huge*. I had such a problem when programming PersistentThreads. Making internal calls to the "ZopeRequestDispatcher" caused sys.path to grow. Unfortunately I don't know a way in Python to list objects that consume more than xy bytes of memory. Christoph Becker-Freyseng From duncan at NOSPAMrcp.co.uk Wed Jul 23 04:36:57 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 23 Jul 2003 08:36:57 +0000 (UTC) Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: Christos "TZOTZIOY" Georgiou wrote in news:amqqhv0gbdok6dnk6ib9342lejpc4ap5pd at 4ax.com: > If I may say it sideways, try searching for google for the french word > "c?fe", as in "un c?fe s'il vous pla?t". Wanna bet my message will be > the only one to be found? :) Since when is 'c?fe' a French word? It doesn't appear in any French dictionary I have tried. -- 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 ulope at gmx.de Fri Jul 25 03:37:46 2003 From: ulope at gmx.de (Ulrich Petri) Date: Fri, 25 Jul 2003 09:37:46 +0200 Subject: file.close() References: Message-ID: "Francois Pinard" schrieb im Newsbeitrag news:mailman.1059052897.16526.python-list at python.org... > [Bryan] > > > I'm curious to know how others handle the closing of files. [...] I'm > > aware that files will automatically be closed when the process exits. > > For one, I systematically avoid cluttering my code with unneeded `close'. > The advantages are simplicity and legibility, both utterly important to me. > > However, I do understand that if I ever have to move a Python script > to Jython, I will have to revise my scripts for adding the clutter I am > sparing today. I'm quite accepting to do that revision if this occurs. > Until then, I prefer keeping my scripts as neat as possible. > > For me, explicitely closing a file, for which the only reference is about > to disappear through function exiting, would be very similar to using > `del' on any variable I happened to use in that function: gross overkill... > > The only reason to call `close' explicitly is when there is a need to close > prematurely. Absolutely no doubt that such needs exist at times. But > closing all the time "just in case" is symptomatic of unsure programming. > Or else, it is using Python while still thinking in other languages. > fire up your python and type: "import this" read the output and rethink your codint techniques Ciao Ulrich From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 24 18:22:52 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 Jul 2003 08:12:52 +0950 Subject: Standard behaviour of a getSomething method References: Message-ID: On Thu, 24 Jul 2003 18:09:53 -0300, Batista, Facundo wrote: > Resending... get no answers, don't remember if this mail reached the > list. It reached the newsgroup, and discussion ensued. -- \ "Too many pieces of music finish too long after the end." -- | `\ Igor Stravinskey | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From bertvansesamstraat at hotmail.com Thu Jul 10 07:46:23 2003 From: bertvansesamstraat at hotmail.com (Maurice) Date: Thu, 10 Jul 2003 11:46:23 +0000 Subject: Maxmium bufsize using open2? Message-ID: Dear all, I've a problem using popen2 when using large files. When I use small input files everything works well but when I feed large inputfile to the pipe nothing happens. Is there a maximum bufsize for using the pipe. The code I use is written down here below. Do I need to specify a waittime between line 4 and 5 ? o,i =popen2('command ')) fh=open(os.path.join(self.dirname, self.filename),'r') i.write(fh.read()) i.close() self.StringData=o.read() o.close() From peter at engcorp.com Sat Jul 12 05:16:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Jul 2003 05:16:38 -0400 Subject: Small Python, Java comparison References: Message-ID: <3F0FD1F6.7EA63344@engcorp.com> Dave Brueck wrote: > > I certainly > wouldn't have gotten "approval" to do the simple rewrite, but doing it in my > spare time and having a comprehensive test suite made it possible. Maybe that will change the next time, after others have seen how short a time it took you and how effective the results are. -Peter From ckohrt at igsb.uiowa.edu Mon Jul 14 10:56:00 2003 From: ckohrt at igsb.uiowa.edu (Casey Kohrt) Date: Mon, 14 Jul 2003 09:56:00 -0500 Subject: Encoding error Message-ID: <60CC7EB7BC00D511B0C80060083FD8F0951EA7@dunleith.igsb.uiowa.edu> I get the following error for the list item below. I know I have to encode it, but am unsure how or where to write that in. I am new to python and have had good luck thus far. Any help is greatly apprecieated. I am not on the list, so a response to me is appreciated. UnicodeError: ASCII encoding error: ordinal not in range(128) eainfo = doc.createElement("eainfo") metadata.appendChild(eainfo) overview = doc.createElement("overview") eainfo.appendChild(overview) eaover = doc.createElement("eaover") text = doc.createTextNode(str(list[83])) eaover.appendChild(text) overview.appendChild(eaover) Casey Kohrt GIS Librarian Iowa Geological Survey 109 Trowbridge Hall Iowa City, Iowa 52242 319-335-1353 ckohrt at igsb.uiowa.edu -------------- next part -------------- An HTML attachment was scrubbed... URL: From tsteward at dodo.com.au Wed Jul 9 06:08:45 2003 From: tsteward at dodo.com.au (Tony Steward) Date: Wed, 09 Jul 2003 10:08:45 GMT Subject: Why Python Message-ID: <3f0be9ac@news.comindico.com.au> Hello All, I am looking for a programming language to use to write a database type application to run on windows machines. Is python for me or pls suggest what is. Is there a page that explains in simple terms what Python can do on windows? Is there an IDE? Is the windows api pre wrapped? Thanks Tony From mis6 at pitt.edu Mon Jul 21 10:26:15 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 21 Jul 2003 07:26:15 -0700 Subject: recognizing empty iterators Message-ID: <2259b0e2.0307210626.11a1bbf1@posting.google.com> After a recent thread on .endswith, I have been thinking about iterators. I realized that I don't know a satisfactory way to check if an iterator is empty. In other words I am looking for an "isempty" function to use in "if" statements such as if isempty(iterator): do_something() without side effects. Here are some unsatisfactory ways of implementing "isempty": #1: converting to a list or tuple def isempty(iterator): return not list(iterator) Easy, but one has to create the entire list, thus defecting the basic purpose of the iterator, i.e. lazy evaluation. #2: checking for StopIteration def isempty(iterator): try: iterator.next() except StopIteration: return True else: return False This works, for instance print isempty(iter([])) gives True and it=iter([1,2,3]) print isempty(it) gives False. However, there is a side effect: after the check, the iterator has advanced of one step and now "it.next()" gives 2, not 1. In order this to work without side effects, I should be able to restart the iterator from the beginning, but I don't know how to do that. Is it possible? #3: comparing with the empty iterator emptyiterator=iter([]) it=iter([]) if it == emptyiterator: print 'Ok!' This simply doesn't work. I wonder if the itertools module should contain a function to check for empty iterators, thus simplifying my life ;) Of course, I may well be missing something obvious, if so, please enlighten me. Michele From logistix at cathoderaymission.net Wed Jul 30 22:05:13 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 30 Jul 2003 19:05:13 -0700 Subject: Embedded python: dotted (sub) module name Message-ID: <3c91a864.0307301805.7cfea740@posting.google.com> I get the feeling I'm just picking the wrong google search phrase here, because I'm finding nothing. I'm trying to namespace out some embedded python modules. This works: Py_InitModule("game", py_game_methods); but this doesn't: Py_InitModule("quake.game", py_game_methods); What am I missing here? Any help would be appreciated. From m.hadfield at niwa.co.nz Thu Jul 10 18:53:48 2003 From: m.hadfield at niwa.co.nz (Mark Hadfield) Date: Fri, 11 Jul 2003 10:53:48 +1200 Subject: Convert between Windows style paths and POSIX style paths References: <3F0DE565.1CEA39C6@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3F0DE565.1CEA39C6 at engcorp.com... > Noah wrote: > > > > Does anyone have a function to convert back and forth between > > NT style paths and POSIX style? It seems trivial, but > > I want to make sure I don't overlook some obscure detail. > > Is it a simple matter of translating / and \ characters? > > > > FYI, I need a Python function that does what cygpath does so that > > I can run a script on either NT or UNIX or Cygwin. > > I want my config files use one style of path. > > You can use forward slashes in paths under Win32, except at the > command prompt. > > Even if you switch to use all forward slashes, however, what do > you plan to do about drive letters? There is no obvious mapping > to anything under POSIX, I think. Are you planning on disallowing > paths that go anywhere but the current drive under NT? Well, if you're running on an NT system with Cygwin installed, then the obvious thing to do (really the only sensible thing to do IMHO) is to use the mappings provided by Cygwin. These are set up in the registry and accessed via commands like mount and cygpath, which call functions in cygwin.dll. Eg my system has the following: D:\Cygwin <==> / D:\Local <==> /usr/local And if you want to do *that* then the easiest way, though not the fastest, is to run the cygpath command and trap the output. I have modules that do this in Windows & Cygwin Python, if you (meaning the OP) are interested. Another way is to access the registry and try to duplicate Cygwin's logic. I tried this but gave up on it--life's too short for that. Or you try to adapt the Cygwin C code. Or try to access the functions in cygwin.dll. Whatever. On an NT system without Cygwin, or on a Unix system, then there is no obvious mapping and (as far I can see) no need for one. Why do you want to use one style of path in your config files? Surely it would be better to use paths that are appropriate for the system, then process them with Python's os module. -- Mark Hadfield "Ka puwaha te tai nei, Hoea tatou" m.hadfield at niwa.co.nz National Institute for Water and Atmospheric Research (NIWA) From gh at ghaering.de Mon Jul 7 10:11:08 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Jul 2003 16:11:08 +0200 Subject: NNTP mirror of c.l.p? In-Reply-To: <2a897f11.0307070510.37a4ad41@posting.google.com> References: <2a897f11.0307070510.37a4ad41@posting.google.com> Message-ID: <3F097F7C.8090108@ghaering.de> Wayne Pierce wrote: > Does anyone know if there is a public server where I can download > c.l.p? I typically use GG, but want to test a program on my > Palm-based system for accessing NNTP servers. You could try news.gmane.org. Look for comp.python.general. -- Gerhard From genew at mail.ocis.net Fri Jul 11 19:52:01 2003 From: genew at mail.ocis.net (Gene Wirchenko) Date: Fri, 11 Jul 2003 23:52:01 GMT Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> <1057926047.339659@saucer.planet.gong> Message-ID: <3f0f2312.10854550@news.ocis.net> "Rupert Pigott" wrote: > >"Abigail" wrote in message >news:slrnbgt6ls.ab5.abigail at alexandra.abigail.nl... >> Walter Bushell (proto at panix.com) wrote on MMMDC September MCMXCIII in >> : >> ++ Charles Richmond wrote: >> ++ >> ++ > int *p, x, y; >> ++ > >> ++ > then: >> ++ > >> ++ > y = x/*p; >> ++ > >> ++ > is quite different from: >> ++ > >> ++ > y = x / *p; >> ++ > >> ++ > The first way, "/*" will begin a comment...the second way, >> ++ > you get the integer "x" divided by the integer pointed to by "p". >> ++ >> ++ Ouch!! That is one reason code coloring is *important*. >> >> Nope. That's a reason why code colouring is evil. If you write code, >> and it isn't clear what you mean without the use of code colouring, >> you did something wrong. Your code shouldn't rely on a specific code >> colouring scheme to be understandable. >> >> All in my opinion of course. And mine. >My preference has been to make heavy use of ()'s to >make the meaning of expressions clear. Also I have >seen people cut & paste expressions from one language >to another without checking the precedence rules. You >know what happened next ! :) Not unless I know the precedence rules. Another fun one is mixing languages that truncate when converting float to integer and that round. Like MBASIC 4 to MBASIC 5. I still remember that boneheaded maneuver over twenty years later. Sincerely, Gene Wirchenko Computerese Irregular Verb Conjugation: I have preferences. You have biases. He/She has prejudices. From FBatista at uniFON.com.ar Wed Jul 23 09:17:27 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 23 Jul 2003 10:17:27 -0300 Subject: Standard behaviour of a getSomething method Message-ID: When I want to know about a attribute (e.g.: myAttrib) of an object, I should use the specific method (e.g.: getMyAttrib). Considering that this attribute is always another object (everything is an object in Python), what should getMyAttrib do? 1) Return the object 2) Return a copy of the object How do I return a copy of the object? Thanks for all. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Sun Jul 6 04:19:06 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: 6 Jul 2003 01:19:06 -0700 Subject: getting a submatrix of all true References: <3f07bd72$1@nntp0.pdx.net> Message-ID: <3f07db7a@nntp0.pdx.net> In article <3f07bd72$1 at nntp0.pdx.net>, scott.daniels at acm.org (Scott David Daniels) writes: > Folllowing Bengt and anton at vredegoor.doge.nl (Anton Vredegoor)'s leads, > the following code can be fast (at times). It is quite sensitive to the > probability of non-zeroness, (.01 works well, the .o5 is nowhere near so > nice). > > I get 2.25 min to do 25 x 25 at .05 > 2.75 min to do 30 x 30 at .05 > It gets slow _very_ fast, but gets good numbers if the probability is low > .25 min to do 45 x 45 at .01 > 1.5 min to do 50 x 50 at .01 OK, a bit faster: (bitcount faster, allow choose to sometimes quit early). I get 0.25 min to do 25 x 25 at .05 5.5 min to do 30 x 30 at .05 (?! maybe above was wrong) and: 1 sec to do 45 x 45 at .01 9 sec to do 50 x 50 at .01 -Scott David Daniels Scott.Daniels at Acm.Org ################################### # myopt.py __version__ = '0.4' try: assert list(enumerate('ab')) == [(0, 'a'), (1, 'b')] except NameError: def enumerate(iterable): lst = list(iterable) return zip(range(len(lst)), lst) def bitcount(row): '''Return the number of on bits in the integer''' assert row >= 0 result = 0 while row: result += 1 lsbit = row & -row row ^= lsbit return result bytebits = [bitcount(n) for n in range(256)] # precalculate byte counts def bitcount(row): # replace previous bitcount '''Return the number of on bits in the integer (byte at a time)''' assert row >= 0 result = bytebits[row & 255] while row >= 256: row >>= 8 result += bytebits[row & 255] return result def rowencode(vector): '''convert from a buncha numbers to a bit-representation''' bit = 1L result = 0 for element in vector: if element: result |= bit bit <<= 1 return result class Answer(object): '''An answer represents a result calculation.''' __slots__ = 'rows', 'colmask', '_score' totalrequests = 0 totalcalcs = 0 def __init__(self, colmask, rows): '''The columns in colmask are the ones we keep.''' self.colmask = colmask self.rows = rows self._score = None def score(self): '''Calculate the score lazily''' self.__class__.totalrequests += 1 if self._score is None: self.__class__.totalcalcs += 1 self._score = bitcount(self.colmask) * len(self.rows) return self._score def __repr__(self): return '%s(%d:%s, %x):%s' % (self.__class__.__name__, len(self.rows), self.rows, self.colmask, self._score) totalcalls = 0 def choose(rows, keepcols, N=0, keeprows=None, best=None): '''Choose rows and columns to keep. Return an Answer for the choice''' global totalcalls totalcalls += 1 if keeprows is None: keeprows = [] try: while 0 == rows[N] & keepcols: keeprows.append(N) N += 1 except IndexError: return Answer(keepcols, keeprows) # a difference: some kept columns in this row are non-0 # must drop either those columns or this row # Calculate result if we keep this row (drop problem columns) newmask = keepcols & ~rows[N] if best and newmask == best.colmask: withrow = best # Already have a calculated with this mask. use it. else: withrow = choose(rows, keepcols & ~rows[N], N+1, keeprows + [N], best) # Calculate result if we drop this row skiprow = choose(rows, keepcols, N+1, keeprows, best or withrow) # Choose the better answer (keep the row if everything is equal). if (withrow.colmask == skiprow.colmask or withrow.score() >= skiprow.score()): return withrow else: return skiprow # The data used from the example X = [ [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0] ] def printrep(row, symbols, mask=0): '''A row representing a single row (column-masked by mask)''' assert mask >= 0 result = [] for element in row: result.append(symbols[(1 & mask) * 2 + (element != 0)]) mask >>= 1 assert mask == 0 # mask doesn't extend beyond data. return ''.join(result) def printanswer(data, rows, keepcols): '''Print the represented row''' toohuge = len(data) rowqueue = rows + [toohuge] rowqueue.reverse() nextrow = rowqueue.pop() for rownumber, row in enumerate(data): if nextrow > rownumber: # This row was zapped print '#', printrep(row, '01OI', keepcols) else: assert rownumber == nextrow # This row was kept nextrow = rowqueue.pop() print '_', printrep(row, '01~@', keepcols) assert nextrow == toohuge and not rowqueue def getanswer(data): '''Calculate the best-cut for a particular matrix''' columns = max([len(row) for row in data]) rowdata = [rowencode(row) for row in data] return choose(rowdata, (1L << columns) - 1) def main(data=X): global totalcalls totalcalls = 0 answer = getanswer(data) print 'Requested: %s, Calculated: %s,' % ( Answer.totalrequests, Answer.totalcalcs), print 'answer: %r,' % answer, print 'Score: %s' % answer.score() print 'Total choose calls required: %s' % totalcalls printanswer(data, answer.rows, answer.colmask) def rangen(rows, columns, probability=0.05): '''create a rows by columns data table with 1s at the given probability''' import random result = [] for row in range(rows): result.append([int(random.random() < probability) for column in range(columns)]) return result if __name__ == '__main__': import sys assert getanswer([[0]]).score() == 1 assert getanswer([[0,1], [1,0]]).score() == 1 assert getanswer([[0,1,0], [1,0,0]]).score() == 2 if len(sys.argv) < 2: main(X) else: args = sys.argv[1:] if '.' in args[-1]: assert len(args) > 1 probability = float(args.pop()) else: probability = .2 rows = int(args[0]) if len(args) == 1: cols = rows else: assert len(args) == 2 cols = int(args[1]) main(rangen(rows, cols, probability)) From carsten at sarum.dk Wed Jul 16 10:23:40 2003 From: carsten at sarum.dk (Carsten Gehling) Date: Wed, 16 Jul 2003 16:23:40 +0200 Subject: pso - ImportError: No module named url Message-ID: I've tried to install pso on my webserver and made the first test example. When trying to run it (eg. from the prompt), I get the following error: Traceback (most recent call last): File "test.py", line 3, in ? from pso.service import ServiceHandler File "/usr/local/lib/python2.2/pso/service.py", line 31, in ? from request import ServiceRequest, SERVER_RETURN File "/usr/local/lib/python2.2/pso/request.py", line 36, in ? from url import Url ImportError: No module named url I've checked my Python installation - there is no module named "url". I thought it might be a misspelling of "urllib", but "urllib" is explicitly imported a few lines above in request.py System info: OS: Redhat Linux 7.3 Python: 2.2.2 pso: 0.98.C-beta - Carsten From hanzspam at yahoo.com.au Tue Jul 29 19:01:59 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 29 Jul 2003 16:01:59 -0700 Subject: while (assignment): References: Message-ID: <840592e1.0307291501.42b1156e@posting.google.com> Sybren Stuvel wrote in message news:... > while info = mydbcursor.fetchone(): > print "Information: "+str(info) Typically this is done by breaking out of the loop: while True: info = mydbcursor.fetchone() if not info: break print "Information: "+str(info) (at least as far as I know) From kevin at cazabon.com Fri Jul 25 18:34:11 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 25 Jul 2003 15:34:11 -0700 Subject: Installation Module References: Message-ID: <5a4226f0.0307251434.2d5532fc@posting.google.com> You're probably looking for distutils now. "Harris, Mark W. (DAY)" wrote in message news:... > I recently acquired support for some scripts that are installed using an > install script which imports the "installutils" module. I can't seem to > find this module anywhere. Anyone know if this still exists? Is it > deprecated, name changed, replaced by something else. > > --Mark From alanmk at hotmail.com Tue Jul 29 10:43:14 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 29 Jul 2003 15:43:14 +0100 Subject: Casting stones (was Re: Debugging Python ?) References: <3c91a864.0307282013.2acb2d1f@posting.google.com> <84fc4588.0307290453.52671e11@posting.google.com> Message-ID: <3F268802.BDB26B67@hotmail.com> Aahz wrote: > Top-posting is more annoying IMO. Aahz, I know that you champion the cause of stopping people from top-posting, and I agree that bottom-posting a good thing. However, there is a down side: it makes it impossible to get meaningful summaries of a posters posting history on Google Groups. For example, here is your own history of posts:- http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=author:aahz%40panix.com+ As you can see if you view that history, the summaries represented do not contain what you actually said or wrote: they contain what other people said, that you replied to. While this is generally not a problem, you might find occasionally that it will appear, at the summary level, that you said something that it is the precise opposite of what you actually think or feel. I don't have a solution, but I thought I would point out the problem. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bdelmee at advalvas.REMOVEME.be Sun Jul 13 15:59:51 2003 From: bdelmee at advalvas.REMOVEME.be (Bernard Delmée) Date: Sun, 13 Jul 2003 21:59:51 +0200 Subject: Can't install csv parser References: Message-ID: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> > I'm hoping someone can help me. I've downloaded the csv.pyd file from > http://www.object-craft.com.au/projects/csv/download.html > and put it into my C:\Python22\DLLs directory. Mmh...works for me - ActivePython 2.2.2 Are you sure you downloaded the pyd file corresponding to your python version? Running the MS "depends" utility on csv.pyd reveals that it only needs python22.dll, msvcrt.dll and kernel32.dll. Are these all on your PATH? > Traceback (most recent call last): > File "", line 1, in ? > import csv What's pyshell? did you try from good ole trusty python.exe in a DOS box? Hope this'll help you diagnose, Bernard. From cybersamurai at mac.com Wed Jul 16 13:44:04 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Wed, 16 Jul 2003 14:44:04 -0300 Subject: Where is xpath documentatios or tutorials Message-ID: <200307161444.04428.cybersamurai@mac.com> I can't find tutorials or documentation to use xpath with Python. I need read, create, write xml files easy. From iandjmsmith at aol.com Thu Jul 24 21:32:25 2003 From: iandjmsmith at aol.com (Ian Smith) Date: 24 Jul 2003 18:32:25 -0700 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: <2dc49b63.0307240824.4e1b2136@posting.google.com> "Alan Dechert" wrote in message news:... > "Andrew Dalke" wrote in message > news:bfkch9$is4$1 at slb4.atl.mindspring.net... > > Alan Dechert: > > > catch it. If one percent of the electronic votes were altered (evenly > > > distributed), you will find one mismatch for sure after checking only a > > > dozen or two ballots. > > > > Actually, around 70 ballots. > > > > The odds of finding one ballot to be wrong is 1%, so there's a 99% > > chance that it's unaltered. There's a 0.99*0.99 chance that two are > > unaltered, and in general a 0.99**n chance that n are unaltered. > > > > To get even odds of noticing an error requires > > > > 0.99**n == 0.5 > > --> log(0.99)*n == log(0.5) > > > > >>> math.log(0.5) / math.log(0.99) > 68.967563936528421 > > >>> > > > > about 70 verifications. > > > A likely story. I actually took combinatorics and a class in statistics in > college. But that was a long time ago. Since then, many brain cells have > died, tragically. > > BTW, do you know about cumulative binomial distribution? I think we need to > include a tool like this to give us some "C.L" (confidence level) short of > verifying that every single paper ballot matches its electronic counterpart. > > http://www.reliasoft.com/newsletter/2q2001/cumulative_binomial.htm > > What I really want is a calculator. Do you know of a free calculator for > this? If not, could you make one? (for free, of course). > > Alan Dechert There's a lot of assumed knowledge in this discussion. I know nothing about electronic voting systems, I know almost nothing about Python as a programming language but I do know how to calculate values associated with the cumulative binomial distribution. A Javascript (sorry!) calculator for the binomial distribution amongst others can be found at http://members.aol.com/iandjmsmith/EXAMPLES.HTM. Javascript can be converted to Java, C etc quite easily. I would imagine with my lack of knowledge of Python you'll probably be better off doing the conversion yourself. The code is quick and accurate and can handle large sample sizes and very small probabilities which you probably need. There's even a calculator for the Hypergeometric distribution should you wish to do sampling without replacement calculations. Ian Smith P.S. the calculation of 70 is fine. If you don't want to calculate anything much more difficult then you probably don't need a calculator anyway. From bgailer at alum.rpi.edu Mon Jul 7 14:03:54 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 07 Jul 2003 12:03:54 -0600 Subject: A story about Python... sort of In-Reply-To: <87wueu7bat.fsf@pobox.com> References: Message-ID: <5.2.1.1.0.20030707120140.025cb7d8@66.28.54.253> At 01:48 PM 7/7/2003 +0100, John J. Lee wrote: >"Tony Meyer" writes: > > > > A chess program > > > is different from a 3D game in that with a 3D game, you can > > > stop at some point and say, "ok, this is fast enough." There >[...] > > This isn't really true. Sure you can say that the framerate is fast > enough, > > but when do you stop and say "the graphics look real enough"? (I'm sure > > there is a point, but it's a distant point, like 'solving' chess). > >No matter how distant, it's nowhere near as far off as 'solving' chess >(which is no doubt physically impossible, at least with classical >(Turing machine) computation). Physically impossible? or impractical. If it can be solved by Turing machine computation then it is physically possible, even though it might take more time/resources than anyone cares to expend. But remember "When Harley Was One" and he invented the G.O.D.? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From jadestar at idiom.com Fri Jul 18 16:50:10 2003 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 18 Jul 2003 20:50:10 -0000 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: <1058561410.563105@smirk> Sean 'Shaleh' Perry wrote: >> If my english was better I would love to help improve the python >> documentation, most modules in the standard libraries lack good >> examples how to *use* them with just a simple description. And a >> short motivation for the design of a module if possible like "just >> copied the C API" or "Because of efficiency ..." or "We use a class >> framework here because ...". A gigantic task. The PSL book by effbot >> is great but it's a book. And it needs a new version. > part of the reason why the docs are not but so great is that most of the > library is Python code which means any questions can be answered by reading > the source. I find myself doing this quite often. That's BS! As a dabbler in programming I have to say that poor documentation is not excused by the availability of sources. If the sources are that informative than relevant portions should be pasted into the docs (or, better, marked up in some way that a doc generator and extract them into the officials docs). If the docs need to refer to the sources so often, perhaps we should re-write the docs so that every page has hyperlink references to the relevant source modules. Making someone manually hunt down information from alternative sources is a great way to frustrate them! > Many modules have a little blurb at the top that gives an example of their > usage. Sounds like a job for doc strings. Moreover it sounds like a job for an automated docstring processing (http://docutils.sourceforge.net/ perhaps?) > from imaplib.py: > Instantiate with: IMAP4([host[, port]]) > host - host's name (default: localhost); > port - port number (default: standard IMAP4 port). > All IMAP4rev1 commands are supported by methods of the same > name (in lower-case). More importantly this module *does* give a 10 line code example: http://www.python.org/doc/current/lib/imap4-example.html It would be nice if it also explained some of the magic numbers and strings in comments or in some text around the example: Why data[0] Why M.search(None, 'ALL') and why '(RFC822)' as the 2nd arg in the M.fetch() Okay, now I go back to another page and read about the .search() and .fetch() methods. Hmmm, .fetch() lists UID and BODY, no reference to RFC822 and not hint as to where I'd find any other valid strings here; I guess I have to go read the IMAP RFCs, where are those? Ooops, another trip to Google! Google would be so necessary if HTML authors would link to other relevant sources! If we expect people to read the RFCs in order to use the bloody module than we ought to at least provide the link to the RFC! (Putting a copy on our own servers to ensure a stable URL is Okay). The documentation of the .search() method also neglects to make any mention of 'ALL' though we might expect that to be the MOST COMMON CRITERIUM! (at least for someone who's just trying to learn the module!) I'm only picking on this particular page because you brought it up. Actually it's one of the better pages because it does include an example. The pty module is one of the worst. Pipe in if you were able to use the pty module just from the docs! Python includes the broadest wealth of modules I've never seen in a programming language. Docstrings are a stroke of pure genius. The interpreter's readline and rlcompleter support is wonderful for beginners and dabblers --- and rlcompleter2 is EVEN BETTER (Guido --- please merge that! :) ). The docs are Okay --- but could be ALOT better. I'd love to see a way for members of the community (even duffers and dabblers like me) to submit doc enhancement suggestions and requests directly through the online HTML documentation (similar to the PHP system at: http://www.php.net/docs.php). Of course more well-known, trusted members of the community should have the power to editing, revise, even throw out comments. One danger I see in __doc__ is the various ways in which they are being overloaded. doctest seems reasonable; a small sample usage that also serves as an automated test suite. (Yes, I have read the little Soapbox note at: http://www.python.org/doc/current/lib/node130.html) However some of the programming by contract (http://www.wayforward.net/pycontract/ ) starts to worry me. How will doctest and pycontract play together? How will docutils handle the results? What will be the next clever uses of __doc__ members? How will it mesh with all the other uses? It sounds like one might very reasonably argue that these other uses should have their own standards (or conventions) with their own namespaces: __testsuite__ and __contract__ (or __pre-condition__, __post-condition__, and __invariants__), for example. (Even that use is *almost* documentation so I can stretch a little to see it --- and it is a nice hack. However, if something like pycontract is ever accepted into the standard libraries, I'd suggest it be given it's own __ namespace) From http Fri Jul 11 01:40:12 2003 From: http (Paul Rubin) Date: 10 Jul 2003 22:40:12 -0700 Subject: Securing 'pickle' References: <7xu19t21ap.fsf@ruckus.brouhaha.com> Message-ID: <7xy8z5ei4j.fsf@ruckus.brouhaha.com> Dave Cole writes: > I have been googling for information on the "appending" attack against > md5 and cannot find anything that clearly describes it. Do you have > any links handy? I think RFC 2104 (the HMAC spec) might describe it. Basically, think about how md5 works. You load the md5 context with the secret key (say 20 bytes) then your data (say 20 bytes), then some padding to fill the 64 byte context, and run the compression function: md5_compress(key + data + 24 bytes of padding) Call the 24 padding bytes P. They are just 16 0's plus an 8 byte length, iirc. The hash output is just the md5 chaining variables after running the compression function. Now look at the 100 byte string E = your data + P (same as above) + 36 bytes of evil stuff Even without knowing your secret key, if the attacker knows your data (which may not be secret), and md5(key+data) (which you've included in the cookie), he can compute the signature of E. It's just the result of running the compression function on his evil stuff plus appropriate additional padding, with the chaining variables set to the original md5 hash that you already sent him. This is not really a failure of md5, which is supposed to be a message digest algorithm, not a MAC. Rather, the authentication fails because md5 is being used in a way it was not intended to be used. The solution is to use HMAC. See RFC 2104 for details. From dhostetler at sopris.net Tue Jul 8 15:01:55 2003 From: dhostetler at sopris.net (.d.hos) Date: 8 Jul 2003 12:01:55 -0700 Subject: parsing flat file to mssql (odbc) Message-ID: <8db020b9.0307081101.23325bd@posting.google.com> ok, fairly new to python, relatively familiar w/ ms-sql. here's my issue: my .py script parses the contents of a (tab delim.) flat file, then attempts to insert the information into the db. I've been fighting this for a day or so, and i'm stuck on the db insertion... basically the script uses .readlines() to capture the flat file contents, and stick the *record* into a container list... something to the effect of: for l in lines: fields = string.split(l,'\t') dic.append(fields) then, I just want to loop over that container list and do a simple INSERT statement. I've tried using the .executemany() method to no avail. .execute(sql, tuple) seems to be working better. sql statement (lots of columns): --------------------------------- INSERT INTO tbl_pyDev (COURSE_SECTIONS_0,Term_1,Synonym_2,Section_Name_3,Location_4,Bldg_5,Room_6, Days_7,Start_Time_8,End_Time_9,Start_Date_10,End_Date_11,Add_Start_Date_12, Drop_Start_Date_13,Add_End_Date_14,Faculty_15,Short_Title_16,Prerequisite_17, Required_18,Coreq_Noncourses_19,Course_20,Cred_Type_21,SEC_CRS_DESC_22, Long_Title_23,Depts_24,Fee_25,Meeting_Days_26,Printed_Comments_27,Subject_28, Supplies_29,Transfer_Status_30,Course_Cost_31,Status_32,Capacity_33, COURSE_SECTIONS_34,Corequisite_Sections_35,Section_36,Min_Cred_37, Instr_Methods_38,SEC_FACULTY_FIRST_NAME_39,SEC_FACULTY_LAST_NAME_40, Refund_41,CoReq_Name_42,Drop_End_43) values (?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ugly eh? well, here's an example of what I'm trying to feed this beast: (the first row of data is col. headers, and thy insert fine. This is actually the chunk of data the script is choking on (dic[1])) --------------------------------------------------------------- ('2475', '03/FA', '25000', 'AAA-010-AS01', 'AS', 'AS', '116', 'TTH', '05:00PM', '06:50PM', '09/09/03', '10/02/03', '09/09/03', '09/09/03', '09/26/03', 'Rameil, Lesley J', 'Aca Achieve Pre-College', '', '', '', '1139', 'UG', "Meets the requirements of the Comprehensive Student AssessmentSystem and the Secretary's Commission on Achieving Necessary Sklls, as well as work and postsecondary enrollment skills. Enabes the student to review and improve in reading, writing, matheatics, science, and social studies in preparation for the GED tst.", 'Academic Achievement in Pre-College', 'AAA', '', 'T', '', 'AAA', '', 'NT', '', 'A', '35', '2475', '', 'AS01', '1.00', 'LEC', 'Lesley', 'Rameil', '09/12/03', '', '09/26/03') I'm executing in this sort of fashion: -------------------------------------- for data in dic: cursor.execute(insertSQL, tuple(data)) Error: --------------------------------------- Traceback (most recent call last): File "C:\Python22\parse_flat.py", line 101, in ? cursor.execute(insertSQL, tuple(data)) dbi.internal-error: [Microsoft][ODBC SQL Server Driver][SQL Server]Location: record.cpp:2253 Expression: m_futureSize == 0 || rec.Size () == m_futureSize SPID: 58 Process ID: 1136 in EXEC so, if the column headers make into the db, it has to be the formatting of the following data?!?! single quotes?!?! i'm fried on this...if anyone has any input I would be very grateful. thanks - d From ageron at HOHOHOHOvideotron.ca Wed Jul 2 09:21:45 2003 From: ageron at HOHOHOHOvideotron.ca (Aurélien Géron) Date: Wed, 2 Jul 2003 15:21:45 +0200 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: > In article <87of0pno5s.fsf at titan.staselog.com>, > Edvard Majakari wrote: > > > >I'm rather interested in (and fond of) unit testing as well as TDD, so I > >though to share my opinions. I once discussed TDD with my friend in here, > >and the common agreement seemed to be that TDD is not a silver bullet - > >often there are types of computational modules that are very hard to unit > >test, eg. think of graphical user interfaces or complex systems, where > >forking or threading is concerned. > . > . > . > While we're all being rational enough to look at bundles of > costs and benefits, this observation hints at a different > insight: that it's possible to *design* for testability. > > Yes, GUIs and forking and threading are hard to test. SO > DON'T DO THEM. Or, as I prefer, adopt models of GUI and > concurrency development that lend themselves to testing. > > At this point, I should explain what I mean by that. I > haven't yet figured out how to say it in less than a book; > therefore, all I can contribute for today are the slogans > above. > > If you're in a situation where unit-testing is bad, you're > probably in a bad situation. Change your situation. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://phaseit.net/claird/home.html I think I sort of understand what you mean, Cameron, but IMHO it looks to me that you are trying to fit everything into one vision ("Everything looks like a nail when you have a hammer"). There are things that are hard to unit test (I'm talking about automated unit tests here) and which you just can't do without in some projects. For instance, the database! I worked in a couple of projects with automatic unit tests for the DB related components, and having lived through it, I'm not sure that it was worth it at all! Manual unit tests would have made much more sense. The same goes for GUIs. I'd be interested to know about projects where they automate unit tests for GUIs, but I suspect it would be just as cumbersome. And live without threads? A lot of projects would be better off not using them, I agree with that, but some projects just can't do without them! Web sites are also horrible to automatically unit test. In all those cases, I much prefer having a human being go out and do the unit tests manually. I guess my point is that though you may be right in some specific contexts, I don't think you can generalize. That's IMHO of course. I may not have understood exactly what you meant, though. You may want to send me a copy of your book? ;-) Aur?lien From posselt at hotmail.com Mon Jul 14 08:10:14 2003 From: posselt at hotmail.com (Peter Vestergaard) Date: Mon, 14 Jul 2003 14:10:14 +0200 Subject: command prompt change dir References: <200307110928.02474.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: Hi The idea of a temporary file seemed a bit ugly to me, but at second thought it ain't that bad, and now I have made a solution with 1 bat file (call python, call temp.bat, del temp.bat), 1 python file and 1 temporary bat file, which works exactly as I wanted it. Thanks for all the suggestions! /Peter "I?igo Serna" wrote in message news:mailman.1058127209.14405.python-list at python.org... From jjl at pobox.com Sat Jul 26 16:25:21 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Jul 2003 21:25:21 +0100 Subject: autoconf-style checking for installed libs with DistUtils References: <60uav-or3.ln1@nb2.stroeder.com> Message-ID: <87znj12fym.fsf@pobox.com> Michael Str?der writes: > Is it possible to probe for installed libs with DistUtils? > > I'd like to automatically search for optional libs and adjust C > compiler switchers before starting the build of a the extension module. Unfortunately, great though it is, distutils can be a bit hard to customize. I remember having trouble getting extra gcc switches in, and getting data put where it needed to go. Generally, you do whatever you like before calling setup(), to figure out library paths and such. I haven't heard of any autoconf-like facilities having been added. If you have a particular problem, try asking about that. I wonder if SCons (pure-Python) could help in some way with this kind of stuff? It *does* have some (newish, I think) autoconfiguration code, but I don't know if it has any distutils support. John From duncan at NOSPAMrcp.co.uk Thu Jul 24 12:21:43 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 24 Jul 2003 16:21:43 +0000 (UTC) Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: Marc Wilson wrote in news:bupvhv4sgqtqlhlpvb8m05ksei86oke79u at 4ax.com: > Oh, and- is there a way to overwrite text onto an image? The site is > a house-sales site, and we want to overwrite "SOLD" across the > thumbnail once a property is sold. It looks like I can do this with > the ImageDraw module, but I can't see how to replicate what we do now > with Image Robot, which is to write "SOLD" across the image diagonally > (using the Add Watermark feature). Any ideas? How about this: from PIL import Image, ImageFont, ImageDraw, ImageChops im = Image.open("test.jpg") im.thumbnail((128, 128), Image.ANTIALIAS) font = ImageFont.truetype("arial.ttf", 30) def AddOverlay(im, origin, text, angle=-45): # Create an overlay with white text and subtract it from the image. # This effectively blacks out the area to be overlaid. overlay = Image.new(im.mode, im.size) draw = ImageDraw.Draw(overlay) draw.text(origin, text, (255, 255, 255), font=font) overlay = overlay.rotate(angle) stamped = ImageChops.subtract(im, overlay, 1, 0) # Now create a red overlay and add it to the subtracted image overlay = Image.new(im.mode, im.size) draw = ImageDraw.Draw(overlay) draw.text(origin, text, (255, 0, 0), font=font) overlay = overlay.rotate(angle) stamped = ImageChops.add(stamped, overlay, 1, 0) return stamped stamped = AddOverlay(im, (10, 50), "SOLD!") stamped.show() -- 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 dtolton at yahoo.com Tue Jul 8 13:21:54 2003 From: dtolton at yahoo.com (Doug Tolton) Date: Tue, 08 Jul 2003 17:21:54 GMT Subject: Embedding as scripting engine References: Message-ID: There are a couple of sources of information. Mark Hammond & Andy Robinsons book "Python Programming on Win32" has an excelent section on Dynamic Code Evaluation. This is in Chapter 8 Adding a Macro language. They also mention that there is a com server included with PythonWin that is located at Python\win32com\servers\interp.py. This is a python interpreter that can be bolted onto any com server. If you are using a unix platform, you obviously won't be able to use com, but the basic concepts will still be the same. You will need to use Eval and Exec for dynamic code evaluation. Good Luck Doug Tolton On 8 Jul 2003 03:50:55 -0700, theincredibleulk at hotmail.com (?lfur Kristj?nsson) wrote: >Python... a great language, no doubt. And the abillity to be able to >extend it with C/C++ code, fantastic. But has anybody been able to >successfully embed Python in their application to use it as a >scripting language of sorts? > >I am in the process of writing a game and from the documentation and >word of mouth gathered that Python would be just the thing for the >scripting part. And sure enough it is easy enough to run Python code >from C/C++. However, in order to be make it do something actually >useful for my game it would be handy to be able to pass in anything >besides the basic data types (strings, numerics) such as either an >instance of or a pointer to a gameobject. What I want to be able to do >is something like this: > >GameObject go; > >Py_Initialize() >... >PyObject* po = GameObject2PyObject(go); >... >result = PyObject_CallObject(func, "O", po ); >... >go = PyObject2GameObject(result); > >Theres alot of documentation and discussion out there that suggests >that this should be possible but noone seems to tell you how it's >actually done. Am I just missing something blatantly obvious? > >Thanks >//ulk From skip at pobox.com Wed Jul 30 15:35:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jul 2003 14:35:02 -0500 Subject: Ver 2.3 install over 2.2? In-Reply-To: <5.2.1.1.0.20030730112144.02c30b88@66.28.54.253> References: <5.2.1.1.0.20030730112144.02c30b88@66.28.54.253> Message-ID: <16168.7654.115889.178699@montanaro.dyndns.org> Bob> Is it OK to install 2.3 in my python22 folder, thus preserving all Bob> the libs and packages already installed, or do I have to reinstall Bob> all of them, or what? I wouldn't do that. Some files may have disappeared between 2.2 and 2.3, in which case they would still be left in the python22 tree waiting to pounce upon some unsuspecting program. You're really going to be better off installing 2.3 alongside 2.2 then reinstalling packages with the new version. Once you're satisfied that 2.3 is working for you, go ahead and uninstall 2.2. Skip From printers at sendme.cz Mon Jul 7 16:12:02 2003 From: printers at sendme.cz (A) Date: Mon, 07 Jul 2003 22:12:02 +0200 Subject: Is there any solution in PYTHON? Message-ID: <3F09F032.20821.AC27E76@localhost> Hi, I have a program that downloads some web pages. Sometimes there is a poor internet connection and my script freezes( hangs) and does not download ALL pages. Is there any solution how to test if the program works and if not re-start it from the point where it stopped? Or simply how to download ALL pages eventhough there is a timeout connection( can be of any value)? Thanks for help Ladislav From tim at zope.com Tue Jul 8 11:54:52 2003 From: tim at zope.com (Tim Peters) Date: Tue, 8 Jul 2003 11:54:52 -0400 Subject: __eq__ and __ne__ In-Reply-To: <3F0AE020.7040701@zope.com> Message-ID: [Shane Hathaway] > I was surprised by the following behavior. Apparently, the "!=" > operator does not fall back to using "not __eq__()". That's true -- there are no magical equivalences among the six rich comparison operators. > I tested this with Python 2.1, 2.2, and 2.2 with new-style classes and > got the same results in every case. Whew! I was afraid a bug may have slipped in . > >>> class foo: > ... def __eq__(self, other): > ... return (other.__class__ is self.__class__ > ... and other.__dict__ == self.__dict__) ... > >>> foo() == foo() > 1 > >>> foo() != foo() > 1 > > I would expect the second test to yield "0". To compensate, I've > started adding the following boilerplate code to all classes that > define only __eq__: > > def __ne__(self, other): > return not self.__eq__(other) That's appropriate if that's what you what "!=" to mean. > Does this surprise anyone else? I have not yet found documentation > on this. The language (not library) Ref Man says this (under "Basic Customization"), and means what it says: The correspondence between operator symbols and method names is as follows: xy call x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y). In the richcmp PEP: http://www.python.org/peps/pep-0207.html point 3 under "Proposed Resolutions" gives one rationale: 3 The == and != operators are not assumed to be each other's complement (e.g. IEEE 754 floating point numbers do not satisfy this). It is up to the type to implement this if desired. Similar for < and >=, or > and <=; there are lots of examples where these assumptions aren't true (e.g. tabnanny). A more involved (and probably more basic) rationale has to do with that the richcmp operators aren't constrained to return Boolean results; as the PEP says at its start: The main motivation comes from NumPy, whose users agree that A In Excel, I have a module named modCSV which has a function named SaveSheet(), which I want to be able to call from python. How do I do it? I've opened the workbook containing the module, and executed the code: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 wb = xlApp.ActiveWorkbook wbc = wb.VBProject.VBComponents("modCSV") wbc.SaveSheet() but I get the error message: Traceback (most recent call last): File "C:\Documents and Settings\mcarter\My Documents\cvs-tree\project\2195\code\temp.py", line 17, in ? wbc.SaveSheet() File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", line 454, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .SaveSheet It apparently likes the line wbc = ... , but then hates wbc.SaveSheet(). *Sigh* From duncan at NOSPAMrcp.co.uk Wed Jul 23 04:16:41 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 23 Jul 2003 08:16:41 +0000 (UTC) Subject: Python and VS.Net References: Message-ID: "Tim Peters" wrote in news:mailman.1058934395.4215.python-list at python.org: > [Ravi] >> Has anyone tried building Python with VC++.NET? Does it work or fail >> horribly like I think it will. > > Yes, several people have built it that way, and it works fine. > >> My boss seems to think it is good to have programs that are in >> managed code because it is more 'portable'. Not that there's another >> complete .NET runtime besides Microsoft's but he does not understand >> that. Note that Python build using VC++.Net won't be managed code. Its just a plain old unmanaged application built with the more recent compiler. Python build for the managed code environment would be a whole different kettle of fish. -- 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 pyguy30 at yahoo.com Wed Jul 30 18:57:41 2003 From: pyguy30 at yahoo.com (john) Date: 30 Jul 2003 15:57:41 -0700 Subject: urllib(2) and https blues? try pytunnel for python tunnelling Message-ID: The python libraries like urllib and httplib do not support ssl through a proxy. Urllib2 supports http through a proxy or https alone, but not https through a proxy. A while ago my wife complained to me that perl had trouble w/https. I was surprised since perl has a lot of networking libraries. Preferring python, I took a look a python and found the same problem. Eventually I figured out what python was missing: tunnelling. Though she may _coax_ me to port the code to perl, I'm writing it first in my favorite language. Pytunnel offers a tunnel that can be used for (among other things) tunnelling the ssl through a proxy. I'd be willing to offer suggestions or myself add the necessary code to urllib2. Anyone know how one goes about doing either? Your python code does not need to be changed except that the port and ip are supplied by the tunnel. Pytunnel uses a custom recvall which is like sendall but for recv. Recvall uses non-blocking sockets,timeouts and sleeps to attempt to get all of the data. If you have a bad network connection you'd want to set the timeout to be high. Recvall will probably be slower than a standard recvall. The code is rough and needs better error handling, comments and such. But since I got it working I decided to post it. You can find it at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213238 Example of usage: import pytunnel,httplib def tunnel_this(ip,port): conn = httplib.HTTPSConnection(ip,port=port) conn.putrequest('GET', '/') conn.endheaders() response = conn.getresponse() print response.read() tunnel=pytunnel.build(host='login.yahoo.com',proxy_host='h1',proxy_user='u',proxy_pass='p') tunnel.run(tunnel_this) From tim.one at comcast.net Wed Jul 23 16:24:21 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 23 Jul 2003 16:24:21 -0400 Subject: python assignment In-Reply-To: <874r1d3avt.fsf@jautero.no-ip.org> Message-ID: [Tim] >> It would be very unusual (because bad design) for the __iadd__ >> method of a mutable type to return a pre-existing object, though. [Juha Autero] > I'm confused. I thought that the idea of __iadd__ is that for > *mutable* types it modifies existing object instead of returning new > one. Bjorn added more appropriate words -- it would be bad design for the __iadd__ method of a mutable type to return a pre-existing object other than self. >>> a = [1, 2] >>> b = [1] >>> b += [2] While "a == b" must be true at this point, it would be a nightmare if "a is b" could be true at this point. For immutable types it doesn't matter: >>> a = (1, 2) >>> b = (1,) >>> b += (2,) It so happens that "a is b" is not true at this point under any Python released so far, but it could be true someday without causing harm. Sorry for the confusion! From adechert at earthlink.net Mon Jul 21 13:48:40 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 17:48:40 GMT Subject: Python voting demo discussion References: Message-ID: "Andrew Dalke" wrote in message news:bfh8rt$3v$1 at slb9.atl.mindspring.net... > So if you want a demo, or you want to experiment with different > interfaces, you might consider using Flash or related tools and only > later, once you're ready for the next development stage, do you > worry about the actual mplementation language used for deployment. > Right. Thanks. That's what we'll do. Alan Dechert From 2002 at weholt.org Wed Jul 16 14:33:41 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 16 Jul 2003 20:33:41 +0200 Subject: Where is xpath documentatios or tutorials References: Message-ID: <1UgRa.6621$os2.100125@news2.e.nsc.no> I don't know if I'm understanding you correctly, but XPath doesn't have that much with the process of reading or writing xml-files. It's used to locate/query for sub-elements of a xml-document ( this might also be slightly incorrect, haven't used XPath that much ). To create a xml-document you can use plain text files you write your structure to manually or you can use something like http://diveintomark.org/archives/2003/07/08/on_simplicity.html. Read the xml-sig docs available on www.python.org. Search www.xml.com or www.ibm.com/developers for python and xml and you'll have tons of things you study. Hope this helps. Thomas "Luiz Siqueira Neto" wrote in message news:mailman.1058377465.26447.python-list at python.org... > I can't find tutorials or documentation to use xpath with Python. > > I need read, create, write xml files easy. > From zathras at thwackety.com Wed Jul 23 07:13:10 2003 From: zathras at thwackety.com (Michael Sparks) Date: Wed, 23 Jul 2003 12:13:10 +0100 (BST) Subject: needs a logo In-Reply-To: <7fe97cc4.0307230144.9119f89@posting.google.com> Message-ID: On 23 Jul 2003, Xah Lee wrote: > it would be good if .. Python have a decent logo. And behold a new highly sought after, long awaited, colourful, graphical and well loved python logo: +------------------------------------------------------+ | _ _ _ | | ___| |__ _ __ _ _| |__ | |__ ___ _ __ _ _ | | / __| '_ \| '__| | | | '_ \| '_ \ / _ \ '__| | | | | | \__ \ | | | | | |_| | |_) | |_) | __/ | | |_| | | | |___/_| |_|_| \__,_|_.__/|_.__/ \___|_| \__, | | | |___/ | +------------------------------------------------------+ ... with apologies to those with the Big Red Python book. Michael. (Sorry, couldn't resist. I'll get my coat) From max at cNOvSisiPonAtecMh.com Wed Jul 23 11:53:45 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 23 Jul 2003 15:53:45 GMT Subject: htaccess & urllib References: <52yTa.21249$On.2682411@twister.nyc.rr.com> Message-ID: thanks! -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Rene Pijlman" wrote in message news:tnbthvorrrc59nn3689ue741lvtb0horke at 4ax.com... > Max Khesin: > >Is there a way to access an htaccess-protected directory with urllib, > >password being known? > > .htaccess is not a protection mechanism, but a configuration > file. If this configuration file specifies HTTP Basic > Authentication you can use: > > "class FancyURLopener(...) > basic HTTP authentication is performed ... > Note: When performing basic authentication, a FancyURLopener > instance calls its prompt_user_passwd() method. The default > implementation asks the users for the required information on > the controlling terminal. A subclass may override this method to > support more appropriate behavior if needed." > http://www.python.org/doc/current/lib/module-urllib.html > > -- > Ren? Pijlman From ed at UDel.Edu Fri Jul 25 15:44:33 2003 From: ed at UDel.Edu (Ed Phillips) Date: Fri, 25 Jul 2003 15:44:33 -0400 (EDT) Subject: Beefing up socket.ssl(...) In-Reply-To: <84e0f331.0307251036.6504b16a@posting.google.com> References: <84e0f331.0307251036.6504b16a@posting.google.com> Message-ID: >From looking at Modules/socketmodule.c in 2.2.2 and 2.2.3, it appears that only a tiny bit of support for SSL has been added. Specifically, unless I'm misunderstanding the operation of the code, there's no way to verify the certificate presented by a server. The code necessary to cause such verification is pretty straightforward for simple "verify the server certificate" purposes so I hacked together some changes to 2.2.2 socketmodule.c to verify the certificates (see below). So now, I can do something like this: from socket import * s = socket(AF_INET, SOCK_STREAM) a = ('www.mycompany.net', 443) s.connect(a) v = ssl(s, '', 'mycacerts.pem') ...and the server certificate is verified according to the CA certs stored in the file. I'm not sure of the intent of the SSL_CTX_use_PrivateKey_file() and SSL_CTX_use_certificate_chain_file() calls in the original socketmodule.c ... they don't seem to do much that is useful at the Python level AFAICT. I guess if you were going to use client certs, and your server requested peer authentication, then it would somehow use private key file (which I guess would contain the client cert and the client private key?) to initiate a client-auth process, but in the normal "I just want to verify the server I'm connecting to has the correct certificate" context, my version seems to be a sufficient starting point. I also, I don't understand the motivation behind requiring both the key_file and cert_file parms. I'm not very good with Python extension modules yet (or OpenSSL for that matter), so I have a printf() stuck in there just to get a meaningful error about the verification process. This could probably be changed to mimic what PySSL_SetError(..) does and return an actual error code and error string tuple, but that's just icing. Also, I noticed that at line 2736 of socketmodule.c (original 2.2.2 version; line 2741 in the 2.2.3 version) there is a "return NULL;" statement missing that may need to be fixed. I don't know what to do with this info. other than post it to this list... maybe someone reading this list will run with it...? Do others beside me find SSL features lacking in Python? Do you use some other module to provide SSL features rather than the basic socket module? Thanks, Ed Ed Phillips University of Delaware (302) 831-6082 Systems Programmer III, Network and Systems Services finger -l ed at polycut.nss.udel.edu for PGP public key *** Modules/socketmodule.c_orig Thu Jul 24 12:26:16 2003 --- Modules/socketmodule.c Thu Jul 24 17:08:36 2003 *************** *** 2760,2769 **** --- 2760,2771 ---- self->ctx = NULL; self->Socket = NULL; + /* if ((key_file && !cert_file) || (!key_file && cert_file)) { errstr = "Both the key & certificate files must be specified"; goto fail; } + */ self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ if (self->ctx == NULL) { *************** *** 2771,2788 **** goto fail; } ! if (key_file) { if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM) < 1) { errstr = "SSL_CTX_use_PrivateKey_file error"; goto fail; } if (SSL_CTX_use_certificate_chain_file(self->ctx, cert_file) < 1) { errstr = "SSL_CTX_use_certificate_chain_file error"; goto fail; } } SSL_CTX_set_verify(self->ctx, --- 2773,2799 ---- goto fail; } ! if (key_file && *key_file) { if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM) < 1) { errstr = "SSL_CTX_use_PrivateKey_file error"; goto fail; } + } + if (cert_file && *cert_file) { + if (SSL_CTX_load_verify_locations(self->ctx, cert_file, NULL) + < 1) { + errstr = "SSL_CTX_load_verify_locations error"; + goto fail; + } + /* if (SSL_CTX_use_certificate_chain_file(self->ctx, cert_file) < 1) { errstr = "SSL_CTX_use_certificate_chain_file error"; goto fail; } + */ } SSL_CTX_set_verify(self->ctx, *************** *** 2805,2810 **** --- 2816,2828 ---- self->server, X509_NAME_MAXLEN); X509_NAME_oneline(X509_get_issuer_name(self->server_cert), self->issuer, X509_NAME_MAXLEN); + ret = SSL_get_verify_result(self->ssl); + if (ret != X509_V_OK) { + /* errstr = "SSL_get_verify_result error"; */ + printf("SSL_get_verify_result returned %d\n", ret); + PySSL_SetError(self->ssl, ret); + goto fail; + } } self->Socket = Sock; Py_INCREF(self->Socket); From jbar at hosting4u.cz Thu Jul 10 10:07:04 2003 From: jbar at hosting4u.cz (Jiri Barton) Date: Thu, 10 Jul 2003 16:07:04 +0200 Subject: LOADING DATA INTO ARRAYS In-Reply-To: <16141.28923.425194.99087@montanaro.dyndns.org> References: <3f0d55db@shknews01> <16141.28923.425194.99087@montanaro.dyndns.org> Message-ID: <200307101607.04338.jbar@hosting4u.cz> > line.split() is not line.split(" "). > > Skip You're right! Shame on me, I did not read the manual properly. Jiri From mertz at gnosis.cx Sat Jul 12 17:11:01 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 12 Jul 2003 17:11:01 -0400 Subject: any such thing as list interleaving? References: Message-ID: Tom Plunket wrote previously: |for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)): | # ... for index,entry in enumerate(aList): #... Or back in the old days: for entry,index in zip(aList,xrange(sys.maxint)): #... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From bokr at oz.net Tue Jul 29 12:19:37 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 16:19:37 GMT Subject: Seeing next character in an file References: Message-ID: On Tue, 29 Jul 2003 09:05:53 +0100, Richie Hindle wrote: > >[Richie] >> seek() works perfectly with text-mode files as long as you only seek to >> places given to you by tell(). So if Keith's peek() function had used >> tell() and then seek()ed (sought()? 8-) back to that point like his >> peekline() does, there would be no problem. > >[Bengt] >> Can you cite a C or C++ standard section that guarantees that seek/tell >> will work that way in text mode? (I'm not saying there isn't one, but >> I couldn't find one quickly ;-) > >ANSI C, ISO/IEC 9899:1990, section 7.9.9.2: "For a text stream, either >offset shall be zero, or offset shall be a value returned by an earlier >call to the ftell function on the same stream and whence shall be >SEEK_SET." > Thank you. It makes sense that you could retrieve and set an underlying binary position and decode forward with arbitrary cooking, so long as that cooking either goes character by character and leaves the binary position to right after what it has used up, or does the equivalent by proper binary repositioning if it grabs a chunk and doesn't use all of it for a given cooking portion, so that the next retrieval (tell) will be valid. I guess I must have been bitten some time in the foggy past, and never recovered trust. Now I have enough at least to use it, though I will probably still want to write a little verification into a unit test if I'm in finicky mode. Thanks again ;-) BTW, is there an ANSI C spec available free on line (or an older, close-enough draft)? Regards, Bengt Richter From elw at euc.cx Wed Jul 30 01:49:26 2003 From: elw at euc.cx (Jeffrey P Shell) Date: 29 Jul 2003 22:49:26 -0700 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> Message-ID: <240b1020.0307292149.2cb95a13@posting.google.com> David Jeske wrote in message news:... > If you are not wedded to Zope for your applications, you may want to > look at Clearsilver. (http://www.clearsilver.net) It is a very mature > system which was developed at eGroups.com, and today is in use on > high-performance sites such as Yahoo! Groups and > wunderground.com. Clearsilver includes a full CGI kit which handles > form variables, cookies, etc. It also includes a PythonObject<->RDBMS > mapping system (MySQL only today, no pgsql yet), and a transparent > translation string extraction system. It is not a "server environment" > like Zope, and in fact you can use it inside of your server of choice > (Apache, Boa, IIS, Zope, etc). > > I find ZPT's model for replacement hard to work with, because it tries > to fit into the xml document namespace. From the ZPT documentation > here: > > http://www.zope.org/Documentation/Books/ZopeBook/current/ZPT.stx > > This example: > > Page Title > > Illustrates how ZPT is making it's "tag" (i.e. tal:content) fit in as > an attribute defined by a new XML namespace. The problem is, this > constrains where you can use template commands to construct the > document. Clearsilver uses a model more like PHP where the tags exist > as items outside of the XML document parsing. This has the drawback > that your template document is not a valid XML document, but it has > the advantage that you can put the tags anywhere. > > For example, in clearsilver, you can construct URLS using sequences of > template commands, even looping. Here is a small example (whitespace > added for readability): > > >a_link I love Zope's page templates. I do have to admit that I worked at Zope Corporation since before Zope was Principia, but am now out in the wild stressful world on my own again. But I grew to *hate* the above style of templating, which Zope's older model (DTML) follows. I've been using DTML since early 1997 and when web applications were still fairly simple, I think it was a nice system (DTML was also simpler then and focused more on being a templating language than on being a programming language, which is what made DTML particularly painful on Zope in later years before ZPT). I work with some very talented designers. It used to be that they would give us (the developers) their designs and we'd rip them to shreds and they could never touch them again. Because now they were in little bits and pieces and stuffed full of tags-within-tags, with silly things like 'standard_html_header' and 'standard_html_footer' (never really fitting a technical definition of header once complex designs enter the equation) making it very painful to apply what they would thing were rudimentary design changes. Not so with ZPT. It's not a holy grail, but it's pretty close. Most of the time, the designers can tweak the site - even in production - without upsetting the natural order of things. Given that they're full time graphic designers (sortof a 'sibling' company. they also do a lot of large volume print material, etc) and not programmers, this is pretty impressive. They are smart enough to watch out for the dynamic parts. But we've had very few issues since moving to it. What I personally like about ZPT is the fact that it feels natural within the HTML/XML environment. It may have taken some getting used to initially, but I find it very natural. And it's extra nice because I can work in smart text editors like XEmacs or BBEdit, or work in GoLive (very nice when used with its WebDAV browser) and can view the whole page - including the 'standard header/footer' (usually supplied by a standard full page macro, which in itself is very easy to modify and edit because it's a single full page and not broken up into chunks like header/footer/sidebar - VERY nice. My life is so much better for this fact alone!). Sometimes adding a dynamic element to a tag from visual mode means just popping up the quick-tag editor and adding in a TAL statement. Close the tag editor, and the page is still intact. You can even do complex things like the following:: .... and have visual editors, or even helpful hilighting editors (BBEdit, XEmacs, etc) not be affected by it. Compared to:: or this, if you only want the class attribute written on even rows (and how we come up with the variable 'even' is being left to the imagination here): class="even"> most editors just die right here - especially visual ones. In TAL, you could do: and most editors would be fine. (Note: 'nothing' is that ZPT equivalent of 'None'. The core components of ZPT (TAL, TALES, METAL) were written as specs first, with the idea/hope that other programming languages could implement them as well, hence 'nothing'. 'None' could have been used in its place just as easily in this situation). Is it more verbose? More typing? At times, yes. But there's a nice explicit nature about it, and many old Zoper's have learned the hard way that explicit is almost always better than implicit (DTML had so many implicit actions going on that in the end - even after years of use - there were always new surprises waiting in the wings. And Radiohead says it best - 'no alarms and no surprises'). Anyways - this is just my personal experience. But I find that (generally) with ZPT, I'm writing better HTML and have a more maintainable web site. It's different, but I think it's a good thing. I'm happy to get away from Server Side Include and Processing Instruction style syntaxes. To get back to your example:: > >a_link ZPT (at least in Zope) has a helpful module called ZTUtils that contains a lot of nice helper functions for building query strings (which I'm increasingly convinced should never be constructed by hand unless absolutely necessary, due to issues with URL and/or HTML quoting), hidden values, etc. Assuming that CGI.Params is a dictionary/mapping, once could do: a_link ``make_query`` (which can also use keyword arguments) is extra nice because it automatically URL quotes all of the values for the query string. This is EXTRA EXTRA nice when passing full LDAP distinguished names in a query string, for example. > > No. Each part of the web page will be "boxes". I would like to be very > > flexible and display "dynamically" some selected boxes. > > For example the same page (url) will not display the same boxes if you are > > administrator, maintener or simple viewer. > > This should be pretty easy in most template systems worth their > weight. > > > An another example will be to have possibility to re-use existing boxes. If > > I have a boxes displaying the last 5 news from Slashdot, I don't want to > > re-write it each time I need a new bacground color (for example). My Idea > > is to use those "boxes" like we use classes : if you need some modification > > you subclass it on the rest remains the same. > > Clearsilver has a macro definition facility for doing just this. You > can supply arguments to macros, and even call macros recursively. Here > is a simple example: > > > title="" > > > > > > > The paramaters can be any expressions, including constructed strings, > or data from your dynamic CGI. For example: > > > > As always, there are lots of systems out there, and YMMV. Macros do make life happy. :) Or at least, happier. ZPT macros (METAL) do things a little differently, but I think it works out for the best. To the best of my knowledge, ZPT compilation/rendering occurs in two steps - first, macros are expanded (METAL statements are executed) into the template like they were there in the template all along, and then all of the TAL statements (including ones that were in the macros) get executed. One thing this allows, when used in a dynamic environment like Zope, is the ability to have the macros be expanded at edit time (optionally, of course). When using a full-page macro, you can add a new ZPT page, fill it in like this::

The body of my new page template

Turn on 'expand macros', and the whole macro 'page' defined in the page template 'standard_template.pt' gets expanded. Macros define 'slots' which clients of the macros can choose to fill in. Nicely, if you don't fill a slot specified by the macro, its defaults are filled in and you can see where the slots are by looking for the 'metal:slot' attributes. The above mentioned macro might contain a slot called 'local_js' and put it on a You can use it if desired, by changing 'metal:slot' to 'metal:fill-slot' and add Javascript to the head of the page - all without requiring changing the header or having to have the page broken up into statements like: ... ... ... Which I've had to do and maintain so many times. I'm not sure when it happened - but at some point, this all got to be unmanageable. It's easy for situations like an intranet or basic web application where you're in control, but when you're on the east coast dealing with a west coast designer who dramatically changes layout every day - it does grow untenable. But I've long been of the personal opinion that HTML and code don't mix. I felt that way ever since I started using CGI and wrote my own little dynamic web system (pummel/pyml/avantpy) in '96 until I got turned on to Bobo (ancestor and still-the-heart of Zope). ZPT lets me see my templates as HTML, but still gives me the programmatic control I need. It's better than the old days when I'd look at my templates and see two conflicting languages that looked alike - an SGML-ish tag based templating language inside the SGML tag based HTML language. For some reason - using basic XML constructs (namespaced attributes) works so much better (for me) than using one set of tags within another set of tags. I think that's all aided by how relatively clean and simple they've managed to keep the core ZPT languages (TAL, METAL). But, as always, mileage will definitely vary. -- Jeffrey P Shell http://toulouse.amber.org/ "Tied you up, placed in tube" http://euc.cx/ From ianb at colorstudy.com Mon Jul 21 05:30:55 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 21 Jul 2003 04:30:55 -0500 Subject: Python voting demo discussion In-Reply-To: References: Message-ID: <1058779855.24478.3073.camel@lothlorien> On Mon, 2003-07-21 at 02:44, Alan Dechert wrote: > Ian Bicking and Andrew Dalke did say they thought Python should be fine for > the demo but I didn't get much detail about why we should prefer it over > some of the other possibilities: HTML, XML, Perl, Java, PHP, C, C++, C#, C, > etc. Well, all of the complexity of you application lies in rendering and UI logic -- the underlying logic of doing a vote is rather simple. It's highly likely that you will want to change both rendering and UI logic as you progress on this. Python is quite appropriate for these sorts of changes, certainly moreso than C and C++, and arguably C# and Java. PHP is tied closely to rendering for the web in a client/server fashion. While you may wish to do this, you may not, and you don't really want to tie yourself to that model. Perl's there's-more-than-one-way-to-do-it motto is a very bad fit for this program. You want a program that is auditable, and Perl is poor at this. HTML and XML don't really count -- you may wish to use those (or not), but you'll still need a programming language. If you want even a nominally Open Source system, C# is out. Technically Mono exists, but the only real development environment you'd have is Windows/Microsoft. I don't believe there's any Open Source community, or significant libraries (but that's mostly conjecture). With all this, I think you are left with Python, Java, and maybe Javascript. Performance is not an issue in this application. Python is faster to develop with, and is particularly faster in terms of ramp-up time (which is what the demo involves). The major obstacle is rendering, as I see it. ReportLab makes rendering the print document fairly easy, and I'm sure similar Java libraries exists. Since you don't seem to want to use normal GUI toolkits (and they don't seem appropriate), you will be off the beaten track to some degree. Pygame offers support, but there's still quite a bit of work involved in handling it. On the positive side, you'll have a high amount of control, as Pygame can take over the screen nicely. I know very little about the Java world, so I have no idea what you might use there. If you use HTML in some fashion (i.e., a browser), you will find rendering a *lot* easier. You can get decent control so long as you are working with just one version of one browser, which is entirely reasonable. Some toolkits have HTML rendering widgets -- I have no idea of their quality or applicability, but it's certainly something worth investigating. Otherwise you may want to use Javascript and program the entire thing that way (possible generating the Javascript at some level -- something that might be appropriate for Python). It's a little odd, and I don't know exactly how to go about it, but I'm pretty sure it is possible. There might be ways you can use a library to render to a pixmap, and use these inside pygame. But what that library might be, I'm not sure. Ian From martin at v.loewis.de Thu Jul 10 16:04:17 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Jul 2003 22:04:17 +0200 Subject: UTF-16-LE and split() under MS-Windows XP References: Message-ID: "Colin S. Miller" writes: > Is there any reason why readline() isn't supported? Because it hasn't been implemented. The naive approach of calling the readline of the underlying stream (as all other codecs do) does not work for UTF-16. > AFAIK, the prefered UNICODE standard line endings are 0x2028 (Line > seperator) 0x2029 (Paragraph seperator) but 0x10 (Line feed) and > 0x13 (carriage return) are also supported for legacy support. Add that on top of that. One should support all line breaking characters for UTF-16, atleast in Universal Newline (U) mode. > I'm using file.read().splitlines() now, but am slightly worried > about perfomance/memory when there a few hundered lines. Feel free to implement and contribute a patch. It has been that way for some years now, and it likely will stay the same for the coming years unless somebody contributes a patch. Regards, Martin From gh at ghaering.de Sun Jul 6 10:19:14 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 06 Jul 2003 16:19:14 +0200 Subject: vim --> python In-Reply-To: References: Message-ID: <3F082FE2.7@ghaering.de> Andreas Steffen wrote: > Hi, > how can I adress the lines, which I send as input from vim to a python > script (in python): > > for example - :1,10!python script.py For this filter, read from sys.stdin and write to sys.stdout. Btw. the print statements writes to sys.stdout as well. > Probably the same problem: > how can I adress something which is piped into a python script? > cat text.txt | python script.py Yup, same problem. Use sys.stdin/sys.stdout. -- Gerhard From rshaw2 at midsouth.rr.com Thu Jul 10 11:07:56 2003 From: rshaw2 at midsouth.rr.com (Richard) Date: 10 Jul 2003 08:07:56 -0700 Subject: Windows Python 2.3b2 bug? Edit with IDLE References: Message-ID: <84e0f331.0307100707.f7f2aba@posting.google.com> "Bartolom? Sintes Marco" wrote in message news:... > Hi, > I am using Python 2.3b2 in a Windows 98 SE machine. If I right-click a .py > file, the menu shows an "Edit with IDLE" option, but when I select it no > IDLE window opens, as Python 2.2.2 did. Is it a known bug, or am I doing > something wrong? > Thanks I had the same problem after installing over 2.3b1, uninstalling python, deleting the directory (C:\Python23) and reinstalling fixed the problem, but realize you'll have to reinstall anything that was installed to the site-packages dir. Richard From alanmk at hotmail.com Thu Jul 10 07:39:36 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 10 Jul 2003 12:39:36 +0100 Subject: Python and freeze (something odd) References: Message-ID: <3F0D5078.1CF6F138@hotmail.com> Aki Niimura wrote: > I'm trying to "freeze" my script to a single executable file under > Solaris using freeze. I have done such many times and it worked > magically (until now). > When I started the generated executable, I got the following: > File "/usr/local/lib/python2.2/email/Generator.py", line 44, in > _is8bitstring [Snip] > unicode(s, 'us-ascii') > LookupError: unknown encoding: us-ascii I think this might be related to a problem that existed in many embedding situations. Check this bug on sourceforge [663074]: codec registry and Python embedding problem https://sourceforge.net/tracker/?func=detail&aid=663074&group_id=5470&atid=105470 I had a similar problem with mod_python and python 2.2.2. I upgraded to python 2.2.3, and the problem just went away. So it's probably worth upgrading to 2.2.3, and see if that fixes the problem? HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From simonb at webone.com.au Tue Jul 1 15:42:06 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 02 Jul 2003 05:42:06 +1000 Subject: function overloading Message-ID: I just wrote the following rediculous code. What do people do when they need to overload like this? Simon. ###################################################### # PIL stuff class Im: def __init__(self,x,xx=None): if xx is not None: w,h = x,xx im = Image.new("I",(w,h)) elif type(x)==str: filename = x im = Image.open(filename) else: im = x self.im = im From Padraig at Linux.ie Wed Jul 9 10:31:36 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Wed, 09 Jul 2003 15:31:36 +0100 Subject: regexp and filenames In-Reply-To: <93f5c5e9.0307090615.1c51f5f7@posting.google.com> References: <93f5c5e9.0307090615.1c51f5f7@posting.google.com> Message-ID: hokiegal99 wrote: > mv test1- "test1*" don't forget to handle the case where test1- already exists. P?draig. From mjackson at alumni.caltech.edu Wed Jul 16 11:37:58 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 16 Jul 2003 15:37:58 GMT Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> Message-ID: Peter Hansen writes: > Mark Jackson wrote: > > > > Michael Chermside writes: > > > Of course, I'm not suggesting that whitespace is *meaningless* in Python > > > outside of indentation... Python is much like C (and many, many others) in > > > that regard. > > > > Note that Fortran (at least historic Fortran - not sure about those > > upstart 9x variants) is *not* among the "many, many others." One can > > write any of > > > > DO 10 I = something > > DO10I = something > > D O 1 0 I = something > > > > and leave it to the compiler to figure out whether you're starting a > > DO-loop or assigning a value to the variable DO10I. > > If you are saying that you leave it up to the compiler to decide how > to interpret any of the three above statements, then clearly whitespace > is *not* meaningless. It might be compiler-dependent or something, > but no meaningless. Unless you are saying that on a given FORTRAN > compiler, only one possible interpretation of all three statements > above is possible. That would be surprising. You misunderstand, probably because I didn't express myself clearly. Again from the Sun Fortran Reference Manual, "Special characters used for punctuation," after the graphic used in the manual for the space character: "Ignored in statements, except as part of a character constant." Ignored means *ignored*, the three examples given will be parsed identically and the meaning will be determined using other information. I think in this case the nature of "something" should be determinative, as the syntax for the range and stride of a DO-loop start, stop [,stride] doesn't match any legal expression (which is what would be required if this were assignment to the variable DO10I. But it's perfectly legal, if insane, to declare (or, with implicit typing undefeated, just go ahead and use) a variable named DO10I and write, say DO 10 I = 1.10 because in Fortran whitespace is *not* considered to delimit tokens. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is necessary to be slightly underemployed if you want to do something significant. - James D. Watson From pwmiller1 at adelphia.net Sun Jul 13 13:44:41 2003 From: pwmiller1 at adelphia.net (Paul Miller) Date: 13 Jul 2003 10:44:41 -0700 Subject: How to crash Python in 1 easy step (python 2.2.2) Message-ID: <2e363c08.0307130944.4c470bc3@posting.google.com> I'm not sure if this is a python bug or a bug in an associated library, and I'm not even sure how to correctly report it, but here is Anytime python is accepting keyboard input, whether it's with raw_input, or sitting on the command line waiting for the user to type code, you can crash python by holding ctrl+shift and then pressing enter. This is on a RedHat 9.0 system running on an Athlon 600. Basically everything about the system is standard except for what's been updated by RedHat itself. If anyone who has the time and ability to track down this bug needs more information, please email me. From bokr at oz.net Tue Jul 15 15:04:15 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2003 19:04:15 GMT Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <3qf6hvcl1j48rnt3m74av0on4ftvd07upd@4ax.com> Message-ID: On Mon, 14 Jul 2003 16:44:09 -0700, Tom Plunket wrote: >Noah wrote: > >> As others have explained, you just return the value. >> It's just a different point of view. Instead of >> change (v) >> you have: >> v = change (v) > >Ahh, now I remember what I wanted to do, and you're right- it's >more verbose and didn't really seem to add anything. I wanted to >in-place clamp integers in a range, or maybe they were even >member variables; > >def Color: > def SomeOperation(): > # modify self.r, g, b > self.r = clamp(self.r, 0, 255) > self.g = clamp(self.g, 0, 255) > self.b = clamp(self.b, 0, 255) > >...that was just more typing than I wanted at that point, >although I'm sure that the keystrokes I burned were more than >made up for by Python's allowing me to do: > > def clamp(val, lowVal, highVal): > if (lowVal <= val <= highVal): > return val > Doesn't clamping ususally return the limit values when exceeded? E.g., def clamp(val, lowVal, highVal): return max(lowVal, min(val, highVal)) Also, if you are dealing with member variables, you can clamp them whenever they are set (including via __init__ code ;-), e.g., (here I built in the clamping code and constants, though it might make sense to parameterize the limits in generating a class or subclass for instances that are all to be clamped the same): >>> class RGB(object): ... def __init__(self, r=0, g=0, b=0): self.r=r; self.g=g; self.b=b ... def __setattr__(self, name, val): ... if name in ('r', 'g', 'b'): object.__setattr__(self, name, max(0, min(val, 255))) ... else: object.__setattr__(self, name, val) ... def __repr__(self): # just so we can see easily ... return '' % (self.r, self.g, self.b, id(self)) ... >>> o = RGB(-3,22,512) >>> o >>> o.g = 256 >>> o >>> o.b = -1 >>> o >>> o.r, o.g, o.b (0, 255, 0) >>> o.g 255 >>> o.other = 'not clamped' >>> o >>> o.other 'not clamped' (Of course, you wouldn't want to use this kind of RGB object to represent pixels where you had to process a lot of them fast ;-) Regards, Bengt Richter From donn at u.washington.edu Mon Jul 14 15:07:48 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 14 Jul 2003 12:07:48 -0700 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058154004.286325@yasure> Message-ID: In article , bokr at oz.net (Bengt Richter) wrote: > On Mon, 14 Jul 2003 03:40:05 -0000, "Donn Cave" wrote: ... > Which might turn out to be equivalent to object.__setattr__(obj, 'x', 10) > or obj.__setattribute__('x', 10) or obj.__class__.__dict__['x'].fset(obj, 10) > or ... > > It depends on what you mean by 'targets'. I argued that the three left hand > expressions all *ultimately* result in some machine level pointer variable > being set > in some object's internal representation to point to the representation of > the object > resulting from evaluating the right hand side, and in that sense all the > assignments > have the same ultimate semantics. Some pointer in some composite object is > set to point > to another object. > > Depending on the left hand object actually involved, we use different > expressions to > retrieve the pointer (and often you have a choice, e.g., x.y or > x.__dict__['y'] or getattr(x,'y') > or vars(x).get('y') etc., some of which might not be valid. Even plain x > might sometimes be > retrieved by sys._getframe().f_locals.get('x'). My point really was that we can't express "pointer" or "target" in Python, so Python can't "retrieve the pointer" from user defined __setitem__ - it just has to hand it the values and assume that an assignment will actually happen somewhere. Not that it's worth making the necessary changes to Python, but it does seem to me that it would have been more elegant and rigorous to have indexing and assignment work that way, and it seems to me that when we can't do it because we can't express "target", that is a structural weakness in the language. The Loc class you proposed as a solution doesn't really do that at all - it's just a round-about way to call __setitem__, for all I can tell. > Or you could say the implementation is internal and you have > to use the right spellings to effect the semantics indirectly. > I.e., op[i]=newitem spells *p = newitem internally (names obviously not > directly related): > > int > PyList_SetItem(register PyObject *op, register int i, > register PyObject *newitem) > { > ... > p = ((PyListObject *)op) -> ob_item + i; > olditem = *p; > *p = newitem; > Py_XDECREF(olditem); > return 0; > } I'm missing something here - this evidently does not apply to user defined __setitem__? Donn Cave, donn at u.washington.edu From claird at lairds.com Sun Jul 6 22:52:51 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 07 Jul 2003 02:52:51 -0000 Subject: Status of Python / Platform-specific support ?? References: Message-ID: In article , Aahz wrote: >In article , >Thomas Weholt <2002 at weholt.org> wrote: >> >>I've been using Python on both Windows 2000 and Linux for some time >>now. On Windows I've used PythonWin as editor, Emacs on Linux. This >>has been working ok so far. Now as Python will be a part of Mac OS X >>Panther will this affect Pythons support for platform-specific modules >>in a big way? I'm not a Mac-expert, but OS X is basically a Unix-clone >>as base with a Apple-GUI on top, right? So most *nix apps will compile >>and run nicely on that platform? With Python as an integrated part of >>the system, I'd be seriously thinking about changing platform. >> >>Can anyone enlighten me as to what the current status is for Python >>on Mac, as for support, IDEs etc. ? Is Mac shaping up to be the best >>platform for Python development and python lovers in general, or is Mac >>just catching up to Linux? > >That's tough to answer. For starters, Python 2.2 is already part of >10.2, but it's somewhat crippled (no Tkinter, and missing the critical >bugfixes of 2.2.1 and 2.2.2). Many Unix apps do compile easily, but >I've had trouble with a couple that aren't part of the Fink project (xli >and lrz/lsz). There are binary installers available for the Mac (see >the download pages on python.org). > >I've been using Python on a Mac for more than a year now, because I >decided to get an iBook as my laptop, but my primary system is still a >Linux box, and I'm happier with that. . . . Me, too. 'Bout two weeks ago, I picked up a PowerBook as my daily desktop. There's a LOT I like about it. I still retreat to Linux or WinNT for Tkinter work, or the latest Python builds. Eventually I'll figure out enough about my new home to make Tkinter work here, too. 'Figured out a mpack/munpack replacement, Aahz? Anyway, no, I don't think anyone can imagine MacOS to be the most natural Python platform, but it's getting closer. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From max at alcyone.com Sun Jul 13 17:10:33 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Jul 2003 14:10:33 -0700 Subject: removing spaces from front and end of filenames References: <3F10BABB.D548961B@alcyone.com> <93f5c5e9.0307130744.7e9d8377@posting.google.com> Message-ID: <3F11CAC9.150B33B9@alcyone.com> hokiegal99 wrote: > for root, dirs, files in os.walk('/home/rbt/scripts'): > for file in files: > fname = (file) > fname = fname.strip( ) > print fname > > When I print fname, it prints the filenames w/o spaces (a file named " > test " looks like "test"), but when I ls the actual files in the > directory they still contain spaces at both ends. That's what I don't > understand. It seems that .strip is ready to remove the spaces, but > that it needs one more step to actually do so. Any ideas? I'm puzzled as to why you find this result confusing. You're getting a list of files, and putting their names (as strings) into a variable. You're then stripping the spaces from that variable and printing it. That doesn't have any effect on the file, because you're manipulating a string containing the file_name_, not the file itself. If you want to rename the file, you need to do something like oldFilename = ... newFilename = oldFilename.strip() os.rename(oldFilename, newFilename) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Life is a zoo in a jungle. \__/ Peter de Vries From stuart at bmsi.com Mon Jul 14 22:24:14 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 14 Jul 2003 22:24:14 -0400 Subject: ANN: dspam-python-2.6.2-3 References: Message-ID: On Mon, 14 Jul 2003 16:48:07 -0400, Stuart D. Gathman wrote: > I have created RPMs and a python wrapper for the DSPAM project. > http://bmsi.com/python/dspam.html Added separate configure patch for those that don't like Source RPMs. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From candiazoo at mac.com Fri Jul 11 23:32:27 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Sat, 12 Jul 2003 03:32:27 GMT Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> Message-ID: <110720032332097185%candiazoo@mac.com> Oh! Btw... here is the test script... The username and password has been changed to protect the innocent! import MySQLdb DB = r"xxxxxx" USER = r"xxxxxx" PASSWD = r"xxxxxx" cnn = MySQLdb.connect(db=DB, user=USER, passwd=PASSWD) cur = cnn.cursor() cur.execute("select * from art") rows = cur.fetchmany() for row in rows: print row cur.close() cnn.close() In article <110720032317344670%candiazoo at mac.com>, Michael S. Jessop wrote: > I made modifications to setup.py to set safe threading to NO and also > to point to the "real" location of the mysql libraries and stuff like > that. To test it I wrote a simple script that just tries to connect to > the database. It fails. It also fails interactively. Here is what I > am getting... > > [h000a9578d1ca:~] mike% /usr/local/bin/python2.3 foo.py > Traceback (most recent call last): > File "foo.py", line 7, in ? > cnn = MySQLdb.connect(db=DB, user=USER, passwd=PASSWD) > File > "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-pa > ckages/MySQLdb/__init__.py", line 63, in Connect > return apply(Connection, args, kwargs) > File > "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-pa > ckages/MySQLdb/connections.py", line 116, in __init__ > self.converter[types.StringType] = self.string_literal > TypeError: object does not support item assignment > Segmentation fault > > The download, build and install went fine. This same code works (well, > different database name, user and password) on a different machine. > The database, username and password are all correct. > > Any thoughts? > > Thanks! > > Mike From spam at magnetic-ink.dk Sat Jul 5 05:17:50 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Sat, 5 Jul 2003 09:17:50 +0000 (UTC) Subject: Debian /etc/python2.2/site.py lost ? References: <3f068c06$0$29650$626a54ce@news.free.fr> Message-ID: <3f0697be-bb88f1aa-4640-484f-a5e5-7ad1a5c5e929@news.szn.dk> Shagshag13 wrote: > i accidentally delete etc/python2.2/site.py on my debian system > could some one help me to recreate this file as i didn't know > what it contains ? # apt-get --reinstall install python2.2 // Klaus -- ><>? unselfish actions pay back better From peter at engcorp.com Fri Jul 4 08:44:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 08:44:35 -0400 Subject: Gathering variable names from within a function. References: Message-ID: <3F0576B3.13403AD@engcorp.com> Xavier wrote: > > I was wondering if there was a way to get a list of all the variables which > were executed/created/modified within a function? Have you looked at the "inspect" standard module? From maxm at mxm.dk Thu Jul 17 06:02:46 2003 From: maxm at mxm.dk (Max M) Date: Thu, 17 Jul 2003 12:02:46 +0200 Subject: Choosing the right framework In-Reply-To: References: Message-ID: <3f1673cd$0$97214$edfadb0f@dread12.news.tele.dk> Carsten Gehling wrote: > I like the ideas behind Zope. For instance the "long running process" > feature that improve performance and retain scripts between requests, among > other things. I do not, however, like the design of the management > interface, it would not appeal to my customers. I'm not yet knowledgable > enough about Zope, to know if this can be changed. Anyone who can elaborate? > (MaxM don't answer "Plone"... ;-) Have you thought about running Python under .asp ?? I have made a few medium sized projects that way, and after aligning my methods to using Python in combination with .asp it was quite good. Another thing. If you find Plone to be too specific, you could just plain cmf. But it is quite easy to rewrite the interface of a Zope product. Even though Zope and especially Plone are hard to get into they buy you a lot of leverage. And you are competing with people who do know Zope/Plone. regards Max M From manuelbastioniNOSPAM at tin.it Fri Jul 25 08:21:55 2003 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Fri, 25 Jul 2003 12:21:55 GMT Subject: decimal to binary Message-ID: How to convert a decimal to binary ? thx, Manuel From duncan at NOSPAMrcp.co.uk Tue Jul 22 04:34:13 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 22 Jul 2003 08:34:13 +0000 (UTC) Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: bokr at oz.net (Bengt Richter) wrote in news:bfi4ir$t21$0 at 216.39.172.122: > I guess the full set of functions might be > any_true, any_false, all_true, and all_false. > > or maybe someone can think of better short phrase? > 'all_false(...)' is simply 'not any_true(...)' 'any_false(...)' is 'not all_true(...)' So you could get by with just two of these functions, in which case 'any_of', and 'all_of' might be suitable names. -- 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 manuelbastioniNOSPAM at tin.it Tue Jul 22 13:35:23 2003 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Tue, 22 Jul 2003 17:35:23 GMT Subject: Pause in a loop References: <%W7Ta.10360$t92.299097@news1.tin.it> Message-ID: Thanks, now I try the various soluctions, and after tell here the result. THANKS, Manuel The same question is here, but Blender oriented: http://www.elysiun.com/forum/viewtopic.php?t=11701&highlight= From dale at riverhall.NOSPAM.co.uk Fri Jul 4 10:31:08 2003 From: dale at riverhall.NOSPAM.co.uk (Dale Strickland-Clak) Date: 04 Jul 2003 14:31:08 GMT Subject: Server Push References: Message-ID: John Bradbury pushed the bounds of literature with: > I want to send updates from a long running cgi. I have tried copying > perl examples of server push and can not get them to work. > Does anyone have an idiot proof example of a working server push or > sending output in chunks in Python? > Thanks > John Bradbury > > > I'm not sure what you mean by 'server push' but if you want to update a web page progressively, you have to make sure that your web server isn't buffering. I think IIS does buffer by default. You can then send out incremental updates to the page using print from a CGI script. Bear in mind though that the web page must suite this type of update. Also, some browsers might not display it correctly until they have the tag. -- Dale Strickland-Clark Riverhall Systems Ltd, www.riverhall.co.uk From llafba at gmx.net Mon Jul 21 11:05:55 2003 From: llafba at gmx.net (Tom) Date: Mon, 21 Jul 2003 17:05:55 +0200 Subject: global variable Message-ID: Hi, I have one "master" program which calls a small program. In this small program I want to work with a value from the "master" program. But I always get this error: NameError: global name 'T' is not defined How can I define a global variable? Thanks for your help. Regards, Tom From bokr at oz.net Mon Jul 14 16:51:20 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 20:51:20 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: On Mon, 14 Jul 2003 14:03:17 GMT, Harry George wrote: >"richardc" writes: > >> Ive just started playing with Python and have a couple of questions. >> >> Im looking for an agument parsing library (from the command line), Ive come >> across optik and argtools. What other ones are there are any of them any >> good, is there a 'standard' lib for doing this. >> >> Also how should I '#define' magic numbers in Python. I spent ages looking >> around for a 'define' statement or anything that will allow me to create a >> constant value 'object'. Am I missing something very obvious ? >> >> Also, what 'IDE/editor' do people recomend for MAC OSX, so far Ive found >> 'Hydra' to be the best as it works on plain files and has Python syntax >> highlighting... what else is there and are any of them any good. >> >> Has nobody written an editor/IDE in Python with wxWindows so that it runs on >> all platforms ? >> >> Many thanks >> >> Rich >> >> > >1. args: I use getopt, which does the job. The idiom is: >if __name__ == '__main__': > opts,pargs=getopt.getopt(sys.argv[1:],'hvd', > ['help','version','debug', > 'bb=']) > for opt in opts: > if opt[0]=='-h' or opt[0]=='--help': > print modname+": version="+__version__ > usage() > sys.exit(0) > elif opt[0]=='-v' or opt[0]=='--version': > print modname+": version="+__version__ > sys.exit(0) > elif opt[0]=='-d' or opt[0]=='--debug': > debug_p=1 > elif opt[0]=='--bb': > opt_b=opt[1] > You know, I don't know how much that buys vs the simple direct method. I haven't tried getopt. Is there something I can't easily do with about the same LOC as below? if __name__ == '__main__': import sys args = sys.argv[1:] while args: opt = args.pop(0) if opt=='-h' or opt=='--help': print modname+": version="+__version__ usage() raise SystemExit(0) elif opt=='-v' or opt=='--version': print modname+": version="+__version__ raise SystemExit(0) elif opt=='-d' or opt=='--debug': debug_p=1 elif opt=='--bb': opt_b= int(args.pop(0)) # note that this way it's also easy to do conversions like int if not 0 <= opt_b <3: raise ValueError, 'Error: opt_b must be 0, 1, or 2 (easy to validate in context also)' else: #you can process non-opt args as file names or whatever and continue looping, # or you could break here and use the rest of what is in args however you want. # or break on an explicit '--' and print arg-error messages otherwise, etc. etc. >2. #define: Use ALLCAPS. I put these all in a globals section at the > top of the module in the order: docstring, imports, globals, > utilities, common functions, classes, "main", and "if > __name__=='__main__':" > > Also, if you have global variables, we use leading "g_" > (e.g,"g_myglobaldata"), so they are easy to find if encountered in > the body of the module. > >-- >harry.g.george at boeing.com >6-6M31 Knowledge Management >Phone: (425) 294-8757 Regards, Bengt Richter From m.stenzel at allanime.de Mon Jul 7 10:06:00 2003 From: m.stenzel at allanime.de (Markus Stenzel) Date: Mon, 07 Jul 2003 16:06:00 +0200 Subject: Reverse Engineering of Windows Distribution Message-ID: I have a Python software for Windows, packed into a single exe file and accompanied with a few dll and package files. Is there any way to reverse engineer this packet by extracting the source files so they can be used on Linux/Unix? I have checked the exe but it seems to be compressed by zlib. Some people on the mailing lists told my friend it's possible to get the code once you can "unpack" the files from the exe. Anyone? Markus From anthony at interlink.com.au Wed Jul 2 08:55:29 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Wed, 02 Jul 2003 22:55:29 +1000 Subject: Possible fix for Bug 494589 - os.path.expandvars bug In-Reply-To: References: <3F02015F.3000903@dadsetan.com> Message-ID: <200307021255.h62CtTGG012178@localhost.localdomain> >>> "Steve Holden" wrote > "Behrang Dadsetan" wrote ... > > Sorry you will be getting no patch from me at the moment > > since sourceforge's anonymous CVS access does not like me. > [...] > > If you can figure out everything you wrote about, it can't be *that* hard to > create a sourceforge account ;-). I assume he's referring to the Sourceforge pserver access being... ahem... well... less than good, of late, rather than being logged in to log a bug or patch. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From danb_83 at yahoo.com Wed Jul 16 01:21:47 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Jul 2003 22:21:47 -0700 Subject: Foreign characters References: Message-ID: tsurusennin at softhome.net (Tetsuo) wrote in message news:... > How do I get Python to work with foreign characters? When I try to > print them, I get a unicode error (characters not ASCII). # -*- coding: latin-1 -*- greeting = "?Hola! ?C?mo est?s?" print greeting Or if you actually need to use Unicode strings: unicodeString = "a byte string".decode('encoding') print unicodeString.encode('encoding') From tzot at sil-tec.gr Tue Jul 8 08:03:01 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jul 2003 15:03:01 +0300 Subject: Shared vs static link performance hit --and Windows? Message-ID: Last night I was compiling the latest python snapshot at my home Linux system (a K6-III @420 --the extra 20 Hz is overclocking :); then I tried building a shared version of the interpreter. I did some speed comparisons, and pystone reported ~6090 pystones for the shared and ~7680 pystones for the (default) static build. This is quite a difference, and while I do know what impact position independent code has on libraries, this was the first time I measured a difference of 25% in performance... This is not a complaint (I am happy with the static build and its speed), but it's a question because I know that in Windows the build is "shared" (there's a python23.dll which is about the same as the .so of the shared lib), and pystone performance is close to ~6100 pystones. I might say something stupid since I am not an "expert" on Windows architectures, but would it be feasible (and useful) to build a static python.exe on windows? Or is it that there would be no difference performance-wise in the final interpreter? Any replies are welcome. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From alex.lapp at bpanet.de Thu Jul 17 06:04:00 2003 From: alex.lapp at bpanet.de (Alex Lapp) Date: Thu, 17 Jul 2003 12:04:00 +0200 Subject: Problems installing cvs / errno? References: <3F165F85.702@bpanet.de> Message-ID: <3F167490.5050803@bpanet.de> Hi again, i found a solution for my csv problem. There is a freebsd port wich installs the module correctly. But now i need a module called PIL. This is not available as freebsd port so i hav to install it manually. After download and doing configure / make in the libImaging directory i got a similar error like installing the csv module manually. (python setup.py build) -snip- not copying PIL/XVThumbImagePlugin.py (output up-to-date) running build_ext building '_imaging' extension cc -Os -pipe -mcpu=i686 -march=pentiumpro -D_THREAD_SAFE -fPIC -IlibImaging -I/usr/local/include/python2.1 -c _imaging.c -o build/temp.freebsd-4.8-RELEASE-i386-2.1/_imaging.o Traceback (most recent call last): File "setup.py", line 306, in ? ext_modules = MODULES, File "/usr/local/lib/python2.1/distutils/core.py", line 138, in setup dist.run_commands() File "/usr/local/lib/python2.1/distutils/dist.py", line 899, in run_commands self.run_command(cmd) File "/usr/local/lib/python2.1/distutils/dist.py", line 919, in run_command cmd_obj.run() File "/usr/local/lib/python2.1/distutils/command/build.py", line 106, in run self.run_command(cmd_name) File "/usr/local/lib/python2.1/distutils/cmd.py", line 328, in run_command self.distribution.run_command(command) File "/usr/local/lib/python2.1/distutils/dist.py", line 919, in run_command cmd_obj.run() File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 256, in run self.build_extensions() File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 383, in build_extensions self.build_extension(ext) File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 457, in build_extension extra_postargs=extra_args) File "/usr/local/lib/python2.1/distutils/unixccompiler.py", line 150, in compile self.spawn(self.compiler_so + cc_args + File "/usr/local/lib/python2.1/distutils/ccompiler.py", line 826, in spawn spawn (cmd, verbose=self.verbose, dry_run=self.dry_run) File "/usr/local/lib/python2.1/distutils/spawn.py", line 38, in spawn _spawn_posix(cmd, search_path, verbose, dry_run) File "/usr/local/lib/python2.1/distutils/spawn.py", line 108, in _spawn_posix exec_fn(cmd[0], cmd) File "/usr/local/lib/python2.1/os.py", line 291, in execvp _execvpe(file, args) File "/usr/local/lib/python2.1/os.py", line 305, in _execvpe from errno import ENOENT, ENOTDIR ImportError: No module named errno error: command 'cc' failed with exit status 1 -snip- It seems like i have problems installing python modules generally. Does anybody knows this problem? Thank you, Alex From davidcfox at post.harvard.edu Mon Jul 21 13:27:57 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Mon, 21 Jul 2003 17:27:57 GMT Subject: detecting containers during object introspection Message-ID: Is there a reasonable way to tell whether a variable is a container (either a mapping or a sequence) and whether it is a mapping or a sequence? [For background on why I'm asking this question, see the end of the message] isMappingType and isSequenceType in the operator module return true for any class instance. The documentation for those functions says (correctly) that there is no general way to tell whether a class supports the complete mapping or sequence interfaces, but still, it would be nice to be able to tell whether for elem in x: would fail or succeed, without relying on something like isinstance(x, list), which would fail for a tuple or a UserList, or any other custom class. Is calling iter(x) and catching the possible TypeError the closest I can get? And what would be the closest equivalent for mapping types. Wouldn't it be helpful to have an abstract base class Sequence which didn't add any actual attributes or methods, but which someone writing a sequence class could include as a base class, as a sort of unenforced promise that the sequence operators were supported? Thanks in advance for any suggestions, David --- Why am I asking this question? I'm trying to write a regression test for a class which pickles dictionaries of attributes to store and retrieve instances. The dictionary includes a version number, and the class has a system for updating out-of-date instances to the current version. As part of the test, I need to be able to compare the structure of the two dictionaries to see if the developer has modified their structure but forgotten to increment the current version. Values in the dictionary may be unknown objects, in which case I just want to compare their types. However, the values may also be sequences or mappings themselves, in which case I want to recursively compare their elements/values. From bokr at oz.net Sat Jul 19 16:01:35 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 20:01:35 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: On Sat, 19 Jul 2003 11:49:25 -0400, "Mike C. Fletcher" wrote: >Michele Simionato wrote: >... > >>I agree with Bengt, from your traceback it seems you are assigning directly >>to client.__dict__, but you cannot do that (I think because client.__dict__ >>is a dictproxy object and not a real dictionary). The right way to >>go is via object.__setattr__ , or type.__setattr__ in the case of >>metaclasses. >> >Try this to see what I'm getting at: > > >>> class o(object): >... class p( object ): >... def __set__( self, client, value, *args, **named ): >... print '__set__', self, client, value, args, named >... # now what do you do here to set without triggering >ourselves >... # (without having to code diff versions of the >descriptor class >... # for each possible type of client object (and for that >matter, just >... # making it possible for (meta-)types with properties >w/out requiring >... # e.g. a new dict object in each such serviced type))?. >... return object.__setattr__( client, "v", value) client.__dict__['v'] = value the above line should work for this example, so it must be different from what you were doing before? Perhaps the client object before was a class? I guess I'm not getting the big picture yet of your design intent. Are you trying to make a base class that has properties that can set same-named properties in the subclass via attributes of objects instantiated from the subclass? Or as attributes of the subclass? Do you need the property ability to munge its arguments dynamically? Otherwise a plain old attribute assignment to the subclass per se should install the property for its instances, no? >... v = p() >... > >>> s = o() > >>> s.v = 3 > >You'll notice you go into an infinite loop. What I'm looking for For this example that's certainly what you'd expect. >(really a thinly veiled attempt to get other people to demand it from >Guido so he doesn't think I'm a lone crackpot ;) ) is a function/method >that provides the default implementation of the get/set functionality >*below* the level of the descriptor hooks, but high enough that it can >deal with the differences between classes, types, instances, and >instances-with-__slots__ (I realise that last one probably isn't going >to work, BTW). > >Thought of another way, it's asking for a superclass of descriptors >which provides this logic in such a way that, by sub-classing from them, >you can readily gain access to this descriptor-building functionality >without needing to always use it, and without introducing unwanted >restrictions (such as requiring a property-class initialisation). > >Thought of another way, it's asking for a further rationalisation of the >get/set hooks so that there's a lower level at which you can either >insert storage code *or* use the default storage code. > More simple examples like the above might help me understand, but I haven't got the picture yet, I am afraid ;-) Regards, Bengt Richter From niessink at serc.nl Tue Jul 15 10:44:01 2003 From: niessink at serc.nl (Frank Niessink) Date: Tue, 15 Jul 2003 16:44:01 +0200 Subject: focus problem with full-screen in Tkinter In-Reply-To: <2259b0e2.0307140746.46cf2e8c@posting.google.com> References: <2259b0e2.0307140746.46cf2e8c@posting.google.com> Message-ID: <20030715144401.GA1564@obstler> On Mon Jul 14 11:56:23 2003, Michele Simionato wrote: > I have a problem with full screen windows in Tkinter. > Here is a minimal script showing the problem: > > from Tkinter import * > root=Tk() > w, h = root.winfo_screenwidth(), root.winfo_screenheight() > root.geometry("%dx%d+0+0" % (w, h)) > #root.overrideredirect(1) > root.focus() > root.bind("",lambda e: root.destroy()) > root.bind("<1>",lambda e: root.destroy()) > root.mainloop() Both 'q' and mouseclick work for me, both with and without the comment. Python 2.2.3 (#1, Jun 19 2003, 12:10:13) [GCC 3.2 20020927 (prerelease)] on cygwin Cheers, Frank -- It was real. At least, if it wasn't real, it did support them, and as that is what sofas are supposed to do, this, by any test that mattered, was a real sofa. -- Douglas Adams, 'Life, the Universe, and Everything' From postmaster at 127.0.0.1 Wed Jul 16 06:06:37 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Wed, 16 Jul 2003 22:06:37 +1200 Subject: Testers wanted - new Python DHTML framework Message-ID: Hi, I'm looking for adventurous pre-alpha testers for a DHTML (active website) framework for Python I've developed. Name: - pyWeb Features: - easy to learn and use - compatible with Python 1.5.2 and later (thus able to run on budget web hosts which insist on staying with old Pythons) - runs purely as CGI (or fastCGI) - lets you build your pages with a simple, intuitive and coherent document object model (DOM) - extremely extensible, lends itself well to templating - not a 'code within the html text' type of DHTML framework (like Spyce). This one puts the emphasis on generating the HTML with python statements - automatic retrieval and dispatch of browser cookies - oersistent datastore that is stored on browser as compressed cookes. secured via hmac/sha1, can store 10-25k of data on browser. Accessed in python code by simply reading and setting attributes of an object License: - GPL Info, examples, doco, download: - http://www.freenet.org.nz/python/pyweb All feedback gratefully received. Cheers David From bens at replytothegroupplease.com Wed Jul 30 22:39:50 2003 From: bens at replytothegroupplease.com (Ben S) Date: Thu, 31 Jul 2003 03:39:50 +0100 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: Skip Montanaro wrote: > kylotan> PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S > %Y')' as a kylotan> reverse-asctime(), and was surprised that I > couldn't find this kylotan> wrapped in a function in any of the > modules. Maybe such a kylotan> function would be considered for > future addition? > > Seems simple enough to not be needed. What makes asctime() all that > special? Sorry...I just rechecked the docs and it would appear that this is the default behaviour of strptime if you omit the format string. Therefore a new function isn't needed. -- Ben Sizer http://pages.eidosnet.co.uk/kylotan From dave at nullcube.com Thu Jul 31 22:59:32 2003 From: dave at nullcube.com (Dave Harrison) Date: Fri, 1 Aug 2003 12:59:32 +1000 Subject: setuid and current paths Message-ID: <20030801025932.GA25071@dave@alana.ucc.usyd.edu.au> hi again, Im clearly a moron, and have solved the problem myself, due to a wish to avoid dire embarrasment I shall not reveal the stupid mistake I made ;-) Apologies for the inconvenience Dave > hi all, > > Im using the setuid-prog.c script to setuid my cgi script. > The C script is chowned to "myuser" (not root, I dont need root access > just the access myuser has). > > However when I do this, the path it executes the script from is not > the same dir as the cgi itself. > > My CGI script uses a dir structure within its own dir, but when > I execute it from another dir (via the setuid script) Im not > in that dir natively. > > Ive tried chdir without success, and chroot runs me into a permissions > problem. > > Anyone want to tell me how I _should_ be doing this ? From amk at amk.ca Thu Jul 10 15:23:41 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 10 Jul 2003 15:23:41 -0400 Subject: Sample Web application In-Reply-To: <1057862845.9505.1262.camel@lothlorien> Message-ID: <040F7757-B30C-11D7-9993-0003931BF218@amk.ca> On Thursday, July 10, 2003, at 02:47 PM, Ian Bicking wrote: > These features do make it a little more complicated, but they solve > particular problems, and reducing duplication would help us all. All > three protocols (mod_scgi, mod_skunkweb, and mod_webkit) do almost > exactly the same thing. And then there's FastCGI... ... and Zope's old mod_pcgi, and mod_lisp, and doubtless a mod_ruby or two; this wheel has been reinvented many, many times. Someone should write a specification for the communication protocol (a protocol simpler than FastCGI, which has a specification but is too complicated) and then we can all use the same communication protocol. Neil's spec for SCGI is at http://python.ca/nas/scgi/protocol.txt . > >> The Dulcinea package (http://www.mems-exchange.org/software/dulcinea/) >> includes scripts for running multiple web sites on a machine >Which portions are you referring to? None of the modules you describe >in the overview seem to apply. This is the bin/site script. See http://www.mems-exchange.org/software/dulcinea/doc/site-management.html for some documentation. (But it assumes that everything -- Apache, site content, code -- live under /www, and changing that assumption would be messy.) --amk From staschuk at telusplanet.net Mon Jul 21 20:42:04 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 21 Jul 2003 18:42:04 -0600 Subject: detecting containers during object introspection In-Reply-To: ; from davidcfox@post.harvard.edu on Mon, Jul 21, 2003 at 05:27:57PM +0000 References: Message-ID: <20030721184204.D188@tibia.amotlpaa.bogus> Quoth David C. Fox: > Is there a reasonable way to tell whether a variable is a container > (either a mapping or a sequence) and whether it is a mapping or a > sequence? [...] Depends what you mean by "reasonable". In the usual scenario, there's a specific facility which you want to make use of, and you can either (a) just try to use it, and catch the relevant exception (called Easier to Ask Forgiveness than Permission, or EAFP), or (b) do some kind of check beforehand for whether the facility exists (called Look Before You Leap, or LBYL). Your example of trying iter(foo) and catching the possible TypeError fits into such approaches. [...] > Wouldn't it be helpful to have an abstract base class Sequence which > didn't add any actual attributes or methods, but which someone writing a > sequence class could include as a base class, as a sort of unenforced > promise that the sequence operators were supported? Consider a DNS name -> address mapping whose __getitem__ actually queries the DNS. (Ignore the fact that this could be better done with a function -- assume we have a function which expects a dict-like object and we want to use it on the DNS.) Such an object could not reasonably implement __len__. Should it falsely imply that it does (by inheriting from an abstract class Mapping) or falsely imply that it's not a mapping (by not inheriting from Mapping)? Such cases -- those in which for conceptual or pragmatic reasons it is infeasible or undesirable to implement all of an interface -- are not uncommon. Also, there's the idea of YAGNI (You Ain't Gonna Need It): implement just what you discover you actually need, not what you think you might need in the future. In particular, when writing a dict-like object, write just as much of the interface as the contexts in which you want to use that object require, not more. Implementing the entire interface just for completeness is (according to YAGNI) a waste of valuable developer time, until you discover you really do need the complete interface. Adherents of this idea won't like the notion of having to make a promise (enforced or not) that they've implemented the entire interface. > Why am I asking this question? > > I'm trying to write a regression test for a class which pickles > dictionaries of attributes to store and retrieve instances. The > dictionary includes a version number, and the class has a system for > updating out-of-date instances to the current version. > > As part of the test, I need to be able to compare the structure of the > two dictionaries to see if the developer has modified their structure > but forgotten to increment the current version. Values in the > dictionary may be unknown objects, in which case I just want to compare > their types. However, the values may also be sequences or mappings > themselves, in which case I want to recursively compare their > elements/values. Interesting. So you have an example of a standard dictionary for a given version number, and you want to compare the structure of the actual dictionary to the standard example dictionary. Is that right? Are your developers actually using dict-like and list-like objects instead of real dicts and lists? If not, isn't the type-check for unknown objects enough? (If they do start using work-alikes instead of the real thing, the test will fail, but YAGNI, right? You can fix it if it ever happens, at worst by adding support for the specific kinds of work-alike the developers want to use. Only if they want to use a wide variety of work-alikes do you really need tests for abstract sequenceness and mappingness.) -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From sergio.lobo at supportdrive.com Sat Jul 5 16:06:37 2003 From: sergio.lobo at supportdrive.com (Sergio Lobo) Date: Sat, 5 Jul 2003 22:06:37 +0200 Subject: Python Open Source Project for Live Support Message-ID: Hello, I have developed a simple Online Support System which is running at www.supportdrive.com. The system is divided in 3 parts: 1- Server - Implemented in Python 2- Client - Delphi 6 3- Web Client - PHP + Javascript All 3 parts communicate with each other using XML-RPC protocol. I would like to make this an Open Source Project if I can find some brave Python souls willing to help me. I have many ideas for this project. One of them is to create Public Topics. At this time the system only handles Private Topics. With Public Topics we could have a page on the main project site with a list of all Public Topics where at least one support person would be online. This support person could be any software developer running the project software client and being online. As a software developer I had many times make good use of Google.com to find answer to my questions. However I would love to be able to go to a web site click on a Topic which I am interested in and have free support from another fellow developer. Well, I believe I could talk a lot about those ideas. Besides the code I already created, this project will count on a dedicated server, which means, we will be able to run as many daemons as needed. The ones who are interested in the project, please let me know. Kind regards, Sergio Lobo From wesc at deirdre.org Sat Jul 19 04:52:56 2003 From: wesc at deirdre.org (Wesley J. Chun) Date: 19 Jul 2003 01:52:56 -0700 Subject: The definition of an object in Python References: <94af9c5a.0307130919.1ab63400@posting.google.com> Message-ID: kak at purdue.edu (Avi Kak) wrote in message news:<94af9c5a.0307130919.1ab63400 at posting.google.com>... > Hello: > > Please forgive me if my question is too silly or just not > well-formed. you're forgiven. :-) your question is well-formed *and* not silly. > Wesley Chun in his book (Core Python Programming) says that > **everything** in Python is an object. So I became curious > about the precise definition of an object in Python. My > curiosity was also driven by Wesley's statement that while > every class instance is an object, this is still true since, as you know, *everything* is an object. :-) > not every object is a class instance. Python's treatment of objects is unique from other languages, which makes this clause "true." Python has a defined set of object types which are NOT classes, general objects such as integers, floats, strings, lists, dictionaries, files, classes, and even types are objects. a class instance is truly only an ob- ject that has been instantiated from a user-defined class. prior to Python 2.2, classes were "class" objects and instances were "instance" objects. as types and classes are starting to merge starting in 2.2, classes are now "type" objects, and instance's "type" is the class they have been instantiated from. EXAMPLE (old-style classes): >>> class C: pass ... >>> c=C() >>> type(C) >>> type(c) EXAMPLE (new-style classes): >>> class myInt(int): pass ... >>> i = myInt() >>> type(i) >>> type(myInt) > Wesley says that every Python object must possess the following > three characteristics: 1) an identity, which can be retrieved > by the function id(); 2) a type, which can be retrieved by > the function type(); and 3) a value. again, this is also (still) true. (1) the identity is what makes an object unique from every other object currently in the interpreter. some people view this as a "memory address" altho you wouldn't use it as such since Python handles the memory management 4 u. you are just guaranteed that any other object in the system will NOT have the same id. (2) the type of an object defines what its characteristics (i.e., what methods and attributes it has, etc.) are, and (3) the value goes without saying. > But when I do the following > > mystring = 'hello' > print mystring.id() > print mystring.type() > > Python complains that mystring does not possess the attributes > id and type. > > So now I am confused. Any help with the resolution of this > issue would be much appreciated. as others have pointed out, id() and type() are built-in FUNCTIONs and not general built-in METHODs. each object type has its own set of methods, and all behavior of an object and its attributes are defined by its TYPE. you can use the dir() built-in function to see what attributes (data and methods) an object has. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, (c) 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://www.baypiggies.net wesley.j.chun :: wesc at deirdre.org cyberweb.consulting :: cyberweb_consulting at yahoo.com http://roadkill.com/~wesc/cyberweb/ E-Mail using vi(m)/emacs with M$ outlook: http://groups.google.com/groups?threadm=fcd9edc1.0208281104.752da4bd%40posting.google.com From andy47 at halfcooked.com Tue Jul 29 07:10:37 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 29 Jul 2003 12:10:37 +0100 Subject: How to properly package/distribute a pure python module? In-Reply-To: <5ab0af73.0307281045.6cb13cfe@posting.google.com> References: <5ab0af73.0307281045.6cb13cfe@posting.google.com> Message-ID: Matt Shomphe wrote: > Are there any guidelines for packaging a pure python module? > Specifically, say I have a set of 10 functions, all of varying > behaviors (no unifying theme to bind them together into clear > subsets), that I would like to make available to others. What is the > best structure for the distributed module? A single file called > "functions.py" that people can put in "site-packages"[1]? A > subdirectory called "MyFunctions" with an "__init__.py" and the > "functions.py" files[2]? Or should the functions be broken out into > individual files[3]? > > I'm sure it depends on some other factorsbut are there general rules > for constructing a nice, logical package for others to use? > > [1] site-packages/functions.py (from functions import f1) > [2] site-packages/MyFunctions/functions.py, __init__.py (from > MyFunctions.functions import f1) > [3] site-packages/MyFunctions/__init__.py, f1.py, f2.py, f3.py (from > MyFunctions.f1 import f1) I'd suggest you look at the distribution utilities for Python; http://www.python.org/sigs/distutils-sig/doc/ Specifically the documentation on distrbuting Python modules; http://www.python.org/doc/current/dist/ The documentation can be a little confusing at first but stick with it and if you have any questions please ask them here or on the distutils-sig mailing list. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From intentionally at blank.co.uk Tue Jul 15 02:03:11 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 07:03:11 +0100 Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: On 15 Jul 2003 05:10:56 GMT, bokr at oz.net (Bengt Richter) wrote: >On Tue, 15 Jul 2003 00:22:15 +0100, Stephen Horne wrote: >[...] >>>> C++ references are tellingly also called self-dereferencing pointers. >>>> They are not a distinct concept - they are syntactic sugar. I suspect >>>> they mainly arise out of the modern desire to disguise pointers and >>>> fantasize that they're not there, though they certainly work very well >>>> in certain contexts. >>> >>>Syntactic sugar or no, they still behave differently than other >>>datatypes and are therefore not consistent... IMHO. >> >>They behave exactly like pointers. You just use different notation to >>get that behaviour. That is what makes them syntactic sugar. >> >BZZT. C++ references do not behave *exactly* like pointers. Try to make one >point to a different place than it was initialized to point to. You can't - at least not without very nasty hacks. But that doesn't necessarily matter. You could make a very strong case for references being a distinct datatype from pointers, I'll admit. It depends whether you think of the notation for operations being an aspect of the data type - obviously the case in C++ programming, but I was thinking in terms of mathematical abstract data types at the time. Just because there is no notation to express an operation, doesn't necessarily mean that operation doesn't exist ;-) From grante at visi.com Mon Jul 7 09:25:46 2003 From: grante at visi.com (Grant Edwards) Date: 07 Jul 2003 13:25:46 GMT Subject: RTS/CTS and DTR/DTS control References: <3F060F8D.94E47DCD@engcorp.com> <3F064661.33614890@engcorp.com> Message-ID: <3f0974da$0$1382$a1866201@newsreader.visi.com> In article <3F064661.33614890 at engcorp.com>, Peter Hansen wrote: > A quick search again with Google using TIOCMSET and TIOCM_CTS and a bunch > of others finally led to this, which might be the best yet, and includes > some constant definitions that might let you get something working, if > this doesn't directly solve your problem: > > http://sparc.dnsalias.net/Python_stuff/PosixSerial.py FWIW, I've added a couple minor features to the PosixSerial module (methods for setting a couple iflag values, getting rx/tx buffer count, resetting the modems on a board you probably don't have). The current version is available at: ftp://ftp.visi.com/users/grante/python/PosixSerial.py -- Grant Edwards grante Yow! Where does it go when at you flush? visi.com From mertz at gnosis.cx Thu Jul 31 21:42:35 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 31 Jul 2003 21:42:35 -0400 Subject: Python speed vs csharp References: Message-ID: Richie Hindle wrote previously: |Using Psyco dropped from 7.1 seconds to 5.4 - not great, but not bad for |two lines of additional code: | import psyco | psyco.bind(erfc) Try these two lines instead: import psyco psyco.full() I tried what Hindle did, intially (actually 'erfcp=psyco.proxy(erfc)'), and was disappointed by a similarly lackluster improvement (about the same order--he probably has a faster machine). Using the call to psyco.full() gives me a much nicer improvement from 18 seconds -> 3.25 seconds. -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From aahz at pythoncraft.com Sun Jul 13 21:30:54 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 21:30:54 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: In article , Terry Reedy wrote: > >In Python, most builtin types are immutable. The two mutable builtin >types are lists and dicts. Instances of user-defined classes are also >mutable by default. Actually, files are mutable, too. Then again, so are modules. And functions. Gee, there are an awful lot of built-in mutable types. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From grundhan at cs.tu-berlin.de Sat Jul 26 20:48:07 2003 From: grundhan at cs.tu-berlin.de (Hannes Grund) Date: Sun, 27 Jul 2003 02:48:07 +0200 Subject: Pythoncom shutdown problems Message-ID: Dear all, probably offtopic for the general python list, but I don't know were to go else. I'm currently developing somekind of middleware wich makes heavy use of pythonwin/com extensions. (The complete setup is: win2000/winXP, python2.2, win32all-152, wxPython resp. wxWindows). The software is aimed to manage data held by a software suite (called chemoffice) to manage chemical substances. It exposes it main components via COM, the intagration to python via win32com.client.Dispatch works well. The problem: When calling a special method on some of these COM objects one component launches a process which appears to be a subprocess of svchost.exe. The result is that I'm unable to terminate the python process after this process has been started, furthermore if I shutdown the python process manually, it keeps alive, causing problems during windows shutdown (i.e. you have to remove it manually as well). Any help or hint would be highly appreciated, thanks in advance, Hannes Grund From ddarch at xyborg.de Thu Jul 10 21:56:15 2003 From: ddarch at xyborg.de (ddaemon) Date: 11 Jul 2003 09:56:15 +0800 Subject: no python mode for my gvim References: <3097082.1057868612@dbforums.com> <3f0dd87c.269088789@news.blueyonder.co.uk> Message-ID: <3f0e193f_1@news.tm.net.my> Alan Gauld wrote: > On Thu, 10 Jul 2003 20:23:32 +0000, pygeek > wrote: > > > "E370: Could not load library python21.dll > > I guess you need to install a copy of Python 2.1 somewhere. You > can delete all the docs and samples if space is tight... > > [ Or you might try finding the call to load the DLL > (loadlibrary()?)and change the name if its hard coded, but I > dunno if that will work, its probably too simple! ] > I'll try installing Python 2.1 later to see if it works. question: how do i use the loadlibrary function? i'm relatively new to gvim, sorry. thanks for the reply. --pygeek-- From staschuk at telusplanet.net Thu Jul 31 21:02:39 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 19:02:39 -0600 Subject: Retrieve source filename In-Reply-To: <3f29207d$0$24768$626a54ce@news.free.fr>; from shrom@admin.zzn.com on Thu, Jul 31, 2003 at 03:58:20PM +0200 References: <3f29207d$0$24768$626a54ce@news.free.fr> Message-ID: <20030731190239.B22513@tibia.amotlpaa.bogus> Quoth Shrom: > I know that you can retrieve main file name with sys.argv[0] and file name > for a module with modulename.__file__ but is there a common way to retrieve > file name for both main program and modules as the __FILE__ constant in PHP > ? As of 2.3, the __main__ module also has a __file__ attribute, so you can just do sys.modules[__name__].__file__ The (an?) exception is when __main__ is the text in a 'python -c' command -- then there is, of course, no file name. And for compatibility with versions < 2.3, you have to check for the case __name__ == '__main__' and go to sys.argv[0]. -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From rxs141 at cwru.edu Sun Jul 20 02:43:56 2003 From: rxs141 at cwru.edu (Ravi) Date: Sun, 20 Jul 2003 02:43:56 -0400 Subject: "Pure Python" MySQL module like Net::MySQL Message-ID: Hi, I did some googling, and found that there doesn't seem to be a pure python MySQL communication module. There is one for perl however, Net::MySQL. I was wondering if there was a specific reason why something similar hasn't been implemented in Python, a limitation of the language or libraries perhaps? I briefly scanned through the perl source for Net::MySQL, and there doesn't seem to be anything that couldn't be done in Python, but I'm a fresh convert from perl land and I don't much beyond the basics of Python yet. Thanks, Ravi From kak at purdue.edu Sun Jul 13 13:25:13 2003 From: kak at purdue.edu (Avi Kak) Date: 13 Jul 2003 10:25:13 -0700 Subject: The definition of an object in Python Message-ID: <94af9c5a.0307130919.1ab63400@posting.google.com> Hello: Please forgive me if my question is too silly or just not well-formed. Wesley Chun in his book (Core Python Programming) says that **everything** in Python is an object. So I became curious about the precise definition of an object in Python. My curiosity was also driven by Wesley's statement that while every class instance is an object, not every object is a class instance. Wesley says that every Python object must possess the following three characteristics: 1) an identity, which can be retrieved by the function id(); 2) a type, which can be retrieved by the function type(); and 3) a value. But when I do the following mystring = 'hello' print mystring.id() print mystring.type() Python complains that mystring does not possess the attributes id and type. So now I am confused. Any help with the resolution of this issue would be much appreciated. Avi Kak kak at purdue.edu From peter at engcorp.com Fri Jul 4 08:42:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 08:42:20 -0400 Subject: Python is a gem, you need to keep pushing it .... References: <41A1CBC76FDECC42B67946519C6677A9A20BBA@pippin.int.etrials.com> Message-ID: <3F05762C.3B673917@engcorp.com> delphiro wrote: > [attribution removed... don't do that!] > > Python *is* great but lets not pretend that its a good fit for every problem. > > I doubt that (unless you develop hardware drivers). Are you saying that you think Python _is_ a good fit for every problem, excluding only hardware drivers? -Peter From tjreedy at udel.edu Thu Jul 17 13:15:03 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 13:15:03 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: "Adam Ruth" wrote in message news:f0f51c80.0307150921.7b6667e2 at posting.google.com... > register int x = 5; > int *y = &x; > > This also cannot be done. Why? Different semantics for register > variables. Minor nit: 'register' is not a mandate, but an ignorable suggestion. So a compiler either could or must ignore 'register' in able to make '&x' possible. Of course, the idea of ignorable keyword suggestion is itself somewhat strange ;-) > In some cases they act like variables, in others they act like pointers. > Now that's confusing. I was certainly confused for awhile. About the time I finally got it, I switched to Python. I *initally* understood *all* Python bindings to be like C++ references (which in terms of the CPython implementation is +- true), but the very uniformity made 'reference' less confusing to me. Interesting comments. I'm glad you piped in. Terry J. Reedy From bokr at oz.net Sat Jul 12 16:21:02 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 20:21:02 GMT Subject: Accessing and updating global variables among several modules References: Message-ID: On 11 Jul 2003 20:38:48 -0700, fumingw at tom.com (Fuming Wang) wrote: >Hi, > >I have several modules that need to access global variables among >them. I can do that by import modules: > >module A: >gA = 'old' > >module B: >import A >print A.gA >>>> 'old' > >change gA in module A after some initialization: >def init_fuct(): global gA # w/o this line, gA is just a local variable, and init_fuct() is well named ;-) > gA = 'new' > (I assume the above function was in module A, and either invoked from there or as A.init_fuct() from somwhere else). >no change in module B: >print A.gA >>>> 'old' With the code above, there was no change in A either ;-) > >However, when I modify these global variables in one module, the other >modules would not see the changes. Any one has any suggestions? ( I >don't want to use from A import *) > Just make sure you actually change A.gA and you should be able to see the change from B as A.gA. Unless I am missing something. Regards, Bengt Richter From alexis.francart at nospam.xagagroup.com Wed Jul 9 07:18:41 2003 From: alexis.francart at nospam.xagagroup.com (Alexis Francart) Date: 9 Jul 2003 11:18:41 GMT Subject: importing re in Jython Message-ID: Hello, I want to use a program called maxq. This program is used for functionnal and regression test of web application. The language it uses is Jython. I need to get a part of a web page using regular expression. However i try to import the RE library but i'm not able to. Since the Jython.jar already contains an ORO i tried to use it but without success. I then tried to import the RE library but was unable to do so. I then try to import the regexp library from jakarta but without success. Do you know how i can import the RE module in Jython? NB: I hope the part on my life interested you since it has not too much to do with the question. Alexis From staschuk at telusplanet.net Tue Jul 1 20:06:46 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 18:06:46 -0600 Subject: (Numeric) should -7 % 5 = -2 ? In-Reply-To: <010720031119590501%pecora@anvil.nrl.navy.mil>; from pecora@anvil.nrl.navy.mil on Tue, Jul 01, 2003 at 11:19:59AM -0400 References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> <010720031119590501%pecora@anvil.nrl.navy.mil> Message-ID: <20030701180646.A16441@tibia.amotlpaa.bogus> Quoth Louis M. Pecora: [...] > The "uniqueness" comes in when we recogize that mod m defines an > equivalence relation on the integers and so for a given m every integer > falls into a unique class (or subset of integers). The set of m > subsets is equivalent to the positive integers 0 to m-1. Or any other complete residue system modulo m; another useful one is [ floor(-m/2), floor(m/2) ). > So it appears that the translation between math and computer science is > not as clear as I thought. In math (well, number theory) mod is a > relation, not an operation. In computer science it is an operation. Graham, Knuth and Patashnik's _Concrete Mathematics_ (2nd ed., 1994) claims that "[m]athematicians have used mod [as a binary operator] informally for a long time, taking various quantities mod 10, mod 2pi, and so on, but only in the last twenty years has it caught on formally." (Section 3.4 'mod': The Binary Operation. There's also a section 4.6 'mod' : The Congruence Relation.) The question of negative operands is actually two separate questions, one for the left operand and one for the right operand. The question for the left operand is easy to a mathematician. One normal definition of the relation "congruent modulo m" is x == y (mod m) := x - y is a multiple of m (I use '==' in this post as an ASCII substitute for the three- lined "is equivalent/congruent to" symbol.) This directly implies that, e.g., -7 == 13 (mod 5) and there is absolutely no question about this in mathematics; it is essential for, e.g., the result that if a == b (mod m) and c == d (mod m) then a+c == b+d (mod m) and many other fundamental properties of congruences. Now, if we want to call an operator 'mod', surely we want x mod m = y mod m iff x == y (mod m) (hereafter "the desideratum"). Thus since (as above) -7 == 13 (mod 5) we must have -7 mod 5 = 13 mod 5 = 3 Python's % does this, but Numeric's does not (so Numeric's % is certainly not mod, though it is a remainder operator). For negative right operands there is afaik no established precedent in mathematics. However, one obvious definition for the behaviour described so far is x mod m := x - m*floor(x/m) and, given the customary way I've defined the mod relation, this satisfies the desideratum for m < 0 too: 7 mod -5 = -3 7 == -3 (mod -5) -7 mod -5 = -2 -7 == -2 (mod -5) Python's % also produces these results. (Another hint that this is the Right Thing is that the identity 0 <= (x mod m)/m < 1. is preserved. This doesn't hold with Numeric's % even for m > 0.) That still leaves the question of zero as a right operand. (Zero as a left operand is no trouble at all, of course.) From the definition of the relation we have the cute fact that x == y (mod 0) iff x = y The way to meet the desideratum in this case is to have x mod 0 = x for all x. This contradicts the definition x mod m := x - m*floor(x/m) since that would have x mod 0 undefined; and indeed Python's % raises ZeroDivisionError here. So Python's % is not *quite* mod either; but an exception is probably more pragmatic for zero modulus anyway. -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From mis6 at pitt.edu Mon Jul 14 15:40:01 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Jul 2003 12:40:01 -0700 Subject: The definition of an object in Python References: <94af9c5a.0307130919.1ab63400@posting.google.com> Message-ID: <2259b0e2.0307140825.701c5c99@posting.google.com> Andrew Koenig wrote in message news:... > Avi> Wesley says that every Python object must possess the following > Avi> three characteristics: 1) an identity, which can be retrieved > Avi> by the function id(); 2) a type, which can be retrieved by > Avi> the function type(); and 3) a value. > > Avi> But when I do the following > > Avi> mystring = 'hello' > > Avi> print mystring.id() > > Avi> print mystring.type() > > Avi> Python complains that mystring does not possess the attributes > Avi> id and type. > > type and id are functions, not methods. > > >>> mystring = 'hello' > >>> print mystring.id() # using id as a method doesn't work > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'str' object has no attribute 'id' > >>> print id(mystring) # using id as a function does > 1456272 > >>> print type(mystring) # ditto for type > Just for fun, to show that the built-ins "id" and "type" are regular objects: >>> id(id) 1076547724 >>> type(type) >>> type(id) >>> id(type) 135272896 Michele From alan.gauld at btinternet.com Thu Jul 24 18:22:41 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jul 2003 22:22:41 GMT Subject: OT, was: Re: needs a logo References: <7fe97cc4.0307230144.9119f89@posting.google.com> Message-ID: <3f205ac9.745241690@news.blueyonder.co.uk> This is way OT but... On 23 Jul 2003 02:44:05 -0700, xah at xahlee.org (Xah Lee) wrote: > Better logos should be reminiscent to what it represents. Good > example's are ... Shell's seashell, I remember my grandfather telling me that the Shell logo originated around WW2 time and it represented a shell exploding (message => dynamic powerful company) on a building and was in two colors. After the war it was deemed a bad marketing image to use warlike logos so they "re-badged" the company as being around sea shells and the logo changed to what we know today. I've never seen any other reference to this anywhere. Does anyone know of a source (another grandfather?!) that can confirm or deny this? Just curious, Alan G. From donald.welch.nospam at hp.com Tue Jul 1 17:01:43 2003 From: donald.welch.nospam at hp.com (djw) Date: Tue, 01 Jul 2003 14:01:43 -0700 Subject: PyQt and async I/O Message-ID: <3f01fb8f@usenet01.boi.hp.com> Greetings- I was looking at the ASPN recipe for async I/O and Tkinter: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 I am interested in using the recipe that is provided in the comments section for PyQt courtesy of Laura Creighton. I have a question though.... In the code, it says: "One important thing to remember is that the thread has to yield control." That appears in this code (the thread that will contain the async I/O): def workerThread1(self): """ This is where we handle the asynchronous I/O. For example, it may be a 'select()'. One important thing to remember is that the thread has to yield control. """ while self.running: # To simulate asynchronous I/O, we create a random number at # random intervals. Replace the following 2 lines with the real # thing. time.sleep(rand.random() * 0.3) msg = rand.random() self.queue.put(msg) If you were to use asyncore for this async I/O, there is no yielding that I can see. Select() doesn't yield, and there is no time.sleep() in the asyncore.loop() code. Even if I were to add a time.sleep() to the loop, wouldn't the fact that select() blocks for some timeout value (default=30.0 sec) imply that it would only yield after the select() timed out each time through the loop? That would seem to make for a pretty unresponsive UI. Hopefully somebody can clue me into understanding this. Thanks, Don From johnroth at ameritech.net Wed Jul 2 07:34:07 2003 From: johnroth at ameritech.net (John Roth) Date: Wed, 2 Jul 2003 07:34:07 -0400 Subject: Circular Inheritance References: Message-ID: "Ian Bicking" wrote in message news:mailman.1057124943.21695.python-list at python.org... > On Tue, 2003-07-01 at 19:00, Ben Finney wrote: > > Re-design the modules so that inheritance is a hierarchy. A band-aid > > solution may be to create a new class that mediates between two others, > > breaking the circle. Much better is to figure out why the classes need > > to know so much about each other, and redesign them with smaller, > > simpler interfaces. > > It seems quite reasonable to have circular dependencies between two or > more classes. The most common case being that one class references the > other, and the other class has back references. Very common, and it > doesn't imply that the classes know too much about each other. However, this wouldn't normally cause import problems. Import problems are very specific: they are caused by the two modules referencing classes or identifiers in the other module ***while they are being loaded***. If all the modules contain are class and function definitions, and all the class definitions contain is method definitions, the only possible problems I could see would be the inheritance part of the class statement, and defaults in the function and method definitions. Both of these need to be defined at import time. Since inheritance is strictly hierarchical, it isn't too difficult to import in the right order. > You might encounter less problems if those classes go together in a > single module, but module boundaries are just there to help the > programmer organize code, they have little formal meaning. > > > Even if there were a way to do circular inheritance, it would be a > > nightmare to understand, so needs to be redesigned anyway. > > He probably just meant circular dependency, since obviously inheritance > doesn't make sense. And circular dependencies are difficult as well. The best policy, as several posters have already said, is to redesign to eliminate it. John Roth > > Ian > > > From ngps at netmemetic.com Sat Jul 5 10:24:36 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 5 Jul 2003 14:24:36 GMT Subject: What does this core dump mean? Message-ID: Hi, I just noticed that demo/evp_ciph_test.py of my M2Crypto package causes a core dump. It used to not do that. ;-) The core dump happens when the program is exiting; in the output below, rc2_40_cbc is the last test run by the program: $ python evp_ciph_test.py ... testing aes_256_cfb ... ok testing aes_256_ofb ... ok testing rc4 ... ok testing rc2_40_cbc ... ok Segmentation fault (core dumped) Here's the gdb trace: #0 0x8099fc4 in _PyObject_GC_UnTrack (op=0x8183c4c) at Modules/gcmodule.c:869 869 _PyObject_GC_UNTRACK(op); (gdb) bt #0 0x8099fc4 in _PyObject_GC_UnTrack (op=0x8183c4c) at Modules/gcmodule.c:869 #1 0x805dfc7 in tupledealloc (op=0x8183c4c) at Objects/tupleobject.c:142 #2 0x807b029 in code_dealloc (co=0x819ba80) at Python/compile.c:98 #3 0x80be6ce in func_dealloc (op=0x81943cc) at Objects/funcobject.c:377 #4 0x80c800b in PyDict_SetItem (op=0x8190b0c, key=0x8198dc0, value=0x80e4adc) at Objects/dictobject.c:373 #5 0x80caddd in _PyModule_Clear (m=0x8181eec) at Objects/moduleobject.c:136 #6 0x808bdab in PyImport_Cleanup () at Python/import.c:352 #7 0x80945fd in Py_Finalize () at Python/pythonrun.c:218 #8 0x8053620 in Py_Main (argc=2, argv=0xbfbffa44) at Modules/main.c:378 #9 0x8052ed0 in main (argc=2, argv=0xbfbffa44) at Modules/python.c:10 #10 0x8052e22 in _start () What does the error mean? TIA. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From dmbkiwi at yahoo.com Sun Jul 13 15:02:19 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Mon, 14 Jul 2003 07:02:19 +1200 Subject: Python - if/else statements References: Message-ID: On Sun, 13 Jul 2003 17:00:11 +0000, Bengt Richter wrote: > On Sun, 13 Jul 2003 16:40:39 +1200, dmbkiwi wrote: > >>On Sun, 13 Jul 2003 03:59:53 +0000, Bengt Richter wrote: >> > [...] >>> BTW, since you uploaded it, is there an URL for it? >> >>http://www.kdelook.org/content/show.php?content=6384 >> > I get a tar file, but winzip thinks it's broken. Usually it handles them fine. > > 03-07-13 09:34 507,442 6384-weather_liquid_py-0_7_2_tar.tar > > [ 9:51] C:\pywk\clp\dmbkiwi>lsm *tar > 3912fe9836d69ec9004da899e08e352e 6384-weather_liquid_py-0_7_2_tar.tar > > That's the MD5 digest, same as from (in case you want to check against a known good you have): > > [ 9:52] C:\pywk\clp\dmbkiwi>python D:\Python22\Tools\Scripts\md5sum.py 6384-weather_liquid_py-0_7_2_tar.tar > 3912fe9836d69ec9004da899e08e352e 6384-weather_liquid_py-0_7_2_tar.tar > > Regards, > Bengt Richter It's a *.tar.bz2 file. Does winzip handle bzipped files? Dunno, don't use it. If you are interested, I can email the script. Alternatively, you could start using linux. Your choice :-). -- Regards Matt If there is any realistic deterrent to marriage, it's the fact that you can't afford divorce. -- Jack Nicholson From bokr at oz.net Fri Jul 18 17:55:46 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 21:55:46 GMT Subject: "\n" in ASCII-file References: Message-ID: On Fri, 18 Jul 2003 14:28:05 +0200, Karl Scalet wrote: >Martin P schrieb: >> Hello, >> >> for a short exercise-program I have to read the lines in an ASCII-file. >> >> But every line has a new-line-feed ("\n") at the end of the line. (The >> ASCII-file was made with Windows Notepad). >> Is this only because I used Windows (and Notepad)? >> >> And... is there any special method to read lines from a file without "\n"? >> >> Bye, >> Martin >> >> > >beside the issue about large or not-so-large files, there >is another difference between Gerhard's line.rstrip() and >my splitlines() method: >entire_file.splitlines() preserves trailing whitespace characters >while line.rstrip() doesn't. Just for the rare case it matters :-) > I guess you could use line.rstrip('\n') in that case, e.g., >>> ' line with trailing space \n'.rstrip() ' line with trailing space' >>> ' line with trailing space \n'.rstrip('\n') ' line with trailing space ' Regards, Bengt Richter From martin at v.loewis.de Fri Jul 18 11:21:27 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Jul 2003 17:21:27 +0200 Subject: Using Unicode scripts References: <3f17c520$0$7194$626a54ce@news.free.fr> <3f17eace$0$23860$626a54ce@news.free.fr> Message-ID: "yzzzzz" writes: > This means that Python doesn't take into account the specified encoding > (Latin 1 or UTF-8) and prints out the raw bytes as they appear in the source > file, regardless of the encoding used. Is this normal? It is. The "standard" string type of Python is a byte string, which is not suitable to represent characters in general (although it works fine for ASCII). As the state of a string object consists just of its bytes, no knowledge of the original source encoding can be preserved. No knowledge of the source encoding is preserved for Unicode strings, either, but that is not a problem since the source gets converted to Unicode while parsing it. Regards, Martin From buki at bukis.org Mon Jul 14 14:27:23 2003 From: buki at bukis.org (Andreas Bauer) Date: Mon, 14 Jul 2003 20:27:23 +0200 Subject: some questions Message-ID: <3f12f613$0$8731$9b622d9e@news.freenet.de> Hi, I need some information on how to deal with strings which I have divided by using split(). I'm new to python and don't know how to handle these split up strings. And I some one could recommend a good tutorial I would be very glad. Can't hardly find any. Thanks in advance. Andreas From mcherm at mcherm.com Thu Jul 10 10:00:51 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 10 Jul 2003 07:00:51 -0700 Subject: How does python work Message-ID: <1057845651.3f0d7193692ac@mcherm.com> First, let me answer your questions: Geiregat Jonas writes: > I'm asking myself how Python code get's executed ... Normally, a compiler compiles the code to a .pyc file, then an interpreter processes the .pyc file executing the code therein. > What happens first etc ... > First read the file and then .. The script you provide is executed statement-by-statement in order from top to bottom. Of course, if a statement (eg: import) involves executing code from another file or from some C extension, then that happens when the invoking statement is processed. Most programs put a bunch of imports then a bunch of class and function definitions, then a small bit of actual code-to-be-executed at the bottom, after a little incantation like this: "if __name__ == '__main__':". > How python handle's variable internally ... In all cases, the actual object is allocated on the heap. A variable is a reference to an object, and they are stored different places depending on the scope of the variable. Global (ie module-level) variables are stored in a hash table (dict). Object instance variables are stored in a dict. Class-level variables like methods are stored in a dict. Local function variables are stored on the stack but made to LOOK like they're in a dict. > also could someone point me to the build in functions in the python source > code ? Pointing you to parts of the Python code is beyond the scope of this posting. Anyway, now that I've answered the questions you've ASKED (except the last one), let me answer the questions you DIDN'T ask but might be wise to ask: QUESTION: Where can I go to see a beginners tutorial on Python? There are quite a few. A list can be found here: http://www.python.org/doc/Newbies.html QUESTION: Where can I find Python's documentation? ANSWER: http://www.python.org/doc/ I would start by reading the Tutorial... it's an excellent introduction to Python. Then you'll probably want to start browsing through bits of the Library Reference. QUESTION: Where can I ask questions about Python? ANSWER: This newsgroup is fine, but you might also want to check out the Python Tutor List, found at http://mail.python.org/mailman/listinfo/tutor QUESTION: Can I learn Python just by experimenting with it? ANSWER: For the most part, YES! I suggest installing Python, then finding a way to run it from the command line (how you do that depends on your operating system). Then play around a bit. Of course, you'll still want the documentation available, but you can figure out lots just by doing this. -- Michael Chermside ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From nbdy9 at hotmail.com.nospam Wed Jul 30 14:02:16 2003 From: nbdy9 at hotmail.com.nospam (Mark) Date: Wed, 30 Jul 2003 14:02:16 -0400 Subject: How to get Windows physical RAM using python? Message-ID: Thanks. From mdgrosse at sbox.tugraz.at Tue Jul 29 19:09:30 2003 From: mdgrosse at sbox.tugraz.at (Michael Gross) Date: Tue, 29 Jul 2003 23:09:30 GMT Subject: PyArg_ParseTuple and float/double Message-ID: I want to use Python to make it possible to do scripting in my application. So I write wrappers for my C++ classes. Everything works fine, but it seems, that I cant use float and double arguments with PyArg_ParseTuple: PyArg_ParseTuple(args, "d", &double_1) and PyArg_ParseTuple(args, "f", &float_1) always returns false. I even looked at the args directly: PyObject* s = PyObject_Str(args); char *ss = PyString_AsString(s); then ss maybe has the value "(2.5339999999999998,)". It works, when I use an integer instead: PyArg_ParseTuple(args, "i", &int_1) But then of course the value is floored. I tried with Python 2.2.2 and 2.2.3. I use PyRun_SimpleString to run the script. tia Michael From scook at elp.rr.com Fri Jul 4 01:59:10 2003 From: scook at elp.rr.com (Stan Cook) Date: Fri, 04 Jul 2003 05:59:10 GMT Subject: File information?? Message-ID: Is there a way to get the file size and modified date of a file? From max at alcyone.com Tue Jul 15 01:02:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 22:02:20 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> Message-ID: <3F138ADC.4BF9DB3A@alcyone.com> Stephen Horne wrote: > True enough. The issue of how assignment is represented is trivial and > unimportant in the scheme of things. Then I retract (or at least soften) my earlier comment; I thought you were suggesting that it was a significant issue. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The actor is not quite a human being -- but then, who is? \__/ George Sanders From jjl at pobox.com Thu Jul 31 21:45:56 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Aug 2003 02:45:56 +0100 Subject: HTML DOM parser? References: <7x7k5y5wfh.fsf_-_@ruckus.brouhaha.com> Message-ID: <87ispi5ewb.fsf@pobox.com> Paul Rubin writes: > Is there an HTML DOM parser available for Python? Preferably one that > does a reasonable job with the crappy HTML out there on real web > pages, that doesn't get upset about unterminated tables and stuff like > that. Many extra points if it understands Javascript. Application is > a screen scraping web robot. Thanks. glork. I just started working on this myself. Email me if you'd like the code, such as it is. I've wrapped the Mozilla JS interpreter but am currently stuck on a segfault, so I could certainly do with a collaborator. I'm using utidylib and 4DOM (latter from PyXML). Mind you, if you actually want to get a job done , for a quick-but-bulky (and somewhat closed) solution, try PyKDE (KHTML / KJS) or IE automation (MSHTML / JScript). Mozilla + XPCOM also, but I think it requires rebuilding Mozilla to get PyXPCOM support. There's also httpunit (in Java, useable from Jython). John From skodela at lithium.com Fri Jul 18 13:54:45 2003 From: skodela at lithium.com (sreekant) Date: Fri, 18 Jul 2003 17:54:45 +0000 (UTC) Subject: how to compile python program to linux executable In-Reply-To: References: Message-ID: Python being interpreted should not depend that much on os version etc. It ofcourse will depend on the python/wxpython/vtk versions themselves though, especially if you use some procedure/facility and that has been changed in the version your client has. I have distributed a gui program in the past and although it gave a few niggles [ I can't remember which ! ] it wasn't a major problem. YMMV sreekant Maurice wrote: > Or can I only do this when they have exactly the same Linux version. > Or is it only possible when they have installed the other progames > containing the modules. > The modules I'm thinking of is for example wxPyhton and/or VTK. > > Maurice > From m.hadfield at niwa.co.nz Mon Jul 21 00:20:48 2003 From: m.hadfield at niwa.co.nz (Mark Hadfield) Date: Mon, 21 Jul 2003 16:20:48 +1200 Subject: A challenge to the ASCII proponents. In-Reply-To: <60dfb6f6.0307201951.4eea1930@posting.google.com> References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <60dfb6f6.0307201951.4eea1930@posting.google.com> Message-ID: Carl Banks wrote: > Alan Kennedy wrote in message news:<3F168011.3AEB3EFC at hotmail.com>... > >>So, the challenge to the ASCII proponents is: put the greek word >>"gignooskoo" on everybody's screen, originating from a usenet message, >>in the original greek, where "oo" -> greek letter omega. > > I accept. > > ____ ____ ___ _____ ___ > | | | |\ | / \ \ | / / \ > | | | | \ | | | \ | / | | > | | | | \ | | | > |< | | > | | | | \| \ / / | \ \ / > | | | | | _\ /_ /____ | \ _\ /_ > > > :-) > I am old enough to remember ASCII art, though I won't admit to ever participating in this activity myself. (It used to be said that it makes one go blind.) I think that answer has to take first prize for originality. I hope you won't think if I'm a spoilsport in pointing out that it fails the "everybody" test, as many people use proportional fonts in their news readers. -- Mark Hadfield "Ka puwaha te tai nei, Hoea tatou" m.hadfield at niwa.co.nz National Institute for Water and Atmospheric Research (NIWA) From dmbkiwi at yahoo.com Fri Jul 11 15:34:18 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sat, 12 Jul 2003 07:34:18 +1200 Subject: Python - if/else statements Message-ID: I am new to this group, and relatively new to python programming, however, have encountered a problem I just cannot solve through reading the documentation, and searching this group on google. I have written a theme in python for the superkaramba theme engine on kde (see http://netdragon.sourceforge.net - if you are a kde/linux user, it is a great visual applet engine). I have uploaded it to www.kdelook.org for others to download and use, however, some users are having an issue, which to me seems to be very strange. Basically the problem is that their version of python is ignoring an if/else statement, and I can't understand why. Over 3000 people have downloaded the theme, and only 3 people have identified this problem. The relevant portion of code is: def meterClicked(widget, meter, button): #print "meterclick" global dayshow, daypicrem, ddon, ddcon, buttonpressed if (meter == mainpic) and (button == 1): if ddcon == 0: if ddon == 1: deleteDayDetail(widget, dayshow) karamba.redrawWidget(widget) createCurrentDetail(widget) karamba.redrawWidget(widget) else: deleteCurrentDetail(widget) else: for i in range(0,5): if (meter == daypicrem[i]) and (button == 1) and (dayshow != i): #print "buttonpressed: day" + str(i) if ddon == 1: deleteDayDetail(widget, dayshow) karamba.redrawWidget(widget) elif ddcon == 1: deleteCurrentDetail(widget) karamba.redrawWidget(widget) createDayDetail(widget, i) karamba.redrawWidget(widget) dayshow = i #print dayshow break if (meter == daypicrem[i]) and (button == 1) and (dayshow == i): if ddon == 1: deleteDayDetail(widget, dayshow) karamba.redrawWidget(widget) elif ddcon == 1: deleteCurrentDetail(widget) karamba.redrawWidget(widget) dayshow = i #print dayshow break buttonpressed = 1 What these users are experiencing is that this portion of code is being processed, and evaluating all if statements as true, however, as you can see, they cannot all be true each time this function is called. Their versions of python also ignore the else construct. Can anyone shed any light on what might be going on with these users? Matt From justinjohnson at fastmail.fm Tue Jul 8 11:31:17 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Tue, 08 Jul 2003 09:31:17 -0600 Subject: process.py problems Message-ID: <20030708153117.127C0326C0@www.fastmail.fm> Hello, I was wondering if anyone has seen this behavior before for the process.py module available at http://starship.python.net/crew/tmick/. I've been using it quite well on windows 2000 servers, but when I try to use it on a window nt 4.0 box I get the results posted below. I have both process.py and which.py installed. Any help you can provide is greatly appreciated. >>> import process >>> p = process.ProcessOpen("dir") Traceback (most recent call last): File "", line 1, in ? File "process.py", line 1108, in __init__ self._startOnWindows() File "process.py", line 1279, in _startOnWindows cmd = _fixupCommand(cmd, self._env) File "process.py", line 506, in _fixupCommand cmd = _whichFirstArg(cmd, env) File "process.py", line 315, in _whichFirstArg candidates = list(which.which(first)) File "which.py", line 251, in which raise WhichError("Could not find '%s' on the path." % command) which.WhichError: Could not find 'dir' on the path. >>> p = process.ProcessOpen("dir.exe") Traceback (most recent call last): File "", line 1, in ? File "process.py", line 1108, in __init__ self._startOnWindows() File "process.py", line 1279, in _startOnWindows cmd = _fixupCommand(cmd, self._env) File "process.py", line 506, in _fixupCommand cmd = _whichFirstArg(cmd, env) File "process.py", line 315, in _whichFirstArg candidates = list(which.which(first)) File "which.py", line 251, in which raise WhichError("Could not find '%s' on the path." % command) which.WhichError: Could not find 'dir.exe' on the path. >>> p = process.ProcessOpen("cmd") Traceback (most recent call last): File "", line 1, in ? File "process.py", line 1108, in __init__ self._startOnWindows() File "process.py", line 1295, in _startOnWindows raise ProcessError(msg=ex.args[2], errno=ex.args[0]) process.ProcessError: The system cannot find the file specified. >>> From tcronj at ananzi.co.za Wed Jul 23 06:54:35 2003 From: tcronj at ananzi.co.za (Tertius) Date: Wed, 23 Jul 2003 12:54:35 +0200 Subject: Design tool Message-ID: <3f1e985d$0$236@hades.is.co.za> Can anyone suggest a favorite, design/Case/UML Tool used by the open source community? (in particular the Python community) Thanks, Tertius From bokr at oz.net Mon Jul 21 17:03:17 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jul 2003 21:03:17 GMT Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> Message-ID: On Mon, 21 Jul 2003 10:51:32 +0100, Alan Kennedy wrote: >I don't want to go on and on about this, and I'm happy to concede that >some of my points are far from proven, and others are disproven. >However, there are one or two small points I'd like to make. > Ditto ;-) >Ben Finney wrote: > >>>> Which quickly leads to "You must use $BROWSER to view this site". >>>> No thanks. > >Alan Kennedy wrote: > >>> No, that's the precise opposite of the point I was making. > >Ben Finney wrote: > >> You also stipulated "... from a Usenet post". Most Usenet readers >> do not handle markup, nor should they. There are many benefits from >> the fact that posts are plain text, readable by any software that can >> handle character streams; > >1. While there may be benefits from posts being plain text, there are >also costs. The cost is a "semantic disconnect", where related >concepts are not searchable, linkable or matchable, because their >character representations are not comparable. Ihopeyou don't want some awful garbage like the above line in postings? Especially since the bulk of it would probably be automatically generated an MS NLP feature ;-/ > >2. I chose the "from a usenet post" restriction precisely because of >the 7-bit issue, because I knew that 8-bit character sets would break >in some places. It was an obstacle course. I see this as a separate issue from semantics, though. Encoding consistent signs for identical things is a different problem from handling and encoding the *meaning* of the things indicated. > >> parsing a markup tree for an article is a whole order >> of complexity that I'd rather not have in my newsreader. >> >> Expecting people to use a news reader that attempts to parse markup >> and render the result, is like expecting people to use an email reader >> that attempts to parse markup and render ther result. Don't. > >I don't expect people's newsreaders or email clients to start parsing >embedded XML (I nearly barfed when I saw Microsoft's "XML Data >Islands" for the first time). > >What I'm really concerned about is the cultural impact. I voluntarily >maintain a web site for an organisation that has members in 26 >countries, who not surprisingly have lots of non-ASCII characters in >their names. Here's one: Ok, but, do we need to embed a full markup language to handle small encoding exceptions, it that's the real concern? (IMO, no ;-) > >http://www.paratuberculosis.org/members/pavlik.htm > >Because of the ASCII restriction in URLs, I was only able to offer Dr. >Pavl?k the above uri, or this: > >http://www.paratuberculosis.org/members/pavl%EDk.htm > >which sucks. Which part, though? The encoding, or the fact that you see the encoding in the above instead of its being rendered with the intended appearance? IOW, any solution will involve *some* encoding and the possibility of rendering it "raw" or interpreted. A smart GUI might have a default mode showing everything interpreted, and have a "view source" button. But "any solution" is not where we are. I think most people would object to getting this kind of stuff in what appears to be just visually enhanced mail, if they were aware every time it happened: (I hope nobody's too-smart-for-its-own-good viewer tries to see the following as actual MIME content ;-/) ----- ... MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="----000000000000000000000000000000000000000000000000000000000000000" ... ----- The trouble is that any automated following of references out of received information is effectively a stealth channel for info, if only to inform that your computer processed the message. Not to mention cookie stuff, and exploitation of real security holes. The defense of filtering out requests to alternate server sources may be a reasonable compromise for web viewing, but IMO such defenses should not be necessary in email. But the large majority of users will use MS stuff with whatever defaults MS decided good for something. So an email winds up doing a lot more than presenting different language encodings and fonts well. That's why alternatives have appeared, but what happens if an html chunk is handed to a MS system DLL to do rendering? How limited is the interpretation? Should it all be rewritten from scratch and duplicate lots of stuff already available? What can safely be handed off? A whole email preview pane presentation? > >Little wonder then that the next generation are choosing to explicitly >remove the accents from their names, i.e. his colleague Dr. Machackova >explicitly asked to have the accents in her name removed. Although I >assured her that her name would be correctly spelled, on web sites >that I maintain, the fact that her name breaks continually with >various ASCII centric technologies makes her think it's not worth the >hassle, or worth the risk of searches for her name failing. > That is a complaint about the current state of affairs, though. The problem is migration to new tools without unacceptable backwards breakage. Unfortuantely, the lowest common denominator tends to be a breakage solution. >http://www.paratuberculosis.org/members/machackova.htm > >And what about Dr. Sigur?ard?ttir, Dr. Dj?nne, and Dr. de la Cruz >Dom?nguez Punaro? Are they destined to be passed over more often than >ASCII-named people? > >[BTW, I've written the above in "windows-1252", apologies if it gets >mangled] > >Solely because of technical inertia, and unwillingness to address the >(perhaps excessive) complexity of our various communications layers, >i.e. our own "Tower of 7-bit Babel", we're suppressing cultural >diversity, for no technically valid reason. > >I personally don't have the slightest problem with reformulating NNTP >and POP to use XML instead: In a way, I think it's almost inevitable, >given how poor our existing "ascii" technologies are at dealing with >i18n and l10n issues. Emails and usenet posts are all just documents >after all. Right, but are they multimedia presentations? I like the option to have the latter, but only by optional and intentional linkage following, and rendered by a separate invoked tool, not as an email reader built-in. That might seem like a fine distinction, but it is easier to trust a limited tool with well-defined and manual control transfers to other functionality than it is to trust and automated doitall. That is the comfort of plain ascii, IMO, and for many that comfort is worth a fair amount of other discomfort. If the information for the other tool has to be embedded, we have MIME attachments, but IMO they should not be delivered by default. ISTM having a selection of simple separate tools that do limited things only on manual command would be better for email than having it be an instance of general purpose XHTML processing. > >Would something like this really be so offensive (the Gaelic isn't, I >promise :-)? Or inefficient? > >#begin--------- > > > An mhaith l'?inne dul go dt? an nGaillimh D? >Domhnaigh? > al?in ? cinn?ide > na cail?n? agus na buachaill? > >#end----------- Hm, your post arrived to me with this in the header: -- Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit -- ISTM the problem is the dual aspect of some meta-data (e.g. headers). I.e., to recognize meta-data, something has to assume an encoding for *it*. The simplest assumption is a fixed standard assumption, like ascii. This dual-aspect problem appears also in file systems, where a box handle also serves as a box label and loose content-type indicator. If you want meta-data also to be GUI-presentation-encoded data you are getting away from a standard assumption, or perhaps substituting the utf-8 standard assumption of XML. If the latter, why not just let that be it, without involving the tagged markup cruft of XML, unless you have specific goals for the markup per se? I can see such goals, but I don't think they belong in normal email, and to do it just to identify header elements is IMO an unclean solution to what rfc2822 already does much more readably (taking glyph encoding as a separate issue). The problem with multiple encoding declarations is that they have to be recognized as meta-data. They belong *on* the box, not in it. The only way to be in a box is to be on a box inside a box that can contain others in a way that separates the contained boxes, like multi-part MIME sections. Otherwise an nested encoding declaration would have to be *itself* encoded in whatever the current encoding was. But then you have to decide that it wasn't just peculiar data, and you have to invent an escape, etc... Just switching to utf-8 as a standard assumption for "box labels" (e.g., email headers and file names etc.) would IMO go a long way towards avoiding XML for email bodies. Thus ... From: Alan Kennedy Organization: just me. ... Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit ... would be encoded in utf-8, but after the blank line that ends the header, it would be assumed text/plain; charset=iso-8859-1. I'm sure people like Martin have given this a lot more thought (not to mention relevant implementation work ;-) than I have, so I would not be surprised to have important issues I've disrgarded pointed out. For special effects in emails, I could see borrowing the XML "processing instruction" escape, of which itself is an example. I.e., That syntax means invoke the named processing, passing ... up to the ?> as arguments to the processing program. I wouldn't want just any of these to take off automatically, though. Imagine, e.g., A smart email reader could hide as a clickable xxx and let you right-click to see the source, but an old reader would just show it as above. Embedded pictures could e.g. be specific to a base64-encoded (and *that* represented in the current encoding, along with the entire ) gif, like Clicking the highlighted "gif" might pop up a picture in a child window, etc. Might be interesting also. All these things could be designed to operate on immediate data vs referred-to data, where the latter could refer to attachments or urls or whatever. This mechanism could also be used to solve the gignooskoo problem, something like (here with immediate data): Where that whole thing is encoded within the current message in its current encoding (which can't be violated by including actual utf-8 characters not in common) but is seen by the smart email reader as invokng "utf8" processing. That might be one that one would elect to have the reader do automatically. Again, for email readers that don't understand you just see it as above. But converting email/news wholesale to an instance of XHTML, please no! ;-) Regards, Bengt Richter From rmunn at pobox.com Tue Jul 29 13:06:51 2003 From: rmunn at pobox.com (Robin Munn) Date: Tue, 29 Jul 2003 17:06:51 GMT Subject: Downloading Python files References: Message-ID: Terry Reedy wrote: > > "Luke StClair" wrote in message > news:slrnbi2j1n.ra.luke at stclair.homelinux.net... >> Only marginally belonging in this newsgroup... but oh well. >> >> I've just started writing in python, and I want to make the files >> available on the web. So I did the standard > href="mypath/myfile.py"> and not surprisingly, it displays like a >> webpage, but just the code. > > What browser on what system? As I remember, with IE6/Win98 with > python installed, even left clicking brings up 'Downloading... open or > save' box. And there is always right click 'Download as..' option. That's because Microsoft is a standard unto themsleves. IE will ignore the Content-Type header being sent by the server; instead, it will look at the user's file type settings for the extension of the file. In this case, the system you were testing on had no entry for the .py extension, so downloading was the default option. But get this: if you had *wanted* to show the code (instead of downloading), the way to do it in a cross-platform way, compatible with every browser *except IE* would be to set "Content-Type: text/plain" on the file. But Microsoft knows best, dear, so IE would override that and make the user download the file instead of displaying it. BTW, for those not familiar with DWS, it means Dripping With Sarcasm. Sorry for the vitriol against IE and Microsoft, but this has been a *very* annoying issue for me from time to time. -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From logiplex at qwest.net Tue Jul 22 18:27:31 2003 From: logiplex at qwest.net (Cliff Wells) Date: 22 Jul 2003 15:27:31 -0700 Subject: wxPython probleme In-Reply-To: References: Message-ID: <1058912851.1448.93.camel@software1.logiplex.internal> On Tue, 2003-07-22 at 13:53, Geiregat Jonas wrote: > Hey, > here's my piece of code : > > class HtmlWindow(wxHtmlWindow): > def __init__(self,parent,id): > wxHtmlWindow.__init__(self,parent,id) > > class channelTree(wxTreeCtrl): > def __init__(self,parent,id): > wxTreeCtrl.__init__(self,parent,id) > self.root = self.AddRoot("Sites") > for i in range(len(names)): > self.AppendItem(self.root,names[i]) > EVT_TREE_SEL_CHANGED(self,105,self.OnCelChanged) > > def OnCelChanged(self,event): > item = event.GetItem() > print self.GetItemText(item) > > class MainSplitter(wxSplitterWindow): > def __init__(self,parent,id): > wxSplitterWindow.__init__(self,parent,id) > self.html = HtmlWindow(self,-1) > self.html.LoadPage("welcome.html") > self.SplitHorizontally(self.html,wxWindow(self,-1),500) > self.Show(1) > > > If you look at the channelTree class I've created a wxTreeCtrl when you > change a sel a execute onCelChanged Now I would like that when you > change a sel he loads an other page into the HtmlWindow. But I don't > really have an idea on how to do this any help ? I'm assuming that self.GetItemText() in OnCelChanged() returns a URL? In that case you can simply pass that to HtmlWindow.LoadPage(). You'll need to pass a reference to your HtmlWindow instance to your channelTree instance so that it can call LoadPage() class channelTree(wxTreeCtrl): def __init__(self,parent,id, htmlWindow): wxTreeCtrl.__init__(self,parent,id) self.root = self.AddRoot("Sites") for i in range(len(names)): self.AppendItem(self.root,names[i]) EVT_TREE_SEL_CHANGED(self,105,self.OnCelChanged) self.htmlWindow = htmlWindow def OnCelChanged(self,event): item = event.GetItem() self.htmlWindow.LoadPage(self.GetItemText(item)) Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From postmaster at 127.0.0.1 Sun Jul 13 20:56:27 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Mon, 14 Jul 2003 12:56:27 +1200 Subject: Any pure-python relational databases? References: <2a897f11.0307121143.4a37113b@posting.google.com> <3f1178ba$0$6533$afc38c87@sisyphus.news.be.easynet.net> Message-ID: On Sun, 13 Jul 2003 17:19:57 +0200, Justin paused, took a deep breath, then came out with: >>> While not relational, have you looked at Metakit? > >> Thank YOU, Wayne!!! :))) > > Be careful, though: the metakit page states that > "There is no multi-user support", so I am not sure > this is the ideal choice for a web-app. Unless the > web clients just fetch dynamic pages and don't need > to _write_ to the db... I have been intrigued by the > library myself, but always thought this warning must > be there for a reason... Cave-man solution - lockfiles and wait loops. If a website is so busy that waiting on locks risks maxing out the 30 second cgi limit, then presumably traffic is high enough to justify getting a better server. From tl_news at nexgo.de Wed Jul 30 07:50:37 2003 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 30 Jul 2003 13:50:37 +0200 Subject: Bottleneck: easy obscurity "encryption" via xor References: <7xwue0pzcl.fsf@ruckus.brouhaha.com> <1d45gb.cjp.ln@217.11.196.167> <7xn0ew1cre.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: Hi! > If you want to encrypt in python, try the p2.py that I posted; it's > been carefully designed with good algorithms and fairly well optimized > and should give much better security than some roll-your-own method. Thanks! But BTW your "time-bomb" and your comments in the file tell me that this script must not be used anymore... Cheers, Tino From leo.broska at NOSPAM.isys.com.au Wed Jul 2 02:40:22 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Wed, 2 Jul 2003 16:40:22 +1000 Subject: experience with emacs and python-mode References: Message-ID: thanks for your information. now i've started to use python-mde a bit more and its qirks quite well. cheers, leooo "Leo" wrote in message news:bdp8gv$2krt$1 at otis.netspace.net.au... > hi all > > i'm new to python and new to the group and i want to develop python with > emacs :-) i try to use python-mode.el version 4.6. > > does somebody else uses this? or what is your recommendation for editing > python code in emacs? > > btw: i have a little customisation problem with python mode: > > after running a script with py-execute-import-or-reload the cursor is in the > output window but i want to have it back in the source code. is there a > option i can tweak? > > thanks for all answers, > > leooo > > -- > recursive (ri-ker-siv): adj.; see "recursive" > > From h.goebel at goebel-consult.de Mon Jul 21 06:01:22 2003 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Mon, 21 Jul 2003 12:01:22 +0200 Subject: feature request: a better str.endswith In-Reply-To: References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <3f1cedc8$0$12995$9b4e6d93@newsread4.arcor-online.net> Skip Montanaro schrieb: > I suggest you submit a feature request to SF. +1 from me :-) This is a commonly used case. Using things like stripext() is only a solution for this specific case where filename-extensions are matched. Michele: I suggesz menatoning this in the feature-request or simple use a different example (not based on filename extension.) Regards Hartmut Goebel -- | Hartmut Goebel | IT-Security -- effizient | | h.goebel at goebel-consult.de | www.goebel-consult.de | From tjg at craigelachie.org Tue Jul 22 13:22:09 2003 From: tjg at craigelachie.org (Timothy Grant) Date: Tue, 22 Jul 2003 10:22:09 -0700 Subject: SAX questions... Message-ID: <200307221022.09513.tjg@craigelachie.org> I've worked with DOM before, but never SAX, I have a script that seems to work quite well, but every time I look at it I think it's amazingly unweildly and that I must be doing something wrong. def startElement(self, name, attr): if name == "foo": do_foo_stuff() elif name == "bar": do_bar_stuff() elif name == "baz": do_baz_stuff() There's similar code in endElement() and characters() and of course, the more tags that need processing the more unweildly each method becomes. I could create a dictionary and dispatch to the correct method based on a dictionary key. But it seems to me there must be a better way. Is there? -- Stand Fast, tjg. Timothy Grant www.craigelachie.org From erhan at uzem.itu.edu.tr Wed Jul 2 04:17:49 2003 From: erhan at uzem.itu.edu.tr (Erhan Ekici) Date: Wed, 2 Jul 2003 11:17:49 +0300 Subject: Partition names with Python In-Reply-To: References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: <1057133869.3f02952d4d733@mail.uzem.itu.edu.tr> Hi, But some machines /proc/partition file is empty.. But /etc/fstab contain drives names..(sda1,sda2,cdrom,floopy etc) For Example My Server(Slackware 9)'s /proc/partition file contain nothing. I must take partition names on all Linux(Redhat,Mandrake,Slackware etc).. Why do some machine's /proc/partition file contain nothing... Erhan, Quoting John Hunter : > >>>>> "Artur" == Artur M Piwko writes: > > Artur> And /proc/partitions. > > Best yet! > > import os > fh = file('/proc/partitions') > > fh.readline() # eat the header > fh.readline() # eat the blank line > > partitions = [line.split()[-1] for line in fh.readlines()] > print partitions > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Erhan Ekici ITU Center for Distance Learning E-Mail : erhan at uzem.itu.edu.tr From guettler at thomas-guettler.de Tue Jul 1 04:56:07 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 01 Jul 2003 10:56:07 +0200 Subject: experience with emacs and python-mode References: Message-ID: Leo wrote: > hi all > > i'm new to python and new to the group and i want to develop python with > emacs :-) i try to use python-mode.el version 4.6. > > does somebody else uses this? or what is your recommendation for editing > python code in emacs? My recommendation is, to only edit code in emacs. I execute it in an xterm. C-c C-g is mapped to goto-line. I prefere to jump to the position of an error in the code myself. From fredrik at pythonware.com Fri Jul 11 03:36:47 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jul 2003 09:36:47 +0200 Subject: Deleting specific characters from a string References: Message-ID: Jeff Hinrichs wrote: > First off, (holding hat in hand), I reread the profile module and then set > my profiler up correctly with the proper bias setting. you *cannot* use the profiler to measure overall execution time; it's designed to let you know where the program spends most of its time, not to compare different algorithms. use 2.3's timeit script, or write your own timing loop. with timeit, I get these results: > python timeit.py -s "import string; text = 'ben at orange?enter&your&code'; delete = '@&'; table = string.maketrans('', '')" "result = text.translate(table, delete)" 100000 loops, best of 3: 13.9 usec per loop > python timeit.py -s "text = 'ben at orange?enter&your&code'; delete = '@&'" "result = text" "for c in delete: result = result.replace(c, '')" 10000 loops, best of 3: 48.4 usec per loop From rich at mchsi.com Wed Jul 30 22:41:23 2003 From: rich at mchsi.com (Rich) Date: Thu, 31 Jul 2003 02:41:23 GMT Subject: how best to handle httplib timeouts ? References: <87k79zx5q6.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:87k79zx5q6.fsf at pobox.com... > [snip] > > 1. Get 2.3final (I don't know whether there was a bug fix, but I have > a vague recollection there was some sort of problem with timeouts > -- see the python-dev summaries and/or SF bug archive). yes, this seems to have made the problem go away... I tried setting the default timeout but it still acted flakey and would not connect, so, I removed this and everything seems to be working, or at lest timing out correctly. 2.3final also solved the "ImportError: No module named warnings" problem with py2exe and I think this may have had something to do with it. thanks, rich. From ianb at colorstudy.com Fri Jul 18 17:42:14 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 18 Jul 2003 16:42:14 -0500 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <3F17ECAC.30104@rogers.com> References: <3F17ECAC.30104@rogers.com> Message-ID: <1058564534.28066.28.camel@lothlorien> On Fri, 2003-07-18 at 07:48, Mike C. Fletcher wrote: > Hi all, > > I'm working on a base meta-type for a plug-in system, and I'd really > like to use the same rich-descriptor objects as I've used everywhere > else in the system. Basically these are descriptors that intercept > x.name, do various transformations, and then store the values in the > instance dictionary. > > Unfortunately: > > >>> type(t).pluginRole > Traceback (most recent call last): > File "", line 1, in ? > File "p:\properties\basicproperty\basic.py", line 231, in __get__ > return self.getDefault( client ) > File "p:\properties\basicproperty\basic.py", line 256, in getDefault > setattr( client, self.name, value ) > File "p:\properties\basicproperty\basic.py", line 283, in __set__ > self._setValue( client, value ) > File "p:\properties\basicproperty\basic.py", line 151, in _setValue > client.__dict__[ self.name ] = value > TypeError: object does not support item assignment > > which would seem to suggest that the only way to use the regular > descriptors would be to do the (annoying) '_'+name thing so that there's > a proliferation of names in the class (which I *really* don't want). > So, does anyone have a pattern which allows setting an attribute on a > class which doesn't go through the setattr machinery (i.e. can be used > within a descriptor)? Maybe you could create just new attribute. Call it _shadow, perhaps. Then the setter does setattr(client._shadow, name, value). The shadow could be a plain class like: class Shadow(object): pass class Plugin(object): def __init__(self): self._shadow = Shadow() May or may not be more elegant, but you can decide for yourself. Ian From zathras at thwackety.com Mon Jul 28 12:08:35 2003 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 28 Jul 2003 17:08:35 +0100 (BST) Subject: Debugging Python ? In-Reply-To: <3F2547F4.4020601@zope.com> Message-ID: On Mon, 28 Jul 2003, Shane Hathaway wrote: > As a bonus, I find that print statements do not rightfully belong in > most of the software I write. Therefore I can happily add print > statements anywhere for debugging purposes, knowing that removing them > later is perfectly safe. As an extra bonus, if you do this you can remove them all automatically: def print(*args): for arg in args: print arg, return True assert print("Well, well, well", "said", "he") To erase all tracks of the debugging statements at runtime, just use the -O flag. I tend to use a variant of this for debugging systems that have "complex" concurrency to make it simpler to track "who" "said" what. I know you can do the same with just grep if you use print - but you have to ensure that your debugging statements don't span multiple lines. Michael. From afriere at yahoo.co.uk Fri Jul 18 01:16:42 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Jul 2003 22:16:42 -0700 Subject: Replacing rexec References: <87adbd73f1.fsf@pobox.com>, <87adbd73f1.fsf@pobox.com> <20030717131402.26541.qmail@green.zadka.com> Message-ID: <38ec68a6.0307172116.433da94f@posting.google.com> Jack Diederich wrote in message news:... > MUDs also have an advantage > because the people writing code are hand picked. They have a stake in doing > the right thing so they rarely write malicious code. Not so with most MOOs (MOO was designed from the ground up to be programmable via a prototyping OO language (the OO in MOO) by any user with a prog bit set), where almost anyone is given programming privleges. In fact the only requirement, AFAIK (and it's been a while), on the MOO cited (LambdaMOO), is membership of one month standing. From thedustbustr at aol.com Sun Jul 27 16:22:45 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 27 Jul 2003 20:22:45 GMT Subject: boost::python> exposing instances from c++ Message-ID: <20030727162245.07099.00000480@mb-m12.aol.com> I'm writing a game in C++ which calls out to python for scripting. I'd like to expose the instance of my Game class (a singleton) to python (so that the instances of Clock, Camera, etc are available to the scripts). I ran into trouble trying to expose a specific instance (or even a function returning the instance). Here is a simplification of my problem in code (c++): class A{ public: int i; }; class B{ public: A a; }; B b; B getb() {return b;} //return the instance int main() { getb().a.i = 42; return 0;} #include #include #include using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_("A",init<>()) .def("i", &A::i); class_("B",init<>()) .def("a", &B::a); def("getb", getb); } Of course, I would be calling any python script using these classes from within main(). This doesn't compile (using bjam with msvc). If I return by reference or pointers in getb it gets ugly (like pages and pages of error messages). Am I doing this the right way? How do I expose an instance to python? From MatthewS at HeyAnita.com Mon Jul 21 20:23:36 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 21 Jul 2003 17:23:36 -0700 Subject: Voting Project Needs Python People References: Message-ID: <5ab0af73.0307211623.6e12f807@posting.google.com> "Alan Dechert" wrote in message news:... > We have an excellent team together. We're looking for a few good Python > coders willing to volunteer for this free open source project. It will be > on sourceforge.net later today. Are there any prerequisites for joining the team? From jmfbahciv at aol.com Tue Jul 22 07:36:59 2003 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 22 Jul 03 11:36:59 GMT Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: In article , Brian Inglis wrote: >On Tue, 08 Jul 03 12:43:14 GMT in alt.folklore.computers, >jmfbahciv at aol.com wrote: > >>In article , >> shoppa at trailing-edge.com (Tim Shoppa) wrote: >> >> >>>Remember the Dilbert where PHB complains that his programmers are using >>>way too many semicolons? :-) >> >>All RIGHT! That's a good PHB. It was so difficult to distinguish >>between a semicolon and a colon on the listings. > >That's a lousy printer operator: the ribbon should have been >flipped end around long before it got to that stage. >(That's the old equivalent of shaking a laser toner cartridge.) >You also wouldn't be able to differentiate between commas and >dots, some apostrophes and quotes, maybe bars and bangs, possibly >parens brackets and braces, if you had and used them. Yep. I know it was due to lousy print quality. However, I firmly believed that lousy print quality should have been a slight constraint in designs. Nowadays, we have great print quality; now, it's my eyesight that smudges the pixels. And it still should be a slight contraint in designs. Distinguishing characters, no matter what the display, has to be a first consideration that is usually forgotten by the time the design takes its first evolution. Just because it's forgotten does not mean that it's no longer an implicit assumption. /BAH Subtract a hundred and four for e-mail. From sismex01 at hebmex.com Mon Jul 14 19:30:15 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 14 Jul 2003 18:30:15 -0500 Subject: anything like C++ references? Message-ID: > From: Tom Plunket [mailto:tomas at fancy.org] > Sent: Lunes, 14 de Julio de 2003 06:15 p.m. > > What I specifically want is a way to have a "second-level > binding", e.g. a reference to a reference (assuming that the > terminology is correct by saying that all Python variables are > references). This is where I see the hole in Python, that there > actually is a class of object that is different from everything > else; you can bind to anything at all in the language...except > references. > > -tom! > What for? What would be the practical use for such a thing? To rebind a name remotely? It's not very consistent with the rest of the language. To have functions which rebind a name in a hidden way seems to me like a veritable fountain of possible bugs. Explicit is better than implicit and all that. Those operations might have sense in a language where a variable name is directly related to a storage location, a memory address; but Python is not like that, and trying to program in that style in Python is quite painful. I find Python to be quite clear and powerful, and never have needed such functionality in all the different type of projects I've done, small-to-medium, but varied: SQL parsers, XML parsers, email messaging systems, GUI frontends, RPC servers and clients, text-formatting utilities, etc... I've never found a single instance where I would have needed such that. A binding can't also be a container, that's a job for an object, if you truly need to "pull" data from a code segment, then you should use a dictionary, or a list, or an instance of some other mutable class, heck, even an empty class: class Inbox: pass IB = Inbox() def fn(obj): obj.value = 25 obj.message = "Here's a value for you" ... etc Even a scheme as simpleminded as this is infinitely better than having functions rebind your variable names to other objects, even if they're the same class. This, at least, is my opinion on the subject. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From michael at stroeder.com Sat Jul 26 14:31:01 2003 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 26 Jul 2003 20:31:01 +0200 Subject: autoconf-style checking for installed libs with DistUtils Message-ID: <60uav-or3.ln1@nb2.stroeder.com> HI! Is it possible to probe for installed libs with DistUtils? I'd like to automatically search for optional libs and adjust C compiler switchers before starting the build of a the extension module. Ciao, Michael. From roy at panix.com Tue Jul 15 11:22:18 2003 From: roy at panix.com (Roy Smith) Date: 15 Jul 2003 11:22:18 -0400 Subject: [OT] sentances with two meanings References: Message-ID: Harvey Thomas wrote: > Also 'I was unknown to you and you deceived me'. Slightly colloquial Given the biblical meaning of "known", this could have even more than two meanings :-) From mdgrosse at sbox.tugraz.at Wed Jul 30 14:25:51 2003 From: mdgrosse at sbox.tugraz.at (Michael Gross) Date: Wed, 30 Jul 2003 18:25:51 GMT Subject: PyArg_ParseTuple and float/double - Solution In-Reply-To: References: Message-ID: > it seems, that I cant use float and double arguments with > PyArg_ParseTuple: The problem was, that there was an error from another PyArg_ParseTuple in another method before, so PyError_Occured() was true and PyArg_ParseTuple test for this when parsing a double or float argument. So a call to PyErr_Clear helps. thx Michael From claird at lairds.com Thu Jul 3 08:39:06 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 03 Jul 2003 12:39:06 -0000 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: In article , Bob Gailer wrote: . . . >This brings back the good old days of FORTRAN IV which had a >single-statement IF and no ELSE. Thus: > C = VALUE1 > IF ( A .EQ. B) C = VALUE2 >Notice the indentation. Cols 1-5 were reserved for line # and col 6 for the >continuation code. So Python is not the only indentation dependent >language. Nor is it the first to use indentation to convey structure. . . . Maybe youngsters don't realize this. One monotonous but unremitting argument that Python inspires is about the wisdom of its white-space-significance (WSS). Modern programmers might not realize how strongly old-timers associate WSS with early FORTRAN and COBOL (as we capitalized them then), and how unpleasant some of those memories are. *That*, I assume, is why WSS discussions become as heated as they do. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jbar at lf1.cuni.cz Thu Jul 3 08:16:55 2003 From: jbar at lf1.cuni.cz (Jiri Barton) Date: Thu, 03 Jul 2003 14:16:55 +0200 Subject: Python - get key pressing ? References: Message-ID: <3f041eb7@shknews01> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203830 From larry_Goodman at yahoo.com Fri Jul 11 11:56:26 2003 From: larry_Goodman at yahoo.com (Chuck Spears) Date: Fri, 11 Jul 2003 15:56:26 GMT Subject: Why Python References: <3f0be9ac@news.comindico.com.au> Message-ID: <3f0edd67.316281478@news.pa.comcast.giganews.com> >There are, but if you're into thin GUI clients like VB6, there is no >direct equivalent. LOL. Tell our VB guys who have to bundle VB6 runtimes, MDAC, and other assorted Activex controls with their apps how thin VB6 clients are. If you want a truly thin windows client, use Delphi or C++ Builder. From staschuk at telusplanet.net Wed Jul 16 04:58:39 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 02:58:39 -0600 Subject: hex check In-Reply-To: <3F150135.8030708@is.lg.ua>; from alienoid@is.lg.ua on Wed, Jul 16, 2003 at 10:39:33AM +0300 References: <3F150135.8030708@is.lg.ua> Message-ID: <20030716025839.B3824@tibia.amotlpaa.bogus> Quoth Ruslan Spivak: > Does anybody have a hint how to check if input hex number is in correct > hex format? It's not entirely clear what you mean by "correct hex format". If you mean "contains only the characters 0-9, a-f, and A-F", then here's three ways: # 1 import re def ishex(s): return re.match('^[0-9a-fA-F]*$', s) is not None # 2 import string def ishex(s): for character in somestring: if character not in string.hexdigits: return False else: return True # 3 import string def ishex(s): return s.strip(string.hexdigits) == '' But I wonder why you want to bother checking this explicitly. Consider these implementations (which are not actually functionally equivalent to the previous three -- details left as an exercise): # 4 def ishex(s): try: int(s, 16) except ValueError: return False else: return True # 5 import binascii def ishex(s): try: binascii.unhexlify(s) except TypeError: return False else: return True Presumably, if the string *is* in correct hex format, you'll want to convert it to an int or a byte string or something. Why not just do whatever it is you want to do and catch the possible exception, as these implementations illustrate? -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From aahz at pythoncraft.com Thu Jul 17 15:26:34 2003 From: aahz at pythoncraft.com (Aahz) Date: 17 Jul 2003 15:26:34 -0400 Subject: Wanted: PyCon e-commerce site Message-ID: [Apologies to those of you who see this multiple times] We're starting to gear up for PyCon 2004, and we're looking for someone willing to handle setting up an e-commerce site for handling registration. If you're interested in taking on this responsibility, please send e-mail to pycon-organizers at mail.python.org We'd like to have this site running by the end of September. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From theller at python.net Wed Jul 23 13:42:26 2003 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jul 2003 19:42:26 +0200 Subject: py2exe prob References: Message-ID: "ryan" writes: > my program uses unicode functions and so i compile like: > "python setup.py py2exe --packages encodings" > > which seems to create unicodedata.pyd and zlib.pyd, the problem is when i > run my exe it acts like it didnt do that, it still gives me the error: > > ImportError: No module named warnings > warning: assignment shadows builtin >From these messages I infer that you are using Python 2.3, correct? There are still some py2exe problems with 2.3, I hope to resolve them soon. Thomas From max at alcyone.com Mon Jul 7 19:46:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jul 2003 16:46:29 -0700 Subject: A story about Python... sort of References: Message-ID: <3F0A0655.99823E25@alcyone.com> John J Lee wrote: > A Google result (appropriately enough, given the origin of > the name Google) ... But the origin of the name was generated from a misspelling of _googol_ (the name for 10^100), which evidently was found via Web searches. So the origin of the name of the search engine > ... suggested 10**120, and I seem to have a number in my head > of 10**80 non-virtual particles in the universe (though I've no > recollection where *that* number came from either!-). Typically the total number of elementary particles in the observable Universe is given as 10^80. But when you're talking about such rough estimates, the difference between 10^80, 10^100, and 10^120, although incredibly huge, aren't all that much. What's twenty or forty orders of magnitude between friends? Note that the qualification "observable Universe" here is crucial. We can only see to the edge of the cosmological horizon, where due to cosmological expansion, particles are receding at greater than the speed of light. This is due to the finiteness of the speed of light and the fact that the Universe is not infinitely old. As time progresses, we'll see more of the Universe, and so the observable Universe will increase in size. In standard Friedmann-Robertson-Walker models, you have open, flat, or closed universes. Recent observations seem to suggest that we live in an open universe -- one which will continue to expand forever until matter itself decays. In FRW models, open (and flat) universes have infinite spatial extent. So, presuming we live in a universe that follows this models, the true Universe is infinitely large, even though we can only see a finite, small part of it. > Possibly there is a quantum algorithm that makes use of many universes > to > solve the problem, though (no I'm not joking: the many-worlds > 'interpretation' is widely accepted amongst physicists working on > quantum > computation). Since it's an interpretation, though, it's just an intuitive way of looking at the situation. Quantum mechanical interpretations do not modify the theory itself; that is, they neither add nor subtract anything from the theory which is testable in any way. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Said it? yep / Regret it? nope \__/ Ice Cube From gumuz at looze.net Wed Jul 16 04:29:03 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 16 Jul 2003 10:29:03 +0200 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: <3f15132a$0$13797$4d4ebb8e@news.nl.uu.net> I spotted one funny 'mistake' .... the first question asks the name of the inventor of python. the second one gives you the answer :) "Anand Pillai" wrote in message news:84fc4588.0307152253.20858619 at posting.google.com... > Hi Pythonistas, > > I have placed a quiz on Python on the trivia site www.funtrivia.com. > Here is the link. > > http://www.funtrivia.com/quizdetails.cfm?id=139672 > > Looks like it is the first quiz on Python on this site. > > Please try it out if you like quizzing. > Let me know if there are any factual errors. > > Thanks > > ~Anand From urnerk at qwest.net Sat Jul 5 22:24:45 2003 From: urnerk at qwest.net (urnerk at qwest.net) Date: Sat, 5 Jul 2003 22:24:45 -0400 Subject: [Edu-sig] Re: Least used builtins? Message-ID: <191690-2200370622445807@M2W045.mail2web.com> Just to represent another viewpoint, I'll say that what's in builtins has nothing to do with what does or does not make sense to the beginner. It's a set of tools, including some low level ones that only make sense to a non-newbie. Likewise, 'copy' isn't there in a generic sense (it's there for dicts, which are builtin and sport a copy method), because the pro doesn't need it that often. What does or doesn't make sense to the newbie is irrelevant. A language need not be designed based on that perspective, to be good. It's the job of teachers to smooth the on ramp, and in that regard, just don't teach all the builtins to start. Just because they're all builtins doesn't mean each must be tackled in order, one by one. The strikes me as unimaginative, plodding. Kirby -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From ben at dadsetan.com Tue Jul 1 17:47:11 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Tue, 01 Jul 2003 22:47:11 +0100 Subject: Possible fix for Bug 494589 - os.path.expandvars bug Message-ID: <3F02015F.3000903@dadsetan.com> Here follows the comment I added to bug "[ 494589 ] os.path.expandvars deletes things on w32". It concerns some mismatching (buggy) implementation / docstrings / comments for the ntpath.py and dospath.py. (Especially) As it is my first post as well as bugfix try for any open-source project, I am very happy receiving constructiv critic. tim_one (see other 494589 bug comments) is right. There is plenty of dodgy things hiding behind the os.path world, especially when it comes to os.path.expandvars() There are two problems here. - Mismatch in between the doc strings of the different implementation of expandvars and the "official" os.path.expandvars documentation. - the ntpath and dospath implementations are buggy when compared to their comments/docstrings. About the first problem, the inconsistency created some time ago in between the different implementations tasks makes it difficult to choose a solution. Everyone will probably agree that all the platform specific implementations of expandvars should have the same functionality. The one that should be taken over will probably need to be announced by the BDFL. Some rule which should not have let this here happen, and on which I believe we all will agree on: Same interface=same documentation->same functionality To implement either copy paste exactly the same expandvars definition from one platform to another (NT, DOS, POSIX). Alternatively somehow rather arrange that when there is no specific implementation for the platform, a "default" python implementation is used on the os.path level. To maximize the fruits of my small work, I would of course prefer that the version below becomes the standard and that the Library documentation get updated. To be complete, shall the documentation remain unchanged (which will probablz be chosen) and the implementation of dos and nt gets adapted (copied from posix). But I really feel its docstring and its documentation should be in line with the rest of the implementations. For the second problem - as of now a real bug whatever we decide, I wrote within this comment (hereafter) a new expandvars version which fits the docstring documentation of dospath.py and the comments of ntpath.py. Sorry you will be getting no patch from me at the moment since sourceforge's anonymous CVS access does not like me. Please note that my version borrows alot from the posixpath.py implementation and my changes are the ones of a python amateur who is open to critic. #expandvars() implementation _varprog = None _findquotes = None def expandvars(path): """Expand paths containing shell variable substitutions. The following rules apply: - no expansion within single quotes - no escape character, except for '$$' which is translated into '$' - ${varname} is accepted. - varnames can be made out of letters, digits and the character '_'""" global _varprog, _findquotes if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\}|\$)') _findquotes = re.compile("'.*?'") quoteareas = [] i = 0 while 1: quotearea = _findquotes.search(path, i) if not quotearea: break (i, j) = quotearea.span(0) quoteareas.append((i, j)) i = j i = 0 while 1: m = _varprog.search(path, i) if not m: break i, j = m.span(0) insidequotes=None for (quotebegin, quoteend) in quoteareas: if quotebegin < i and quoteend > i: insidequotes=1 break if insidequotes: i = j continue name = m.group(1) if name[:1] == '$': path = path[:i] + '$' + path[j:] i = i + 1 else: if name[:1] == '{' and name[-1:] == '}': name = name[1:-1] if os.environ.has_key(name): tail = path[j:] path = path[:i] + os.environ[name] i = len(path) path = path + tail else: i = j return path Regards, Ben. From http Sun Jul 20 19:30:28 2003 From: http (Paul Rubin) Date: 20 Jul 2003 16:30:28 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: <7xk7acai97.fsf@ruckus.brouhaha.com> "Ulrich Petri" writes: > "Alan Dechert" schrieb im Newsbeitrag > news:P9DSa.111436$Io.9552373 at newsread2.prod.itd.earthlink.net... > > Sorry but why on earth you dont just print that on paper and let people make > their crosses where they want? In the past there has been a lot of trouble with manual ballot systems, because people can't understand the instructions, the ballots get printed incorrectly, stuff like that. You might remember the big mess in the 2000 US presidential election, that revolved around such problems. Choosing the US President turned out to mostly be a battle between lawyers over which ballots to count rather than about what the voters wanted, and a lot of the legal decisions were made according to the political leanings of the particular judges. The ballots themselves didn't get a thorough tabulation until long after the January inauguration and people disagree about how to intepret the results even to this day. US elections are also different than elections in most other countries because a lot of different issues get voted in them. Rather than just choosing one of a bunch of different parties like in a parliamentary system, we vote separately for (potentially) the President, Senator, Congressional representative, Governor of the state, Lieutenant governor, Attorney General, Mayor of the town, members of the local school board, ballot initatives on whether to collect an extra tax on soda bottles, on whether to build a new highway somewhere, and so on and so on. Dozens of different things, all in one election. Counting ballots by hand would require reading off from each ballot all the separate votes on each of these issues. It's not like in France or Canada (I have no idea about Germany) where there's basically just one question to vote on. From news at exultants.org Mon Jul 7 05:48:21 2003 From: news at exultants.org (Van Gale) Date: Mon, 07 Jul 2003 09:48:21 GMT Subject: FYI: pyBoards.com In-Reply-To: <3F04E609.2010500@dadsetan.com> References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F04E609.2010500@dadsetan.com> Message-ID: <3F094141.9020604@exultants.org> Behrang Dadsetan wrote: > Does anyone know about message board systems written in python? > > Ben. I don't know of any polished ones, but there are a few for Zope/Plone. I don't have any links immediately handy other than (still-in-planning-stage?) Ploneboard: http://plone.org/Members/tesdal/PloneboardWiki/FrontPage There's also a minimal feature one called qxbb that I think is linked from the Quixote site. Van From pythonguy at Hotpop.com Sun Jul 20 11:26:46 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 20 Jul 2003 08:26:46 -0700 Subject: Volunteers need more visibility (was Re: www.python.org hacked?) References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> <3F131F69.8FD9B8DD@engcorp.com> Message-ID: <84fc4588.0307200726.6464d9e@posting.google.com> I would be very interested in this. I have a 24 hr internet connection at my home on cable modem, and I am interested in learning more about web site designs. I could use a tip or two in improving my own home page apart from helping the community :-) The problem is that I am in India. If that is no problem, I would like to volunteer for this task. Do let me know what I can do. Thanks ~Anand http://members.lycos.co.uk/anandpillai aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <3F131F69.8FD9B8DD at engcorp.com>, > Peter Hansen wrote: > > > >Thanks then to Aahz, Skip, Thomas, and anyone else involved. I think we > >should find a place to give more visible credit to the many people > >involved in handling with such things. I had no idea so many people > >who regularly contribute here were also the ones who step in to resolve > >such problems, or who manage the day-to-day updates and additions. > >And obviously this is a very distributed effort, unless you all happen > >to be roommates. ;-) > > Nope, we're even on separate continents. > > >To add to the workload then :-), but also perhaps to help inspire > >additional people to volunteer and share the load, I suggest adding a > >reasonably prominent page to www.python.org with a quick summary of who > >helps run the site, or other community efforts, and perhaps something > >like a one-sentence bio to give a bit more of a face to some of the > >lesser known folks. > > Enh. Maybe, but I'm too tired/busy to think about it. What I suggest > is that anyone who has an interest in how the web site is set up join > the site design list at > http://mail.python.org/mailman/listinfo/pydotorg-redesign > > (This is a discussion list, not a list for the people doing the > maintenance work.) From bokr at oz.net Thu Jul 17 11:07:42 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 15:07:42 GMT Subject: hex to signed integer References: Message-ID: On Wed, 16 Jul 2003 20:13:20 -0600, Steven Taschuk wrote: >Quoth Tom Goulet: >> My question basically is: What is the opposite of the following? >> | "%08X" % -1 > >Here's one way, very like what you already have: > > def hex2signed(s): > return struct.unpack('!i', binascii.unhexlify(s))[0] > >(This will not be the inverse of '%08x' % n in Python 2.4, when >'%x' % -1 will produce '-1', but I think it does what you want.) > Not that this helps 1.5.2-2.4 compatibility, but I was hoping the signed analogue of 0[xX][0-9A-Fa-f]+ (i.e., [01][xX][0-9A-Fa-f]+ with leading 1 for negatives) would be available for 2.4. IMO '-'+hex(abs(x)) really stinks as a hex representation of a negative number x ;-) >>> -2**31 -2147483648L Oops, is that a wart/buglet BTW? >>> int(-2**31) -2147483648 >>> hex(int(-2**31)) '0x80000000' with the new format,'1x80000000' would be the way to write int(-2**31) in hex and '0x80000000' would be +2**31 (which would be internally promoted to long on 32-bit-integer machines). Other examples -1 => 1xF # maybe extended (like 0x1 -> 0x0001), i.e., 1xFFFF has same integral value. -2 => 1xE -8 => 1x8 -9 => 1x7 -15 => 1x1 -16 => 1x0 # or 1xF0 or 1xFF...F0 -17 => 1xEF Regards, Bengt Richter From deets_noospaam at web.de Sun Jul 27 16:35:52 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2003 22:35:52 +0200 Subject: multithreading-problem References: <3f243632$1@nntp0.pdx.net> Message-ID: > The problem is that your lambda expression looks up "i" at function > evaluation time (when target is called), not when you assign the > target function for the thread. Ah, ok. That makes sense. Where do I find this curry-function, only in the book? It appears not to be a standard function. Regards, Diez From bokr at oz.net Sat Jul 5 18:26:47 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Jul 2003 22:26:47 GMT Subject: Calculating Year, Month and Day of Life References: Message-ID: On Sat, 05 Jul 2003 15:51:58 -0400, hokiegal99 wrote: >hokiegal99 wrote: > >> hokiegal99 wrote: >> [...] > >Once again, I'm making progress on my own. Here's where I stand now: > >---------------------- >from time import * >local = localtime() > >y = input("Enter the year of birth: ") >m = input("Enter the month of birth: ") >d = input("Enter the day of birth: ") > >age = y,m,d >print "You are", local[0] - age[0], "years", local[1] - age[1], "months" >----------------------- > Looks like you're enjoying yourself, so I won't interfere too much ;-) You might want to look at the calendar module that comes with python if you want to get age as exact total number of days or day of week on birth date, etc.: http://www.python.org/doc/current/lib/module-calendar.html Also, you might want to consider providing for re-try in a function, and using raw_input instead of input(), e.g., def getymd(prompt): while 1: try: return int(raw_input(prompt)) except ValueError, e: print ' Error:', e y = getinp("Enter the year of birth: ") m = getinp("Enter the month of birth: ") d = getinp("Enter the day of birth: ") Of course, you could validate y,m,d integer values and retry the date entry as a whole too. Regards, Bengt Richter From mis6 at pitt.edu Tue Jul 29 12:44:19 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 09:44:19 -0700 Subject: while (assignment): References: Message-ID: <2259b0e2.0307290844.6cbcad85@posting.google.com> Sybren Stuvel wrote in message news:... > Hi there, > > Is it possible to use an assignment in a while-loop? I'd like to do > something like "loop while there is still something to be read, and if > there is, put it in this variable". I've been a C programmer since I > was 14, so a construct like: > > while info = mydbcursor.fetchone(): > print "Information: "+str(info) > > comes to mind. Unfortunately, this doesn't work. Is there a similar > construct in python? > > Sybren First answer: DON'T DO THAT!! Second answer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234 ;) Michele From newsgroups at jhrothjr.com Sun Jul 13 14:38:29 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 13 Jul 2003 14:38:29 -0400 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in message news:bert0r$o6$01$1 at news.t-online.com... > John Roth wrote: > > Good point. That does make it somewhat harder; the routine > > would have to precompute both versions, and store them with > > both standard strings and unicode strings as keys. > > That doesn't work. You cannot have separate dictionary entries > for unicode and byte string keys if the keys compare and hash > equal, which is the case for all-ASCII keys (which environment > variable names typically are). Ah, so. John Roth > > Regards, > Martin > From intentionally at blank.co.uk Sun Jul 13 09:24:03 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 14:24:03 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: On Sun, 13 Jul 2003 00:55:22 -0700, Erik Max Francis wrote: >Tom Plunket wrote: > >> IMHO the variable binding discussion doesn't answer the question, >> it just provokes more questions. :) > >But the answer to those questions is usually something ending with, >"Look, Python just doesn't handle variables the same way C++ does." :-) And my traditional answer to that is... "yes, and the way that Python handles variables is definitely a wart." One of the few things I hate about Python is that mutable objects are implicitly shared using a reference system whereas immutable objects are not. It is unnecessarily confusing and error prone. A system where all objects are copied unless a reference type is explicitly applied (and with an assignment operators recognising references on the LHS by default and assigns to the object rather than the reference, though with an extra one which overwrites the reference) seems much more logical to me. It even seems 'Pythonic' to me. But it is much closer to C++ references than current Python system. From camelo at esss.com.br Tue Jul 8 14:48:30 2003 From: camelo at esss.com.br (Marcelo A. Camelo) Date: Tue, 8 Jul 2003 15:48:30 -0300 Subject: Embedding as scripting engine Message-ID: <009f01c34581$86a0aac0$0d00000a@esss.com.br> If you're using c++, take a look at boost::python, a fantastic tool that can save you a lot of work when it comes to write the bindings. I would seriously consider extending instead of embedding. I've done both and extending is, IMO, the way to go. http://twistedmatrix.com/users/glyph/rant/extendit.html has some good points on the subject. I second to all arguments presented there. --camelo -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of ?lfur Kristj?nsson Sent: ter?a-feira, 8 de julho de 2003 07:51 To: python-list at python.org Subject: Embedding as scripting engine Python... a great language, no doubt. And the abillity to be able to extend it with C/C++ code, fantastic. But has anybody been able to successfully embed Python in their application to use it as a scripting language of sorts? I am in the process of writing a game and from the documentation and word of mouth gathered that Python would be just the thing for the scripting part. And sure enough it is easy enough to run Python code from C/C++. However, in order to be make it do something actually useful for my game it would be handy to be able to pass in anything besides the basic data types (strings, numerics) such as either an instance of or a pointer to a gameobject. What I want to be able to do is something like this: GameObject go; Py_Initialize() ... PyObject* po = GameObject2PyObject(go); ... result = PyObject_CallObject(func, "O", po ); ... go = PyObject2GameObject(result); Theres alot of documentation and discussion out there that suggests that this should be possible but noone seems to tell you how it's actually done. Am I just missing something blatantly obvious? Thanks //ulk -- http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Wed Jul 2 10:09:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 09:09:11 -0500 Subject: Meerkat script suddenly fails: output format changed? In-Reply-To: References: Message-ID: <16130.59271.792007.980887@montanaro.dyndns.org> Steve> server.meerkat.getitems(). Printing out the list of items Steve> confirms this, with what I can only describe as a Steve> somewhat-unexpected output: Steve> {'description': "Senator Kennedy's new inaccessible web site. On writing for Steve> the web. The Python path module. The art", 'title': 'In brief: Superbowl Steve> Sunday'} ... Looks like a Meerkat bug. Have you contacted O'Reilly about it? Not only is the output of a "python" search odd, the links for such odd searches just point back to the Meerkat front page. Skip From h.b.furuseth at usit.uio.no Fri Jul 4 14:02:59 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 04 Jul 2003 20:02:59 +0200 Subject: How to get CGI request-URL Message-ID: How can I get the URL the user typed (except the part after '?') with the cgi module? I expect the 'Host:' HTTP header + os.environ['SCRIPT_NAME'] would do it, but I don't see how to find the Host header. The www server has several names, so I can't just use the default host name. -- Hallvard From ulope at gmx.de Wed Jul 2 12:58:58 2003 From: ulope at gmx.de (Ulrich Petri) Date: Wed, 2 Jul 2003 18:58:58 +0200 Subject: undo tab References: <3F02E7D5.4060401@gmx.net> <3F02ECF0.105@gmx.net> Message-ID: "Tom" schrieb im Newsbeitrag news:3F02ECF0.105 at gmx.net... > Hi, > > it doesn't work with any editor that I tried. The one I use on a regular > basis is the standard python IDLE. Sometimes I also use the editor of > pythonwin and Boa-Constructor. > > Maybe you can just give me a general hint how you do it and which editor > you use. That would probably also help. > > Thank you, Tom. > I use UltraEdit-32. There it works with Shift-Tab. Ciao Ulrich From woooee at yahoo.com Thu Jul 3 15:41:14 2003 From: woooee at yahoo.com (Curly Joe) Date: Thu, 3 Jul 2003 12:41:14 -0700 (PDT) Subject: Good code patterns in Python Message-ID: <20030703194114.9833.qmail@web20511.mail.yahoo.com> Andrew Bennetts wrote: > > if cond: > x = special_val > else: > x = some_val > > can be "read" more-or-less directly into English: "if the condition is > true, then 'x' is set to 'special_val'; otherwise, 'x' is set to > 'some_val'". > Saying "'x' is set to 'some_val'. Now, if some condition is true, 'x' is > set to 'special_val'" is counter-intuitive to my way of thinking. > > That said, I can readily recognise both idioms (despite having a slight > preference for one form), so it's really a non-issue... It is mostly a non-issue, and excuse me if I am stating the obvious, but we have to be careful about setting the default to special_val or some_val. The code depends on what we want to do when the inevitable new type of data is silently introduced. In very general terms, we want to include what we want - as the above code does, not exclude what we don't want - as in the original post. That way, new data is not included, whereas it would be if we had excluded. To belabor the point, suppose we have the following code: .if MALE : . male += 1 .else : . female += 1 instead of .if not FEMALE : . male += 1 .else : . female += 1 These both work the same way until someone adds a check box for "I prefer to not state my gender". The file gets updated with this new type, and we then run our summary program. In the first code example, it is counted as female, and in the second, it is counted as male. This is the main reason, as far as I know, that we use the "if exception: else: general" format. And if we have had our toes stepped on a few times, we quit lying in our programs and state .if MALE : . male += 1 .else : . not_male += 1 since that is all we really know because we didn't explicitly test for female. Again pardon me if I am taking up a lot of space with an issue that most don't care about. __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From max at alcyone.com Fri Jul 18 01:06:54 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 22:06:54 -0700 Subject: null pointer exceptions References: Message-ID: <3F17806E.3B9B4F75@alcyone.com> Tennessee James Leeuwenburg wrote: > I have a class which includes adding an ImageIcon. If the required > graphic > resource isn't present, there is a NullPointerException. Java doesn't > care > - the straight Java program handles it internally and gets on with > life. > But when I include it from Python, it explodes. A java.lang.NullPointerException is just an exception like anything else. Can't you just catch it? max at oxygen:~/tmp% cat NullCaster.java import java.lang.*; public class NullCaster { public static void main(String[] args) { Object nullObject = null; String nullString = (String) nullObject; nullString.length(); } } max at oxygen:~/tmp% javac NullCaster.java max at oxygen:~/tmp% jython Jython 2.1 on java1.4.1 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import java.lang >>> import NullCaster >>> try: ... NullCaster.main([]) ... except java.lang.NullPointerException, e: ... print 'oops:', e ... oops: java.lang.NullPointerException -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Wretches hang that jurymen may dine. \__/ Alexander Pope From lehrig at t-online.de Fri Jul 18 01:45:59 2003 From: lehrig at t-online.de (lehrig) Date: Fri, 18 Jul 2003 07:45:59 +0200 Subject: scanf string in python References: Message-ID: lehrig wrote: > I have a string which is returned by a C extension. > > mystring = '(1,2,3)' > > HOW can I read the numbers in python ? Now I have done it like this: tmp = mystring[1:-1] tmplist = string.split(tmp,',') x = int(tmplist[0]) y = int(tmplist[1]) z = int(tmplist[2]) But there should be a more convenient solution. From tl_news at nexgo.de Wed Jul 30 02:21:09 2003 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 30 Jul 2003 08:21:09 +0200 Subject: Thank you developers for 2.3 References: Message-ID: On Wed, 30 Jul 2003 05:35:02 GMT, David Lees wrote: >Flawless install and it ran my very simple minded (try not to laugh) >nested loop integer arithmetic benchmark twice as fast as 2.2.3 >version 2.3 5.04 sec >version 2.2.3 9.77 sec Hi! By the way: What was/is the speed with 2.1.x on the same system? Cheers, Tino From vivek at cs.unipune.ernet.in Mon Jul 28 08:25:42 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Mon, 28 Jul 2003 17:55:42 +0530 Subject: How to get success/failure in case of thread Message-ID: <20030728175542.A23857@cs.unipune.ernet.in> Hi all, I am trying to learn using threads in python. But the main problem I am facing is how to check whether the function called using a thread succeeded or failed. like when I call: import thread thread.start_new_thread(my_func,(args,)) here my_func will return true/1 on success and false/0 on failure. How can I check whether the function failed/succeeded ??? TIA and Kind Regards Vivek Kumar From bokr at oz.net Fri Jul 25 20:09:28 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 00:09:28 GMT Subject: looping through a file References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> Message-ID: On Fri, 25 Jul 2003 22:29:15 +0200, Adam wrote: >Psybar Phreak wrote: (Sorry, your original post seems out of sight, so I'm answering this one) >> hi all - ive just started with python (after having done java and c) and am >> having a little bit of trouble with the script. Im using as a login script. >> >> There's a users.dat file in the format >> user1 >> user1password >> user2 >> user2password >> ... etc >> >> at the moment - the code i work, only checks the first and second lines (ie. >> details of user1). but it appears that python doesn't have a do... while... >> until loop. >> >> >> can anyone help? >> >> thanks!! >> >> Ive attached the appropriate part of the code i have working >> >> ------------------------------- >> >> #!/usr/local/bin/python >> >> import cgi, string >> >> form = cgi.FieldStorage() >> >> if form.has_key('usernameField') and form.has_key('passwordField'): >> users_username = string.strip(form['usernameField'].value) >> users_password = string.strip(form['passwordField'].value) >> >> InFile = open('users.dat', 'r') inFile = file('users.dat') # file replaces open in newer versions, and 'r' is default ^--(unconvential to capitalize unless name of "constant" (all caps) or class (first or mixed caps)) >> UIAM, the rest can be done with just this (untested!): while 1: file_username = string.strip(InFile.readline()) # assumes first line is username file_password = string.strip(InFile.readline()) # assumes every username followed by password authorized = file_username == users_username and file_password == users_password if authorized or not file_username: break (I assume you're using an old version, or you could use s.strip() instead of string.strip(s)) >> file_username = string.strip(InFile.readline()) >> file_password = string.strip(InFile.readline()) >> >> >> >> >> authorised = 0 >> >> while file_username and file_password: >> if file_username == users_username: >> if file_password == users_password: # correct >> authorised = 1 >> break >> else: # login matched but not >> password >> file_username = InFile.readline() >> file_password = InFile.readline() >> else: # neither match >> file_username = InFile.readline() >> file_password = InFile.readline() >> >> >use the readline method. take advantage of the fact that readline >returns an empty string when it reaches EOF, and do: >while(line): > line=readline > Regards, Bengt Richter From shannon at news.widomaker.com Fri Jul 4 23:08:33 2003 From: shannon at news.widomaker.com (Charles Shannon Hendrix) Date: Fri, 4 Jul 2003 23:08:33 -0400 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: In article , Cameron Laird wrote: > Maybe youngsters don't realize this. > > One monotonous but unremitting argument that Python inspires > is about the wisdom of its white-space-significance (WSS). > Modern programmers might not realize how strongly old-timers > associate WSS with early FORTRAN and COBOL (as we capitalized > them then), and how unpleasant some of those memories are. > *That*, I assume, is why WSS discussions become as heated as > they do. The problem with Python is that its use of indentation is not the same as COBOL or FORTRAN. Apples and Oranges. Those languages just had an arbitrary format, but it was specific and easy to catch. Python uses it for actually determining the logic in your program, which IMHO is dangerous. if Is part of the if statement, or did someone with different tab settings from the author make a mistake and align it accidentally? One really funny problem was when I guy reformatted his Python code, around 15K lines of it, and basically unindented *ALL* of the code to column 1. It was the only recoverable copy of the code too. He had to read the entire program line by line to recreate the logic. The thing that bothers me though is I have found indent-related bugs in Python code that no one knew about. The code still ran, but some people had obviously made some bad assumptions about the logic and indented it wrong, changing the nature of the program. I know a lot of people disagree, but I really think whitespace should not determine flow-control in a program. -- Ah... you gotta love it when your ISP switches to a SPAMMING newsfeed. Sigh... -----= 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 vm_usenet at yahoo.com Thu Jul 3 17:41:26 2003 From: vm_usenet at yahoo.com (vm_usenet) Date: 3 Jul 2003 14:41:26 -0700 Subject: A possible bug in python threading/time module? References: Message-ID: > If you run "enough" threads, chances are high you'll eventually run into a > platform thread bug on any platform -- but into different platform bugs on > different platforms. You didn't say which OS or platform thread library you > were using, and those are probably the only things that matter. > > Here's a simplified and generalized minor rewrite of the above, with a > comment about what happens under Win2K and 2.3b2. I've got no interest in > chasing it down, since it's hung in the bowels of a Windows DLL and there's > no evidence of a Python bug: > > """ > import time > import threading > > # One thread hung at the end on Win2K at N == 2011. > # No problem if N < 2011. > N = 2011 > sem = threading.Semaphore(N) > > class MyThread(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > sem.acquire() > > def run(self): > time.sleep(5) > sem.release() > > for i in range(2*N): > MyThread().start() > """ I tried it on Windows 2000 and XP. I guess it could be a platform-specific bug, but it still disturbs me because I later programmed the same thing in C - and it worked perfectly. It's a long-shot, but I guess somewhere the bug is caused due to a misuse by the python runtime (or perhaps an inefficient use) of the platform-specific threading facilities... The From jubafre at brturbo.com Thu Jul 17 14:48:47 2003 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Thu, 17 Jul 2003 15:48:47 -0300 (BRT) Subject: xml.sax in py2exe Message-ID: <10185335.1058467727506.JavaMail.nobody@webmail1.brturbo.com> I want a binnary file to my aplicattion, but py2exe don't match the xmll.sax module. the py2exe shows this errors: warning: py2exe: *************************************************************** ********** warning: py2exe: * The following modules were not found: warning: py2exe: * xml.sax warning: py2exe: * win32con warning: py2exe: * pywintypes warning: py2exe: * os.path warning: py2exe: * hexdump warning: py2exe: * win32com.client.gencache warning: py2exe: * win32api warning: py2exe: *************************************************************** ********** but in python if i import the module, its works very well! Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import xml.sax >>> xml.sax Message-ID: Is there anything consistent about either the version of Python these people are using, or the version of KDE? The reason I ask is that there are a lot of different versions out there, and while the Python maintainers are very good, some of them have subtle bugs. Likewise for KDE, and for various distributions. I also second Bengt's comment about tabs. Outlook Express, for one, eliminates them so your code example is simply unreadable. The python standard coding style is to use 4 spaces for each level of indentation. Python aware editors supply them automatically when you hit the tab key. John Roth "dmbkiwi" wrote in message news:pan.2003.07.11.19.34.16.330762 at yahoo.com... > I am new to this group, and relatively new to python programming, however, > have encountered a problem I just cannot solve through reading the > documentation, and searching this group on google. > > I have written a theme in python for the superkaramba theme engine on kde > (see http://netdragon.sourceforge.net - if you are a kde/linux user, it is > a great visual applet engine). I have uploaded it to www.kdelook.org for > others to download and use, however, some users are having an issue, which > to me seems to be very strange. > > Basically the problem is that their version of python is ignoring an > if/else statement, and I can't understand why. Over 3000 people have > downloaded the theme, and only 3 people have identified this problem. The > relevant portion of code is: > > def meterClicked(widget, meter, button): > #print "meterclick" > global dayshow, daypicrem, ddon, ddcon, buttonpressed > if (meter == mainpic) and (button == 1): > if ddcon == 0: > if ddon == 1: > deleteDayDetail(widget, dayshow) > karamba.redrawWidget(widget) > createCurrentDetail(widget) > karamba.redrawWidget(widget) > else: > deleteCurrentDetail(widget) > else: > for i in range(0,5): > if (meter == daypicrem[i]) and (button == 1) and (dayshow != i): > #print "buttonpressed: day" + str(i) > if ddon == 1: > deleteDayDetail(widget, dayshow) > karamba.redrawWidget(widget) > elif ddcon == 1: > deleteCurrentDetail(widget) > karamba.redrawWidget(widget) > createDayDetail(widget, i) > karamba.redrawWidget(widget) > dayshow = i > #print dayshow > break > if (meter == daypicrem[i]) and (button == 1) and (dayshow == i): > if ddon == 1: > deleteDayDetail(widget, dayshow) > karamba.redrawWidget(widget) > elif ddcon == 1: > deleteCurrentDetail(widget) > karamba.redrawWidget(widget) > dayshow = i > #print dayshow > break > buttonpressed = 1 > > > What these users are experiencing is that this portion of code is being > processed, and evaluating all if statements as true, however, as you can > see, they cannot all be true each time this function is called. Their > versions of python also ignore the else construct. > > Can anyone shed any light on what might be going on with these users? > > Matt From bignose-hates-spam at and-benfinney-does-too.id.au Sun Jul 27 17:17:10 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Jul 2003 07:07:10 +0950 Subject: changing the List's behaviour? References: Message-ID: On Sun, 27 Jul 2003 22:41:43 +0200, meinrad recheis wrote: > i am very annoyed by the List's index out of bouds exception > it forces me to complicate my code by adding length checking No, it forces you to ensure your code doesn't try to access a non-existent list element. Or, it forces you to catch the exception and deal with it. > i want to change the List so that it returns None if the index for > accesssing list elements is out of bound. This would prevent you from distinguishing between "the index was out of range" and "the element at that index is the None object". > i am not very experienced in python, so i ask you for suggestions. Take a good look at the code that is accessing non-existent index values. Why is it doing so? Do you really want a list (ordered collection, with a fixed set of keys) or are there cases where you want a dict (unordered collection, arbitrary set of keys)? -- \ "I know you believe you understood what you think I said, but I | `\ am not sure you realize that what you heard is not what I | _o__) meant." -- Robert J. McCloskey | Ben Finney From jjl at pobox.com Thu Jul 31 14:17:49 2003 From: jjl at pobox.com (John J. Lee) Date: 31 Jul 2003 19:17:49 +0100 Subject: looking for design pattern name References: Message-ID: <87adaud0he.fsf@pobox.com> "Andrew Dalke" writes: > Raymond Hettinger: > > What happens in Bond() if O1 and O2 have different parents? > > Raises an exception - TypeError seems best. Here's the code [...] Yuck. Doesn't the standard library reserve TypeError for occasions where the, um, type of an argument is not appropriate? 'Type' does generally means the interface rather than type(object), but that's quite different to what you're checking. Checking whether atoms have different parents surely isn't a type check. Why not ValueError or your own exception (possibly derived from ValueError)? [.........] > Err, I tangented, didn't I. [...] "Verbing weirds language", to quote Calvin. :-) John From grante at visi.com Thu Jul 10 15:10:36 2003 From: grante at visi.com (Grant Edwards) Date: 10 Jul 2003 19:10:36 GMT Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <3f0dba2c$0$179$a1866201@newsreader.visi.com> In article <246a4e07.0307100613.fc2fc50 at posting.google.com>, Frank Millman wrote: > However, any support of the software from a business or accounting > perspective will be available to registered users only. For a monthly > support fee (I am thinking of a range of $50-100 per month - let me > know if it is too high or too low) What do competing products charge for support? > Here are a couple of pitfalls that I can see, and my possible > solutions to them. Firstly, a user will be able to terminate his > support contract at any time, and the software will continue to > function. Therefore some may be tempted to stop paying until they have > a problem, then pay for a month, get an answer, and stop again. My > thinking is that 3 months must be paid up front to activate a support > contract. I'd suggest doing support a year at a time. Most of the commercial SW for which I've bought support did it that way. If I were a customer, I sure wouldn't want to have to go through the hassle of getting you a check cut every month. One place I work calcualted that the cost of processing a purchase order or cutting a reimbursement check was $50-$100. > These are my thoughts so far. Any comments - suggestions, > warnings, personal experiences - will be much appreciated. I don't know much about accounting systems, but if they're anything like manufacturing/inventory systems, almost every installation is heavily customized. Charging for doing the customization is probably a good source of revenue. -- Grant Edwards grante Yow! ALFRED JARRY! Say at something about th' DEATH visi.com of DISCO!! From giles_brown at hotmail.com Fri Jul 4 04:41:36 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 4 Jul 2003 01:41:36 -0700 Subject: Question about "exec in globals, locals" Message-ID: <57de9986.0307040041.553ff329@posting.google.com> I do not understand why the following code produces NameError: name 'FirstClass' is not defined when both a global and local dict are passed into exec, but not when only a global dict is passed in. I seek enlightenment! Thanks, Giles Brown source = """ class FirstClass: pass class SecondClass: References = [FirstClass] """ # Case - 1 myglobals = {'__builtins__' : None, '__name__': None} exec source in myglobals print "Global names are:", myglobals.keys() # Case - 2 myglobals = {'__builtins__' : None, '__name__': None} mylocals = {} exec source in myglobals, mylocals print "Global names are:", myglobals.keys() print "Local names are:", mylocals.keys() From martin at v.loewis.de Wed Jul 16 00:14:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Jul 2003 06:14:25 +0200 Subject: Solaris 9, problem building Python 2.1.1 References: <20030716003454.GA2860@dave@alana.ucc.usyd.edu.au> Message-ID: Heiko Wundram writes: > Seems like your lib(open)ssl is missing, or invalid. More likely, it is located in /usr/local/lib. Set LD_LIBRARY_PATH. Regards, Martin From gumuz at looze.net Thu Jul 17 04:16:09 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 17 Jul 2003 10:16:09 +0200 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: <3f1661b9$0$13799$4d4ebb8e@news.nl.uu.net> Maybe it is an idea to include existing examples like the ones from the cookbook in the pyhton documentation. This will enhance the documentation quite a bit I think. > If my english was better I would love to help improve the python > documentation, most modules in the standard libraries lack good > examples how to *use* them with just a simple description. And a > short motivation for the design of a module if possible like "just > copied the C API" or "Because of efficiency ..." or "We use a class > framework here because ...". A gigantic task. The PSL book by effbot > is great but it's a book. And it needs a new version. From davidcfox at post.harvard.edu Wed Jul 23 17:35:36 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Wed, 23 Jul 2003 21:35:36 GMT Subject: Design tool In-Reply-To: <3F1EFDA6.2060808@nospam.com> References: <3f1e985d$0$236@hades.is.co.za> <3F1EFDA6.2060808@nospam.com> Message-ID: max wrote: > >> All work on Windows (ArgoUML is Java application). >> > I meant Argo does. dia does not, AFAIK > It depends what you mean by works. There is a Windows version, and it runs, but printing was extremely buggy the last time I tried it. Of course, I think that was v. 0.7, so maybe it's been improved since then. David From harry.g.george at boeing.com Mon Jul 14 10:03:17 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 14 Jul 2003 14:03:17 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: "richardc" writes: > Ive just started playing with Python and have a couple of questions. > > Im looking for an agument parsing library (from the command line), Ive come > across optik and argtools. What other ones are there are any of them any > good, is there a 'standard' lib for doing this. > > Also how should I '#define' magic numbers in Python. I spent ages looking > around for a 'define' statement or anything that will allow me to create a > constant value 'object'. Am I missing something very obvious ? > > Also, what 'IDE/editor' do people recomend for MAC OSX, so far Ive found > 'Hydra' to be the best as it works on plain files and has Python syntax > highlighting... what else is there and are any of them any good. > > Has nobody written an editor/IDE in Python with wxWindows so that it runs on > all platforms ? > > Many thanks > > Rich > > 1. args: I use getopt, which does the job. The idiom is: if __name__ == '__main__': opts,pargs=getopt.getopt(sys.argv[1:],'hvd', ['help','version','debug', 'bb=']) for opt in opts: if opt[0]=='-h' or opt[0]=='--help': print modname+": version="+__version__ usage() sys.exit(0) elif opt[0]=='-v' or opt[0]=='--version': print modname+": version="+__version__ sys.exit(0) elif opt[0]=='-d' or opt[0]=='--debug': debug_p=1 elif opt[0]=='--bb': opt_b=opt[1] 2. #define: Use ALLCAPS. I put these all in a globals section at the top of the module in the order: docstring, imports, globals, utilities, common functions, classes, "main", and "if __name__=='__main__':" Also, if you have global variables, we use leading "g_" (e.g,"g_myglobaldata"), so they are easy to find if encountered in the body of the module. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From printers at sendme.cz Mon Jul 7 15:53:12 2003 From: printers at sendme.cz (A) Date: Mon, 07 Jul 2003 21:53:12 +0200 Subject: Is there any solution in PYTHON? Message-ID: <3F09EBC8.357.AB1425E@localhost> Hi, I have a program that downloads some web pages. Sometimes there is a poor internet connection and my script freezes( hangs) and does not download ALL pages. Is there any solution how to test if the program works and if not re-start it from the point where it stopped? Or simply how to download ALL pages eventhough there is a timeout connection( can be of any value)? Thanks for help Ladislav From cidolfas at rpgclassics.com Fri Jul 25 10:19:16 2003 From: cidolfas at rpgclassics.com (Daniel Orner) Date: 25 Jul 2003 07:19:16 -0700 Subject: CGI "download" prompt? References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> Message-ID: <77dd287a.0307250619.7c2ec441@posting.google.com> > Try setting the Content-Type: header to something other than text/html, > such as: application/octet-stream > > I think that any browser that respects the mime type will prompt to save > a file with this mime-type. > > YMMV, especially with IE, because that thing tends to try to act > 'smart' and looks at the file extension to determine > what to do with the file. It will likely just display it.... > > --Irmen Hmm... this doesn't seem to work. The problem is, I think, that once I include a "Location:" header to redirect the browser, the Content-type doesn't apply to the place I'm redirecting to. However, I don't know of any way to include a header in a plain file that isn't a CGI file (and that's what I want, because I want to keep the filename). >_< Does anyone else have any ideas? Thanks, --Daniel From max at alcyone.com Wed Jul 2 18:14:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 15:14:48 -0700 Subject: arbitrary long integer aritmetics References: Message-ID: <3F035958.FADD276E@alcyone.com> Russell Reagan wrote: > "Fredrik Lundh" wrote > > > >>> 2147483647 * 2147483647 * 2147483647 > > 4611686014132420609L > > > > (note the trailing L). > > Oddly, I get a different answer than you. What's the problem? Probably because he pasted in an incomplete transcript. The calculation he shows is multiplying it twice, not three times: >>> x = 2147483647L >>> x**2 4611686014132420609L >>> x**3 9903520300447984150353281023L -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Divorces are made in Heaven. \__/ Oscar Wilde From nbdy9 at hotmail.com.nospam Wed Jul 30 14:37:45 2003 From: nbdy9 at hotmail.com.nospam (Mark) Date: Wed, 30 Jul 2003 14:37:45 -0400 Subject: How to get Windows physical RAM using python? In-Reply-To: References: Message-ID: OK, How to check the amount of Windows physical RAM using python? Mark wrote: > Thanks. > From edreamleo at charter.net Mon Jul 14 12:38:29 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 14 Jul 2003 11:38:29 -0500 Subject: anygui questions Message-ID: Does anyone have any experience with anygui with a non-trivial app? It would be nice to host my app using a native toolkit, and I am worried that native tree widgets won't be as flexible as the Tk.Canvas widget that my app presently uses. It hardly seems like progress to use the anygui canvas widget. Can anyone suggest a way around this? Other concerns: How can anygui make sense out of different event models? Same question for widget options. Maybe the best way of summarizing my concerns is this question: how close is anygui to the least common denominator? Anything else I should know about anygui? Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From abigail at abigail.nl Fri Jul 11 07:08:44 2003 From: abigail at abigail.nl (Abigail) Date: 11 Jul 2003 11:08:44 GMT Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: Walter Bushell (proto at panix.com) wrote on MMMDC September MCMXCIII in : ++ Charles Richmond wrote: ++ ++ > int *p, x, y; ++ > ++ > then: ++ > ++ > y = x/*p; ++ > ++ > is quite different from: ++ > ++ > y = x / *p; ++ > ++ > The first way, "/*" will begin a comment...the second way, ++ > you get the integer "x" divided by the integer pointed to by "p". ++ ++ Ouch!! That is one reason code coloring is *important*. Nope. That's a reason why code colouring is evil. If you write code, and it isn't clear what you mean without the use of code colouring, you did something wrong. Your code shouldn't rely on a specific code colouring scheme to be understandable. All in my opinion of course. Abigail From aahz at pythoncraft.com Sat Jul 19 19:46:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2003 19:46:15 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: In article , Mike C. Fletcher wrote: > >Nope, I'm trying to make meta-classes which have rich properties. The >particular project is a plug-in system, where the classes (the >metaclass-instances) want to have all sorts of rich metadata associated >with them in a way which meshes with the rest of the system (i.e. using >a descriptor-based introspection mechanism). >... Keeping in mind that I'm really not following this discussion all that closely (because metaclasses give me headaches), are you trying to make a *metaclass* that has properties or a *metaclass instance* (i.e. a class) that has properties? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From sross at connectmail.carleton.ca Thu Jul 3 12:08:27 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 3 Jul 2003 12:08:27 -0400 Subject: OT: Genetic Algorithm Recipe Bug Fix Message-ID: Hi. For anyone who has chosen to use my Genetic Algorithm recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/199121), I'd like to make you aware of a fairly serious oversite on my part - I left out the division part of the standard deviation routine! That's been fixed on the recipe page, but not on my personal web site - which will be done when I post the new version I'm building for a study I'll be working on this fall. I'd like to apologize for any difficulties and/or confusion this error may have caused you. Thanks for your time. Sean From tomas at fancy.org Sat Jul 12 16:49:38 2003 From: tomas at fancy.org (Tom Plunket) Date: Sat, 12 Jul 2003 13:49:38 -0700 Subject: Assigning to global variables from within a function References: Message-ID: Psymaster wrote: > I want to do this: > > int= 0 > > def change_int(): > int += 1 > > change_int() You shouldn't do that, 'int' is a built-in name. Additionally, you need to tell the function that the variable is a global one. my_int = 0 def change_int(): global my_int my_int += 1 change_int() You'll find that it works fine. -tom! From dave at pythonapocrypha.com Tue Jul 15 10:07:55 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 15 Jul 2003 08:07:55 -0600 Subject: anything like C++ references? In-Reply-To: References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <200307150807.55839.dave@pythonapocrypha.com> On Tuesday 15 July 2003 02:18 am, Stephen Horne wrote: > >Why don't you respect the possibility of a language that is *designed* to > > deal with entities and relationships in ways you are not used to? ;-) > > Basically, because I've seen too many threads started by confused > people who've made a mistake because of this, and because I've made > the mistake an annoying number of times myself. But the problem is that you're inferring from those threads that this is a widespread problem. It is not. Compared to the total number of people using Python, this issue isn't brought up that often (especially compared to, say, "can I make an EXE of a Python app?"). Also, in *every* case it is someone "thinking in C" rather than Python. Once they reset their brains to the way Python does things, then the problem goes away, if they had a problem with it in the first place. This is not the same thing as people "just dealing with it" or forcing themselves to think in and odd way but a slightly *different* way. At most I'd concede that this is a documentation problem, but nothing more - for many, many people the way Python does it works terrifically well. I just don't see how having to adjust your thinking a little when using a different language implies the new language isn't doing the right thing, especially when the new way works so well in practice. > It's not just about theory - it's about peoples intuitions about how > things should work. Obviously it can't match everyone's intuitions. Besides, intuitions are heavily influenced by past experience, so there do exist times when it's best to go against the grain in that respect. The "problem" here is that newcomers to Python often make an incorrect assumption. The moment they let go of that assumption, everything is fine. Guido has a pretty good track record as a language designer, so when you see something in Python that is different than previous languages you've used it might be wart, but it might also be a place where there's good reason for being different. This is an example of the latter - in real programs this approach works well and is quite powerful and elegant. As a result I'm more comfortable with languages that work this way and less so with those that don't. > A goal of Python is to be a 'very high level language'. Another is to > 'do the right thing'. If so, then in the opinion of most users it *is* succeeding at both goals. The theoretical or mathematical parallels may be interesting, but they're irrelevent because (for a large number of users, probably the overwhelming majority) the way references and binding are handled in Python works very, very well in practice, plain and simple. > > If you > >read "variable" where you should be reading "alias" > > If I should be reading "alias", then how come the Python manuals say > "variable"? Perhaps because most people don't have a hangup about it? And perhaps because the few who do get over it rather quickly? Seriously - it's such a tiny thing. -Dave From vm_usenet at yahoo.com Sun Jul 6 14:04:15 2003 From: vm_usenet at yahoo.com (vm_usenet) Date: 6 Jul 2003 11:04:15 -0700 Subject: A possible bug in python threading/time module? References: <3F071424.520DC852@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3F071424.520DC852 at engcorp.com>... > vm_usenet wrote: > > > > Right after I read Tim's recent post, I went to the python CVS and > > noted that Tim refered to me as an 'anonymous coward'. Well Tim, I > > just wanted to say that I appreciate you being part of the community, > > too. > > See http://www.computerhope.com/jargon/a/ac.htm, definition #2. This > is a fairly well-known term for someone who, like you, for some > strange reason does not want to use their name in discourse with > others (such as those who are helping them, hint, hint) online. > > > I hope to see more mature people working on the Python project than > > Tim. > > If you mean you want a greater number of mature people than just > Tim alone working on the Python project, then we can all agree and, > fortunately, that is the current situation. > > If you meant something else, I suggest you learn more about Python > history and about those who have really made Python what it is before > you make comments of that nature. > > -Peter Ok, Ok... I beg the forgiveness of everyone whom I insulted. I wasn't aware of the term 'Anonymous Coward' and so I interpreted it as an insult. Tim - I'm sorry and I won't be making that mistake again. And on that opportunity, I'd really like to admit that you indeed did your work perfectly. I love the Python language very much and I went through hell making my organization adopt it as its formal prototyping and scripting language. Keep up the good work, everyone! From curty at free.fr Wed Jul 30 11:07:44 2003 From: curty at free.fr (Curt) Date: 30 Jul 2003 15:07:44 GMT Subject: Python..Tkinter..PYTHONPATH.. References: Message-ID: On 29 Jul 2003 11:54:16 -0700, q wrote: > I have a Linux RH8.0 system. I installed Python2.2 from the 8.0 ISO > updates. I installed the Tcl 8.3.3 from the Tcl site... I also > installed the tcllib 1.0. > My goal is to get viewcvs to run. However, when I check to see where > the system thinks things are, the PYTHONPATH env var is blank. > echo $PYTHONPATH --> produces nothing.... It produces nothing on my system either, because I haven't set that environment variable. I haven't needed to. The installation-dependant default works fine. > So, can anyone tell me what it should say? Can anyone shed any light > as to how this var is populated, and why it might be blank....? Can > anyone suggest what file I need to alter/should modify to have this > properly set whenever a user logs into the system....? Well, my understanding as a complete and utter oldie but newbie is that it should point to where your python modules are located. It has the same syntax as the shell PATH variable. If your shell is bash, you can set it for all users in /etc/profile, well, at least you can in Slackware. export PYTHONPATH=/path/to/modules:/path/to/other/modules From bokr at oz.net Tue Jul 29 14:04:29 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 18:04:29 GMT Subject: pretty printing graphs References: Message-ID: On Tue, 29 Jul 2003 08:53:27 -0500, John Hunter wrote: >>>>>> "Bengt" == Bengt Richter writes: > > Bengt> How about (I added a name in the first node line for > Bengt> debugging, and boxing): (code follows output). Not tested > Bengt> much ;-) > >Thanks Bengt - that looks great. You really should be on the payroll. > Email me for particulars on how to send money ;-)) >I won't have time until tonight to wrap my head around your code, but >I think I'll add a to_dot method to the Node class which generates dot >output, so I can use your ascii output for day-to-day stuff, and then >go to dot for publication quality. If you have an interactive window with tty font with box characters, it could look pretty nice for "day-to-day", I think (though requiring a little more logic for choosing boxing and connection line characters). > >Thanks all for the suggestions, You're welcome. Be aware that I just copied your original post and vimmed at it until something emerged. It's pretty brute force, recomputing a lot, etc etc. And not very well factored. OTOH, it seems to work, within its limits ;-) It could use some sanity checks etc. though. BTW, also in this thread there is a version with connector lines called pptree.py, in case that is of interest. I think to make a real tool, I would design differently. Off hand IWT using a random access 2-dimensional mutable character array as a page "canvas" to paint on would eliminate some of the constraints on the layout that are inherent in the way I did it in pptree. (I.e., hierarchical box model where any box may be contain a centered smaller box connected to one row of boxes underneath it, and any of those may similarly either be a single box or contain a smaller top box with its row of children, etc., so each box is only a matter of one top single box and one row of child boxes, whatever the content of the child boxes. Then its just a matter of dealing with the different sizes.) Also more abstract element definitions and drawing primitives could allow for subclassing for different output media like ascii, tty/boxchars, tkinter, postscript, etc. I'm curious as to what your actual text blocks represent... Regards, Bengt Richter From postmaster at 127.0.0.1 Sat Jul 12 23:22:30 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Sun, 13 Jul 2003 15:22:30 +1200 Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: On Sat, 12 Jul 2003 21:07:48 +0000, Elaine Jackson paused, took a deep breath, then came out with: > Thank you. Elaine, Firstly, the McMillan Installer suggested to you is indeed very good, and in nearly all cases creates fully standalone packaged apps for windows. If ever it fails (rare cases), you can also try py2exe. Getting it to create independent runtime packages on Linux could be problematic, but this is less of an issue since any decent Linux system has Python installed or available on tap. Secondly, I can't see why some people accused you of being vague and flippant. Your original enquiry was clear enough to me - you want to take your python code and turn it into a form where it can be deployed on any target system without bothering or confusing users by making them install a python environment. A very clear and reasonable ask. Do please persist with python, and don't let any pedantry on this group get to you. The Python community on the whole is very friendly and supportive. Add to this the marvel of a pain-saving language that Python is, and you'll be feeling totally at home in a short time. You can also get very fast answers to your questions in the IRC channel #python on irc.freenode.net. Most people there are very welcoming of newer python converts. One caveat - please be warned that if you spend more than a little time with Python, you'll develop a discomfort and dislike of other languages to the point where you won't want to program in anything else. For instance, I switched from PHP to Python 6 months ago. I used to like PHP, but I can't stand it now. But maybe that's a *good* thing. Have fun in your travels. Cheers David > > Wayne Pierce wrote in message > news:2a897f11.0307121139.21470fbb at posting.google.com... > | "Elaine Jackson" wrote in message > news:... > | > Can Python be compiled? If so, how? (I have the 2.2 version of the > interpreter.) > | > TIA for any and all helps > | > | If you want to be able to distribute your Python apps without the end > | user needing a Python interpreter take a look at the following: > | > | http://www.mcmillan-inc.com/install1.html > | > | Wayne From bdesth.nospam at removeme.free.fr Sun Jul 27 18:23:26 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2003 00:23:26 +0200 Subject: Static typing In-Reply-To: <20030727.141111.1139901474.9957@demon.mindhog.net> References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> <20030727.141111.1139901474.9957@demon.mindhog.net> Message-ID: <3f244eff$0$21092$626a54ce@news.free.fr> Michael Muller wrote: > In article <3f23ae06$0$21093$626a54ce at news.free.fr>, "Bruno Desthuilliers" > wrote: > >>Michael Muller wrote: >>Interface documentation may be obtained in others ways (docstring for >>exemple). > > > Yes, and that's the way that I do it now. But the problem with this is > that it's "non-binding": it doesn't impose any programmatic constraints. > Because of this: > > - it's hard to enforce automatically (if you want to make sure that all > programmers in your team are using the prescribed argument definition > conventions, you have to parse all the docstrings) It's a management problem, not a programming language issue. > - there is no global standard (I might use "name: type info" in my > docstring, you might use "type name") Idem. > - it is hard to guarantee that the documentation is in sync with the code > (if you change the type expectations of a function, you can do so without > changing the documented expectations) Idem. If your programmers don't care about keeping doc in sync, you're in trouble whatever the language. > - it makes type errors less obvious (you end up getting an attribute > error when you perform an operation on the value instead of a type error > when you initially abuse the interface) Although, I must say that this is > surprisingly less of a problem in Python than one might expect. Yep. Type errors are not the most common nor the most annoying bugs. If only declaring types three times was enough to get bug-free programs... > >>And I'm not sure static typing would optimize anything, but not being a >>Python (nor anything else) guru, I would not bet my hand on this... my 2 >>cents... > > > In and of itself, static typing does not optimize anything. In fact, it > could slow things down because you suddenly have to do typechecks all over > the place. > > Static typing can be /used/ for optimizations because it allows for > optimized forms of attribute access - Right. > without it you must do dynamic name > resolution at runtime. Which is a Good Thing IMHO. > For example, if you want to resolve a method name, you currently have to > look up the method name in the object and its classes. With static > typing, since you know the type of the object at compile time, you can > just reference it in a "vtable" (a virtual function table) associated with > the object. > > In short, static typing brings us one step closer to "python compiled to > machine code". Well... Objective C is compiled to machine code, and still has dynamic binding (not late binding as in C++), so static typing does not seem mandatory here. Anyway, I personnally don't have a compelling need for Python being compiled into machine code, and just don't want to here about it if it implies static typing !-) The only thing that could make sens to me would be a protocol-checking mechanism, and there are already some. Bruno From tgerla at outsourcefinancial.com Mon Jul 14 16:34:27 2003 From: tgerla at outsourcefinancial.com (Tim Gerla) Date: 14 Jul 2003 13:34:27 -0700 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser In-Reply-To: References: Message-ID: <1058214866.5032.1.camel@redwall.ofsloans.com> > I just thought of something: what if the Z doesn't allow single quotes > around the "color" attribute? I gave it a try, and replaced the text > with: > > <me>: hello world > > And it works! > Very fun stuff. Someday I hope to have a Zaurus or similar device to toy with. Anyway, to actually be on topic, "proper" HTML (XHTML 1.0, and maybe HTML 4.0? I don't recall...) requires double-quotes to be used. Single quotes are illegal. So, the Qt version your Zaurus is using must be a little more strict. -Tim From bokr at oz.net Fri Jul 18 17:40:20 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 21:40:20 GMT Subject: Co-routines References: Message-ID: On Fri, 18 Jul 2003 14:57:35 +0000 (UTC), Duncan Booth wrote: > wrote in >news:g7xRa.305$fF.9914 at nnrp1.ozemail.com.au: > >> I have an application in which I want the users to be able to create >> python functions: >> >> def f1(): >> print "1-1" >> print "1-2" >> print "1-3" >> >> def f2(): >> print "2-1" >> print "2-2" >> print "3-3" >> >> and when my application runs, I want to execute these functions in >> "lock-step", so that the output looks like: >> [...] > [...] >----- begin steplock.py ----- ># Execute functions in steplock [...] >if __name__=='__main__': > test() >----- end steplock.py ----- > >-- >Duncan Booth duncan at rcp.co.uk >int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" >"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? OP: From: Newsgroups: comp.lang.python Subject: Co-routines Lines: 63 Date: Thu, 17 Jul 2003 23:07:36 +1000 SOLUTION: From: Duncan Booth Newsgroups: comp.lang.python Subject: Re: Co-routines Date: Fri, 18 Jul 2003 14:57:35 +0000 (UTC) Organization: RCP Consultants Lines: 248 Ok, I'm impressed ;-) Regards, Bengt Richter From missive at frontiernet.net Thu Jul 24 17:12:13 2003 From: missive at frontiernet.net (Lee Harr) Date: Thu, 24 Jul 2003 21:12:13 GMT Subject: Trying to contact Lee Harr References: Message-ID: > Not sure why my email got bounced. If you read this please reply back so I > can send you the appropriate documentation so I can get your help in finding > out what's in the spider.Collection[i] name space. > Best bet is to send mail to the list, I have not checked that mailbox in about 2 years... probably why it's full. > > Thank you for all your help. Sorry for the late response to your answer. I > am not used to the python list and wasn't aware of such volume of posts that > are generated on this emailing. List. To answer one of your question, no I > am not familiar with Python, like I mentioned in my email I have been tasked > to integrate verity enterprise search with our J2EE compliant app server. I > am trying to pick up python but I still haven't caught up yet. I haven't > been able to find a good reference book that deals with html embedded > python. most books talk about generating html through python. Can you > recommend a good book for that purpose. The book I picked up is titled Core > Python Programming by Wesley Chow. > > I am not sure if any API calls are being made. I am including the html doc > for your reference > I did not get this, and I don't really think I have time to read it. I was just suggesting that it looked to me like the code you had was not valid python, and it needed to be. From pyth at devel.trillke.net Fri Jul 25 12:41:58 2003 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 25 Jul 2003 18:41:58 +0200 Subject: path module In-Reply-To: ; from just@xs4all.nl on Fri, Jul 25, 2003 at 05:22:17PM +0200 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <20030725184158.O6906@prim.han.de> Hello Just, Just wrote: > holger krekel wrote: > > I think it's convenient enough to use "str(path)" if passing a 'path' > > instance as a string somewhere. > > If the path object has a __str__ method, apparently it should work > without explicit conversion. However, this seems to fail for me on OSX, > where an attempt is made to convert to unicode. Providing a __unicode__ > method doesn't help. But then again, I think we'd be fine if we add the > most used path-taking functions to the path object as methods. I can > even see adding some win-specific methods to it. Yes, i think adding platform specific methods to a Path object makes sense. A friend and me started working on (local and subversion) Path implementations last week. Currently a Path instance provides these "path-taking" methods open read write visit (a recursive walker) listdir stat load/save (unpickle/pickle object) setmtime (set modification time, uses os.utime) apart from all the os.path.* stuff like 'exists', 'dirname' etc. Providing these "path-taking" methods on the Path object is very important because otherwise you'll have to convert back and fro for using those os.* and os.path.* or builtin methods (which is evil). cheers, holger From milyon at wp.pl Thu Jul 10 06:27:09 2003 From: milyon at wp.pl (K) Date: Thu, 10 Jul 2003 12:27:09 +0200 Subject: Odp: Newbie - No module named stdwin References: <3f0c5faf.172627925@news.blueyonder.co.uk> Message-ID: but in visual basic 6 i have graphical Interface - in Python only text based is that correct ? From webmaster at nextmovetech.com Mon Jul 7 23:56:45 2003 From: webmaster at nextmovetech.com (James Tan) Date: Tue, 8 Jul 2003 11:56:45 +0800 Subject: window wxpython programmer required... Message-ID: <3f0a3f38_2@news.tm.net.my> dear all, We are looking for a wxpython programmer in building up a software for us. Preferably in the valley of kl, malaysia. We would like to know: 1. How do you charge? 2. How much will you charge for a software that takes in the duration of 1month? H 3. How long have you been in the python development? 4. Are you familar with xrc, py2exe, wxpython and ms access database? best regards, James IT Consultant MercStudio Dot Com From sholden at holdenweb.com Tue Jul 1 23:53:51 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 02 Jul 2003 03:53:51 GMT Subject: whitespace and ?asc()? References: <3F02086D.9010300@ihug.co.nz> Message-ID: "Ray Tomes" wrote in message news:3F02086D.9010300 at ihug.co.nz... > Hi all > > I am totally new to python. On the whole I really like the design of the > language and after just one day may be considered a convert. > > I was trying to find out the exact definition of whitespace so I went to > look at strings.whitespace to find out which chars were whitespace, and > found 9, 10, 11, 12, 13, 32 which according to my ancient ascii chart are > TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? > > Also, in trying to find the ASCII (or is it ANSI) values for characters I > could not find the reverse function for chr() [in BASIC it is asc()]- can > someone please tell me what reverses chr()? > > I had to do this yucky thing to decode whitespace ... > > import string > x=string.whitespace > for b in x: > for i in range(256): > if chr(i) == b: > print i > 1: http://www.asciitable.com/ 2: ord() 3: import string; print [ord(x) for x in string.whitespace] You did pretty well to get the output you needed, though! regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ > From alanmk at hotmail.com Fri Jul 11 06:27:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Jul 2003 11:27:49 +0100 Subject: Embedding Python, threading and scalability References: Message-ID: <3F0E9125.10185EB9@hotmail.com> [Aahz] >>...the way to scale Python in a threaded environment is to call out >> to a C extension that releases the GIL. Simon Wittber (Maptek) wrote: > To write scalable applications in Python, one must write the > 'scalabilty-required' parts n C. Or Pyrex? Or Boost? Do either of these products release the GIL when control is transferred to the C/C++ extensions? > Does anyone else see this as a problem? Comparatively, perhaps. But certainly less of a problem than writing your entire program in C++, for example. Perhaps easiest to write the whole thing in jython, if the jython free threading claim is true? Ype? Aahz? I'd really like to know the truth of the assertion that jython will utilise all processors in a multi-processor box. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bogus at antispam.com Sat Jul 19 17:26:34 2003 From: bogus at antispam.com (Alex) Date: Sat, 19 Jul 2003 17:26:34 -0400 Subject: Stopping a loop with user input. in curses Message-ID: Hello all, I've written a small clock program in curses that I would like to have end when someone presses 'q'. I've included the code below. I'm *very* new to python so I apologize in advance if this seems like a horribly obvious problem. I've spent all day trying various structures but none of them have worked out. Any help would be greatly appreciated. Thanks, Alex #! /usr/bin/python # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() while 1: t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) def main(stdscr): # Bring up the clock function theClock() # If 'q' is pressed, exit while 2: c = stdscr.getch() if c == ord('q'): curses.beep() break if __name__ == '__main__': curses.wrapper(main) From scpusenet at werbung.schabi.de Fri Jul 4 07:16:17 2003 From: scpusenet at werbung.schabi.de (Markus Schaber) Date: Fri, 4 Jul 2003 13:16:17 +0200 Subject: Apache mod_python and Sessions Message-ID: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> Hi, Does anybody know a module that works with Apache 1.3 mod_python and provides session tracking? I tried pso, but this didn't work as it should. Running in mod_python gives me one session per server process, and the session data is not rewritten to disk. Explicitly calling session.save() (as stated in the doc) fails with the error message that a dictionary doesn't have the "save" attribute. Calling it as CGI sputs the log files with error messages about missing permissions. The apache-provided mod_session seems to miss python bindings. I tried to google, but only found perl modules (except the pso package that doesn't work.) Does anybody know a working solution? Thanks, Markus From fabien_arnaud at yahoo.fr Tue Jul 1 20:29:50 2003 From: fabien_arnaud at yahoo.fr (Fabien) Date: 1 Jul 2003 17:29:50 -0700 Subject: Python on Pocket PC (with graphics) Message-ID: Hello, I'm completly new on python and on Pocket PC ! I want to write an application and plane to us python, but I need graphical display. If I well enderstood, I will not find any port of TkInter on Pocket PC. Is there a way to use the standard pocket PC API from python ? any web site or book to start from without boriing anyone on this group ? Thanks for the answer ! Fabien ARNAUD From domma at procoders.net Sun Jul 6 17:29:38 2003 From: domma at procoders.net (Achim Domma) Date: Sun, 6 Jul 2003 23:29:38 +0200 Subject: Search for mapping solution References: Message-ID: "Markus Joschko" wrote in message news:bea0fe$2otcq$1 at ID-47851.news.dfncis.de... > thanks it works. But maybe I can complicate the example a little bit > (because in real world it's more complicated): > > What if I every list in lines has 20 or more entries and I have only the > index number to access the name, e.g. > > lines = [['elem1','elem2','fred','elem3',.......;'elem > 17','333','elem18','0.10'],[...],[...]] I'm not sure, if I understand you right, but I think you could do it like this: nameIndex = 3 costs = {} for item in lines: name = item[nameIndex] costs[name] = costs.setdefault(name,0)+float(item[-1]) print costs This assumes, that the price is always on the last position. Depending on your requirements there are differnt ways to write it more clearly: nameIndex = 3 costs = {} for name,price in [ (x[nameIndex],x[-1]) for x in lines) ]: costs[name] = costs.setdefault(name,0)+float(price) Or something like that: def priceIter(lines,nameIndex): for x in lines: yield x[nameIndex],x[-1] costs = {} for name,price in priceIter(lines,3): costs[name] = costs.setdefault(name,0)+float(price) It depends on your situation, what's the best solution for you. Depending on your control flow it might be convenient do something like this: def createLinesIter(nameIndex,priceIndex): def priceIter(lines,nameIdx=nameIndex,priceIdx=priceIndex): for x in lines: yield x[nameIdx],x[priceIdx] Now you could create special Iterators for your lists an pass them around: TypA_Iter = createLinesIter(0,-1) TypB_Iter = creaetLinesIter(3,7) now you can pass these funtions around with your matching lines list: def processLines(lines,linesIter): costs = {} for name,price in linesIter(lines): costs[name] = costs.setdefault(name,0)+float(price) return costs And now for your first list: lines = .... costs = processLines(lines,TypA_Iter) The examples are written from head, so there might be some typos. But they should give you a hint on what's possible in python. regards, Achim From skip at pobox.com Sun Jul 20 12:20:12 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 20 Jul 2003 11:20:12 -0500 Subject: "Pure Python" MySQL module like Net::MySQL In-Reply-To: References: Message-ID: <16154.49468.497887.827235@montanaro.dyndns.org> Ravi> I did some googling, and found that there doesn't seem to be a Ravi> pure python MySQL communication module. There is one for perl Ravi> however, Net::MySQL. This has benefits and disadvantages. As the author points out, this lets you connect to MySQL databases from systems to which the MySQL client libraries haven't been ported. On the other hand, the MySQL wire protocol is probably not part of the official external interface, so the author has to track changes to the protocol. Skip From andy at wild-flower.co.uk Fri Jul 4 18:39:26 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 4 Jul 2003 23:39:26 +0100 Subject: print attitude In-Reply-To: References: Message-ID: <200307042339.26727.andy@wild-flower.co.uk> On Friday 04 Jul 2003 10:49 pm, Batista, Facundo wrote: > One detail I found, don't now if it's ok: > > Python 2.1.1 (#4, Mar 8 2002, 12:32:24) > [GCC 2.95.3 20010315 (release)] on sunos5 > > >>> a = '?' > >>> a > > '\xf1' > > >>> print a > > ? > > >>> l = ['?'] > >>> l > > ['\xf1'] > > >>> print l > > ['\xf1'] > > > Is this OK? > > Why this different behaviour? > > Thank you! > > . Facundo Facundo, Short answer: '?' is not in 7-bit ASCII, so python 'escapes' it, to it's hex value, when evaluating it. ['?'] is a list, containing 1 string, and when displaying lists (and other containers), python displays the escaped contents, as this is the only way that 'makes sense'. Long answer: Remember, everything in Python is an Object, so... >>> a=1 # and 'int' object, with the name 'a' When you use print, it calls the __str__ method of the object you are printing, which returns the 'string representation' of the object's data: >>> print a 1 >>> print str(1) 1 When you just 'evaluate' the expression on the python command-line, the __repr__ method of the object is called, which returns a 'quoted' string, that can be used to re-create the object with the same value. For some types (integers and floats), str(n) == repr(n) - their string representation is the same as their quoted representation. For other types (strings for instance), str(s) != repr(s) >>> a 1 >>> repr(a) 1 >>> s="hello" >>> print s hello >>> print str(s) hello>>> ord("?") UnicodeError: ASCII encoding error: ordinal not in range(128) >>> print repr(s) 'hello' If the object is a 'container' object - a list, tuple or dict, for example, their __str__ method returns the same as their __repr__ function: a string which can be used to recreate the object. So when you ask python to print it, what you see is it's 'quoted' representation. How else would you print a list? a dict? It only makes sense to print the 'quoted' version in these cases.>>> ord("?") UnicodeError: ASCII encoding error: ordinal not in range(128) Ok - that covers a the mechanics, but what about your '?'? Well, that's not a standard 7-bit ASCII character. Python is '7-bit ASCII clean' - which means it ONLY uses characters 0-127 in program code. Programs can manipulate any character code, but you can't write them in python /directly/: (on my box i get this): >>> ord("?") UnicodeError: ASCII encoding error: ordinal not in range(128) I notice you're using an older version of Python than me (2.1.1) - I believe this *does* allow coded over 127 (but I'm not sure of the rules). Right, when you ask python to print a list like ['?'], it simply prints the 'quoted' data in it data structure. As '?' > chr(127), it 'escapes' it to it's hex value '\xf1'. If I've got any of that wrong/inaccurate, I'm sure one of the Kindred will correct me :-) hope that helps -andyj From manish.j at gmx.net Fri Jul 25 08:58:48 2003 From: manish.j at gmx.net (Manish Jethani) Date: Fri, 25 Jul 2003 18:28:48 +0530 Subject: decimal to binary In-Reply-To: References: Message-ID: <6_9Ua.3$gZ.73@news.oracle.com> manuel wrote: > How to convert a decimal to binary ? def foo(i): b = '' while i > 0: j = i & 1 b = str(j) + b i >>= 1 return b Maybe this is inefficient, but... -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From ajsiegel at optonline.net Wed Jul 30 08:11:16 2003 From: ajsiegel at optonline.net (Arthur) Date: Wed, 30 Jul 2003 08:11:16 -0400 Subject: Wrtiting AVI files with Python Message-ID: <000501c35693$ae54f350$0c02a8c0@Arts> JET asks: >Does any one know if there is such a tool for >Python or some libraries that I could import and use in my code? I'd check out: http://sourceforge.net/projects/ganim8/ Art From theller at python.net Mon Jul 28 09:46:41 2003 From: theller at python.net (Thomas Heller) Date: Mon, 28 Jul 2003 15:46:41 +0200 Subject: Can't compile, miss library/modules ............... ? References: Message-ID: "PythonMan" writes: > warning: py2exe: * The following modules were not found: > warning: py2exe: * SOCKS > warning: py2exe: * rourl2path > warning: py2exe: * ic > > when i compile btdownloadheadless.py of BitTorrent , justmsg is shown , the > souce code should have no error , but why i get such error ? how get back > this modules ? thx~~~ It's a warning, and the exe should work. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 15 18:25:07 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 16 Jul 2003 00:25:07 +0200 Subject: UDP client-server problem In-Reply-To: <538fc8e.0307151318.12551933@posting.google.com> References: <538fc8e.0307151318.12551933@posting.google.com> Message-ID: <3f147f42$0$49112$e4fe514c@news.xs4all.nl> WIWA wrote: > The question is: when I add "svrsocket.sendto(resultaat, (ip, port))" > in the UDP server, my application closes while running. When I leave > it away, it works fine. I really need this statement as the purpose is > that a client sends sth to the server and the server sends back the > time ticks. It would have helped if you were more specific about: "closes while running"? In my case (running your code) I get an exception in the server: Traceback (most recent call last): File "server.py", line 44, in ? svrsocket.sendto(resultaat, (ip, port)) File "", line 1, in sendto TypeError: sendto() takes exactly 3 arguments (2 given) this pretty much tells you what's wrong. Your sendto() call is faulty. The first argument in your case is of type while it should be a . So try svrsocket.sendto(str(resultaat), (ip, port)) however, this triggers a loop in your code if your client is on the same machine as the server (the server sends out a UDP packet to the same port as it itself is listening on, on my machine, it gets back its own UDP packet....) HTH, --Irmen de Jong From nico at DUMPTHISfarumdata.dk Tue Jul 29 03:16:48 2003 From: nico at DUMPTHISfarumdata.dk (Nico de Jong) Date: Tue, 29 Jul 2003 09:16:48 +0200 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: > Among the latter were two posters printed on [now I have forgotten the > English word for this type of paper, but it has tractor holes along > both sides, and is flimsy, and has horizontal perforations every now > and then] paper, with a silk-screeened slogan advocating recycling on > the supposedly blank side. You are thinking of fanfold and/or leporello. Leporello comes probably from the operette figure, who in a scene reads a list of his masters "conquests", and as there are about 1000 names, he had to fold it in some way. Nice touch of folklore, I think Nico From djc at object-craft.com.au Fri Jul 11 01:19:35 2003 From: djc at object-craft.com.au (Dave Cole) Date: 11 Jul 2003 15:19:35 +1000 Subject: Securing 'pickle' References: <7xu19t21ap.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Ian Bicking writes: >> A much easier way to secure your pickle is to sign it, like: >> >> cookie = dumps(object) secret = 'really secret!' hasher = >> md5.new() hasher.update(secret) hasher.update(cookie) >> cookie_signature = md5.digest() Paul> That method is vulnerable to an "appending" attack against md5. Paul> I'll spare the gory details, but you should call md5 through the Paul> HMAC module to make the signature instead of using md5 directly. Paul> HMAC is designed to stop that attack. I have been googling for information on the "appending" attack against md5 and cannot find anything that clearly describes it. Do you have any links handy? - Dave -- http://www.object-craft.com.au From pedro.werneck at bol.com.br Mon Jul 28 18:49:15 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 28 Jul 2003 15:49:15 -0700 Subject: Debugging Python ? References: Message-ID: I use: if __debug__: print "bla, bla, bla..." And I was just wondering if it's legal to define a "print" function... isn't print a keyword ? From icarroll at pobox.com Sat Jul 12 16:46:51 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Sat, 12 Jul 2003 13:46:51 -0700 Subject: Assigning to global variables from within a function References: Message-ID: <3F1073BB.2020603@pobox.com> Psymaster wrote: > I want to do this: > > int= 0 > > def change_int(): > int += 1 > > change_int() > > but of course it doesn't work, Python thinks it is a local > variable and refuses to reference the global one. So what would > be a good way of doing this. Note that creating a new global > variable from within the function isn't convenient because the > function is intended to be used in loops. First of all, remember that "int" is a built-in, so it's not a good idea to use it for another purpose. Have you tried declaring i as a global? i = 0 def change_i(): global i i += 1 change_i() This doesn't make a new global variable, it just tells the compiler that the i referenced inside the function is the global i, even though it's being assigned to. TTFN From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jul 12 16:42:06 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 12 Jul 2003 22:42:06 +0200 Subject: Assigning to global variables from within a function In-Reply-To: References: Message-ID: <3f10729d$0$49100$e4fe514c@news.xs4all.nl> Psymaster wrote: > I want to do this: > > int= 0 > > def change_int(): > int += 1 > > change_int() > > but of course it doesn't work, Python thinks it is a local > variable and refuses to reference the global one. So what would > be a good way of doing this. Note that creating a new global > variable from within the function isn't convenient because the > function is intended to be used in loops. A function that modifies a global is generally considered bad design (it has 'side-effects'). But if you really need to do this, just add a 'global' statement: def change_i(): global i i+=1 PS don't use 'int' for a name of your own, it is a builtin in Python. From mday at apple.com Thu Jul 31 16:27:22 2003 From: mday at apple.com (Mark Day) Date: Thu, 31 Jul 2003 13:27:22 -0700 Subject: list indexing References: Message-ID: <310720031327225125%mday@apple.com> In article , Matthew wrote: > What I would like to > know is if there is a way to get the index number of a list element by > name. Sort of the inverse of the .index() method. > > For example > > list = ['this', 'is', 'a', 'list'] > for item in list: > if item = 'list': > print ???? > > > ???? Is where I want to be able to get the index number, in this case > 3 from the list in a simple fasion. If you're using Python 2.3, you can use enumerate() like this: for index,item in enumerate(list): if item == 'list': print index BTW: I'd suggest not using the name of a built-in class for your variable "list". Perhaps "mylist" or "words"? -Mark From paulpaterson at users.sourceforge.net Fri Jul 25 22:11:05 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sat, 26 Jul 2003 02:11:05 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Ian Bicking wrote: > On Fri, 2003-07-25 at 12:28, Paul Paterson wrote: > >>Thanks Terry! I adjusted my tests and now see this behaviour exactly. >>The function itself works but the changes do not propogate out to the >>calling scope. So this approach of using locals() appears to be dead. >> >>Are there any other approaches? > > > Think about what you are trying to do, and try to identify a (mutable) > object that can encapsulate that. Then pass the object, and modify its > instance variables, like: > > class Point: > def __init__(self, x, y): > self.x = x > self.y = y > > def change(p): > p.y = 10 > > obj = Point(0, 0) > change(obj) > assert obj.y == 10 > > > Maybe this mutable object will simply be the main application object, > and instead of functions you will use methods of that application > object. > > Ian This is a very interesting (and Pythonic) approach, thanks for suggesting it! This is certainly what I would try to do if I were writing the code from scratch. It may be possible to construct a "namespace" type object which gets passed to the function. VB does have multiple namespaces so a single App object is probably not feasible but since my parser knows the App structure it can determine which namespace a variable will be resolved from anyway and just translate all attempts to access it to the relevant namespace object lookup. Paul From max at alcyone.com Wed Jul 23 23:29:27 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 Jul 2003 20:29:27 -0700 Subject: file.close() References: Message-ID: <3F1F5297.15D768EF@alcyone.com> Bryan wrote: > which explicitly closes f1 & f2 > any exceptions opening f1 or f2 is handled outside of this structure > or is > allowed to fall out of the program. i'm aware that files will > automatically > be closed when the process exits. i'm just curious how others do this > for > small scripts and larger programs. is what i'm doing is overkill? No, not at all; it's safe and portable. Python the language does not specify when objects get reclaimed, although CPython the implementation does it promptly. Use of external resources -- which should be released as soon as you're done with them -- are best done in try/finally clauses. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It is fatal to enter any war without the will to win it. \__/ Douglas MacArthur From meinrad.recheis at gmx.at Sun Jul 27 16:41:43 2003 From: meinrad.recheis at gmx.at (meinrad recheis) Date: Sun, 27 Jul 2003 22:41:43 +0200 Subject: changing the List's behaviour? Message-ID: hi pythoneers i am very annoyed by the List's index out of bouds exception it forces me to complicate my code by adding length checking i might be spoilt by Ruby which returns nil for not existing indices. i want to change the List so that it returns None if the index for accesssing list elements is out of bound. i am not very experienced in python, so i ask you for suggestions. thanks in advance, Meinrad Recheis From usenet_spam at janc.invalid Sun Jul 27 22:21:36 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 28 Jul 2003 02:21:36 GMT Subject: Help with Boa on Win98 with unicode installed References: <20030727102742.18087.00000494@mb-m15.aol.com> Message-ID: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) schreef: > Has anyone ever struggeled with that install of Boa in Win98. > I've followed the Docs. Tryed the "-E" switch while in DosPrompt. Made > sure the wxPython version matched Python version... > > What am I missing folks? Don't use the unicode version of wxPython on Win9x, if that's possible? Unicode wxPython gives problems on my Win98SE system too, but Boa starts up fine when I run it with ANSI wxPython (didn't try to actually use it yet). -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From roo at dark-try-removing-this-boong.demon.co.uk Thu Jul 3 10:41:49 2003 From: roo at dark-try-removing-this-boong.demon.co.uk (Rupert Pigott) Date: Thu, 3 Jul 2003 15:41:49 +0100 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: <1057243309.793889@saucer.planet.gong> "Cameron Laird" wrote in message news:vg88va53uha8e at corp.supernews.com... > In article , > Bob Gailer wrote: > . > . > . > >This brings back the good old days of FORTRAN IV which had a > >single-statement IF and no ELSE. Thus: > > C = VALUE1 > > IF ( A .EQ. B) C = VALUE2 > >Notice the indentation. Cols 1-5 were reserved for line # and col 6 for the > >continuation code. So Python is not the only indentation dependent > >language. Nor is it the first to use indentation to convey structure. > . > . > . > Maybe youngsters don't realize this. > > One monotonous but unremitting argument that Python inspires > is about the wisdom of its white-space-significance (WSS). > Modern programmers might not realize how strongly old-timers > associate WSS with early FORTRAN and COBOL (as we capitalized > them then), and how unpleasant some of those memories are. > *That*, I assume, is why WSS discussions become as heated as > they do. OCCAM used WS to denote block structure... For example the IF construct : IF x > 0 y := 10 x < 0 y := 0 x = 0 y := 5 Personally I also found this a pain coming from a C background... BUT, I grew to love it. It normalised code layout, which meant that picking up someone else's code was MUCH easier... As a bonus it eliminated the holy wars about formatting that have ravaged through every gathering of >=2 C coders. :) Cheers, Rupert From bdesth.nospam at removeme.free.fr Sun Jul 13 09:47:57 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sun, 13 Jul 2003 13:47:57 +0000 Subject: What's new with Gnosis [wrong thread ?] References: <87d6gf6cc6.fsf@pobox.com> Message-ID: <3F11630D.9090806@removeme.free.fr> John J. Lee wrote: > "Raymond Hettinger" writes: > [...] > >>ACT I --------------------------------------- >> (snip) John, is it my newsreader going mad, or did you post in the wrong thread ? Bruno From staschuk at telusplanet.net Thu Jul 31 23:01:59 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 21:01:59 -0600 Subject: handle
tags In-Reply-To: ; from ben@dadsetan.com on Thu, Jul 31, 2003 at 11:54:48PM +0200 References: Message-ID: <20030731210159.A23533@tibia.amotlpaa.bogus> Quoth Behrang Dadsetan: [...] > I believe SGML does not like none closing tags. BR is one of the many > none closing tags in HTML (also look at IMG or HR) SGML has facilities for allowing closing tags to be omitted. At , for example, we see That "- O" means the start tag is mandatory but the end tag may be omitted. If it is omitted, SGML parsers infer where it belongs (which in this case is immediately after the start tag). -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From mike at nospam.com Tue Jul 8 13:13:13 2003 From: mike at nospam.com (Mike Rovner) Date: Tue, 8 Jul 2003 10:13:13 -0700 Subject: printing html document with internet explorer References: <003401c3456a$20be53e0$410100a4@utente65> Message-ID: Luca Calderano wrote: > > Does anyone know how-to automatically print an html doc using Internet > Explorer ??? See attached program. > I've tried these ways: > > 1) wxHtmlEasyPrinting > 2) win32api.ShellExecute You missed OLECMDEXECOPT_DONTPROMPTUSER = 2 Enjoy! Mike begin 666 printall.py M9&5F(&EN:71?:64H*3H-"B @9VQO8F%L(&EE#0H@(&9R;VT@=VEN,S)C;VTN M8VQI96YT(&EM<&]R="!$:7-P871C:$5X#0H@(&EE(#T at 1&ES<&%T8VA%>"@B M26YT97)N971%>'!L;W)E3H@<&%S3H-"B @("!I;FET M7VEE*"D-"B @97AC97!T. at T*(" @('!R:6YT("=&051!3" M($EN=&5R;F5T M($5X<&QO&ET*"D@(" -"B @ M3H-"B @("!N86UE/69I;F1?9FEL92AS>7,N87)G=ELQ72D-"B @ M("!P7,N97AI="@I(" @#0H@(&-H87 ],0T*("!W:&EL92!43H-"B @(" @(&EF(&-H87 ^&-E<'0Z#0H@(" @("!S>7,N97AI="@I#0H- )"FUA:6XH*0T* ` end From tojopiter at yahoo.com Tue Jul 8 04:12:21 2003 From: tojopiter at yahoo.com (piter) Date: Tue, 8 Jul 2003 10:12:21 +0200 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: Uzytkownik "Steffen Brodowski" napisal w wiadomosci news:381a2b17.0307072326.211c21b5 at posting.google.com... > Hello everyone, > > since one week, I'm programming with python. Its a realy interesting > tool. I wrote a script for generating barcodes in jpg-format. > Everything is ok, but my function "CreateBarcode" should write the jpg > data into an outstream. All barcodes will be generate online, without > saving the jpgs on harddisk. > > Can you give me a tip witch objects I need and how to put the jpg into > an outgoing stream? > > import Image, ImageDraw > def CreateBarcode(SourceString,Linewidth,WriteText): > blablabla > ... > NewImage = Image.new("L",NewSize,Backcolor) > ImgDraw = ImageDraw.Draw(NewImage) > .... > > #How to put the image into an stream? Image.save save(outfile, options) save(outfile, format, options) Saves the image under the given filename. If format is omitted, the format is determined from the filename extension, if possible. This method returns None. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described later in this handbook. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode. hth Piter > > best regards > > Steffen Brodowksi > Germany From stuart at bmsi.com Mon Jul 14 16:48:07 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 14 Jul 2003 16:48:07 -0400 Subject: ANN: dspam-python-2.6.2-3 Message-ID: I have created RPMs and a python wrapper for the DSPAM project. The DSPAM project was created by NetworkDweebs and provides a Bayesian spam filtering Mail Delivery Agent. More importantly, it exports the core engine as a C library. The core library is what is wrapped for Python. I also took the liberty of creating a 'tokenize' entry point to the core library allowing python code to use its own database structure. Tokenizing is the only step that needs C speed. There are no docs yet for the python wrapper, but good short examples in python are included in the source. The python versions of some of the DSPAM utilities, like dspam_corpus.py, are faster than their C counterpart (26 vs. 33 secs)! (This is due to the python code not opening and closing the database for each message.) The web page has an example of using dspam in a Python milter. http://bmsi.com/python/dspam.html From aahz at pythoncraft.com Sun Jul 13 13:40:13 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 13:40:13 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: In article <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah at 4ax.com>, Tom Plunket wrote: > >I want to do something along the lines of the following C++ code: > >void change(int& i) >{ > i++; >} class Counter: def __init__(self, start=0): self.counter = start def inc(self, increment=1): self.counter += increment def change(counter): counter.inc() There's no need to get into all the special methods required to implement a number type, and it's a Bad Idea to use a random container object. Just pass around a mutable class instance, and your code becomes simpler and clearer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From hokiegal99 at hotmail.com Tue Jul 22 22:29:44 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Tue, 22 Jul 2003 22:29:44 -0400 Subject: lists and files question References: <3F1DCF52.7040607@hotmail.com> Message-ID: <3F1DF318.20308@hotmail.com> "print fname" prints out the list of files in "setpath" w/o problem. How does it do that if os.walk doesn't give it the path to the files? Here's some output from "print fname": ['index.txt', 'CELL-MINUTES.xls', '.nautilus-metafile.xml'] ['2000 Schedule.xls', '2001 State.pdf', '2001.pdf', 'A Little More Like Bill.doc', 'AARP.doc', "Accounting's of Dad's Est.xls", 'Amortization_Table.xls', 'huey letter.doc', 'utt-R&D.pdf', 'utt.pdf', 'rest.xls', 'Debts and Assets.xls', 'First Accounting - Estate.xls', 'Friends.doc', "Grace's.doc", 'Home Address.doc', 'Ins.doc', 'Insurance.doc', 'Interro.doc', 'Marshall.doc', 'NBB home loan.doc', 'Position Description.doc', "andy's", "Andy's Travel Voucher.xls", "Andy's Travel.xls", 'Rebuttal.doc', 'Refinance.doc', 'TaxReturn 2.pdf', 'TaxReturn 3.pdf', 'TaxReturn 4.pdf', 'TaxReturn 5.pdf', 'TaxReturn.pdf', 'The Casey Song.doc', "Touch of the Hand.xls", 'Workout Sheet.xls', 'application.pdf', 'budsum.pdf'] When I add os.path.join like this: setpath = raw_input("Enter the path: ") for root, dirs, files in os.walk(setpath): id = re.compile('Microsoft Excel Worksheet') fname = files print fname content = open(os.path.join(root,fname[0]),'rb') I get a "IndexError: list index out of range" error. This is a Linux 2.4 computer running Python 2.3b2... if that matters. Thanks! Sean 'Shaleh' Perry wrote: > On Tuesday 22 July 2003 16:57, hokiegal99 wrote: > >>This code: >> >>import os, re, string >>setpath = raw_input("Enter the path: ") >>for root, dirs, files in os.walk(setpath): >> id = re.compile('Microsoft Excel Worksheet') >> fname = files >># print fname >> content = open(fname[1],'rb') >> >>Produces this error: >> >>IOError: Error[2] No such file or directory 'Name of File' >> > > > if you replace your logic with some prints you will quickly see the problem. > > What happens is os.walk() passes filenames without their path. You need to > use os.path.join() to get the full name back. From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 11 04:28:02 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 11 Jul 2003 09:28:02 +0100 Subject: command prompt change dir In-Reply-To: References: Message-ID: <200307110928.02474.mfranklin1@gatwick.westerngeco.slb.com> On Friday 11 July 2003 07:39, Peter Vestergaard wrote: > Hi > Probably a simple question but I have not been able to find out how: > I want my python script to generate a path based on some simple lookups and > then change my path so that when the script exits my command prompt (from > which I launched the script) is standing at this path. The path already > exists. > I have tried chdir(path), system('cd '+path) and many others but none > changes my actual path. > Hope anyone can help > Regards, Peter Vestergaard I don't think it is possible to change the path of the calling program (in this case the command prompt you use to start the python script....) However you could use a shell trick to kind of do what you want:- #!/usr/local/bin/python # ChangePath script # invoke from command line like so: # cd `ChangePath.py` # # simple lookup... path = "/usr/oracle/" print path Invoke the above from your command line (xterm or whatever...) cd `ChangePath.py` I have only tested this on Linux + bash and I would guess this would not work on Windows... Regards Martin From lorenb2 at bezeqint.net Sun Jul 20 17:57:48 2003 From: lorenb2 at bezeqint.net (Bobbie) Date: Sun, 20 Jul 2003 23:57:48 +0200 Subject: httplib\urllib attributes problem References: <005201c34f05$e273da60$6700a8c0@inet43> <006001c34f07$03bb0760$6700a8c0@inet43> Message-ID: <007a01c34f09$f5329a20$6700a8c0@inet43> I'm really doing my first python steps here... can you show me where and how should the "opener.addheaders = []" code be added to a simple web-client like the following: import urllib2 url = 'http://www.google.com' body = None headers = {"User-Agent" : "My first python browser", "Accept-Language" : "en-us", "Accept-Encoding" : "deflate", "Connection" : "Close"} connectobj = urllib2.Request(url,body,headers) webfile = urllib2.urlopen(connectobj) thanks B. ----- Original Message ----- From: "Jordan Krushen" To: "Bobbie" Cc: Sent: Monday, July 21, 2003 10:43 AM Subject: Re: httplib\urllib attributes problem > On Sun, 20 Jul 2003 23:36:44 +0200, Bobbie wrote: > > > hmmm. > > But doesn't that apply to the suggested "opener.addheaders = []" change > > as > > well ? > > That would go in your code, not in urllib2.py. You have control over when > your code changes, and if you ship a package to other users, this would > still be able to override their libraries, too. > > J. > > > From mis6 at pitt.edu Wed Jul 23 17:11:47 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 23 Jul 2003 14:11:47 -0700 Subject: classes References: <2259b0e2.0307210451.203db2ef@posting.google.com> Message-ID: <2259b0e2.0307231311.1102621a@posting.google.com> Steven Taschuk wrote in message news:... > Quoth Michele Simionato: > > Steven Taschuk wrote in message news:... > [...] > > > _the_instance = None > > > class MySingleton(object): > > > def __new__(self): > > > global _the_instance > > > if _the_instance is None: > > > _the_instance = object.__new__(self) > > > return _the_instance > > > > Why are you using a global here and not [a class attribute] > > The memory of that thread a little while back about using __del__ > with singletons. If the instance is referenced by a class > attribute, the cyclic reference prevents the __del__ from being > used. If the cycle goes through a module attribute, though, the > zapping of module dicts during shutdown breaks the cycle and lets > the __del__ run. (Whether all this is true depends on the version > of Python, I think, but I don't know the details.) > > This might be relevant to the OP, whose example was a singleton > representing the single database connection used by an entire > application -- in such a case, __del__ would be a natural place to > make sure the connection is closed properly. > > I should have explained this bit of trickery. :( > Thanks for the explation, I missed that thread. Michele From jepler at unpythonic.net Wed Jul 30 07:59:08 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 30 Jul 2003 06:59:08 -0500 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) In-Reply-To: <67fdivk9iu0q1p7nc8smfj1miip3cbvobf@4ax.com> References: <3f2627c7$0$76067$edfadb0f@dread11.news.tele.dk> <67fdivk9iu0q1p7nc8smfj1miip3cbvobf@4ax.com> Message-ID: <20030730115903.GA10227@unpythonic.net> On Tue, Jul 29, 2003 at 07:29:19PM +0100, Marc Wilson wrote: > In comp.lang.python, aahz at pythoncraft.com (Aahz) (Aahz) wrote in > :: > > |Fair enough. Note carefully that I said "submit a patch" -- that > |doesn't guarantee that the patch will be accepted, and it's quite likely > |that it won't be. But "submit a patch" is usually a good way to get > |people to shut up. ;-) > > Shame it doesn't work in *all* newsgroups, eh? I'll have you know that I've submitted a number of Python patches that were clearly bad ideas. In fact, I'm a little hurt that Aahz doesn't think of me as "that guy who often posts or submits horrible patches and won't shut up". Jeff From peter at engcorp.com Thu Jul 3 22:12:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 22:12:49 -0400 Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F04E609.2010500@dadsetan.com> Message-ID: <3F04E2A1.448FD235@engcorp.com> (Please don't top-post.) Behrang Dadsetan wrote: > > A bit a pitty the message board system is php based.. > > Does anyone know about message board systems written in python? Sounds like you should post this to the board itself, which asks the very same question: http://pyboards.com/phpbb/viewtopic.php?t=3 -Peter From duncan at NOSPAMrcp.co.uk Wed Jul 9 09:06:06 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 9 Jul 2003 13:06:06 +0000 (UTC) Subject: copy list, which way is best? /style References: Message-ID: "Andreas Kuntzagk" wrote in news:begt35$4sd5m$1 at fu-berlin.de: > There are three ways to (shallow)copy a list l I'm aware of: > >>>> l2=list(l) >>>> l2=l[:] >>>> l2.copy.copy(l) > > Are there any differences? Are there more (reasonable) ways? > I think the first is the most pythonic, second looks more like this other > p-language and third requires an import, so I would prefer the first. > Do you agree? They all do slightly different things. I think this is a fairly accurate description of what each of these does: >>> l2 = list(l) This will copy any iterable object and will produce a new, distinct list as a result. >>> l2=l[:] This will copy a sequence, and will return an object of the same type as the original. If the original is immutable, then it may simply return the original object and not bother with making a copy. >>> l2=copy.copy(l) This will copy any object whether or not it is a sequence, but it may still return the original object for immutables. >>> l2=copy.deepcopy(l) This will make a deep copy of an object. It only returns the original object for immutables if any objects they contain are also immutable (including their contents). -- 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 jdhunter at ace.bsd.uchicago.edu Thu Jul 10 13:59:19 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 10 Jul 2003 12:59:19 -0500 Subject: Parsing In-Reply-To: (whatsupg21@hotmail.com's message of "10 Jul 2003 10:38:48 -0700") References: Message-ID: >>>>> "Michael" == Michael writes: Michael> I have been assigned a project to parse a webpage for Michael> data using Python. I have finished only basic Michael> tutorials. Any suggestions as to where I should go from Michael> here? Thanks in advance. -- Michael> http://mail.python.org/mailman/listinfo/python-list Check out this article http://www.unixreview.com/documents/s=7822/ur0302h/ and then search the comp.lang.python achives for "web scraping" http://www.google.com/groups?as_q=web%20scraping&safe=off&ie=UTF-8&oe=UTF-8&as_ugroup=*python*&lr=&num=20&hl=en See, for example, http://www.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&threadm=mailman.1055971051.1456.python-list%40python.org&rnum=1&prev=/groups%3Fnum%3D20%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26safe%3Doff%26q%3Dparsing%2Bcomplex%2Bweb%2Bpages%2Bgroup%253A*python*%26btnG%3DGoogle%2BSearch You should look at the string and re modules for relatively simple information retrieval, and the htmllib and formatter modules for more complicated solutions where parsing is required. The best solution depends on the format of the web pages you need to parse. John Hunter From exarkun at twistedmatrix.com Sun Jul 13 15:38:46 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Sun, 13 Jul 2003 15:38:46 -0400 Subject: Library for pop over ssl? In-Reply-To: References: Message-ID: <20030713193840.GB24564@intarweb.us> On Sun, Jul 13, 2003 at 03:08:53PM +0000, Marco Herrn wrote: > Hi, I know of poplib, which does what I need except that it doesn't > support SSL encryption. imaplib has SSL-support. But I want it with > pop3. Is there a library available that does this or do I have to > implement it myself? http://www.twistedmatrix.com/ Jp -- http://catandgirl.com/view.cgi?44 From BPettersen at NAREX.com Tue Jul 22 16:28:15 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 22 Jul 2003 14:28:15 -0600 Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88) Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE46E2@admin56.narex.com> > From: Ames Andreas (MPA/DF) [mailto:Andreas.Ames at tenovis.com] > > Hello, > > during execution of an assignment statement like > > x = y > . > . > . > x = z # <-- > > is y's reference count decremented (and therefore its __del__ possibly > called) *before* x is bound to z (or is z bound to x, I don't know the > correct wording) or *afterwards*? I'm not sure exactly what you're asking, but "x = y", is similar to the following C-pseudo-code: 1 incref(*y); 2 tmp = x 3 x = y; 4 decref(*tmp); // potentially calling __del__ [[if I'm reading ceval.c correctly... lines 2-4 being in SETLOCAL, called from STORE_FAST, based on the following code: >>> def f(a,b): ... a = b ... >>> import dis >>> dis.dis(f) 2 0 LOAD_FAST 1 (b) 3 STORE_FAST 0 (a) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE ]] whether this should matter to you is dubious since the case you seem to be worried about (y being deleted before z assigned to x) would only matter if it caused z to have a dangling reference to y. However, if z has a reference to y, its reference count can't go to zero, thus no __del__ would ever be called. -- bjorn From max at cNOvSisiPonAtecMh.com Thu Jul 3 13:25:29 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 03 Jul 2003 17:25:29 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: "BearMan" wrote in message news:FiZMa.2097$_k2.145814 at nnrp1.ptd.net... > Not to mention all the time spent recompiling through out the debugging and > troubleshooting process. Has Max ever programmed in Python? How about > Assembly? Yes to both in varying degree. > The fact of the matter is there is no such thing as one ULTIMATE language. A > real programmer will have mastered several languages so as to integrate the > best features for any given situation. > > IMHO I am not sure where we disagree. This is exactly my point. The statement " Engineering Lessons ------------------- 1. C/C++ is no longer a viable development language " is pure rubbish. C++ is still great for certain kinds of projects, and there are lots of open-source and proprietary projects to prove this. I mean, is Linux (or Windows) 'not a viable project'?? As I said, this is a very narrow-minded and conceited statement: rubbish. max. From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 7 00:34:21 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Mon, 07 Jul 2003 04:34:21 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: On Mon, 07 Jul 2003 03:27:04 GMT, Russell Reagan wrote: > I agree that it is not good to worry about optimization prematurely, > but computer chess might be a bit of a unique area. I am extremely skeptical of any statement like this. *Everyone* thinks their area is a unique exception to the guidelines. The area in which one chooses to specialise is fascinating, and one spends a lot of happy time exploring its unfathomable complexities. It is a hideously common mistake to extrapolate, from this, that the area whose complexities you know in detail is therefore more complex than others, and thus exempt from the guidelines. It is then a very small step to assume a priori that it *is* an exception, in this one unique area. I'm not saying yours is not, but you'd better prove that "might be" before it becomes "let's assume it is". > This is also why OOP might not be of much use for chess programming. Programming in Python doesn't necessitate OOP; one can make use of the rich data structures as is while being happily procedural. > There is really not a lot you can do to improve [position evaluation] > short of starting over from scratch and creating your data structures > in such a way as to exploit lots of low level tricks. Sounds like you're already focusing in the right area. Make smart data, so that the code can be dumb. The advantage is that you can write dumb code in most any language -- so you can choose Python if you want to prototype your smart data structures. And, who knows, your data structures may be so well designed that your dumb Python code is good enough, except just in this little bit here that needs to be tweaked in C. >> at least you've debugged a working algorithm, and can treat it as >> pseudocode for the port to C. > > It sounds like you're thinking, "I'll just implement this python > program in C/C++, and then it will be faster," but I'm not sure that > is the case. I was referring more to algorithms rather than entire programs, since they are more often at a "module" level, but in essence, yes. Once you decide you've made the algorithm as fast as it can be while remaining implemented in readable Python, that's the point to think about re-implementing the algorithm in C. > Sure it will be faster, but probably still pretty slow. This is the assumption that will trip you up and cause you to optimise prematurely. Do *not* assume you know exactly where your program will be slow until you see it working and profiled, or which parts will be best implemented in C. > Making a really fast chess program would require changing the data > structures significantly, and I'm not sure what use the python code > would be after you made a big overhaul of the data representations. Again, make the data structures smart and you can manipulate them in dumb code written in Python or C. > What do you think? I may be way off. Maybe I'm putting too much > emphasis on speed. It's understandable, given that the focus on chess-playing programs is mostly on finding ways to make them go faster or do more in the same time. But if you want to implement a program in Python, don't make any assumptions about where it is slow. Much of the Python core is *already optimised* in C libraries, so attempting to optimise before profiling is doubly foolish. One of PYthon's strengths is rich data structures, that work very fast under most all conditions because their implementation is smart. Take advantage of Python's powerful types when you design your own smart data; but start with the simple algorithms and tweak them only when they prove to be slow in Python. -- \ "I spent all my money on a FAX machine. Now I can only FAX | `\ collect." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From hitectahir at hotmail.com Tue Jul 1 11:00:59 2003 From: hitectahir at hotmail.com (hitectahir) Date: 1 Jul 2003 08:00:59 -0700 Subject: Problem with self.fp.readline() in httplib.py Message-ID: Hi, I have been using a remote data server named Clarens which runs on top of the Apache web server and communicates through xmlrpc on Redhat Linux 7.3. It has been working fine for about a month, but today it has started giving some error in httplib.py. The complete traceback is given below: Traceback (most recent call last): File "clarensclient.py", line 2, in ? dbsvr=Clarens.clarens_client('http://localhost:80/xmlrpc/clarens_server.py',certfile='/root/rpms/CA.crt',keyfile='/root/rpms/CA.key',debug=1) File "Clarens.py", line 280, in __init__ text_scert,crypt_server_nonce_64,crypt_user_nonce_64 = self.system.auth() File "xmlrpclib.py", line 821, in __call__ return self.__send(self.__name, args) File "xmlrpclib.py", line 975, in __request verbose=self.__verbose File "Clarens.py", line 178, in request errcode, errmsg, headers = h.getreply() File "httplib.py", line 752, in getreply response = self._conn.getresponse() File "httplib.py", line 595, in getresponse response.begin() File "httplib.py", line 119, in begin line = self.fp.readline() This also occurs when i press Ctrl+C. Otherwise the python script just hangs up.Can somebody tell me how this error can be removed? Ive already tried reinstalling the python2 rpm, the py-xmlrpc rpm and mod_python, but still it doesnt work. Tahir. From bgailer at alum.rpi.edu Tue Jul 8 14:23:52 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 08 Jul 2003 12:23:52 -0600 Subject: Collective memory In-Reply-To: References: <3F09F136.6060000@srv.net> Message-ID: <5.2.1.1.0.20030708122151.023d59b8@66.28.54.253> At 03:48 AM 7/8/2003 -0500, Richard Steiner wrote: >Here in alt.folklore.computers, >Dennis Lee Bieber spake unto us, saying: > > >Kevin Handy fed this fish to the penguins on Monday 07 July 2003 03:16 > >pm: > > > >> In FORTRAN, certial columns were allocated to specific purposes. > >> 1-5 for the line number, 6 for comment/continuation, 7-75 for the > >> program line, 76-80 for sequence numbers. [iirc] > > > > > > C in 1 for Comment > >Or an "*" in some compilers. > > > Anything in 6 for Continuation > >...except a space. :-) Or the digit zero! I got caught by that when sequentially numbering continuation lines in col 6: 1,2,3,4,5,6,7,8,9,0... when it hit 0 the compiler saw it as a new line. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From pheniks at softhome.net Sun Jul 13 11:09:48 2003 From: pheniks at softhome.net (Sage) Date: 13 Jul 2003 17:09:48 +0200 Subject: installing python library modules (general question) In-Reply-To: <20030713140624.30781.77624.Mailman@mail.python.org> References: <20030713140624.30781.77624.Mailman@mail.python.org> Message-ID: <1058108988.29786.5.camel@reality.page.za.net> This might be a long shot, but try making symlink(s) to the libraries in your /usr/lib path cd /usr/lib ; ln -s /usr/local/lib/libmad.so.0 (you'll need to be root to do that) Other than that, see if you can import the module if you are root. Does your user account have access right to the lib in question? > From: juliagoolia301 at hotmail.com (Julia Goolia) > Subject: installing python library modules (general question) > Date: 13 Jul 2003 06:42:59 -0700 > Organization: http://groups.google.com/ > To: python-list at python.org > > Hi, > > I'm sure this issue has been brought up a billion times... but I'm > having trouble installing a python module. I have read all the > documentation for all the buzz words I know related to this problem > but to no avail. > > Basically I downloaded a python module called pymad. This module is > supposed to be simplified API to libmad (an mp3 decoder) (I want to > play mp3's from python). > > I installed libmad. The libraries appear to be in /usr/local/lib. I > did all the distutils stuff for the module. Now when I try to "import > mad" I get an ImportError exception: > > ImportError: libmad.so.0: cannot open shared object file: No such file > or directory > > I know the file /usr/local/lib/libmad.so.0 exists, but python can't > seem to find it. I tried adding this path to LD_LIBRARY_PATH, but > that didn't help. > > I guess that I just really dont' know enought about libraries and > linux (redhat 9). I don't really know where they are supposed to go > after being compiled, and how python "loads" and uses them. > > Any help is much appreciated, > Julia > From usenet_spam at janc.invalid Tue Jul 15 14:32:46 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 15 Jul 2003 18:32:46 GMT Subject: wxPython - question References: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> <4737hvob87b2699fvqkhl61i9ufqm1jnc4@4ax.com> Message-ID: Tim Roberts schreef: > but the same thing could be achieved by plopping up a dialog box. That's why almost everybody is using a pop-up stopper these days. ;-p Most people don't like dialog boxes to pop up unexpectedly when they are concentrating on their work or a game or ... Tray icons for IM clients are also often used for visual feedback about things like connection state. OTOH, some other programs do indeed have useless tray icons... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From max at alcyone.com Sun Jul 13 16:42:23 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Jul 2003 13:42:23 -0700 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <3F11C42F.5030406@alcyone.com> David McNab wrote: > In Python, basic types like strings and numbers are a weird exception to > the 'everything is an object' rule. > > When you pass any other object in a function, the function gets a ref to > that object. > > But when you pass a string or numeric object, the whole thing (not a ref) > gets passed. This is completely incorrect. On the contrary, builtin types are handled exactly uniformly in Python. The only difference here is that the builtin types that you've listed, along with some others, are immutable, so you cannot change them if you have a reference to them. Contrast this to, say, Java, where there really is a solid distinction between builtin fundamental types, like int and long, and actual object types, derived from java.lang.Object, which are all passed by reference. Python doesn't make this distinction. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ But who shall dwell in these worlds if they be inhabited? \__/ Johannes Kepler From sigurd at 12move.de Thu Jul 3 16:14:36 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu, 03 Jul 2003 22:14:36 +0200 Subject: Emacs + py-mode + tkinter problem References: Message-ID: On 3 Jul 2003, Thomas G?ttler <- guettler at thomas-guettler.de wrote: > the interactive prompt from a terminal. Since I am quite happy > I would like to konw why you want the python interpreter in emacs? Because it's much more convenient if you needn't leave the editor. Editing is also a lot more comfortable. KP -- Der wahre Weltuntergang ist die Vernichtung des Geistes, der andere h?ngt von dem gleichgiltigen Versuch ab, ob nach der Vernichtung des Geistes noch eine Welt bestehen kann. Karl Kraus 'Untergang der Welt durch schwarze Magie' From andy at wild-flower.co.uk Wed Jul 23 18:22:19 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Wed, 23 Jul 2003 23:22:19 +0100 Subject: The global statement In-Reply-To: References: Message-ID: <200307232322.19827.andy@wild-flower.co.uk> Gentlepeople, I found it easier to envisage the Python global statement as the inverse of the Pascal/Modula/C concept: In traditional (compiled procedural) languages, one *declares* a variable at the 'top-level' scope, and then uses it as one would a local variable in functions/procedures, but without declaring it again. Global variables in these types of languages are treated differently in most respects (where they are stored for example: heap rather than stack, usually). There is usually no special notation, however, to enable the reader (especially one not skilled in the language at hand) to determine that a given variable is, in fact, global or local: you have to know the scoping rules of the language. If you define a variable outside of a function, it's global (notwithstanding the placement/sequencing rules for that language). Python is different (as always). It allows you to *read* the value (pardon the over-simplification) of variables declared at the 'top level', that is, created outside of a function, but you can't *write* to it without first telling Python that you wish to do so (by using the global statement): forgetting to do so results in the creation of a similarly named local variable, with no relation whatsoever to the intended global variable. I tend to think of it as 'telling python it's ok to change' the variable. pascal; var a_global: integer; function read_a_global; begin read_a_global:=a_global; (* return the value of global variable *) end; procedure modify_a_global; begin a_global:=10; (* modify global variable *) end; end. #python: a_global=1 def read_a_global(): return a_global # REFERENCE the global variable def cant_modify_a_global(): a_global = 10 # makes a local variable called a_global # which disappears after this point: def modify_a_global(n): global a_global # Makes a_global locally accessible for modifying a_global = 10 # top-level a_global variable is modified When I first tried to do this sort of thing in python, i wrote: global a_global def modify_a_global(): a_global=10 ...and wondered why it didn't work. I admit that the docs didn't really help much either, as they don't tell you to put the statement *inside* the function that needs to modify the variable! I only finally understood by reading some of the standard library code, after searching it for the word 'global' itself! just my 2p... hope that helps -andyj From mhammond at skippinet.com.au Thu Jul 31 19:02:03 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 01 Aug 2003 09:02:03 +1000 Subject: How to get Windows physical RAM using python? In-Reply-To: References: Message-ID: Why not submit that as a patch to win32all ? Mark. Bengt Richter wrote: > On Wed, 30 Jul 2003 23:04:56 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: > > >>Mark wrote: >> >> >>>OK, How to check the amount of Windows physical RAM using python? >> >>You should call the GlobalMemoryStatus(Ex) function. To my knowledge, >>there is no Python wrapper for it, yet, so you would need to write one. >> >>Regards, >>Martin >> > > ====< memorystatus.c >============================================= > /* > ** memorystatus.c > ** Version 0.01 20030731 10:45:12 Bengt Richter bokr at oz.net > ** > */ > > #include "Python.h" > #include > > static char doc_memstat[] = > "Returns list of 7 integers:\n" > " [0]: percent of memory in use\n" > " [1]: bytes of physical memory\n" > " [2]: free physical memory bytes\n" > " [3]: bytes of paging file\n" > " [4]: free bytes of paging file\n" > " [5]: user bytes of address space\n" > " [6]: free user bytes\n"; > > static PyObject * > memorystatus_memstat(PyObject *self, PyObject *args) > { > PyObject *rv; > MEMORYSTATUS ms; > GlobalMemoryStatus( &ms ); > > if (!PyArg_ParseTuple(args, "")) /* No arguments */ > return NULL; > rv = Py_BuildValue("[i,i,i,i,i,i,i]", > ms.dwMemoryLoad, // percent of memory in use > ms.dwTotalPhys, // bytes of physical memory > ms.dwAvailPhys, // free physical memory bytes > ms.dwTotalPageFile, // bytes of paging file > ms.dwAvailPageFile, // free bytes of paging file > ms.dwTotalVirtual, // user bytes of address space > ms.dwAvailVirtual // free user bytes > ); > return rv; > } > > /* List of functions defined in the module */ > static struct PyMethodDef memorystatus_module_methods[] = { > {"memstat", memorystatus_memstat, METH_VARARGS, doc_memstat}, > {NULL, NULL} /* sentinel */ > }; > > > /* Initialization function for the module (*must* be called initmemorystatus) */ > static char doc_memorystatus[] = "Get win32 memory status numbers (see memstat method)"; > > DL_EXPORT(void) > initmemorystatus(void) > { > PyObject *m, *d, *x; > > /* Create the module and add the functions */ > m = Py_InitModule("memorystatus", memorystatus_module_methods); > d = PyModule_GetDict(m); > x = PyString_FromString(doc_memorystatus); > PyDict_SetItemString(d, "__doc__", x); > Py_XDECREF(x); > } > =================================================================== > > You may find a little .cmd file like this (tailored to your system) handy: > > [10:55] C:\pywk\ut\memorystatus>type \util\mkpydll.cmd > @cl -LD -nologo -Id:\python22\include %1.c -link -LIBPATH:D:\python22\libs -export:init%1 > > [10:56] C:\pywk\ut\memorystatus>mkpydll memorystatus > memorystatus.c > Creating library memorystatus.lib and object memorystatus.exp > > [10:56] C:\pywk\ut\memorystatus>python > > (I'll indent this one space to avoid spurious quote highlights) > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import memorystatus > >>> help(memorystatus) > Help on module memorystatus: > > NAME > memorystatus - Get win32 memory status numbers (see memstat method) > > FILE > c:\pywk\ut\memorystatus\memorystatus.dll > > FUNCTIONS > memstat(...) > Returns list of 7 integers: > [0]: percent of memory in use > [1]: bytes of physical memory > [2]: free physical memory bytes > [3]: bytes of paging file > [4]: free bytes of paging file > [5]: user bytes of address space > [6]: free user bytes > > DATA > __file__ = 'memorystatus.dll' > __name__ = 'memorystatus' > > > >>> memorystatus.memstat() > [0, 334929920, 271536128, 942825472, 861339648, 2147352576, 2129780736] > > Warning: Just now did this. Not tested beyond what you see!! > > Regards, > Bengt Richter From guettler at thomas-guettler.de Thu Jul 24 06:12:18 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 24 Jul 2003 12:12:18 +0200 Subject: zope ZMySQLDA References: Message-ID: Don Rivard wrote: > zope 2.71b > ZMySQLDA 2.08 > MySQL-python-0.9.2 > mysql 3.23.55NT > > When I attempt to connect, by creating a Add Z MySQL Database Connection, > I set the connection string > to database user password, and i keep getting the following error > Site Error > An error was encountered while publishing this resource. > > Error Type: AttributeError > Error Value: server_capabilities Hi, If you want to see the stacktrace in error messages put in the standard_error_message of Zope. This needs to be done trough the web and is very handy for debugging. The stacktrace shows you the file and the line where the error occured. Maybe this helps you to find your problem. thomas From mis6 at pitt.edu Thu Jul 31 12:53:45 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 31 Jul 2003 09:53:45 -0700 Subject: curses newwin Message-ID: <2259b0e2.0307310853.23972d6d@posting.google.com> I have just performed this experiment with curses: from curses import * maxwidth=79 maxheight=21 def wait4q(stdscr): scr=stdscr scr.addstr("Press 'q' to exit\n") x,y,=0,0 while True: c=scr.getch() if c==KEY_LEFT and x > 0: x-=1; scr.move(y,x) elif c==KEY_RIGHT and x < maxwidth: x+=1; scr.move(y,x) elif c==KEY_UP and y > 0: y-=1; scr.move(y,x) elif c==KEY_DOWN and y < maxheight: y+=1; scr.move(y,x) elif c==ord('q'): break if __name__=='__main__': wrapper(wait4q) It works fine and one can move the cursor on the screen. The question is: why that does not work for a generic window different from stdscr? i.e. if I replace the line ``scr=stdscr`` with ``scr=newwin(0,0)``I don't see the cursor moving anymore. The 'q' is still recognized, however. I tried with some refresh(), but didn't work. What I am missing? TIA, Michele From ambiod at sbcglobal.net Mon Jul 21 02:50:42 2003 From: ambiod at sbcglobal.net (ryan) Date: Sun, 20 Jul 2003 23:50:42 -0700 Subject: py2exe prob Message-ID: <001901c34f54$67f59220$58fb7243@h5p1n4> my program uses unicode functions and so i compile like: "python setup.py py2exe --packages encodings" which seems to create unicodedata.pyd and zlib.pyd, the problem is when i run my exe it acts like it didnt do that, it still gives me the error: ImportError: No module named warnings warning: assignment shadows builtin Traceback (most recent call last): File "", line 110, in ? File "", line 82, in main File "handle_keyboard.pyc", line 113, in handle_keyboard File "open_url.pyc", line 126, in open_url File "input_box.pyc", line 53, in ask File "input_box.pyc", line 21, in get_key LookupError: no codec search functions registered: can't find encoding also at the top of the error it said: ImportError: No module named warnings warning: assignment shadows builtin anyone know how to fix this or at least what it means? From mwh at python.net Tue Jul 22 14:18:29 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 18:18:29 GMT Subject: Check from C that Interpreter is running References: Message-ID: <7h3r84ixwib.fsf@pc150.maths.bris.ac.uk> Florian Schulze writes: > Hi! > > I want to check from C that the Python Interpreter is still running > and it's save to call things like PySys_GetObject, PyFile_WriteString > etc. I need this in a C function which might be called during shutdown > in a program embedding Python. Currently I get this error: > > Fatal Python error: PyThreadState_Get: no current thread > Abort! Py_IsInitialized? Cheers, mwh -- The proponent of the PEP shall be placed in a gladiatorial arena together with half a dozen hungry lions, and permitted to debate the merits of the proposal with them. -- Greg Ewing, comp.lang.python From alanmk at hotmail.com Sun Jul 6 09:29:57 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 14:29:57 +0100 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: <3F082455.D2E0FB@hotmail.com> Andrew Bennetts wrote: > C code is indented to reflect its structure, but uses braces to reflect > that structure. This is IMHO worse. > > if (something) > work(); > more_work(); > add_numbers(); Back in my C programming days (late 80s, 90s), I used to always indent my code python style anyway (before I even knew of the existence of python, ABC, etc). For example if (cond) { work(); more_work(); } else { other_work(); and_yet_more(); } And I still write all my java that way to this day. I occasionally got and get some complaints/ribbing from co-workers, who most often preferred a style like this :- if (cond) { work(); more_work(); } else { otherwork(); } But to me that was far less readable, especially when there are multiple nested if/switch/while/etc statements. OK, you can find out out where code blocks begin and end by using the bracket matching facilities available in most editors, but that's no use to you when you're reading a hard-copy printout, for example. And in practically every C job I ever did, I used to get compliments from "occasional programmers" (e.g. hardware engineers), who sometimes had to work with my code to make minor changes. They would say things like "your code is so easy to read", "I was able to find really quickly the bit that I needed to change", etc. It was only the full time programmers who complained, and they were generally from the "it was hard to write, it should be hard to read" camp. When I found python (oh serendipity :-), the indentation was completely natural to me, and I got it right from my very first if statement. It made my source look more readable, since it did away with all those lines containing only '{' and '}'. born-to-code-python-style-ly yrs :-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From aahz at pythoncraft.com Thu Jul 17 19:46:31 2003 From: aahz at pythoncraft.com (Aahz) Date: 17 Jul 2003 19:46:31 -0400 Subject: A challenge to the ASCII proponents. References: <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: In article <3F172442.2040907 at v.loewis.de>, Martin v. Loewis wrote: > >So what do you think about this message?: > >???????????????? Well, that renders as .......<1/2 symbol>.....o.. in trn3.6 running in a vt100 emulator window, and it renders as .......<1/2 symbol>.~I.~C.o.~I when I started up vi to follow up (again in the vt100 emulator). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From intentionally at blank.co.uk Sun Jul 13 15:39:56 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 20:39:56 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: On Sun, 13 Jul 2003 15:07:23 -0400, "Terry Reedy" wrote: >How a particular interpreter performs name binding is its own >business, as long as the specified semantics are implemented. You could use the same argument to rationalise a language which used the + operator to express subtraction. The fact is that 'assignment' has a common meaning separate from the choice of programming language, and that the way Python handles name binding means that meaning is not respected by Python for mutable objects. >What any computer does is >probably significantly different from what human interpreters do. And using references with a copy-on-write or lazy-assignment system is different to immediate copying of values, but that is irrelevent as both systems respect the common meaning of assignment. Python, however, does not respect this meaning. It uses an arbitrary distinction based on whether or not the object has internals that can be usefully in-place modified, and uses that distinction to vary the effect of assignment in an arbitrary, inconsistent and error-prone way. The need for a distinct tuple type is a symptom of the arbitrary nature of this. I've already posted too much on this, so this is going to be the end to it. But Pythons semantics with regard to mutable and immutable objects are simply bizarre. A historic justification may be plausible and backward compatibility is then an important issue, but I really cannot accept claims that Python is doing the right thing here. From theller at python.net Thu Jul 31 14:00:23 2003 From: theller at python.net (Thomas Heller) Date: Thu, 31 Jul 2003 20:00:23 +0200 Subject: Retrieve source filename References: <3f29207d$0$24768$626a54ce@news.free.fr> <3f2952da$0$49110$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong writes: > Shrom wrote: > >> I know that you can retrieve main file name with sys.argv[0] and file name >> for a module with modulename.__file__ but is there a common way to retrieve >> file name for both main program and modules as the __FILE__ constant in PHP >> ? > > I don't know if it's the "right" way, but this works: > > import inspect > print inspect.getfile(inspect.currentframe()) > This one should also work: if __name__ == "__main__": import sys __file__ = sys.argv[0] Thomas From JensRie at gmx.de Thu Jul 10 07:22:28 2003 From: JensRie at gmx.de (Jens Riedel) Date: Thu, 10 Jul 2003 13:22:28 +0200 Subject: Zope problem: objectValues('Folder') References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> <3F0D2405.1070606@gmx.de> <3F0D2EAC.2010605@mxm.dk> Message-ID: <3F0D4C74.5040304@gmx.de> The problem seems to be somewhere else: I used the objectValues('Folder')-method in a DTML-method named 'navigation'. I include in a 'standard_html_header' DTML method, and this standard_html_header is used in the index_html document. All three are in the same folder which contains 3 Subfolders. If I view 'navigation' or 'standard_html_header' in the management area, I see the 3 folders, but in the index_html they don't appear. Everything else in the standard_html_header, like stylesheets etc. are correctly shown so I'm sure that the correct standard_html_header is included. Jens From gregbrunet at NOSPAMsempersoft.com Thu Jul 31 20:59:11 2003 From: gregbrunet at NOSPAMsempersoft.com (Greg Brunet) Date: Thu, 31 Jul 2003 19:59:11 -0500 Subject: What does "*list" mean? References: Message-ID: "Raymond Hettinger" wrote in message news:mfiWa.308$W%3.168 at nwrdny01.gnilink.net... > Hmm, it sounds like the *args calling format > needs to be added to the tutorial. > > > Raymond Hettinger And also added to the index of the reference manual! I remember trying to figure it out the first time that I ran into it - it's pretty frustrating to not be able to look up these kinds of 'special' symbols. -- Greg From neil.padgen at mon.bbc.co.uk Mon Jul 28 11:45:39 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Mon, 28 Jul 2003 15:45:39 +0000 Subject: DOM as a flat dictionary References: <3f21335a_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: On Friday 25 July 2003 13:38, don't dash! wrote: > My thought was to generate a flat dictionary representation of the > foreign > and local formats with the absolute Xpath expression as dictionary > key. The user is presented with a list of elements&attributes in > the local file and > asked to select the foreign element|attribute fills that role. I > could then use the keys from this mapping to generate XSLT which can > be stored. > > Using dictionary keys means that duplicate elements will be lost, > but this is not problematic since I am attempting to map the > structure not the > content. What are the other implications of this approach? Or is > there an easier way to do what that I cannot find in Google? You'll lose any ordering of the elements. With the XML translated into a flat dictionary { '/spam': True, '/spam/eggs': True, '/spam/bacon': True, '/spam/lobster_thermidor': True, '/spam/lobster_thermidor/more_spam': True, } there is no way that you can tell whether /spam/eggs comes before /spam/bacon in the original XML. -- Neil From mgerrans at mindspring.com Wed Jul 23 03:59:32 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 23 Jul 2003 00:59:32 -0700 Subject: Python and VS.Net References: Message-ID: > > My boss seems to think it is good to have programs that are in managed > > code because it is more 'portable'. Not that there's another complete > > .NET runtime besides Microsoft's but he does not understand that. By the way, just because you compile something with the compiler that comes with .NET doesn't mean it is managed code. In particular, if you did compile Python with it, I don't think the result will be any more managed than the what you compiled with a previous version of the Microsoft compiler. Anyway, Python is *already* more portable than .NET and it is *already* managed code running in a "managed" environment. It is called the interpreter (or "virtual machine" in Sun's parlance, or "runtime" as Microsoft would have it -- "A rose is a rose is a rose is a rose."). If your Python code could thereby access the .NET libraries, that would be another story. That would be like Jython for .NET. I was hoping that was what Active State's Python-in-VS.NET-thingy was, but alas it was too good to be true: it is only (so far) a color-syntaxing Python editor that takes two or three minutes to load up. - Matt From puccio_13 at yahoo.it Mon Jul 21 05:55:49 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Mon, 21 Jul 2003 11:55:49 +0200 Subject: distutils.core not in Debian python2.2 package References: Message-ID: I wonder why the corresponding package python2.3-dev does not exist.. No distutils for python2.3 developers? -- bye Alessio Pace David M. Cooke wrote: > At some point, Kent Tenney wrote: > >> David M. Cooke wrote: >>> At some point, Kent Tenney wrote: >>> >>>>Howdy, >>>> >>>>I did; >>>># apt-get install python2.2 >>>> >>>># python >>>>Python 2.2.1 >>>>... >>>> >>> >>>> >>>>then checked docutils out of CVS >>>>and did; >>>> >>>>docutils# python ./setup.py install >>>> >>>>ImportError: No module named distutils.core >>>> >>>>How do I install distutils? >>> Install the python2.2-dev package. >> >> It surprises me to find distutils in a package described as: >> >> "Header files and a static library for Python (v2.2)" >> >> Kent > > > Except in the extended description, where it says > """ > Includes the python distutils, which were in a separate package up to > version 1.5.2. > """ > > In general, if you need to compile, or develop, you need the > corresponding *-dev packages. > From jjl at pobox.com Wed Jul 30 18:27:35 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 23:27:35 +0100 Subject: unittest problems References: <87el095733.fsf@pobox.com> Message-ID: <87k79z8xbc.fsf@pobox.com> Richard Wesley writes: [...] > worked and the main unit_test.py will run everything. I used your > code, driving it with the results of os.path.walk and parameterizing the [...] *My* code? Well, fine, I suppose, but probably Bernhard Herzog's & somebody else's posts there had better code... John From rastm2 at aol.commorespam Sun Jul 20 14:36:06 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 18:36:06 GMT Subject: List of declared variables in interactive Python session? References: Message-ID: <20030720143606.18124.00000262@mb-m15.aol.com> >> Hello. >> >> Is there a way to list all the declared variables in an interactive >> Python session? > >use "vars() " > >HTH, > >Vincent Wehren > >> >> Thanks, >> Fredrik >> > > I got one for ya. I read some where that when the dir( ) has a lot of stuff in it, it is convenient to use a for loop to see the contents. (example follows) Now the reason for my 2 cents in this post. >>> >>> dir( ) ['__builtins__', '__doc__', '__name__', 'pywin'] >>> for d in dir(): print d ... __builtins__ __doc__ __name__ pywin >>> vars( ) {'d': 'pywin', '__builtins__': , '__name__': '__main__', 'pywin': , '__doc__': None} >>> for v in vars(): print v ... d ### prints the first variable I declared in the first for loop then Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration ### opps no v in the dir( ) so... >>> for v in vars(): print v ... d v __builtins__ __name__ pywin __doc__ >>> You can see that you can print the same kind of display for vars( ) as you can for the dir( ), so long as your iterater variable is declared previous to the for loop. Ray St.M Proudly stating the obvious since birth. From mgerrans at mindspring.com Mon Jul 14 15:14:38 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 14 Jul 2003 12:14:38 -0700 Subject: some questions References: <3f12f613$0$8731$9b622d9e@news.freenet.de> Message-ID: "Andreas Bauer" wrote: > I need some information on how to deal with strings which I have > divided by using split(). I'm new to python and don't know how to > handle these split up strings. Hmm, doesn't that kind of depend on what you want to do with them? > And I some one could recommend a good tutorial I would be very > glad. Where have you already looked? Have you tried "Python tutorial" on google? Have you tried Python.org? Python itself comes with a tutorial (maybe you are unaware of this, or maybe you want another?). > Can't hardly find any. Was ist das? Can't or can? Or do you really mean "Can't hardly find nothin'?" ;-) From max at alcyone.com Fri Jul 18 00:54:10 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 21:54:10 -0700 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <3F177D72.FF10EAEA@alcyone.com> "Martin v. Loewis" wrote: > So what do you think about this message?: > > [non ASCII characters] > > Look Ma, no markup. Yeah, but that only works if everyone's expecting the same encoding. I just see garbage non-ASCII characters, for instance, with my lowly Netscape 4 newsreader. > And not every character uses two bytes, either. Looked like it was probably was here, I saw what looked very strongly like eight double-byte characters (and two bytes each). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Wretches hang that jurymen may dine. \__/ Alexander Pope From news at garthy.com Thu Jul 24 16:18:53 2003 From: news at garthy.com (Garth) Date: Thu, 24 Jul 2003 21:18:53 +0100 Subject: possible error in socketmodule / asyncore on win32 Message-ID: Hi, I think there's an error in ther socketmodule.c code under windows. The code in internal connect should test exceptfds to check for connecttion refused. If this is so it should call getsockopt(SOL_SOCKET, SO_ERROR,..) to get the error status. (Source microsoft Platform SDK) If this isn't then the asynccore module fails on windows and never returns connection refused. The code should probably look something like this (untested) if (s->sock_timeout > 0.0) { if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) { /* This is a mess. Best solution: trust select */ fd_set exfds; struct timeval tv; tv.tv_sec = (int)s->sock_timeout; tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); FD_ZERO(&exfds); FD_SET(s->sock_fd, &exfds); /* Platform SDK says so */ res = select(s->sock_fd+1, NULL, NULL, &exfds, &tv); if (res == 0) { if( FD_ISSET( &exfds ) ) { /* Get the real reason */ getsockopt(s->sock_fd,SOL_SOCKET,SO_ERROR,(char*)&res,sizeof(res)); } else { res = 0; } } else if (res > 0) { res = WSAGetLastError(); } } } else if (res < 0) res = WSAGetLastError(); This still doesn't solve the problem in asyncore as it doesn't test exfss. I guess it should test exfs if it's not connected (again not tested) def poll(timeout=0.0, map=None): if map is None: map = socket_map if map: r = []; w = []; e = [] for fd, obj in map.items(): if obj.readable(): r.append(fd) if obj.writable(): w.append(fd) if sys.platform == 'win32': if not obj.connected: e.append(fd) if [] == r == w == e: time.sleep(timeout) else: try: r, w, e = select.select(r, w, e, timeout) except select.error, err: if err[0] != EINTR: raise else: return if sys.platform == 'win32': for fd in e: obj = map.get(fd) if obj is None: continue errno = fs.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) raise socket.error,(errno,socketerrorTab[error]) for fd in r: obj = map.get(fd) if obj is None: continue read(obj) for fd in w: obj = map.get(fd) if obj is None: continue write(obj) Not really sure where to report this so I'm posting here. This is all against 2.3c1 (Cheers to all for a wicked language.) Garth From usc_dog at yahoo.com Tue Jul 29 14:54:16 2003 From: usc_dog at yahoo.com (q) Date: 29 Jul 2003 11:54:16 -0700 Subject: Python..Tkinter..PYTHONPATH.. Message-ID: Hi... I have a Linux RH8.0 system. I installed Python2.2 from the 8.0 ISO updates. I installed the Tcl 8.3.3 from the Tcl site... I also installed the tcllib 1.0. My goal is to get viewcvs to run. However, when I check to see where the system thinks things are, the PYTHONPATH env var is blank. echo $PYTHONPATH --> produces nothing.... So, can anyone tell me what it should say? Can anyone shed any light as to how this var is populated, and why it might be blank....? Can anyone suggest what file I need to alter/should modify to have this properly set whenever a user logs into the system....? Thanks Bruce bedouglas at earthlink.net From skip at pobox.com Mon Jul 21 01:55:16 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 21 Jul 2003 00:55:16 -0500 Subject: PythonQuestions forum - does it exist? In-Reply-To: References: Message-ID: <16155.32836.938522.634@montanaro.dyndns.org> Alex> I'm wondering if there is a help forum for Python on the web Alex> similar to LinuxQuestions.org? There's no web-based forum that I'm aware of, however there are a number of resources: tutor at python.org - subscribe at http://mail.python.org/mailman/listinfo/tutor help at python.org - no need to subscribe - just post your questions The newbies page - lots of pointers - http://www.python.org/doc/Newbies.html Skip From gh at ghaering.de Thu Jul 17 11:43:03 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 17 Jul 2003 17:43:03 +0200 Subject: what u'=' mean??? In-Reply-To: <200307171224.57003.cybersamurai@mac.com> References: <200307171224.57003.cybersamurai@mac.com> Message-ID: <3F16C407.702@ghaering.de> Luiz Siqueira Neto wrote: > What > ---- > u'=' > ---- > mean?? [...] It's a Unicode string literal. Unicode strings are explained in the tutorial here: http://python.org/doc/current/tut/node5.html#SECTION005130000000000000000 -- Gerhard From ronald at PassTheDairy.net Thu Jul 3 13:34:18 2003 From: ronald at PassTheDairy.net (BearMan) Date: Thu, 03 Jul 2003 17:34:18 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: Agreed... From Adrien.DiMascio at logilab.fr Fri Jul 4 06:51:56 2003 From: Adrien.DiMascio at logilab.fr (Adrien Di Mascio) Date: Fri, 4 Jul 2003 12:51:56 +0200 Subject: Question about "exec in globals, locals" In-Reply-To: <57de9986.0307040041.553ff329@posting.google.com> References: <57de9986.0307040041.553ff329@posting.google.com> Message-ID: <20030704105156.GB19558@logilab.fr> Hi, > source = """ > class FirstClass: > pass > class SecondClass: > References = [FirstClass] > """ When you specify both locals() and globals(), here's what happen : """ class FirstClass: pass ## ---------> Here, your locals() dict have been updated, but not your ## globals() one. ## But, here, you can do : References = [FirstClass] since your ## locals() ## know about 'FirstClass' class SecondClass: ## ---------> Here, your locals() dict is a new one since you've just ## entered a new scope. So, 'FirstClass' is neither defined in ## 'locals()' nor in 'globals()', that's why you have your NameError """ I'm not quite sure of my explanation, but that could explain your problem. Sorry if I've made any Python mistake. Cheers, -- Adrien Di Mascio LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From thedustbustr at aol.com Fri Jul 25 09:03:37 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 25 Jul 2003 13:03:37 GMT Subject: generator within a generator doesn't execute? Message-ID: <20030725090337.24383.00000414@mb-m16.aol.com> from __future__ import generators from time import time threads=[] def xsleep(n): t=time() while (t+n>time()): yield None def sleep(n): for i in xsleep(n): pass def cutscene(): yield None #start on second pass print "\nEvil Death Knight: I will kill you now!" sleep(1.5) #t=time() #while (t+1.5>time()): yield None print "\nOur Hero: I shall fight you to the death. Bring it on!" sleep(3) #t=time() #while (t+3>time()): yield None print "\nEnd of cutscene." def ticker(): yield None #wait till second time through print "." t=time() while 1: while (t+.5>time()): yield None t=time() #sleep(.5) print "." def scheduler(): global threads try: while 1: for thread in threads: thread.next() except StopIteration: pass if __name__=="__main__": threads.append(ticker()) threads.append(cutscene()) scheduler() I added xsleep() (a generator) and modified sleep() (now, not a generator). cutscene() works as expected. Why does sleep() block execution of ticker()? Shouldn't xsleep() yield to the scheduler to allow ticker() to run? Is there any way, save using Stackless Python microthreads, to make the sleep function 'just work' transparently? From fredrik at pythonware.com Wed Jul 2 06:05:29 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Jul 2003 12:05:29 +0200 Subject: arbitrary long integer aritmetics References: Message-ID: "Leo" wrote: > is there a python module around allow using arbitrary long integers? nope, but it's built into the language: http://www.python.org/doc/current/ref/integers.html http://www.python.org/doc/current/ref/types.html > i.e. the result of an integer operation is as long as necessary, so that a*b > never produces an overflow error. what's an overflow error? ;-) $ python Python 2.2 >>> import sys >>> sys.maxint 2147483647 >>> 2147483647 * 2147483647 * 2147483647 4611686014132420609L (note the trailing L). From jack at performancedrivers.com Tue Jul 22 06:26:22 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 22 Jul 2003 06:26:22 -0400 Subject: Python Mystery Theatre -- Episode 3: Extend this In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4DD@hendrix.empolisuk.com>; from hst@empolis.co.uk on Tue, Jul 22, 2003 at 10:49:41AM +0100 References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4DD@hendrix.empolisuk.com> Message-ID: <20030722062622.A1208@localhost.localdomain> On Tue, Jul 22, 2003 at 10:49:41AM +0100, Harvey Thomas wrote: > Raymond Hettinger wrote: > > i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1 > > It's a quick and dirty bubble sort. Not sure what's wrong without running the code, but it looks wrong to mess around with the loop indices. Perhaps the swapping line should read > a[i], a[j], swaps = a[j], a[i], swaps+1. BTW isn't there an indentation error in the code? > > I didn't bother checking if the side effect in that line was ruinous or not, but it certainly is frightening. Here is my test of the same abuse >>> l = list('abc') >>> l ['a', 'b', 'c'] >>> (i, l[i], i, l[i]) = (0,'X',1,'Y') >>> l ['X', 'Y', 'c'] Could we call that undefined, just to scare people from using it? Showing up to their office with a bat is sometimes impractical. -jack From mcherm at mcherm.com Wed Jul 2 19:06:58 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 2 Jul 2003 16:06:58 -0700 Subject: Clever One Liners Message-ID: <1057187218.3f036592c353c@mcherm.com> Hannu Kankaanp?? writes: > Could be even written as a perverted one-liner. I'm not picking on you in particular, there have been several people doing this lately, but I'd like to ask folks to please lay off the quest for one-liners. I understand the neat, oh-so-clever feeling one gets by trying to cram the most functionality into the least space, but if you're going to try that, do it in Perl (or better yet, APL) where it works so much better. I'm not putting down the exercise... I realize that it's all in good fun... but people who are new to Python and who read this newsgroup might get the wrong idea if they see a clever one-liner proposed as the solution for every easy question. It's simply NOT Pythonic to try to write clever one-liners, and we don't want to let newbies think it's appropriate. > ...Maybe a real 'for' loop for getting the words would be better > in this case though. So that the input could be verified too. See, I can bring this up in response to Hannu's posting without pointing fingers since he clearly understands (and points out) the advantages of a less compact style. Donning-my-asbestos-suit-now lly, -- Michael Chermside From djc at object-craft.com.au Thu Jul 17 00:44:44 2003 From: djc at object-craft.com.au (Dave Cole) Date: 17 Jul 2003 14:44:44 +1000 Subject: Documentation examples needed References: Message-ID: >>>>> "Stuart" == Stuart D Gathman writes: Stuart> I am still wanting to produce Python standard format Stuart> documentation for Python extensions I have written. I have Stuart> looked at the docs that come with Python itself, but I am new Stuart> to Latex, and don't know how to add the document classes and Stuart> styles from texinput for a new project. Stuart> Is there a small project with documentation in the Python Stuart> standard that I can use as an example? We have some: http://www.object-craft.com.au/projects/albatross/ http://www.object-craft.com.au/projects/sybase/sybase/ - Dave -- http://www.object-craft.com.au From peter at engcorp.com Thu Jul 3 12:28:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 12:28:40 -0400 Subject: 'For' loop symmetry with list comprehensions. References: <840592e1.0307021036.508d7d7d@posting.google.com> Message-ID: <3F0459B8.A8E5FF54@engcorp.com> Hannu Kankaanp?? wrote: > > One can currently say this with list comprehensions: > > [x.lower() for x in words if x.startswith('foo')] > > Wouldn't it be better if the normal 'for' syntax was symmetrical > with the notation used in list comprehensions? To be more specific, > it lacks the 'if' part. I.e. this should be possible: > > for x in words if x.startswith('foo'): > print x > > Naturally this is the same as: > > for x in words: > if x.startswith('foo'): > print x My brain tends to parse the one-line statement form of the syntax (which works so nicely in the list-comprehension expression) in a different way: for x in words if x.startswith('foo'): print x looks more like it is just another way to say: if x.startswith('foo'): for x in words: print x Besides, hasn't everyone got the idea lately that it should require a *very strong* benefit to even begin to consider discussion another change in Python syntax? Why do people keep suggesting what amount to trivial tweaks which will _never_ pay back the effort that would have to go into the discussion and the changes to the compiler, the documentation, and everything else, before this would ever be accepted? -Peter From legere at ll.mit.edu Tue Jul 29 08:32:14 2003 From: legere at ll.mit.edu (Ronald Legere) Date: Tue, 29 Jul 2003 08:32:14 -0400 Subject: Itertools Message-ID: The new itertools stuff is pretty cool. One thing that bothers me though is that there seems to be no way to copy an iterator. How does one work around this? Is there a trick that I am missing? Without being able to 'split' an iterator, I can't think of how to do some of the cool things you can do with lazy lists in Haskell. It seems quite often you want to be able to do this 'splitting', and if I had more coffee I would post an example :) The ones I can think of are also defined recursively, which is another kettle of fish. But I hope that someone knows what I am talking about and has thought of a way... Cheers! From andy47 at halfcooked.com Thu Jul 31 10:23:50 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Thu, 31 Jul 2003 15:23:50 +0100 Subject: SQL2000 database vs python In-Reply-To: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> References: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Ok I was too happy. > > mssqldb doesn't help me to connect my python app on a linux OS to a sql2000 (windows os) database. > I can't even compile the package, I guess it is missing sybase stuff (sybdb.h and sybfront.h), > which is correct because I don't have that database. > Also, mssqldb supports ms sql server 7.0, my hope is that that won't be a problem in using ms sql 2000. > > Pfew, there goes my hope. > > Vincent > [snip] Have you looked at mxODBC? It will allow you to connect via ODBC from linux to SQL Server running on a Windows server. http://www.egenix.com/files/python/mxODBC.html Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From mis6 at pitt.edu Sat Jul 5 09:11:51 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Jul 2003 06:11:51 -0700 Subject: Gathering variable names from within a function. References: Message-ID: <2259b0e2.0307050511.55253683@posting.google.com> "Xavier" wrote in message news:... > Greetings, > > I was wondering if there was a way to get a list of all the variables which > were executed/created/modified within a function? > > Here is a simple example that comes to my mind: > > def getVars(func): > ... > ... > ... > > def modVar(arg, arg2): > > Var1 = arg > Var2 = arg2 > Var3 = arg+arg2 > return Var3 > > def main(): > > print getVars(modVar('test', 'test2')) > > # end > > naturally, "Var1", "Var2" and "Var3" should be printed to the user. Any > idea? > What about def modVar(arg, arg2): Var1 = arg Var2 = arg2 Var3 = arg+arg2 print vars() return Var3 modVar('test', 'test2') => {'arg2': 'test2', 'arg': 'test', 'Var1': 'test', 'Var3': 'testtest2', 'Var2': 'test2'} > -- Xavier > > oderint dum metuant Michele From abcdebl2nonspammy at verizon.net Fri Jul 18 00:31:32 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Fri, 18 Jul 2003 04:31:32 GMT Subject: Regular expression help In-Reply-To: References: Message-ID: Andrew Bennetts wrote: > On Thu, Jul 17, 2003 at 04:27:23AM +0000, David Lees wrote: > >>I forget how to find multiple instances of stuff between tags using >>regular expressions. Specifically I want to find all the text between a > > ^^^^^^^^ > > How about re.findall? > > E.g.: > > >>> re.findall('BEGIN(.*?)END', 'BEGIN foo END BEGIN bar END') > [' foo ', ' bar '] > > -Andrew. > > Actually this fails with the multi-line type of file I was asking about. >>> re.findall('BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') [' bar '] From david.isal at wanadoo.fr Fri Jul 11 09:58:16 2003 From: david.isal at wanadoo.fr (David Isal) Date: Fri, 11 Jul 2003 15:58:16 +0200 Subject: Python extension on Windows Message-ID: hi all, i'm new to python and i'm trying to build a python extension on win98, written in c++, with cygwin. but i keep having the same error message, and i didnt't find much resources on the web about it: >g++ -I/cygdrive/c/python22/include -c demomodule.cpp -o demomodule.o In file included from /cygdrive/c/python22/include/Python.h:62, from demomodule.cpp:1: /cygdrive/c/python22/include/pyport.h:480:2: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." i read that it is mandatory to use Micro$oft visual c++ to build any extensions on windows beacuse it's the same compiler used to build python for windows. does anybody has advices about that? i would rather use cygwin/g++ but i don't know if it's possible or how to fix this error message. thanks in advance, David. From johnfabel at btinternet.com Tue Jul 8 15:00:31 2003 From: johnfabel at btinternet.com (John Abel) Date: Tue, 08 Jul 2003 20:00:31 +0100 Subject: win32security.LogonUser In-Reply-To: <20030708171923.6788.qmail@web21414.mail.yahoo.com> References: <20030708171923.6788.qmail@web21414.mail.yahoo.com> Message-ID: <3F0B14CF.6040102@btinternet.com> OK, try adding it to "Replace A Process Level Token" (sorry about this, when I was trying to get my FTP server running, I forgot to write down, which ones I'd changed. Doh!) Here's the code I'm using, to adjust the tokens, and the calls that I make: self.AdjustPrivilege( ntsecuritycon.SE_CHANGE_NOTIFY_NAME ) self.AdjustPrivilege( ntsecuritycon.SE_ASSIGNPRIMARYTOKEN_NAME ) self.AdjustPrivilege( ntsecuritycon.SE_TCB_NAME ) def AdjustPrivilege( self, priv ): flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) id = win32security.LookupPrivilegeValue(None, priv) newPrivileges = [(id, ntsecuritycon.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) Darrell Gallion wrote: >Thanks John > >That was done with no luck. >Added it to Administrators and Administrator. > > > >__________________________________ >Do you Yahoo!? >SBC Yahoo! DSL - Now only $29.95 per month! >http://sbc.yahoo.com > > > From not.valid at address.org Wed Jul 2 16:04:53 2003 From: not.valid at address.org (not your business) Date: Wed, 02 Jul 2003 20:04:53 GMT Subject: How Do You Get Redirected Input? References: <3f0333b6$0$49116$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > not your business wrote: >> I have a shell tool that accepts arguments on the command line. I would >> like >> to check if the input is being piped in. That is, >> >> $ mytool.py < cmdlst.txt >> >> In this case sys.argv is empty. So I added >> >> pipein = os.read(sys.stdin.fileno(),256) >> if (pipein): >> input_args = pipein.split() >> else: >> input_args = sys.argv[1:] >> >> Problem is that if nothing is redirected in, the script waits for a Enter >> pressed on the the keyboard. Anyone know a solution to this? Thanx in >> advance for any help. > > Why not turn it around? First check if sys.argv is *not* empty, > in which case the user provided command line arguments, and > proceed to parse those. Otherwise (if sys.argv *is* empty), > assume the input is piped in and proceed to read the standard > input. > > --Irmen Okay, but there still seems to be a problem. Lets say you typed $ mytool.py If sys.argv[1:] is empty, I want to display help. But if I'm checking for redirected input by my problematic method next, the script hangs, again, waiting for a Enter to be pressed and the user, therefore, doesn't my usage help. I think I need to find a way to test for redirected input without the actual os.read() thing. One hack that came to mind was to fork() a seperate process to do this and pipe back within a time period any results. The parent could just go on if no response. But that seems a little extreme (and ugly) plus it's platform dependent unless, I guess, I it do it with threads. From pinard at iro.umontreal.ca Fri Jul 11 19:38:44 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 11 Jul 2003 19:38:44 -0400 Subject: call one python script from within another In-Reply-To: References: Message-ID: [Tubby Tudor] > What is the best way to call one python script from within another python > script? For example: one.py finishes succesfully and calls two.py which > finishes OK and then calls three.py I do not know if my way is the best way :-), but the following goes fine for us. Each of our programs is installed (through `distutils') as a small bootstrap, on the loader search path, looking like: ----------------------------------------------------------------------> #!/usr/bin/env python # [...] """\ SHORT_DESCRIPTION. """ import sys from PACKAGE.MODULE import main main(*sys.argv[1:]) ----------------------------------------------------------------------< and within the main MODULE for the PACKAGE holding the application, we have: ----------------------------------------------------------------------> #!/usr/bin/env python # [...] """\ LONGER_DESCRITPION. """ [...] def main(*arguments): [...] if __name__ == '__main__': main(*sys.argv[1:]) ----------------------------------------------------------------------< We often use this instead, when the complexity warrants it: ----------------------------------------------------------------------> #!/usr/bin/env python # [...] """\ LONGER_DESCRITPION. """ [...] class Main: [...] def main(self, *arguments): [...] run = Main() main = run.main [...] if __name__ == '__main__': main(*sys.argv[1:]) ----------------------------------------------------------------------< So very systematically, one may call any `main' giving, as string arguments, what would be successive arguments in a shell command calling that program. When a Python program needs to "execute" another Python program, it often does something like: ----------------------------------------------------------------------> [...] import PACKAGE.MODULE PACKAGE.MODULE.main(ARGUMENT1, ARGUMENT2, ...) ----------------------------------------------------------------------< The only reason we would prefer to `exec' or `fork' another Python process would be to reclaim the storage taken by the imported package modules code, in the rather unusual cases it would matter. As for the rest of the data, we merely rely on the garbage collector. If we were in your situation, it is likely that a small driver would successively call the three programs as above, one after the other. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From klapotec at chello.at Thu Jul 31 23:45:44 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 01 Aug 2003 03:45:44 GMT Subject: time, calendar, datetime, etc References: Message-ID: On Thu, 31 Jul 2003 22:49:28 -0400, "Tim Peters" wrote: >The time module consists of thin wrappers around C's mish-mash of quirky, >platform-dependent time manipulation functions. We eventually want to >pretend the time module never existed <0.9 wink>. 9-tuples are absurd. No, it's reality that's absurd. C's mish-mash of quirky, platform-dependent time manipulation stems from the fact that defining a standard way of handling time is difficult when it's 1. subject to the platform designers interpretation of what is useful, 2. subject to politics and most severely, 3. subject to changes in nature. Leap seconds! --Christopher From mgerrans at mindspring.com Fri Jul 18 02:40:22 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 17 Jul 2003 23:40:22 -0700 Subject: dumping command-history in python interactive mode References: Message-ID: "Christoph Becker-Freyseng" wrote: > is there a way to dump (and save) the command-history of the python > interactive mode. I don't know about that, but it is pretty easy if you use IDLE. I always prefer IDLE over the console interactive mode, unless there is some particular reason not to (like experimenting with TKinter, or running in a non-GUI OS. What? Where you find such a thing these days?!). - Matt From sjmachin at lexicon.net Tue Jul 15 08:56:09 2003 From: sjmachin at lexicon.net (John Machin) Date: 15 Jul 2003 05:56:09 -0700 Subject: =?ISO-8859-1?Q?Python_Mystery_Theatre_--_Episode_2:__As=ED__Fue?= References: <8f35dab2.0307141258.3da9b9d4@posting.google.com> <6qvfu4jgh1.fsf@salmakis.intevation.de> Message-ID: Robin Becker wrote in message news:... > In article <6qvfu4jgh1.fsf at salmakis.intevation.de>, Bernhard Herzog > writes > >"Raymond Hettinger" writes: > > > >> [Jason Trowbridge] > >> > Act I > >> > I didn't know that python formatting could do that! I've always > >> > treated it like C's printf-style of statements, as that seems to be > >> > what it's primarily based off. > >> > >> That's why this one was included. > >> Hope everyone learned something new. > > > >C's printf can do this too. At least the one in the GNU libc can. It's > >docs don't say anything about this being a GNU extension so I guess it > >can be found in other libcs as well, though probably not in all. > > > > Bernhard > > > I know that it's in microsoft > > the print width description contains > > '''If the width specification is an asterisk (*), an int argument from > the argument list supplies the value. The width argument must precede > the value being formatted in the argument list. A nonexistent or small > field width does not cause the truncation of a field; if the result of a > conversion is wider than the field width, the field expands to contain > the conversion result.''' It's pretty much bog-standard C. E.g. K&R2, appendix B, section 1.2 says: ''' Width or precision or both may be specified as *, in which case the value is computed by converting the next argument(s), which must be int. ''' >>> "%+0*.*f" % (10,3,123.45678) '+00123.457' There you go, as advertised. From mis6 at pitt.edu Tue Jul 15 10:42:01 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Jul 2003 07:42:01 -0700 Subject: focus problem with full-screen in Tkinter References: <2259b0e2.0307140746.46cf2e8c@posting.google.com> <5a4226f0.0307141400.36684d3b@posting.google.com> Message-ID: <2259b0e2.0307150642.4daae156@posting.google.com> kevin at cazabon.com (Kevin Cazabon) wrote in message news:<5a4226f0.0307141400.36684d3b at posting.google.com>... > Wouldn't you have to do the bind as: > > root.bind("q",lambda e: root.destroy()) > > I don't know if evaluates to the same thing, but I know that > "normal" keys are not normally enclosed in <>. It may or may not be > part of your problem. > > Kevin. No, the problem is not with "". I have just discovered that it works perfectly fine under Windows 98SE, therefore it must be some problem of configuration of Tk under Linux. Any idea? Michele From nospam at mega-nerd.com Sat Jul 19 23:28:55 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 20 Jul 2003 03:28:55 GMT Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: Message-ID: <3F1A0C2D.6DBFAB2B@mega-nerd.com> Raseliarison nirinA wrote: > > hi all, > i found an unanswered question at > http://www.faqts.com/knowledge_base/index.phtml/fid/538 > with possible response below. i've tried to send it at > faqt.python but can't figure out how to edit the page. so i put it here. > i want to kwon if this can convert all wave file. is there other > encodage than 8 or 16 bits for .wav files? > any bug and comment are welcome Just in case you don't know, there is a Python wrapper to my own libsndfile ( http://www.zip.com.au/~erikd/libsndfile ) being developed here: http://www.arcsin.org/archive/20030520025359.shtml libsndfile handles a large number of different file types (AU, AIFF, WAV and many more) as well as many encodings (8, 16, 24, and 32 bit integer PCM, 23 and 64 bit float PCM, A-law, u-law, MS ADPCM, IMA ADPCM, G721, G723 and so on). Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "In civilian equipment, such as computers, the number of components alone makes miniaturization essential if the computer is to be housed in a reasonable-sized building." Electronics Oct. 1, 1957, p. 178 From alanmk at hotmail.com Thu Jul 17 10:19:11 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 15:19:11 +0100 Subject: Co-routines References: Message-ID: <3F16B05F.5D8812B8@hotmail.com> thewrights at ozemail.com.au wrote: > I want to execute these functions in > "lock-step", so that the output looks like: > > 1-1 > 2-2 > 1-2 > 2-2 > 1-3 > 2-3 Have you made a mistake in this output? Should it be this? 1-1 2-1 1-2 2-2 1-3 2-3 If yes, how about this? #------------------------- import itertools def seq(which, iterable): for i in iterable: yield "%d-%d" % (which, i) times = [1,2,3] seq1 = seq(1, times) seq2 = seq(2, times) for v1, v2 in itertools.izip(seq1, seq2): print v1 print v2 #-------------------------- If you want to generalise the number of iterators, how about this? #-------------------------- def lizip(iterables): iterables = map(iter, iterables) while True: result = [i.next() for i in iterables] yield tuple(result) def seq(which, iterable): for i in iterable: yield "%d-%d" % (which, i) y = [1,2,3] ; max_x = 5 iters = [seq(x, y) for x in range(1, max_x+1)] for vertslice in lizip(iters): for v in vertslice: print v #-------------------------- Note that these examples don't use "coroutines". Instead they use python generators, which are classified as "semi-coroutines". -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From Andreas.Ames at tenovis.com Tue Jul 22 13:16:37 2003 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Tue, 22 Jul 2003 19:16:37 +0200 Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88) Message-ID: <788E231C269961418F38D3E360D1652526C9CC@tndefr-ws00021.tenovis.corp.lan> Hello, during execution of an assignment statement like x = y . . . x = z # <-- is y's reference count decremented (and therefore its __del__ possibly called) *before* x is bound to z (or is z bound to x, I don't know the correct wording) or *afterwards*? I'm asking because I want to use threading.RLock but I'm a little scared about the use of the '__owner' instance variable without locking throughout the whole implementation. Python FAQ 4.88 seems to suggest y is deleted before x is rebound, in which case I'd rather not use RLock (because several of Thread's ctor arguments can very well be objects with explicit __del__ methods and the Threads which should use my RLock are definitely not under my control). Please note that I'm using Python 2.1; I haven't looked at the implementation in more recent versions. Just curious, TIA andreas From hwlgw at hotmail.com Fri Jul 11 09:33:22 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 11 Jul 2003 06:33:22 -0700 Subject: XML, xmlproc, MathML and validation Message-ID: I am trying to validate a document with mixed XHTML and MathML. The doctype declaration is: And the w3c validator at http://validator.w3.org/ says my XML file is valid. So far so good. But now I want to use xmlproc to both validate it and change something in it. I use "from xml.parsers.xmlproc import xmlval". This works good when the DTD is local but does not work in this case, where the DTD is remote. I can't have the MathML DTD local (it is now available as one file cause they made some stupid decision when designing it). The error message: ERROR: xml:space must have exactly the values 'default' and 'preserve' at http:/ /www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd:2025:1 ============================================================= My original problem: I am trying to write a valid2browser.py that replaces all occurences of by so my browser can display it. And before that validate it if possible. And then I want a browser2valid.py program. Fun projects! From jude-venn at blueyonder.co.uk Fri Jul 4 17:44:25 2003 From: jude-venn at blueyonder.co.uk (Jude Venn) Date: Fri, 4 Jul 2003 21:44:25 +0000 Subject: Delete item from wxListCtrl References: <3f05842f$0$49105$e4fe514c@news.xs4all.nl> Message-ID: <20030704214425.5bb4e81a.jude-venn@blueyonder.co.uk> haven't checked, but i think there's a GetIndex() method on the event object that returns the index of the selection. On Fri, 4 Jul 2003 15:39:20 +0200 "Joost van Rooij" wrote: > Hi, > > I am having problems deleting one item from a list in a wxListCtrl widget. > My thought was to select it as presented below: > > def onSelect(self, event): > self.item = event.GetItem() > self.list.DeleteItem(self.item) > > This won't work, it appaers GetItem() is returning an object while > DeleteItem() requires a long as its input. How do I pass the item to the > DeleteItem function? > > Regards, > Joost > > From http Fri Jul 4 13:58:08 2003 From: http (Paul Rubin) Date: 04 Jul 2003 10:58:08 -0700 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: Message-ID: <7xadbuuqbz.fsf@ruckus.brouhaha.com> "Francesco Bochicchio" writes: > I've given some thought to this idea, but I was blocked by the theoric (?) > impossibility to correctly call a C function without knowing its prototype > at compile time. Hmm, if the library is compiled with debugging symbols, type info is available.... From spam at yourself.pl Wed Jul 30 09:12:31 2003 From: spam at yourself.pl (Matthias) Date: Wed, 30 Jul 2003 15:12:31 +0200 Subject: python in parallel for pattern discovery in genome data References: Message-ID: BalyanM wrote: > Hi, > > I am new to python.I am using it on redhat linux 9. > I am interested to run python on a sun machine(SunE420R,os=solaris) > with 4 cpu's for a pattern discovery/search program on biological > sequence(genomic sequence).I want to write the python code so that it > utilizes all the 4 cpu's.Moreover do i need some other libraries. > Kindly advice. Don't write the speed-critical parts in python. From mwh at python.net Wed Jul 16 12:02:32 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 16 Jul 2003 16:02:32 GMT Subject: How does python work References: Message-ID: <7h3u19mlb4h.fsf@pc150.maths.bris.ac.uk> "A.M. Kuchling" writes: > On Thu, 10 Jul 2003 13:05:07 +0200, > Geiregat Jonas wrote: > > I'm asking myself how Python code get's executed ... > > What happens first etc ... > > First read the file and then .. > > The code is parsed and compiled into bytecode that can then be executed. > Consult a textbook on parsing or programming language implementation for > more details about how parsing is done. > > I thought someone (MWH?) wrote an explanation of Python's internals once, > but can't find anything at the moment. I've threatened to do it, but not actually done it. If you can read C, these things aren't that hard to figure out (though tags or cscope certainly help...). Cheers, M. -- You owe the Oracle a star-spangled dunce cap. -- Internet Oracularity Internet Oracularity #1299-08 From intentionally at blank.co.uk Mon Jul 14 21:40:27 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 02:40:27 +0100 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: On Mon, 14 Jul 2003 00:07:44 -0700, Erik Max Francis wrote: >Stephen Horne wrote: > >> Imagine, for instance, changing all assignments and other 'copying' to >> use a copy-on-write system. Then add a pointer type and a 'newcopyof' >> operator. And nick the C-style prefix '*' for dereferencing and add >> '&' as a 'make a pointer to this object' operator (absolutely NOT a >> physical memory address). > >The problem is that this misses the point that Python is not C++. You >shouldn't try grafting syntaxes and approaches that make Python look >more like C++, you should be learning to use Python on its own merits. Not true. If you eliminate all violations of the idea of variables bound to values (basically the whole point of my thread), then mutable containers cannot achieve the same thing. If a copy-on-write scheme is added to Python, you'd get the following results from using mutable containers... >>> a = [1, 2, 3] >>> b = a >>> b[2] = 4 >>> a [1, 2, 3] >>> b [1, 2, 4] That is, mutability of the list object could be used to conveniently and efficiently rebind the variable b (in this case to the value [1, 2, 4]) but that doesn't implicitly rebind the variable a which has nothing to do with this assignment. In the implementation, Python would create a copy of the object bound to [1, 2, 3] just in time to apply the change that object, without affecting the object that a is bound to. Efficient, and it implements the variable-bound-to-value concept. Having done this, there would be a need for a way of indirectly referencing objects. You wouldn't be able to abuse containers for this goal. Pointers are the logical way to achieve the goal of indirect referencing - they don't need to be associated with a type of container which may have nothing to do with the problem, and they can be used to reference *any* type of object. >Or, to put it another way, if you want to program in C++, why not use >C++? I don't want to program in C++ (though sadly I have to). The concept of a pointer as an indirect way of referencing an object, however, is useful. It isn't just a C++ concept. It is a widely used concept from many languages which has gone out of fashion, mainly because of the low level detail of how pointers are implemented in languages such as C++ (ie simple store addresses). I don't want the C++ bug-prone implementation of pointers. I want something which allows indirect referencing of objects in a logical and safe, high level way - and something which doesn't require the language to break the principle of variables bound to values. The fact that pointers are generally useful can be seen in the regular abuse of single item lists to fake the functionality of pointers. If people are routinely faking the abstraction, maybe that is because it is a useful abstraction to have. Maybe it would be better to support it explicitly instead of forcing people to use tricks and hacks. From mcfletch at rogers.com Tue Jul 22 00:30:12 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 22 Jul 2003 00:30:12 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <2259b0e2.0307210533.6fd22744@posting.google.com> References: <2259b0e2.0307190640.56266017@posting.google.com> <2259b0e2.0307200652.131ed45e@posting.google.com> <2259b0e2.0307210533.6fd22744@posting.google.com> Message-ID: <3F1CBDD4.60305@rogers.com> Michele Simionato wrote: >"Mike C. Fletcher" wrote in message news:... > > ... >>You are aware that you have just created a class-attribute, rather than >>an instance attribute? The property/descriptor object exists within the >>class 'o' namespace, not the instance namespace. Try creating two >>instances of your o class and setting v on both of them. There is one >>'p' instance "self" to which you are assigning/retrieving an attribute >>for all instances of o. Creating class variables is certainly a valid >>use for descriptors, but I'm not sure if that's really what you were >>trying to do. >> >> > >I have just copied your code, I thought you wanted a class attribute. > I should have been more precise. Your value is stored in the descriptor, so it is not a per-class attribute, it is an attribute stored in one place for *all* instances of all sub-classes of the defined class, it is not a property of the class, but an effectively static variable in the class definition. That is, each instance modifies the one copy of the value, regardless of the instance' class. I'm looking for a meta-property, a property of a class, rather than a property of a class-instance. Changing an instance's value for that name shouldn't affect this value. Changing the meta-property value should only occur when you do setattr( cls, key, value ), and should store the value in the *particular* concrete class having the value set, not on some ancestor of that class, just as if you were to do setattr( cls, key, value) without any meta-descriptor being present. >It is is trivial to do the same for instance attributes: > >class o(object): > class p( object ): # descriptor class > def __set__( self, client, value, *args, **named ): > print '__set__', self, client, value, args, named > self.value=value > def __get__(self,obj,cls): > return self.value > > def __init__(self): > self.v = self.p() > >I understand that you aware of this, but you don't like it. Still I >do not understand why do you feel it to be ugly and/or inelegant. It >seems to me quite idiomatic. > > It's just not what I'm trying to do (create active properties on meta-classes). It's a perfectly fine way to create class-static variables shared among a hierarchy of instance objects. >Yes, I understand you want to be able to set class dictionaries just >as object dictionaries, bypassing descriptors. Still, I am not sure >if this would be a good idea. > Well, just to clean up the descriptor API it's probably worth it IMO, but I only seem to have Michael to back me up on that so far :) . There's a missing level of functionality/hooks that haven't been exposed and should be exposed to allow more general & orthogonal operation of descriptor code. Basically, it should be possible to mimic the built-in behaviour of setattr/getattr w/out resorting to horrific hacks just to get that behaviour. In other words, it should be possible to interpose an operation in the descriptor-processing stream in much the same way that super() allows for co-operative mix-in classes to inter-operate by saying 'okay, do what would have been done if this "filter" method didn't exist'. >Elegance is in the eye of the beholder ;) > Indeed. >Good luck with your project, > Thanks. Enjoy, Mike From revthoren at k7.net Mon Jul 28 13:09:00 2003 From: revthoren at k7.net (bthoren) Date: Mon, 28 Jul 2003 13:09:00 -0400 Subject: where is the awk to python translator program In-Reply-To: <87smounf2z.fsf@jidanni.org> References: <87smounf2z.fsf@jidanni.org> Message-ID: Why translate? PyAWK may do what you need: http://pyawk.sourceforge.net/ I don't have any direct experiences with it, but it does look interesting. Dan Jacobson wrote: > An old dog can't learn new tricks, so where's the a2py awk to python > translator? Perl has a2p. E.g. today I wonder how to do '{print > $1}', well with a2p I know how to do it in perl, but with python I am > supposed to hunker down with the manuals. From drlinux at columbus.rr.com Wed Jul 9 11:17:18 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Wed, 9 Jul 2003 11:17:18 -0400 Subject: Application Development in Python In-Reply-To: References: <3089454.1057738936@dbforums.com> <200307091017.49419.drlinux@columbus.rr.com> Message-ID: <200307091117.18631.drlinux@columbus.rr.com> On Wednesday 09 July 2003 10:37, John Hunter wrote: > >>>>> "Dave" == Dave Reed writes: > > Dave> Also note that using the database for manipulating the data > Dave> makes the speed very acceptable. I'm almost certain that > Dave> manipulating the data in Python would be way too slow to > Dave> make it usable (e.g., generating a balance sheet that looks > Dave> through all the transactions and groups them by account in > Dave> Python would be much slower than using sql commands to do > Dave> that). > > I'm not arguing that the dbase isn't the way to go, but if you wanted > to do the manipulations in python, the Numeric package certainly > provides the speed you need to manipulate large quantities of data > rapidly. I sometimes use a C extension to put data from an SQL > database directly into Numeric arrays and then manipulate the data in > python. > > John Hunter Yes, Numeric is great for numeric data. The data I have is a mix of numeric and text data (for example, patient name, frame description, etc.). The other benefit of using the database is it provides automatic persistence (permanent storage) and atomic transaction processing. And of course sql statements allow you to easily get the data you want using joins, group by, and order by. Dave From gh at ghaering.de Thu Jul 17 09:25:39 2003 From: gh at ghaering.de (=?ISO-8859-2?Q?Gerhard_H=E4ring?=) Date: Thu, 17 Jul 2003 15:25:39 +0200 Subject: python.dll In-Reply-To: <3f169c26$1@newspilot.put.poznan.pl> References: <3f169c26$1@newspilot.put.poznan.pl> Message-ID: <3F16A3D3.3060001@ghaering.de> Jacek Potrymaj?o wrote: > Hi, > > I have a question about python installing. I try to install program which > require Python 2.2. Which software is this? If it requires Python, why isn't Python part of the setup? > I installed this version of python software, but when I > try to install software which use Python I have an error - incorrect version > of python.dll is installed. [...] Is that the exact error message you get? If not, please tell us the exact error message. You wonder why I don't believe that this is the exact error message? There is no such thing as a python.dll on Windows. The Python DLLs always carry the major and minor version numbers, like python21.dll or python22.dll. -- Gerhard From harry.g.george at boeing.com Thu Jul 10 13:49:16 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 10 Jul 2003 17:49:16 GMT Subject: object instance data to docbook, xml, pdf, etc? Message-ID: We traverse a database to find complex data objects, and place them temporarily in python objects. From there we want to generate xml, html, pdf. The results are generally in tabular format, with appropriate headers/footers, narrative. The obvious path is to go to xml-based docbook and from there to desired reports. Are there any tools which ease to generation of the initial docbook files? Or another path altogether? Notice that this is NOT the same as traversing the python code to generate module documentation, a la PyDoc. We are outputting the instance data, sort of like Gnosis xml_objectify, but to docbook DTD. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From sebastien.hugues at swissinfo.org Fri Jul 11 11:03:21 2003 From: sebastien.hugues at swissinfo.org (sebastien.hugues) Date: Fri, 11 Jul 2003 17:03:21 +0200 Subject: Windows XP - Environment variable - Unicode Message-ID: <3f0ed1ba@epflnews.epfl.ch> Alan Kennedy wrote: > Of course, this may not work if the APPDATA environment variable is > set outside a command window. If, for example, it was set through the > control panel, then it should be in the system default encoding. But > we'll cross that bridge when we come to it. > > > Thanks for you fast answer. Actually the issue is that this variable is set by the system itself. It is not accessible from the control panel. In the other hand, i don't use any terminal. So the question is how to get the default encoding of the system ? I was looking for a while in win32api documentation, msdn and Google but i didn't get nothing. Regards Sebastien From anton at vredegoor.doge.nl Thu Jul 17 05:57:05 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 17 Jul 2003 11:57:05 +0200 Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: John Hunter wrote: > Anton> http://home.hccnet.nl/a.vredegoor/twomax > >Hmm, now if I can only figure out what it all means :-) Me too. A friend of mine showed me that it's really a bipartite graph optimization problem and that it's in NP because it's harder than the maximum clique problem. Go figure :-) Anyway it seems to be possible to solve a maximum clique problem like this: - start with a graph containing your clique problem - copy the graph and color the original nodes white and the nodes of the copy black - connect the two graphs by drawing lines between black and white nodes that originate from the same node, and between black and white nodes where the original graph had a line between the original nodes. - make a matrix where the rows represent black nodes and the columns represent white nodes and where a "1" is in the matrix if there's a line between two nodes You now should have a matrix with ones on the diagonal and which is symmetric along the diagonal. Solve the matrix using the code above (I did some back porting to Python22) Look at the columns that are kept, it should be the nodes of a maximum clique. Is anybody still with me? I'd like to know if anyone can reproduce this result or understand my explanation (I'm just repeating what I saw on the blackboard) Anton From rastm2 at aol.commorespam Sun Jul 27 10:27:42 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 27 Jul 2003 14:27:42 GMT Subject: Help with Boa on Win98 with unicode installed Message-ID: <20030727102742.18087.00000494@mb-m15.aol.com> Hey Group, a question please. Has anyone ever struggeled with that install of Boa in Win98. I've followed the Docs. Tryed the "-E" switch while in DosPrompt. Made sure the wxPython version matched Python version... What am I missing folks? Recomendations on just waiting for Python2.3 and the next higher wxPython? TIA Ray From aahz at pythoncraft.com Thu Jul 10 19:48:57 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2003 19:48:57 -0400 Subject: Embedding Python, threading and scalability References: Message-ID: In article , Jeff Epler wrote: >On Thu, Jul 10, 2003 at 03:54:14PM -0400, Aahz wrote: >> >> Other people have mentioned Perl and Tcl in this thread. I wonder how >> they deal with the problem of loading DLLs with static data. > >As far as I know, tcl enforces a one interpreter to one thread >requirement. An extension should have only thread-local data, using a >Tcl-supplied API. What happens when Tcl wants to interact with some 3rd-party DLL that is *not* thread-safe? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Thu Jul 10 08:51:13 2003 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Koczian) Date: Thu, 10 Jul 2003 14:51:13 +0200 Subject: mx.DateTime.Parser.DateFromString('crap') Message-ID: This doesn't raise an exception but returns the current date. I know the comment in the notes for the Parser submodule: "The Parser submodule ... will try very hard to come up with a reasonable output given a valid input." But this is no valid input, so I'd prefer an exception or at least not a valid DateTime object. I've got to parse a file where some lines contain months in the form "Jul 2003", lots of lines contain no date at all (DateFromString returns the current date again), and the first line with something that's neither empty nor a valid month should end the processing. Working on Windows I haven't got strptime. No better way than checking explicitly for the content of the last line? Thanks for any help, 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 ta-meyer at ihug.co.nz Sat Jul 19 00:29:57 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 19 Jul 2003 16:29:57 +1200 Subject: IMAP examples In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F86B5@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AB59@its-xchg4.massey.ac.nz> > Well, to be fair, the first question, "Why data[0]" has more > to do with imaplib than IMAP4rev1. I doubt it has an > interesting answer, though - might as well just say "Because". Well, I suppose so, if the why is 'why index 0' and not 'why data'. I should probably point out that I was wrong when I said that ALL was a macro, as well. I wasn't paying enough attention and assumed that the ALL was being passed to FETCH, where it is a macro, rather than to SEARCH, where it isn't. The point is still valid, though :) =Tony Meyer From rzantow at ntelos.net Thu Jul 3 20:13:01 2003 From: rzantow at ntelos.net (rzed) Date: Thu, 3 Jul 2003 20:13:01 -0400 Subject: Python Code Snippets References: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> <3F04903A.8080009@dadsetan.com> Message-ID: Behrang Dadsetan wrote: > Guyon Mor?e wrote: >> You're gonna love this :) >> >> http://aspn.activestate.com/ASPN/Cookbook/Python >> >> >> "Aur?lien G?ron" wrote in message >> news:be1hs0$111s$1 at biggoron.nerim.net... >> >>> Hi, >>> >>> Does anyone know where I can find a lot of Python code snippets? >>> > > Or you might want to just look around here. In this > newsgroup/mailing-list one gets to see really lots of nice code. > > One that I would nominate as the best test for measuring a hard-core > python programmer would be to explain the following code without the > context :) > > Karl Scalet wrote: > > there are very likely easier ways, but at least > > > > s = 'C6 H12 O6' > > print [' '.join(xx) for xx in apply( > > zip,[(x[0],x[1:]) for x in s.split()])] > > > > gives some results, > > > > Karl > > Once I understood the above, I beleive I will write python in my > Resume... > > What was this about "One simple obvious way doing it"? ;) Obviously, this is just what people mean by "syntactic sugar." -- rzed From max at alcyone.com Wed Jul 2 01:56:08 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jul 2003 22:56:08 -0700 Subject: __del__ not working with cyclic reference? (and memory-leaked?) References: Message-ID: <3F0273F8.D3517ACE@alcyone.com> Jane Austine wrote: > I read the gc module reference thoroughly and > thanks to your short comment, I could understand it. > (I should not use __del__ for singleton patterns, but > any other alternatives?) I'm not sure why you'd want to use __del__ for a singleton pattern in the first place, since singleton patterns are supposed to cushion the creation and destruction of the singleton object away from the interface user. What are you trying to do with singleton patterns as it relates to __del__? > But does the fact that __del__ is not called for some > objects mean they are not freed from memory and therefore > memory-leaked? No, most operating systems guarantee that when a process exits any memory it allocated through normal means will be freed whether or not the application explicitly does it. So just as with C, C++, or Java, Python ensures that when the program exits you won't have leaked memory away from your operating system. However, Python doesn't make any guarantees about how timely __del__ will be called, or indeed even if it will be (in the case of circular references). If you're finding yourself needing to rely on using __del__ to get rid of important objects (such as those that are attached to significant resources), a far better solution would be to use try: ... finally: clauses surrounding the usage of such objects: resource = Resource() try: ... use resource ... finally: resource.close() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Men and women, women and men. It will never work. \__/ Erica Jong From usenet03q2 at hczim.de Sat Jul 19 15:33:03 2003 From: usenet03q2 at hczim.de (Heike C. Zimmerer) Date: Sat, 19 Jul 2003 21:33:03 +0200 Subject: Executing a program References: Message-ID: Eirik writes: > File "./PPP", line 9, in run_app > os.execvp("home/eirik/ppp-skript", argument) > File "/usr/lib/python2.2/os.py", line 298, in execvp > _execvpe(file, args) > File "/usr/lib/python2.2/os.py", line 324, in _execvpe > apply(func, (file,) + argrest) > OSError: [Errno 2] No such file or directory The error message seems clear to me. You're sure you did not mean "/home.." instead of "home.." (note the slash)? Greetings, Heike From ageron at HOHOHOHOvideotron.ca Wed Jul 2 14:49:38 2003 From: ageron at HOHOHOHOvideotron.ca (Aurélien Géron) Date: Wed, 2 Jul 2003 20:49:38 +0200 Subject: My Big Dict. References: Message-ID: > [...snippage...] > > d={} > for l in file("test.txt"): > try: i=l.index('!') > except ValueError: continue > d[l[:i]]=l[i+1:] > > [...snippage...] Just a little note : I generally try to avoid lowercase L and uppercase i as variable names, because in many fonts, there's barely any difference (sometimes none at all) between l and 1 and I (resp. lowercase L, number 1 and capital i). For example : would you be able to find out what the result of the following code is just by looking at it? If you think you can, run it through python and see if you were right! l=1l I=1+l print l+l*I Cya, Aur?lien From thanks200 at hotmail.com Sun Jul 13 23:55:42 2003 From: thanks200 at hotmail.com (Tom Hanks) Date: 13 Jul 2003 20:55:42 -0700 Subject: py2exe References: Message-ID: <6152d0a0.0307131955.6eee2ad6@posting.google.com> cybersamurai at mac.com wrote in message news:... > I am develop a application with wxpython, pycrypto, and Python 2.2, I > need know if py2exe get all modules needed for my application work > without install any application stead one exec file of my application > and without I select manually this modules? I don't know about pycrypto, but I have used py2exe on a Python 2.2 & wxPython program. Pleasantly straight-forward with few surprises. Regards, Tom Hanks. From sybrenUSE at YOURthirdtower.imagination.com Wed Jul 30 02:41:19 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 30 Jul 2003 06:41:19 GMT Subject: while (assignment): References: <13a533e8.0307291300.be1423a@posting.google.com> Message-ID: Peter Abel enlightened us with: > The following should work: > > info = mydbcursor.fetchone() > while info: > print "Information: "+str(info) > info = mydbcursor.fetchone() I don't really like the double info assignment, but I've thought it over a bit, and I like this better than the while True info = mydbcursor.fetchone() if not info: break construction. In the upper solution the "while info" makes the loop condition very clear. The lower solution is less clear in that, but doesn't have the double assignment. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From pablo at bogus.domain.org Sat Jul 19 16:46:34 2003 From: pablo at bogus.domain.org (Pablo) Date: Sat, 19 Jul 2003 22:46:34 +0200 Subject: classes Message-ID: Hello everyone I have a problem with classes and hope someone can help me. I'm used to Java and want to make a singleton class which would allow to create only one instance of the class. In Java it looks as follows: public class DBConnection{ private static DBConnection instance = null; private Conn conn = null; // it is supposed to be object returned be pg.connect() method of the PyGreSQL module /* a constructor must be private to forbid instantiation of the class */ private DBConnection(){ conn = new Conn(); } public static DBConnection getInstance(){ if(instance == null) instance = new DBConnection(); return instance; } }; How can I do the same in Python? My main problems are: 1) how to declare a static field (class field not object field) 2) how to declare a static method 3) how to declare a private constructor (is it possible?) Can someone help me or point me to some documentation with strong emphasis on classes? It would be perfect if that documentation had some comparisons with classes in Java or C++. Best regards Pablo From peter at engcorp.com Sun Jul 20 15:18:19 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 15:18:19 -0400 Subject: List of declared variables in interactive Python session? References: <20030720143606.18124.00000262@mb-m15.aol.com> Message-ID: <3F1AEAFB.3C62F613@engcorp.com> "Raymond Arthur St. Marie II of III" wrote: > > >>> vars( ) > > {'d': 'pywin', '__builtins__': , '__name__': > '__main__', 'pywin': 'C:\PYTHON22\lib\site-packages\Pythonwin\pywin\__init__.pyc'>, '__doc__': None} > > >>> for v in vars(): print v > ... > > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration for v in vars().copy(): print v works fine... -Peter From ianb at colorstudy.com Tue Jul 1 19:32:08 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 01 Jul 2003 18:32:08 -0500 Subject: Circular Inheritance In-Reply-To: <234cc7238020.238020234cc7@usc.edu> References: <234cc7238020.238020234cc7@usc.edu> Message-ID: <1057102328.726.124.camel@lothlorien> On Tue, 2003-07-01 at 17:36, jinal jhaveri wrote: > B requires C > C requires A > A requires B > > and when I try to do this using > > from ...import.... > it tells me that you cannot import this. Instead of using from...import..., just use import. To explain: A.py: from B import B class A: ... uses B B.py: from A import A class B: ... uses A Now, let's say you import A. When you do that, the first line is executed ("from B import B"). So B is imported, and its first line is executed ("from A import A"). But the class A does not yet exist -- we're still just on the first line of that module. The A module *does* exist, and you can import it, it just hasn't been completely set up. This is why it will usually work to use a plain import, and just refer to A.A in B (and B.B in A). Ian From vze4rx4y at verizon.net Thu Jul 24 22:39:10 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 25 Jul 2003 02:39:10 GMT Subject: ndiff References: Message-ID: > 1. both ndiff and Differ.compare return all the lines including lines that > are the same in both files, not just the diffs. is the convention to take > the output and then filter out lines that contain a space as the first > character to just get the diffs? it seems strange to me that the output is > not just the deltas and a lot of wasted filtering (especially if the file is > very large) to get the diff you wanted in the first place. isn't there a > better way? The new difflib.py in Py2.3 has two new functions, context_diff() and unified_diff(). The new functions and an exposed underlying method strip-away the commonalities leaving only the changes and context, if desired. Raymond Hettinger From mis6 at pitt.edu Fri Jul 4 09:11:40 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Jul 2003 06:11:40 -0700 Subject: cooperation of buitlin methods usingtsuper References: <2259b0e2.0307020855.478300c2@posting.google.com> <2259b0e2.0307030652.697001dd@posting.google.com> Message-ID: <2259b0e2.0307040511.1eb91faa@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > ISTM (and I don't know super much) that in the above, if you factor out > x = super(C,c) > and then compare > len(x) > vs > x.__len__() > > then the results above suggest that implementation is not > getattr(x,'__len__')() > but effectively more like > getattr(x.__class__,'__len__')(x) > > Note: > > >>> class B(object): > ... def __len__(self): return 1111 > ... > >>> class C(B): pass > ... > >>> c=C() > >>> super(C,c).__len__() > 1111 > >>> len(super(C,c)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > > Ok, now let's look at c vs x: > > >>> getattr(c,'__len__')() > 1111 > >>> getattr(c.__class__,'__len__')(c) > 1111 > > vs > > >>> getattr(x,'__len__')() > 1111 > >>> getattr(x.__class__,'__len__')(x) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: type object 'super' has no attribute '__len__' > > I guess generally continuing a failed method lookup in x.__class__.__dict__ or equivalent > and trying to find it as an instance attribute might make this super problem > work, but weren't instance methods intentionally bypassed for the new style? > > That would mean solving the problem specifically in super somehow, but how? I guess by > fiddling with lookup of methods of/via super instances? I guess it could be done in C. > I'll have to look in typeobject.c more sometime. It looks already tricky ;-) > > Regards, > Bengt Richter To add trickyness to trickyness, I show you a couple of examples where the same problems appear. These examples (or examples similar to them) where pointed out to me by Bjorn Pettersen. The real problem seems to be in the lookup rule for len(x) which is not always equivalent to x.__len__() when tricks with __getattr__ are performed: First example: defining __len__ on the object does not work class E(object): def __getattr__(self,name): if name=='__len__': return lambda:0 >>> e=E() >>> e.__len__() 0 >>> len(e) Traceback ... Second example: defining __len__ on the class does not work: class M(type): def __getattr__(self,name): if name=='__len__': return lambda self:0 class F: __metaclass__=M >>> f=F() >>> F.__len__(f) # okay 0 >>> len(f) # TypeError: len() of unsized object f.__len__() # AttributeError: 'F' object has no attribute '__len__' As you see, the problem is that len(x) is not calling x.__len__(), nor x.__class__.__len__(x); I really would like to know how ``len`` (or ``str``, ``repr``, etc.) work: I think this is the core of the problem, whereas ``super`` is probably a red herring. Michele From stevenswan at sina.com Wed Jul 2 21:41:05 2003 From: stevenswan at sina.com (stevenswan) Date: Thu, 03 Jul 2003 09:41:05 +0800 Subject: anything like a "pointer" in python? Message-ID: <20030703014105.16688.qmail@sina.com> I want to open a file in python and read something and process the file in c++ moduel, but there is no "pointer" in python, so how can I pass the arg(file buffer) between python and c++ modules? ______________________________________ =================================================================== From theller at python.net Thu Jul 17 15:35:21 2003 From: theller at python.net (Thomas Heller) Date: Thu, 17 Jul 2003 21:35:21 +0200 Subject: xml.sax in py2exe References: Message-ID: writes: > I want a binnary file to my aplicattion, but py2exe don't match the > xmll.sax module. > > the py2exe shows this errors: > > warning: py2exe: *************************************************************** > ********** > warning: py2exe: * The following modules were not found: > warning: py2exe: * xml.sax > warning: py2exe: * win32con > warning: py2exe: * pywintypes > warning: py2exe: * os.path > warning: py2exe: * hexdump > warning: py2exe: * win32com.client.gencache > warning: py2exe: * win32api > warning: py2exe: *************************************************************** > ********** > > but in python if i import the module, its works very well! > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import xml.sax >>>> xml.sax > Message-ID: | Does anybody know where can I get the html version | for offline browsing? | | It's cumbersome to use the pdf. I've got dial-up | and I can't connect all the time to see the reference. Psymaster ... I built a local HTML version of Introduction to Tkinter by using a couple of Python scripts that downloaded everything from the on-line HTML version ... All links have been edited to point to local files ... If Fredrik Lundh says its OK I'll zip it up and post a link for download ... -- Cousin Stanley Human Being Phoenix, Arizona From aaron at reportlab.com Wed Jul 2 13:59:08 2003 From: aaron at reportlab.com (Aaron Watters) Date: 2 Jul 2003 10:59:08 -0700 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> <3064b51d.0306170436.2b31f9e@posting.google.com> Message-ID: <9a6d7d9d.0307020959.634ceb4e@posting.google.com> David Abrahams wrote in message news:... > Duncan Booth writes: > > I'm not saying that Python isn't a wonderful language -- it is. It's > great to have the flexibility of fully dynamic typing available. All > the same, I'm not going to pretend that static typing doesn't have > real advantages. I seriously believe that it's better most of the > time, because it helps catch mistakes earlier, makes even simple code > easier to maintain, and makes complex code easier to write. I would > trade some convenience for these other strengths. Although it's very > popular around here to say that research has shown static typing > doesn't help, I've never seen that research, and my personal > experience contradicts the claim anyway. I'm somewhere on the fence. I've seen static typing catch errors, but I've also seen static typing (in java, say) make the use of a hash table into an exercise in code obfuscation. I'd really like some sort of compromise where you could harden types incrementally. Also static typing can make it more difficult for bad programmers to do stupid things... I'd like to see research either way. I've heard of rumored research in both directions. Personally, I suspect the widely repeated statement "90% of programming errors are typing errors" can be traced back to the 60's when engineers wrote programs on graph paper-like sheets and handed them to TYPISTS who then TYPED THEM WRONG onto punch cards. -- Aaron Watters "You mean life is not a fountain???" From ianb at colorstudy.com Sat Jul 12 01:27:49 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2003 00:27:49 -0500 Subject: The "intellectual property" misnomer In-Reply-To: References: Message-ID: <1057987669.28456.79.camel@lothlorien> On Fri, 2003-07-11 at 22:30, Ben Finney wrote: > > and you proved you're not [confused by the term] > > [by listing some disparate fields of law that might be referred to by > > the term] > > This doesn't follow at all. I requested that the "rights" being > referred to should be stated, not handwaved with a term that presumes > that copyright, patent, trademark, trade secret, or many other disparate > legal areas can be lumped together. > > If PSF holds rights that are covered by *all* those fields of law, I'd > be very surprised; but if the "rights" are *not* covered by all those > different legal areas, then the term is useless. Functionally, though, I think the term intellectual property here works. PSF holds (to their knowledge) all intellectual property associated with Python -- there may be no patents, but with the statement they assert that either there are no patents or they hold them. We also know (implied from other sources) that PSF does not restrict its intellectual property. The intent of this statement is that someone using Python need not worry about "intellectual property" associated with Python, which includes at least patent, copyright, and trade secrets. I don't know how this applies to trademarks, since they are different from the others, and obviously PSF does not hold every trademark that contains Python and relates to computers. > If the PSF holds software patents in Python, I imagine many would be > outraged. I don't believe it does. If it's not the case, why imply it > with an overbroad term? I would not be outraged. If they enforced those patents, then I might be outraged. Ian From martin at v.loewis.de Fri Jul 18 11:13:13 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Jul 2003 17:13:13 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> Message-ID: Alan Kennedy writes: > More worrying however is the failure of modern browsers to display the > characters when accessed through Google Groups. It's not the browsers that display it incorrectly; it is Google rendering it incorrectly. Fortunately, they keep the original data at http://groups.google.com/groups?selm=3F172442.2040907%40v.loewis.de&oe=UTF-8&output=gplain Regards, Martin From intentionally at blank.co.uk Tue Jul 15 17:04:29 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 22:04:29 +0100 Subject: anything like C++ references? References: Message-ID: On 15 Jul 2003 10:45:10 -0700, owski at hotmail.com (Adam Ruth) wrote: >I came to Python from Ada, and all I have to say is: Pointer-like >semantics are evil. They're worse than goto's, they're deadly, >damaging, and should be avoided at all costs. > >They're an unhappy necessity, akin to stop-lights. You need them >because roads intersect, but if roads don't intersect, don't use them! Absolutely true. And the worst thing you can do when you really can't avoid pointers is to obscure the issue even more by disguising them as something else. The biggest problems with pointers relate to things with pointer math, pointers to deleted objects etc. These things need not exist in a scripting language that provides pointers - pointers don't have to be implemented using store addresses. That is just a concept from C, C++, Pascal, Ada etc - not something I want to see imitated. If pointers can be created that refer to given objects, and if pointers can be dereferenced, that is actually enough to support indirect referencing. From drs at ecp.cc Wed Jul 2 03:50:57 2003 From: drs at ecp.cc (drs) Date: Wed, 02 Jul 2003 07:50:57 GMT Subject: dcom client from non-windows python References: Message-ID: "Paul Rudin" wrote in message news:ur85a8we8.fsf at scientia.com... > > > This is mostly idle speculation from a position of considerable > ignorance :-) > > In theory it should be possible to do client side dcom from > non-windows boxes. The existing python win32com stuff is only > distributed for windows. The python wrappers could be generated from > a type library on a windows box; copied across to (e.g.) a linux box > and used to do write client side dcom python programs to talk to a > servers running on a windows box. I wonder how much of the current > dcom client code depends on the presence of windows? Does this sound > like a big job getting this kind of thing to work? Or should it be > fairly easy to modify the existing com client stuff for this purpose? > Maybe somebody has already done this (although I could find anything > with a quick google)? My guess is you would be more successful using pyro for the distributed stuff. my other guess is that python com simply wraps windows stuff, and that reimplementing windows on linux would take a while. -d From mwh at python.net Tue Jul 15 11:55:37 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jul 2003 15:55:37 GMT Subject: How to crash Python in 1 easy step (python 2.2.2) References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <7h3isq3n63w.fsf@pc150.maths.bris.ac.uk> gavriep at yahoo.com (Gavrie Philipson) writes: > pwmiller1 at adelphia.net (Paul Miller) wrote in message news:<2e363c08.0307130944.4c470bc3 at posting.google.com>... > > I'm not sure if this is a python bug or a bug in an associated > > library, and I'm not even sure how to correctly report it, but here is > > Anytime python is accepting keyboard input, whether it's with > > raw_input, or sitting on the command line waiting for the user to type > > code, you can crash python by holding ctrl+shift and then pressing > > enter. > > > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > > everything about the system is standard except for what's been updated > > by RedHat itself. If anyone who has the time and ability to track > > down this bug needs more information, please email me. > > I'm seeing the same effect on RH9, using KDE's "konsole" terminal > emulator. > When pressing Ctrl-Shift-Enter, it actually sends the ^[OM characters > (Escape, O, M). > Manually sending the key sequence Esc-O-something also crashes Python. > > Why this happens is still a good question... This has almost surely got to be a readline problem. Does it happen in (e.g.) gdb? Cheers, mwh PS: pressing ctrl-\ also crashes Python... PPS: unless you've been mucking with stty -- 'stty quit i' makes for an abbreviated python programming experience :-) -- well, take it from an old hand: the only reason it would be easier to program in C is that you can't easily express complex problems in C, so you don't. -- Erik Naggum, comp.lang.lisp From null-spam at tfh.ca Mon Jul 14 11:18:53 2003 From: null-spam at tfh.ca (Sean) Date: Mon, 14 Jul 2003 10:18:53 -0500 Subject: Expressing time. Message-ID: I'm playing around times and dates. I'd like to determine the age of particular sets of data in a user friendly matter. I've got everything ready but dealing with time in a user friendly manner. What would be a good way to express (in python): time.localtime()+30 days time.localtime()+5 minutes time.localtime()+2 months time.localtime()-2 years I know I could probably just calculate out each of those in seconds but that seems unelegant and very unfriendly (not to mention prone to error). Is there any python facilities to make this an easier chore (aka time.localtime()+months(3))? (I included months as it is a special case in that you can't just arbitrarily calculate months in seconds without being relative to a particular month). -- Sean From tdelaney at avaya.com Mon Jul 21 20:41:09 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 22 Jul 2003 10:41:09 +1000 Subject: [OT] On the TimBot Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D426C@au3010avexu1.global.avaya.com> > From: Christos "TZOTZIOY" Georgiou [mailto:tzot at sil-tec.gr] > > 3. To "Tron" fans: yes, you could assign the name TimBit to > it, but it's > a broken Bit; what's the use of a Bit that's always true? Well, it compresses really well ... Tim Delaney From dmbkiwi at yahoo.com Sun Jul 13 00:40:39 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sun, 13 Jul 2003 16:40:39 +1200 Subject: Python - if/else statements References: Message-ID: On Sun, 13 Jul 2003 03:59:53 +0000, Bengt Richter wrote: > On Sun, 13 Jul 2003 12:30:52 +1200, dmbkiwi wrote: > >>On Sat, 12 Jul 2003 23:11:20 +0000, Bengt Richter wrote: >> >>> On Sat, 12 Jul 2003 14:27:33 +1200, dmbkiwi wrote: >>> >>>>On Sat, 12 Jul 2003 01:58:13 +0000, Bengt Richter wrote: >>>> >>> [...] >>> Is it a single .py file? > BTW, since you uploaded it, is there an URL for it? http://www.kdelook.org/content/show.php?content=6384 >> >>Yes, although it imports a module called karamba (see my original post - >>this is a theme run through a theme engine called superkaramba). >> > Unfortunately that makes me imagine an engine in a theme park, maybe in > Argentina ;-P IOW I know nothing about theme engines ;-) Same here. Don't know if it's a theme engine or not, but it seemed an appropriate description. > > >> >>It is being executed through the superkaramba engine (written in c++ I >>believe). Not sure if I, or my users have enough gumption to do the >>debugging you are referring to. I have asked them to execute the script >>which contains a number of print statements to verify that it is ignoring >>the else statement. Is there other debugging info that I should be >>printing when running the script? > Maybe write a little test of if/else that doesn't depend on any data that > you don't control right in the test. E.g., since most of your tests test > for == 1 or 0, > > >>> for testval in (0, 1, None, (), [], '', 'x'): > ... if testval == 0: print '%r==0?'%(testval,), ... else: print > 'not %r==0?'%(testval,), ... if testval == 1: print > '%r==1?'%(testval,), ... else: print 'not %r==1?'%(testval,), ... > if testval: print 'if %r?'%(testval,), ... else: print 'not if > %r?'%(testval,), ... print > ... > 0==0? not 0==1? not if 0? > not 1==0? 1==1? if 1? > not None==0? not None==1? not if None? not ()==0? not ()==1? not if ()? > not []==0? not []==1? not if []? > not ''==0? not ''==1? not if ''? > not 'x'==0? not 'x'==1? if 'x'? > > Everything should be true (with not prefixes considered). > > If the if/else tests are not working right for local variables, maybe the > results will be glitched. Also declare a global _with the rest, not a > separate line_, say g_testval, and do another loop like the above with > testval changed to g_testval everywhere. If either of these glitch, I'd > bet on the global one, but I actually expect them both to work. It would > make another data point though. > > And just FTHOI, give them a version with 100% space indenting. > > Then the question would be, if these tests work, why don't the tests in > the original code. We could also ask users to run these tests in some > simpler context -- what if they just run the above loops in a def test(): > (so there's a difference between local and global) with nothing more in > the script than test() to invoke it? That must work from the console > command line python, or they are totally FUBAR. But it's a data point on > the no-errors side of the fence. > > We could then break down the code into painfully primitive steps, and > print (where does printing go, BTW? is stdout captured for you in a file?) > the results of each step. Again if something is parsing and potentially > modifying the code before executing, giving it something dead simple to > parse might help. Can someone say if the code is given to the interpreter > completely unmodified, so we can put that to rest? > > In the meanwhile, if most users have no problem, maybe you have to make a > table of user configurations -- versions of linux, bsd, python > (multiversion? how last upgraded?), libraries? gcc stuff? etc. until a > pattern emerges as to who has the problems and how they are different. > > Maybe make a little script to capture all that info and make it easy for > folks to give it to you. (I wouldn't try to make it automatically send an > email without their informed consent, though ;-) > > Regards, > Bengt Richter I'll contact the users, and see if they're up for it. Matt From fmeehan at ctbr.com Wed Jul 23 13:19:26 2003 From: fmeehan at ctbr.com (Francois Meehan) Date: Wed, 23 Jul 2003 13:19:26 -0400 Subject: Getting started with win32pdh... Message-ID: Hi all, Can someone give me an example on how to use win32pdh module (that access windows performance counters)? For example, how to retreive the number of processes running on a win2k server, with the Objects-Processes counter? Any ideas? Francois From zathras at thwackety.com Fri Jul 25 04:48:33 2003 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 25 Jul 2003 09:48:33 +0100 (BST) Subject: generator function within a generator function doesn't execute? In-Reply-To: <20030724190941.18070.00000520@mb-m17.aol.com> Message-ID: Whereever you have this: > sleep(1.5) You need to _run_ your generator - the above call just _creates_ the generator. ie you'd change the above line to: for i in sleep(1.5): yield None You've got the idea elsewhere AFAICT, just that you haven't chained the execution of generators. (Generators don't nest - the yield keyword instantly turns the function into a generator) Chaining generators: value,anotherValue,yetAnotherValue=1,2,3 if 1: def n_plus2(): while 1: yield value def n_plus1(): while 1: for i in n_plus2(): yield (anotherValue,i) def n(): while 1: for i in n_plus1(): yield (yetAnotherValue,i) for i in n(): print i > expected. Why doesn't the sleep() function execute? In summary - it doesn't run because you're not iterating through the generator created by your sleep function. You need to do this, and in order to pass control back to your scheduler you need to yield a value back whilst you iterate through. Hope that helps, Michael. From jjl at pobox.com Sun Jul 20 13:20:52 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jul 2003 18:20:52 +0100 Subject: Browser plugins References: Message-ID: <87el0lf72j.fsf@pobox.com> "Aur?lien G?ron" writes: > I'd like to write a simple portable browser plugin for Internet Explorer, > Netscape and if possible other navigators too. Is there a way to do that > using Python? For now I'd like to develop something like the GoogleBar, but > I'd also like to know how to develop "in-frame" plugins such as Flash or > Realplayer. I *think* Netscape plugins are quite simple, and it's not possible to do things like toolbars without taking over the whole window. I may be completely wrong there -- I've never written one. The Mozilla documentation is no doubt the place to start (Netscape Navigator is now a flavour of Mozilla, in case you don't know). I'm sure Mozilla will have lots of more sophisticated ways of doing things, but maybe not ones that make it possible to write cross-browser code -- unless you write a framework yourself, of course. [...] > Any ideas? Any links to documentation for browser plugins development? Any > code examples or open source project I could check out? It might not be as bad as it first appears, since XPCOM is heavily modelled on MS COM, and was designed to interoperate with it to an extent, I believe. PyXPCOM exists (written by Mark Hammond, of PythonCOM (etc.) fame). Other starting points: -ActiveX Control for Netscape plugins + Netscape plugin for ActiveX controls + Mozilla ActiveX control (not relevant to your question, but interesting) http://www.iol.ie/~locka/mozilla/mozilla.htm I think both Opera and Konqueror support Netscape plugins. -Codeweavers sells a product that uses a hacked version of wine to allow ActiveX plugins to work in Mozilla, Konqueror, etc. Called 'Crossover Plugin', or something. -Qt has classes for implementing Netscape plugins. At least, it did -- can't find it in Qt 3. Not sure if that's accessible from PyQt, either. Qt for Windows is not free (but there is a weird noncommercial license for a single release of Qt/win 2.x). Qt/win 3 includes some COM support, so there's a chance that might help you do a cross-platform plugin, if you can afford the licence. There may well be other ways of doing this, I haven't looked hard. Google away... John From paul_rudin at scientia.com Mon Jul 21 04:58:05 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 21 Jul 2003 09:58:05 +0100 Subject: Python voting demo discussion References: <3F1BA496.6080305@embeddedsystems.nl> Message-ID: >>>>> "Gerrit" == Gerrit Muller writes: > (very long links, will be broken by most newsreaders!) Surrounding urls with angle brackets prevents most news/mail software from inserting unwanted line breaks. I understand it even works with the horrible OE! From aahz at pythoncraft.com Mon Jul 14 10:30:22 2003 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2003 10:30:22 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: In article <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv at 4ax.com>, Stephen Horne wrote: > >C++ has precisely one type of variable. That variable is a placeholder >for a value of a datatype which is specified in the declaration. The >datatype may be a pointer datatype, but so what? Pointer datatypes are >not treated any differently than other datatype except that they, like >all datatypes, they have their own set of functionality. Really? I would argue that the differing syntaxes is an argument against a single type of variable. What happens with this: char a; a->b; -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From jepler at unpythonic.net Wed Jul 16 11:28:09 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 16 Jul 2003 10:28:09 -0500 Subject: How to crash Python in 1 easy step (python 2.2.2) In-Reply-To: <7h3isq3n63w.fsf@pc150.maths.bris.ac.uk> References: <2e363c08.0307130944.4c470bc3@posting.google.com> <7h3isq3n63w.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030716152806.GA1967@unpythonic.net> On Tue, Jul 15, 2003 at 03:55:37PM +0000, Michael Hudson wrote: > This has almost surely got to be a readline problem. Does it happen > in (e.g.) gdb? It happens in bc, but not in gdb or my shell. The traceback is endless frames of #2094 0x4045e803 in _rl_dispatch_subseq () from /usr/lib/libreadline.so.4 #2095 0x4045e77e in _rl_dispatch () from /usr/lib/libreadline.so.4 .. the same in bc or python So does this simple C program: #include #include #include int main(void) { char *line = readline(">>>"); if(line == NULL) return 1; printf("The user entered %s\n", line); free(line); return 0; } It seems fairly clear that this is a readline bug. I'm not sure what Python can do about it, if anything... Jeff From gsmatthew at ozemail.com.au Thu Jul 17 07:27:00 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Thu, 17 Jul 2003 21:27:00 +1000 Subject: Python Asynchronous Services Message-ID: Hi all, I have hit a serious snag ... I am writing an app server. I am happy with pythons threading etc however I am totally confused with handling large request on a socket. For example I can create a threadingTCPServer, the script that calls the app server might send a file or an xml request. Where I am stuck is how do you handle large files ? for example: while 1: data = recv(1024) if not data: break surely in a thread this will block all other threads until all data is recieved. I have also been told that one cannot rely on this mechanism as the socket might end up in a continious loop, i.e you need to send a header included in the data that states the length (bytes) that is been sent, or you need some terminator, what happens if the terminator is within the requests data and not at the end ? please any help or examples as I have now been on this for 2 days without any luck. I have looked at asyncore and asynchat, problem is once the server socket input is completed then their will be an area that is CPU bound where it will need to call the model, database etc and produce the html request, this means that control will only be handed back to IO operations when this is finished, effectively blocking all other requests .... I suppose another question is can python handle large files and requests at the same time or is one better off simply forking the process even though its costly ? Many thanks ..... From mis6 at pitt.edu Sat Jul 5 08:55:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Jul 2003 05:55:46 -0700 Subject: module and file locations References: Message-ID: <2259b0e2.0307050455.4d63c93d@posting.google.com> Stuart Galloway wrote in message news:... > Hi, > > I am writing a debugging a Tkinter program. > > While debugging I want to run it by pressing F5. > When in use I want to run it by double-clicking (win2000) > > The program reads and write to various files which I want to store in > the same directory (or a sub directory) of the main script. > > My question is: How can my program where it lives so I can get the base > directory? > argv[0] - will this work debugging if I just import the file? > There is some about finding where a module is. This seems to return > readable text that would require parsing rather than just a file name > > Thanks, > > Stuart The global variable __file__ contains the file name of the current module. For instance #put this in a file called x.py print __file__ returns 'x.py' when you do $ python x.py For some strange reason it does not work if I execute x.py from IDLE 1.0b2 on a Windows 98SE machine. Is it working for you? Michele From pw-google at terlkin.org Mon Jul 14 13:02:59 2003 From: pw-google at terlkin.org (Peter Wilkinson) Date: 14 Jul 2003 10:02:59 -0700 Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> <120720032321075007%candiazoo@mac.com> Message-ID: <3344b1fa.0307140315.321bb6b2@posting.google.com> "Michael S. Jessop" wrote in message news:<120720032321075007%candiazoo at mac.com>... > [[ This message was both posted and mailed: see > the "To," "Cc," and "Newsgroups" headers for details. ]] > > I tried supplying host as well, same error. :/ Something is hosed. > I guess I could try reinstalling. I really want to get this to work. > I am trying to write a maintenance program for my wife, so she can > remotely modify the database containing information about her artwork, > distribution lists, etc. > I see exactly the same problem. My install is with MySQL and Python both via Fink. Trying both 2.2 and 2.3 Python I get the same problem. Trying to dig into it a little it looks as though the setup code isn't populating some of the fields and methods and the error thrown shows up because self.converter is set to None. I'm going to try and figure this out but would be interested in any insight others might have. Peter. From gh at ghaering.de Thu Jul 17 11:12:13 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 17 Jul 2003 17:12:13 +0200 Subject: Python2.3 logging utilities In-Reply-To: <20030717142015.77268.qmail@web41504.mail.yahoo.com> References: <20030717142015.77268.qmail@web41504.mail.yahoo.com> Message-ID: <3F16BCCD.9060409@ghaering.de> Samir Patel wrote: > First of all, hats of on logging module in python 2.3. > Very elegant... > > I have 2 questions regarding Handler class in logging: > [...] > 2. SMTPHandler: Is there any way to send an email > where server requires authentication through > logconfig.ini file. I send an email message to myself > through logging and SMTPHandler and it works perfect, > but if I want to send an email to external email > address, I can't do it because replying is not allow. > I can do it this in a python program by using ehlo and > docmd of smtplib object, There's no need for such low-level hacks. SMTP AUTH is accessible through the login() method of SMTP objects. > but how can I do same thing > in loggers' config.ini file. You can't, currently. You're welcome to submit a patch that provides this feature, though :) From a quick glance it should be quite easy to implement. While at it, it would make sense to be able to use a nonstandard SMTP port as well :) -- Gerhard From jdhunter at ace.bsd.uchicago.edu Wed Jul 23 09:04:37 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 23 Jul 2003 08:04:37 -0500 Subject: lists and files question In-Reply-To: <3F1DCF52.7040607@hotmail.com> (hokiegal99's message of "Tue, 22 Jul 2003 19:57:06 -0400") References: <3F1DCF52.7040607@hotmail.com> Message-ID: Others have already answered your question - I just want to point out a few of other things import os, re, string setpath = raw_input("Enter the path: ") for root, dirs, files in os.walk(setpath): id = re.compile('Microsoft Excel Worksheet') 1) id is a built in function; you may not want to override it with your variable name >>> x = 1 >>> id(x) 135313208 2) The reason to use re.compile is for efficiency. There is no need to call it inside the loop, since you're just recompiling the same regex over and over again. Instead, compile the regex outside the loop >>> rgx = re.compile('[A-Z]+') >>> for some_text in some_list: ... m = rgx.match(some_text) 3) If you want to match 'Microsoft Excel Worksheet', you don't need regular expressions since this is a string literal. You will probably be better off just using the string find method, as in s.find('Microsoft Excel Worksheet') 4) You may want to look at the path module, which provides a nice interface for walking over files: http://www.jorendorff.com/articles/python/path/ >>> from path import path >>> xldir = path(setpath) >>> for f in xldir.files('*.xls'): ... print f.read().find('Microsoft Excel Worksheet') Cheers, John Hunter From mcherm at mcherm.com Tue Jul 1 13:13:50 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 1 Jul 2003 10:13:50 -0700 Subject: Good code patterns in Python Message-ID: <1057079630.3f01c14ed962a@mcherm.com> Will Stuyvesant writes: > If you know that your source code is going to be used > later by others, then I feel that code with the pattern: > > if some_condition: > some_name = some_value > else: > some_name = other_value > > is often a mistake. Much better, safer, would be: > > some_name = some_value > if not some_condition: > some_name = other_value I disagree with you... I think that the first form is superior to the second. Here are two reasons. My number one reason is readability. Seeing "some_name = some_value" when some_name is ACTUALLY going to take on other_value is very misleading to the reader. Particularly in Python, I strive to make my code very readable -- it's typically more important to me to be readable than it is to be fast. Furthermore, if the code is easily understood, then that maintanence programmer or re-user of your code that you mentioned is less likely to make a mistake like leaving some_name undefined. My second reason is the danger of this maintanence programmer. You are concerned that they might "change or adapt the 'if' part". Frankly, I don't find this to be much of a worry. After all, the use of an if with an else clause CLEARLY indicates that you expect one of these two branches to be taken, and that if they change it so neither is taken, they'd better be sure they know what they're doing. On the other hand, I'm QUITE worried about the maintanence programmer modifying your second example. If they somehow fail to set some_name it would result in "NameError: name 'some_name' is not defined" the first time that it used -- a pretty clear error message. But (unlike modifying the if-else), a maintanence programmer is quite likely to simply add some new lines of code... perhaps (foolishly) between the first assignment and the if statement. If this happened, the resulting error would be that some_name DID have a value, but it was the WRONG value. This could result in some peculiar exception at an arbitrary time, or (much worse) perhaps NO exception at all... the program would proceed, producing incorrect data with no warning. Finally, I'd like to make reference to the wonderful world of unit tests. If the code has no unit tests, then either error is possible. But if there are unit tests, then the person who re-uses that code and modifies it so that some_name is no longer set properly will find a test failing. This will immediately alert them that their change is causing problems... they will examine the situation and either fix the problem or change the test ("now I WANT some_name to be undefined in some cases"). -- Michael Chermside From yzzzzz at netcourrier.com Fri Jul 18 08:40:46 2003 From: yzzzzz at netcourrier.com (yzzzzz) Date: Fri, 18 Jul 2003 14:40:46 +0200 Subject: Using Unicode scripts References: <3f17c520$0$7194$626a54ce@news.free.fr> Message-ID: <3f17eace$0$23860$626a54ce@news.free.fr> OK, problem solved! I got the new Python, it all works. I just had to add the UTF-8 BOM myself (UltraEdit doesn't do it by default) but that wasn't too difficult to do (copy and paste a ZWNBSP). One last question: I'm using windows, so the console's encoding is CP437. If I try to print a unicode string, the string is converted to CP437 and printed and that works fine. However if I try to print a normal (non-unicode) string from a UTF-8 encoded file with BOM, for example print "?", it sends out the two UTF-8 bytes ?? which appear as lines in the CP437 charset. But if I print the exact same character in a Latin 1 encoded file, it comes out as the Latin 1 byte for "?" which shows up as a theta in CP437. This means that Python doesn't take into account the specified encoding (Latin 1 or UTF-8) and prints out the raw bytes as they appear in the source file, regardless of the encoding used. Is this normal? (this isn't really a problem for me as I am only going to use unicode strings now) From jack at performancedrivers.com Tue Jul 15 00:40:24 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 15 Jul 2003 00:40:24 -0400 Subject: anything like C++ references? In-Reply-To: ; from intentionally@blank.co.uk on Tue, Jul 15, 2003 at 03:59:53AM +0100 References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: <20030715004024.E1005@localhost.localdomain> On Tue, Jul 15, 2003 at 03:59:53AM +0100, Stephen Horne wrote: > > The term 'variable' is defined by mathematics and computer science. > The fact that Python has arbitrarily redefined it is the cause of very > real confusion and errors. > Previously I thought you were just trolling. But what are we going on now? three days? I know you, true believer. This is not C++, this is python: [Jack as an undergrad, entering his prof's office] Me: Sir, Mr Diederich here. you asked me to come by? Prof: I've something to tell you, prophecy of a sort. Me: a quick sort? Prof: no, a prophecy sort. Me: I haven't taken that course yet. Prof: *sigh* You had some trouble in class today? Me: variable. Prof: variably across the board, but variables constantly. Me: that's my problem, constantly variables. Prof: you just did it again. Me: you just lost me again. Prof: Son, comp sci has fallen into confusion. Me: constant or variable? Prof [raised eyebrow] Prof: Ada of Lovelace wrote about this a long, long time ago. Our profession has fallen into disrepair, but one will come to make all things clear. Me: I'm not up to it, Sir. Prof: *glance* fallen into disrepair, but hope will come in the form of a man. Me: Still not ready, Sir. Prof: *thwap* You will know Him by his heresy and by his name 'Stephen' Me: Its Jack Sir, you've been my adviser for two semesters. Prof: *solid beating* You will know Him by his heresy, by his name 'Stephen' and his never ending glyphs. Me: glyphs Sir? Prof: don't be an asshole, He will type a lot. Me: And I will know Him by his typing? Prof: No, you will know Him by his heresy, his name 'Stephen', AND his typing. Prof: And pasties, he will definitely be wearing pasties. -jack From tjreedy at udel.edu Sat Jul 5 17:26:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Jul 2003 17:26:11 -0400 Subject: What does this core dump mean? References: Message-ID: > I just noticed that demo/evp_ciph_test.py of my M2Crypto package > causes a core dump. It used to not do that. ;-) I cannot interprete the gdb trace either. Info on the platform, Python version, what you changed to change the behavior, and the reproducibility of the dump behavior might help someone who can. TJR From anton at vredegoor.doge.nl Wed Jul 2 13:00:18 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 02 Jul 2003 19:00:18 +0200 Subject: splitting a string into 2 new strings References: Message-ID: "Mark Light" wrote: > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 >strings >'C H O' and '6 12 6'. I have played with string.split() and the re module - >but can't quite get there. The issue seems to be resolved already, but I haven't seen the split and strip combination: from string import letters,digits def mysplit(s): L = [(x.strip(digits) ,x.strip(letters)) for x in s.split()] return [ ' '.join(x) for x in zip(*L)] Anton From skip at pobox.com Thu Jul 31 13:22:03 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 12:22:03 -0500 Subject: time, calendar, datetime, etc In-Reply-To: References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <16169.20539.104524.273029@montanaro.dyndns.org> Ben> Problem is, time.localtime() doesn't return a 9-element tuple any Ben> more, it returns a struct_time. (Since 2.2, I think.) Struct_time objects work like tuples, and you get the added benefit of named attribute access: >>> t = time.localtime() >>> t (2003, 7, 31, 12, 19, 35, 3, 212, 1) >>> t[2] 31 >>> t.tm_mday 31 >>> t.tm_isdst 1 >>> t[-1] 1 >>> t[0:3] (2003, 7, 31) Skip From paul at boddie.net Tue Jul 1 05:11:27 2003 From: paul at boddie.net (Paul Boddie) Date: 1 Jul 2003 02:11:27 -0700 Subject: Fast CGI Vs Java Application Servers References: <20030630120924.209$qh@newsreader.com> Message-ID: <23891c90.0307010111.43fd3c43@posting.google.com> ctcgag at hotmail.com wrote in message news:<20030630120924.209$qh at newsreader.com>... > Charles Handy wrote: > > How does FastCGI compare against java Apps running in java app servers > > like TomCat, Sun One, WebLogic and WebSphere? Is there a business case > > for switching from CGI to Java? > > Do you want there to be one? I think that other contributors to this thread have given interesting "recruitment cases" for introducing Java (the usual stuff about Java being a standard and there being lots of "Java people" in the job market), but then FastCGI/CGI is a very vague term. Is the application in question written in C or C++ (insane as that may seem to developers using more modern languages)? Is the person who posted the question still reading this thread? ;-) One might well argue that a switch from C/C++ to Java might be a worthwhile investment, given the benefits of Java over those languages, but a switch from Tcl, Perl or Python to Java needs to be more rigourously justified in my opinion. > > Performance? > > I've seen dozens of features that were implemented in CGI (not mod_perl > or FastCGI) rewritten to run on a java app server on a beefier machine. > None of them were noticably faster, and many were slower. In various respects, I also believe this to be true. However, there was an interesting case a few months ago where the scalability of Zope was compared with WebSphere on some serious hardware. The outcome (which highlighted certain issues with Zope's threaded execution model, at least in the way it was employed in that particular case) doesn't reduce the relevance of other solutions available for Tcl, Perl and Python. Indeed, in Python solutions there are various different execution models on offer: http://www.python.org/cgi-bin/moinmoin/WebProgramming Contrast Twisted, mod_python, Webware and SkunkWeb. > > Productivity? > > I'm about 5x less productive in Java. Indeed. But in the development of a Web application, one also has to consider how productive different members of the extended team are, too. That can have a lot more to do with the chosen technologies deployed on top of the programming language and application server in question. [...] > > Code Reuse? > > Switching a working application to a new language is about the > greatest possible crime there is against code reuse. "We believe in code reuse. Apart from the system we just threw away, of course." Paul From mcherm at mcherm.com Thu Jul 10 10:25:11 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 10 Jul 2003 07:25:11 -0700 Subject: Deleting specific characters from a string Message-ID: <1057847111.3f0d77471178b@mcherm.com> Paul Rudin writes: > I haven't been following this thread closely but isn't a regexp the > obvious way to do this? No. The one thing that's QUITE clear is that there are multiple ways to do this, some of which are more readable than others, but there's no "one obvious way". > I'd expect it to be faster than your solution > - particularly on large input (although I haven't actually > tried). Hmm... I doubt it. I'd expect the translate() version to be the fastest, with multiple string.remove()'s being competative when the number of different characters to be removed is small. RE's are NOT renown for their speed when doing simple character replacement, deletion or insertion on strings. But _I_ haven't timed it either, so I'm going to shut up now. -- Michael Chermside ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From glauco at sferacarta.com Mon Jul 28 05:47:46 2003 From: glauco at sferacarta.com (Glauco) Date: Mon, 28 Jul 2003 09:47:46 GMT Subject: Python and VS.Net References: <221d8dbe.0307272345.63503afd@posting.google.com> Message-ID: <6j6Va.208584$lK4.6037642@twister1.libero.it> Good work . i hope in a fast, simple, pythonic solution for WS in .NET .. I wrote a client library in python based on SOAPpy for use of WS in .NET . Is very difficult for me understand how many solution and how it works for this scope. The server i must use has 2 kind os Web Services .. I understood that in .NET you can create 2 kind of client. The SOAP-XML is something like an XML body into the SOAP message and the other is SOAP-RPC , i think this is a sort of a full enveloping of msg. I've builded some client whith SOAP-XML and it works whith a little of manipulation in some modules of package SOAPpy but now im'trying to "simply understand" how to use SOAP-RPC Web Service and how to modify my libs fot the scope. Someone use this 2 types of .NET Web Services with Python ? sorry for my engl. Glauco From jlh at cox.net Thu Jul 10 00:35:39 2003 From: jlh at cox.net (Jeff Hinrichs) Date: Thu, 10 Jul 2003 04:35:39 GMT Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de><3F0C8AC3.5010304@dadsetan.com> Message-ID: "John Hunter" wrote in message news:mailman.1057789156.27025.python-list at python.org... > >>>>> "Behrang" == Behrang Dadsetan writes: > > Behrang> is going to finally be what I am going to use. I not > Behrang> feel lambdas are so readable, unless one has serious > Behrang> experience in using them and python in general. I feel it > Behrang> is acceptable to add a named method that documents with > Behrang> its name what it is doing there. > > If you want to go the functional programing route, you can generalize > your function somewhat using a callable class: > > class remove_char: > def __init__(self,remove): > self.remove = dict([ (c,1) for c in remove]) > > def __call__(self,c): > return not self.remove.has_key(c) > > print filter(remove_char('on'), 'John Hunter') I've been following this thread, and on a whim I built a test harness to time the different ideas that have been put forth in this thread. I will post complete results tomorrow on the web but the short version is that using the .replace method is the overall champ by quite a bit. Below is the function I tested against the others in the harness: def stringReplace(s,c): """Remove any occurrences of characters in c, from string s s - string to be filtered, c - characters to filter""" for a in c: s = s.replace(a,'') return s It wins also by being easy to understand, no filter or lambda. Not that I have anything against filter or lambda, but when the speediest method is the most readable, that solution is definitely the Pythonic champ. :) -Jeff Hinrichs From creedy at mitretek.org Tue Jul 15 11:14:12 2003 From: creedy at mitretek.org (Chris Reedy) Date: Tue, 15 Jul 2003 11:14:12 -0400 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= In-Reply-To: References: <3F140F34.1030401@mitretek.org> Message-ID: <3f141a3e_2@corp-news.newsgroups.com> Aahz wrote: > In article <3F140F34.1030401 at mitretek.org>, > Chris Reedy wrote: > >>Aside: I have to admit that the ((42,) * 2) did confuse me at first. I'm >>so used to doing 2 * (42,) when I want to repeat a sequence that I >>hadn't thought about the reversed form. > > > My experience is that most people do it the way Ray did, * . This must be my math background confusing me. Conventionally, a+a is written as 2a, and a*a is written as a^2 (or a**2). Of course, if you recognize that concatenation of sequences is really a multiplication (by convention in mathematics addition is always a commutative operator), a*2 makes sense. I guess I'll change the way I write this in the future. From staschuk at telusplanet.net Thu Jul 31 02:06:17 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 00:06:17 -0600 Subject: Exceptions as New Style Classes In-Reply-To: ; from imbosol@aerojockey.com on Wed, Jul 30, 2003 at 11:16:36PM +0000 References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: <20030731000617.A2806@tibia.amotlpaa.bogus> Quoth Carl Banks: > Steven Taschuk wrote: > > At the moment the dominant idea for solving these problems is to > > make inheritance from Exception mandatory for exception types; see [...] > Why not give exceptions their own metaclass? So if type(x) is > ExceptionMetaclass, it's a class. If type(type(x)) is > ExceptionMetaclass, it's an instance. Otherwise, it's illegal to > raise it. That seems workable. (I'd prefer, though, to test isinstance(type(x), ExceptionMetaclass) and likewise for the second case.) I'm not sure what it gains us, though, over the idea of mandatory inheritance from Exception. Am I missing something? -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 24 17:22:46 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 24 Jul 2003 23:22:46 +0200 Subject: i've been close to python's cradle :) In-Reply-To: References: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> Message-ID: <3f204e26$0$49113$e4fe514c@news.xs4all.nl> Sybren Stuvel wrote: > I live close to the CWI, and will probably even do a few courses > there. Perhaps I'll look up Guido sometime :) Hard time finding him at the CWI: http://mail.zope.org/pipermail/zope3-dev/2003-July/007598.html Guido's been working in the USA for quite some time now. --Irmen From belred1 at yahoo.com Tue Jul 29 09:44:42 2003 From: belred1 at yahoo.com (Bryan) Date: Tue, 29 Jul 2003 13:44:42 GMT Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: "Anton Vredegoor" wrote in message news:bg5htl$b2h$1 at news.hccnet.nl... > rick_hunter357 at hotmail.com (Rick) wrote: > > >PS. Before someone starts on how college kids are using the internet > >(or the help available on the 'net) to do the work for them, No I am > >not cheating. The actual assignment is to select 9 papers that you > >find interesting and write a report on each of them. I already have my > >9 papers selected. Now I want to know if I would like to replace some > >from my collection. > > Why not take 9 threads in this newsgroup or the Python developers > mailing list and write a report on that? Of course you'd have to > convince your teacher somehow that this is the way things work > nowadays and that the days where a single author wrote a monolithic > paper are gone. > > Knowledge production and decision making are much more interactive and > hands-on than before, and discussions involve a lot more people of > varying degrees of expertise and having a more diverse background. > > If it makes any difference: I would love to see some threads reviewed, > especially threads that have had some time to cool down and that can > be viewed from some distance now. Post the result of your assignment > here, you'll get free error checking this way and at the same time you > prove that the system works by interacting with it. Isn't it Pythonic > :-) > > Anton. > anton, excellant idea. here are the most recent 3 threads that contain over 100 postings... must be good "report material" in these... 201 postings anything like C++ references 130 postings does lack of type declarations make Python unsafe? - has 130 postings opening a text document to show a .txt file through a browser link bryan From ianb at colorstudy.com Wed Jul 2 20:16:14 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 02 Jul 2003 19:16:14 -0500 Subject: Suggesting for overloading the assign operator In-Reply-To: References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <1057191374.720.198.camel@lothlorien> On Wed, 2003-07-02 at 15:09, Bengt Richter wrote: > Hm, it just occurred to me that one could have yet another form of sugar > [ It's now later, and I think this may be more than sugar ;-) ] > to help with this, by treating the dot operator slightly more symmetrically, > like, e.g., '+'. > > Example, then explanation: > > a = 7 .USD # (using symbols from http://www.xe.com/iso4217.htm by convention, no hard defs) > # ... > a = 6 .USD Does 7 .USD *really* look that much better than USD(7)? And, really, how often do you need currency literals? All my currency values come from non-literal sources -- databases and XML files, an excel spreadsheet, etc. I don't think this objection is particular to currency either -- for most types this is true. If you are using them a lot, you are acquiring them from non-code sources. Though I suppose Rebol would be a counterexample. And, in the case of scripting (a kind of programming, not a kind of programming language :) it might be a more valid need. But most of Rebol's interesting data types aren't syntactically valid in Python anyway. Ian From altis at semi-retired.com Sun Jul 13 12:59:37 2003 From: altis at semi-retired.com (Kevin Altis) Date: Sun, 13 Jul 2003 09:59:37 -0700 Subject: PythonCard newbie question References: Message-ID: Yep, the problem is PythonCard has been using the __version__ attribute from a low-level wxPython module when it shouldn't have and in wxPython 2.4.1 the location of the __version__ attribute in that low-level module changed and so it broke PythonCard. This is fixed in cvs and will be fixed in release 0.7.1 which I plan to get out this week after I have recovered from OSCON. The fix is simple, simply change the line in PythonCardPrototype/model.py to assert wx.__version__ >= "2.3.3" the reference in the resourceEditor can be removed entirely. ka "Karl Lopes" wrote in message news:Xns93B71174A7F15karllopeshotmailcom at 24.69.255.211... > Hello All, > I downloaded and installed PythonCard. When I try to run the minimal app > in samples > I get the following errors: module' object has no attribute 'Background'. > : module' object has no attribute '__version__' > Any ideas what I am missing here. > Thanks > Karl. From abelikov72 at hotmail.com Wed Jul 9 21:14:06 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 10 Jul 2003 01:14:06 GMT Subject: Embedding Python, threading and scalability References: Message-ID: <5oepgvkrju9ilu33rlatgnajet7f3cjprj@4ax.com> On 8 Jul 2003 14:54:22 -0700, wenning_qiu at csgsystems.com (Wenning Qiu) wrote: >I am researching issues related to emdedding Python in C++ for a >project. > >My project will be running on an SMP box and requires scalability. >However, my test shows that Python threading has very poor performance >in terms of scaling. In fact it doesn't scale at all. > >I wrote a simple test program to complete given number of iterations >of a simple loop. The total number of iterations can be divided evenly >among a number of threads. My test shows that as the number of threads >grows, the CPU usage grows and the response time gets longer. For >example, to complete the same amount of work, one thread takes 10 >seconds, 2 threads take 20 seconds and 3 threads take 30 seconds. > >The fundamental reason for lacking scalability is that Python uses a >global interpreter lock for thread safety. That global lock must be >held by a thread before it can safely access Python objects. I asked once and was told it was best fixed by removing the documentation which mentioned it. Others also stated it was unlikely to be fixed. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=53u1evk5jmdcgma5e8eupbe3tn45js302i%404ax.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D53u1evk5jmdcgma5e8eupbe3tn45js302i%25404ax.com However, I believe Lua since 4-work4, just before Lua 5, solved this. Unfortunately Lua is not Python. Another thing to consider if you care about SMP, is your C/C++ memory management, assuming you aren't using something custom already, maybe a shared heap. I have worked wonders with libhoard (and SmartHeap, commercially). Some applications will run slower on SMP than if you removed one of the processors. www.hoard.org www.microquill.com mmm, graphs -AB From bober at acm.cs.nyu.edu Tue Jul 1 21:20:29 2003 From: bober at acm.cs.nyu.edu (Jonathan Bober) Date: 01 Jul 2003 20:20:29 -0500 Subject: Idiomatic way of repeating items in a sequence. In-Reply-To: References: Message-ID: <1057108829.433.9.camel@ziggy> On Mon, 2003-06-30 at 10:53, Batista, Facundo wrote: > Whitout a lambda and without a for: > > def repeatitems(L, n): > return [x for x in L*n] > > CAUTION: the resulting list is not in the same order of your example: > > >>> repeatitems(['a', 'b', 'c'], 3) > ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] OUCH!!! this code hurts so bad that i must respond... L * n is the same as [x for x in L * n] except that the latter iterates through L * n applying the identity transformation, and is much much slower. keep things simple. From jordan at krushen.com Mon Jul 21 03:45:19 2003 From: jordan at krushen.com (Jordan Krushen) Date: Mon, 21 Jul 2003 07:45:19 GMT Subject: httplib\urllib attributes problem References: Message-ID: On Sun, 20 Jul 2003 21:28:54 +0200, Bobbie wrote: > The problem with urllib2 is that a "User-agent: Python-urllib/2.0a1" is, > again, sent > by default. in case I setup a "User-Agent" attribute of my own it just, > again, sends > them both. Note the lower-case 'a' letter in the former user-agent > automatically sent by the library. I can't even overrun it because of > that. > > I'll be happy for any kind of help, suggestion,... At least for this one, here's the relevant code from urllib2.py: class OpenerDirector: def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] You should be able to override your opener's addheaders attribute (untested): opener.addheaders = None J. From FBatista at uniFON.com.ar Fri Jul 4 15:11:30 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 4 Jul 2003 16:11:30 -0300 Subject: sys.setedefaultencoding() Message-ID: #- sys.setdefaultencoding() shouldn't be used by application programs; #- it was added for test purposes only. #- #- if you really need to change the encoding, tweak site or #- sitecustomize, #- and be aware that 1) python programs you write may not work on other #- systems, and 2) extensions may not work properly on your system. Why? I *always* work with this type of enconding (I live in Argentina). #- > - Why this happens? #- #- site.py removes the function. Thanks! I changed it. From guettler at thomas-guettler.de Fri Jul 18 03:00:50 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Fri, 18 Jul 2003 09:00:50 +0200 Subject: Solved: tkinter: Better Traceback References: Message-ID: Thomas G?ttler wrote: > Fredrik Lundh wrote: > >> Thomas G?ttler wrote: >> >>> Is there a way to get a better traceback in tkinter? >>> It would be nice to see the line number of the last line >>> of "my" code. >>> >>> Exception in Tkinter callback >>> Traceback (most recent call last): >>> File >>> "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", >>> line 1299, in __call__ >>> args = apply(self.subst, args) >>> File >>> "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", >>> line 1035, in _substitute >>> e.height = getint(h) >>> ValueError: invalid literal for int(): ?? >> >> it's not a bug in your code, it's an incompatible change in Tk 8.4.2, >> which uses "??" to represent an "undefined integer". >> >> either upgrade your Tkinter (Python 2.3 contains a workaround), or down- >> grade your Tk to 8.4.1 or earlier (or link Tkinter against Tk 8.3.x). > > Hi Fredrik, > > Both solutions are need to change this which only root can do. > The application will be installed on several workstations > running Suse Linux8.2. Is there a workaround? > > Would be good if I could use the default python (2.2.2) > and TK version (8.4.2). > > thomas Solved with the new python-tk rpm from: http://www.suse.de/en/private/download/updates/82_i386.html thomas From usenet_spam at janc.invalid Wed Jul 9 23:25:35 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 10 Jul 2003 03:25:35 GMT Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: Fernando Perez schreef: >>> or even gif (the patents expired recently). >> >> Only in the US, not in (some countries in) Europe & Japan. > > Ah, you're right. But I think they also expire soon, don't they? Somewhere next year IIRC (at least in most countries). -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From Thomas.Sunshine at web.de Tue Jul 22 10:18:58 2003 From: Thomas.Sunshine at web.de (Thomas M.) Date: Tue, 22 Jul 2003 16:18:58 +0200 Subject: How do i run an external program in an python script? References: Message-ID: > I have no idea about python. I got a c++ program which i want to be > called from an python script. How do i do that? > > My programs path under Linux is: > /bin/Prinit import os (prinit_input, prinit_output) = os.popen2('/bin/Prinit') input and output are filelike objects... From pascalbarbedor at free.fr Tue Jul 29 06:14:58 2003 From: pascalbarbedor at free.fr (pascal barbedor) Date: Tue, 29 Jul 2003 12:14:58 +0200 Subject: blanks embedded in python 2.3 optparse References: <3f2625b7$0$24594$626a54ce@news.free.fr> Message-ID: <3f26490b$0$24605$626a54ce@news.free.fr> > you need to quote the name like > prog --name="mr jones" > > That should work > > Karl > it works thanks From raims at dot.com Sun Jul 20 05:29:03 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 20 Jul 2003 11:29:03 +0200 Subject: object as a reserved keyword Message-ID: Does it worth to make "object" keyword a reserved one? I'd like to avoid oddities like this: Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class c(object): pass ... >>> object = 4 >>> class c(object): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: int() takes at most 2 arguments (3 given) >>> Lawrence From Kepes.Krisztian at peto.hu Wed Jul 9 03:49:15 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Wed, 09 Jul 2003 09:49:15 +0200 Subject: Python Global Constant Message-ID: Hi ! I want to create an module and I want to use some Global Constant in it. How to I create an global constant in module what is accessable in from other modules ? like this example: *** module dirs *** const Const_Up=1 const Const_Down=1 *** module any *** import dirs; def CheckDir(Dir): if Dir=dirs.Const_Up: xxx ????? Thx: Chris From peter at engcorp.com Sun Jul 20 00:00:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 00:00:30 -0400 Subject: Strange (?) list comprehension behavior References: <3F1A138F.549D1D@engcorp.com> Message-ID: <3F1A13DE.1A7964AC@engcorp.com> Peter Hansen wrote: > > George Henry wrote: [a question] > > Please post the precise traceback, cut and pasted. If it really said > that, and your subsequent analysis is valid, I think one of your "ops" > is not a string... Cancel that... I didn't see your subsequent followup before I posted, because it was not linked to the previous thread. You already found the problem... :-) -Peter From brian at sweetapp.com Thu Jul 31 01:50:25 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 30 Jul 2003 22:50:25 -0700 Subject: Ver 2.3 install over 2.2? In-Reply-To: <4c877253.0307301628.7d73a1a6@posting.google.com> Message-ID: <000001c35727$a3dbd4e0$21795418@dell1700> > Make sure you have VC6 installed, else you'll be unable to build > extensions for Python23. VC7 worked for building Python22 extensions, but > no longer (and if anyone can explain why, I'd love to know). > > error: Python was built with version 6 of Visual Studio, and > extensions need to be built with the same version of the > compiler, but it isn't installed. > > I'm reinstalling 2.2.3 so I can keep developing with Reportlab until I can > get hold of VC6 or a fix for 2.3. Actually, extensions built with VC7 never worked (with Python compiled with VC6). Now you get a helpful error message instead of a crash. The reason that these extensions don't work is that VC7 introduced incompatibilities in the C runtime library. The layout for the FILE data type has changed, for example, so extensions using the FILE returned by PyFile_AsFile may crash. You could get lucky, of course, and have a set of extensions that never use any unsafe routines. Cheers, Brian From alanmk at hotmail.com Sun Jul 6 15:02:12 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 20:02:12 +0100 Subject: absolute beginners question about API documentation References: Message-ID: <3F087234.2AB40C2C@hotmail.com> Markus Joschko wrote: >>> Is there an API documentation like the javadoc API from java? Dave Kuhlman wrote: >> If you are asking about the *Python* API, then look here: >> >> http://www.python.org/doc/current/lib/typesmapping.html Markus Joschko wrote: > Thanks. That's it. I hadn't suspect it there. And don't forget the interactive help available on most objects, through the use of the dir() and help() functions, e.g. Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> d = {} >>> dir(d) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'setdefault', 'update', 'values'] >>> help(d.keys) Help on built-in function keys: keys(...) D.keys() -> list of D's keys >>> help(d.has_key) Help on built-in function has_key: has_key(...) D.has_key(k) -> 1 if D has a key k, else 0 >>> HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From scook at elp.rr.com Fri Jul 4 11:49:07 2003 From: scook at elp.rr.com (Stan Cook) Date: Fri, 04 Jul 2003 15:49:07 GMT Subject: File information?? References: Message-ID: Thanks.....That did it... Just what I was looking for! Stan "Ian Bicking" wrote in message news:mailman.1057300149.8085.python-list at python.org... > On Fri, 2003-07-04 at 00:59, Stan Cook wrote: > > Is there a way to get the file size and modified date of a file? > > os.stat(filename).st_size and os.stat(filename).st_mtime > > Ian > > > From gh at ghaering.de Thu Jul 17 19:58:06 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jul 2003 01:58:06 +0200 Subject: ps in windows In-Reply-To: <3F1720EF.DCA2AD12@juno.com> References: <3F1720EF.DCA2AD12@juno.com> Message-ID: <3F17380E.8010006@ghaering.de> Jeff Sandys wrote: > Not really a Python question except I will use Python to write the > script. > > I have several Windows98SE PCs and a Linux PC on a home network. > I want the Linux PC running a cron job to query the Windows PCs to find > out what programs they are running. > Any pointers on how to do this? If I had this problem what I'd do is go to http://groups.google.com/ and search for the keywords "python win32 list processes" ;-) -- Gerhard From grundhan at cs.tu-berlin.de Tue Jul 29 19:45:06 2003 From: grundhan at cs.tu-berlin.de (Hannes Grund) Date: Wed, 30 Jul 2003 01:45:06 +0200 Subject: Problem passing COM objects from COM Server to ActiveX Control and back. Message-ID: Dear all, I'm currently developing an application that makes heavy use of COM objects. I'm struggling with the following Problem: In short the setup: Machine: Win2000, python2.2, win32com extensions, wxPython (The application is aimed to manage a molecule database, The COM objects being created via win32com.client.Dispatch(..)) The main actors within the problem: - A server component that reads molecule data from a propitiery database, it is instanciated via win32com.client.Dispatch(PROGID), on demand it delivers "Molecule"-Objects which are itself COM objects, when returned back by the server these are outlined as > (i.e. these are NOT build by win32com.client etc. they come out as the result of a function call on the server component) - An ActiveX Control (from the same vendor, same typelib) aimed to display molecules of the above type. This control is integrated in the wxPython framework via the method MakeActiveXClass from "activexwrapper.py". My problem: The control itself exposes a property where a molecule of the above type can be assigned (which is displayed then within the control). If the property is read afterwards, the molecule has become a which seems to be OK so far. This instance can be processed without problems via python or even the above server object. The problem arises when one tries to put this object again in the control (via the property, what initially worked). It simply to refuses to show up again. I guess there are happening many things on the interfaces when passing these objects from one component to the other, but I cannot finger out the crucial step. Furthermore I don't know whether it is really the problem of pythoncom (in a previous version of the above software suite everything worked well). Although this seems to be a rather special kind of problem, any help, hint or advise would be highly appreciated. Hannes Grund From exarkun at intarweb.us Tue Jul 22 06:57:35 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 22 Jul 2003 06:57:35 -0400 Subject: Pause in a loop In-Reply-To: <%W7Ta.10360$t92.299097@news1.tin.it> References: <%W7Ta.10360$t92.299097@news1.tin.it> Message-ID: <20030722105735.GA15769@intarweb.us> On Tue, Jul 22, 2003 at 10:00:27AM +0000, manuel wrote: > > I've two modules: main.py and eval.py > > Eval.py is imported in main.py, but I've a loop > in eval.py that must call a function in main.py... > > I can't import main.py in eval.py too, because > that would create an import loop. > > But I'm thinking a different solution: > a pause in a loop to return periodically an > output. It's possible? > Generators, or "resumable functions" may be one possible solution for this: from __future__ import generators # Necessary until Python 2.3 class MoreWorkToDo: pass class NearlyDone: pass def f1(): for i in xrange(100): do_something_expensive_and_slow() yield MoreWorkToDo for i in xrange(10): cleanup_a_little() yield NearlyDone def f2(): for x in f1(): print str(x), Another possibility is to use a callback: class MoreWorkToDo: pass class NearlyDone: pass def f1(perLoop): for i in xrange(100): do_something_expensive_and_slow() perLoop(MoreWorkToDo) for i in xrange(10): cleanup_a_little() perLoop(NearlyDone) def cbFunc(v): print str(v), def f2(): f1(cbFunc) Still another approach might create an iterator out of an explicit state machine: class MoreWorkToDo: pass class NearlyDone: pass class Worker: def __iter__(self): return _WorkerIter() class _WorkerIter: def __init__(self): self.state = 'working' self.workCount = 100 self.cleanCount = 10 def next(self): return getattr(self, 'state_' + self.state)() def state_working(self): do_something_expensive_and_slow() self.workCount -= 1 if self.workCount <= 0: self.state = 'cleanup' return MoreWorkToDo def state_cleanup(self): cleanup_a_little() self.cleanCount -= 1 if self.cleanCount <= 0: raise StopIteration() return NearlyDone def f2(): for x in Worker(): print str(x), The iterator solution is very similar to the generator solution (in fact, the generator also creates an iterator, just a different kind) but as you can see is a bit more code. The advantage is the iterator version may be able to continue if an unexpected exception is raised in one of the calls to `next', whereas the generator form will never be able to do so. The iterator version is also pickleable. Hope this helps, Jp > > thanks, > > Manuel > > > -- > http://mail.python.org/mailman/listinfo/python-list -- "If you find a neighbor in need, you're responsible for serving that neighbor in need, you're responsible for loving a neighbor just like you'd like to love yourself." -- George W. Bush, Sept. 16, 2002 From sholden at holdenweb.com Thu Jul 24 17:05:13 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 24 Jul 2003 21:05:13 GMT Subject: [newbie] MySQL : How to check if no row returned? References: <5ua0ivcl3loh45cq6pnoimsoa86nt0q4db@4ax.com> Message-ID: "Skip Montanaro" wrote in message news:mailman.1059075503.7037.python-list at python.org... > > Jane> I browsed through the archives of this site, but I didn't see how > Jane> to check if a SELECT through the MySql module returns an empty set > Jane> (whether a row exists or not, the "else" part below is always > Jane> called). > > The return value of the cursor's execute method indicates how many rows were > selected: > > >>> import MySQLdb > >>> conn = MySQLdb.Connection(...) > >>> curs = conn.cursor() > >>> print curs.execute("select * from cities where city like 'San %'") > 51 > >>> rows = curs.fetchall() > >>> print len(rows) > 51 > Alternatively, you can observer that the fetchall() method will return an empty list, and use if not rows: # empty set returned This is a bit more portable, which is maybe not important, but if you planned to distribute your software to users with other database platforms, not all DBI modules' execute() methods return the row count. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From martin_a_clausen at hotmail.com Tue Jul 22 21:37:26 2003 From: martin_a_clausen at hotmail.com (Mars) Date: 22 Jul 2003 18:37:26 -0700 Subject: How does Mr. Martelli's Borg recipe work ? Message-ID: <764b8294.0307221520.18017b09@posting.google.com> I have looked long and hard at Mr. Martelli's Borg recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 It is a very useful substitute for a Singleton, but I can't figure out how it works. _shared_state is never assigned any value, only self.__dict__ is assigend self._shared_sate's value - or rather (self.)_shared_state must be assigned a value at some point, otherwise the code wouldn't work(right ?). I have gone through the code in the debugger several(many) times, and inserted god knows how many print statements, but without luck(or skill i guess). Just so you don't waste your time, i do understand that _shared_state is a class field(variable, or what not) and that its state is shared by all instances. Sorry if this question is banal, but I really need to understand this, even if it means exposing my complete lack of understanding as far as what is probaly basic Python knowledge. Regards, Martin From spam at spam.com Mon Jul 7 05:59:58 2003 From: spam at spam.com (Ton K.) Date: Mon, 07 Jul 2003 11:59:58 +0200 Subject: bug in Tkinter? invalid literal for int() line 1035 In-Reply-To: <1057339224.48048.0@damia.uk.clara.net> References: <1057339224.48048.0@damia.uk.clara.net> Message-ID: Richard Townsend wrote: > "Fredrik Lundh" wrote in message > news:mailman.1057326192.22017.python-list at python.org... > >>Ton K. wrote: >> >> >>>I get subject when binding to a listbox. >>>The value for h is '??' which triggers the error. >>>I'm running Python 2.2.2 from SuSE. >> >>you're using a version of Tk that's newer than your Tkinter; that "??" >>you're seeing how really recent versions of Tk represent an "undefined >>integer value"... >> >>this has been fixed in Python 2.3, so you can either upgrade Python >>or link against an older Tk. >> >>(or modify Tkinter.py slightly, adding try/except clauses around the >>problem spots in Tkinter.py) >> >> >> >> > > If you are running SuSE 8.2 there is a fix on > http://www.suse.de/en/private/download/updates/82_i386.html for this > problem. > > Look for the python-tk 2.2.2 link, dated 18 April 2003. Update installed. Problem's gone. Many thanks. TK From frank at chagford.com Fri Jul 11 04:53:48 2003 From: frank at chagford.com (Frank Millman) Date: 11 Jul 2003 01:53:48 -0700 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <246a4e07.0307110053.71b78d5a@posting.google.com> Thanks to all for the replies. Much good advice and food for thought. It seems that this is an idea worth pursuing. I will now keep a low profile for a few more months to get the software to a stable state, and then hopefully you will hear from me again. Frank Millman From jerf at jerf.org Wed Jul 2 22:34:28 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Jul 2003 02:34:28 GMT Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: On Thu, 03 Jul 2003 01:14:44 +0000, Jeremy Bowers wrote: > On Wed, 02 Jul 2003 15:21:45 +0200, Aur?lien G?ron wrote: >> In all those cases, I much prefer having a human being go out and do the >> unit tests manually. > > The thing is, they won't. We've got about 50 years of collective > experience backing that up. It occurs I can expand on this. What I'm doing right now at my job (as opposed to the posting I'm replying to which is my hobby), I'm writing unittests for an existing mod_perl-based application that is several years old now. Been an adventure. Part of the reason I'm doing this is we're safely past the point where we can just poke and stab at the system and get any sort of coverage. We've got a role-based system (a user can have several types of roles, and technically, it's a permission-based system where roles are bundles of permissions...), and of course any number of things the user can do. Add up 10-ish roles, any number of actions (lets just call it 50 for simplicity, though there's no real way good way to put a number on "distinct actions in this system"), and a couple of other dimensions, and you've got a lot to cover. Well, actually, it's not addition, it's multiplication, so even in this rather simple case, you've got 10*50*8 or something things to cover. Each of these actions are relatively easy to characterize as unit tests (well, in proper XP terms these would be acceptance tests, which is still a step up for the existing system and while I hope to see true unit tests someday, a whole lotta refactoring would have to happen first), but we've recently been getting *hammered* with bugs that only occur on one or two cells in that (easily) 4000-cell matrix. (Of course they're the .5% fringe cases, important enough to actually occur but not important enough to bang on in poke-and-grunt testing.) We had a bug that only occurred with Role A in situation B in environment-type C. Unfortunately, while none of us ever though to test that exact combination of settings, it was reasonably common in the real world. Fully automated testing with absolutely no human interaction needed during the testing is really, really important, and I can't believe it took me this long to realize that. Not to mention the rest of the industry. On that topic, I'm starting to develop a multi-level unit testing philosophy, since it seems like every program I've ever worked on ends up with these multi-dimensional tests, and *yes* the equivalent of (1,4,2,4) will sometimes fail, all by itself. Is there any official XP dogma on that? Running a complete suite would take too long to be practical, so I'm starting to get this image of defining a subset of tests for development purposes (each axis, selected diagonals, smattering of others), and running the full suite, say, overnight for full coverage... or even constantly on a spare machine. Would make a great demo for tourists coming into the lab, with suitably verbose output, probably impress customers too. ;-) From peter at engcorp.com Fri Jul 11 09:47:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jul 2003 09:47:25 -0400 Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> <3F0D962E.23DA9F59@engcorp.com> <2c6431ab.0307110529.7a336f30@posting.google.com> Message-ID: <3F0EBFED.BB283660@engcorp.com> lamar_air wrote: > > Peter Hansen wrote in message news:<3F0D962E.23DA9F59 at engcorp.com>... > > "Bartolom? Sintes Marco" wrote: > > > > > > I have a program that unzip some zip files. After unzipping them, > > > I want to delete the zip files with os.remove, but I get this error: > > > OSError: [Errno 13] Permission denied: .... > > > > Close the files properly after unzipping them, perhaps? If that > > doesn't help, please specify operating system, and give details > > on how you are unzipping. Is it using Python's zipfile module, > > or some other method, and exactly how do you do it? > > I want to be able to delete a file on my C: drive through my python > script. My script writes a file. So i want to delete the file if it > already exists then write it. What's the best way to do this? Your question is still not clear, if it's the same as the original question. Please read http://www.catb.org/~esr/faqs/smart-questions.html for assistance in formulating your questions a little better. The simplest answer is that if *you* are creating the files, you just open them with "w" mode (as in "f = open('filename', 'w')") and it will automatically truncate the file if it already exists. Hoping that helps, -Peter From bokr at oz.net Sat Jul 12 15:41:54 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 19:41:54 GMT Subject: Help Support Python References: <3F0FE171.1090102@mxm.dk> Message-ID: On Sat, 12 Jul 2003 12:22:41 +0200, Max M wrote: >Guido van Rossum wrote: > >> I'm pleased to announce that the Python Software Foundation (PSF) is now >> accepting donations from individuals and companies interested in >> supporting our mission to improve the Python programming language. > > >It would be nice if there was some suggested amounts. > >Like: > > $x.xx for a "one year Student Python subscription" > $xx.xx for a "one year private Python subscription" > $xxx.xx for a "one year company Python subscription" > I wonder how employers would react to being asked by employees to contribute some percentage of (employee's estimate of time savings)*(employee pay rate) when some free python resource results in such a savings. Even if approvals are not forthcoming, with $-estimates presented the idea may sink in that free software (and participation in a free software community) is valuable ;-) (It might be that a log of such incidents would have to be logged & accumulated to get a number that was bigger than the company cost of processing approval and cutting check (and the cost of keeping the log ;-), unless they establish policy so it can be done cheaper). Contributions could be informally classified, to give some indication of what was $-valuable, e.g., "for cookbok recipe," or "for c.l.py support" or to encourage specific development, e.g., "for distutils," or "for unittest" etc. Of course. if someone wants to pay for entertainment value received, that's fine too ;-) >Etc. That could make it easier to decide what amount to donate. To me at >least. > >Anyhoo, I plunked in some $ and hope others will too. It's a great >language that has made my workday a lot more fun. > True. But money isn't everything. I think it must be recognized that the bulk of contributions to free software in general is still *, even though increasingly organizations are recognizing that free software is a process they can benefit from, and most if they contribute. So it is recognized that some level of * can be justified. But it is a social interaction. Being the only cook and provider at a pot luck is not a very good pot luck, but if most contribute, it can be great. If professional chefs volunteer or are paid to contribute, all the better. And digital pot lucks are magic, since eating doesn't use up what's on the table!! ... unless someone can limit the table access artificially, like with patents and copyrights etc. ;-/ Regards, Bengt Richter From nirina at mail.blueline.mg Mon Jul 21 00:44:16 2003 From: nirina at mail.blueline.mg (Raseliarison nirinA) Date: Mon, 21 Jul 2003 07:44:16 +0300 Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: <3F1A0C2D.6DBFAB2B@mega-nerd.com> Message-ID: <007201c34f43$6b3f0080$f3a2383e@raseliar> "Erik de Castro Lopo" wrote: > > Just in case you don't know, there is a Python wrapper > to my own libsndfile ( http://www.zip.com.au/~erikd/libsndfile ) > being developed here: > > http://www.arcsin.org/archive/20030520025359.shtml > > libsndfile handles a large number of different file types > (AU, AIFF, WAV and many more) as well as many encodings > (8, 16, 24, and 32 bit integer PCM, 23 and 64 bit float > PCM, A-law, u-law, MS ADPCM, IMA ADPCM, G721, G723 and > so on). > > Erik many thanks for the links. i will have a look at it - nirinA > -- > +-----------------------------------------------------------+ > Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) > +-----------------------------------------------------------+ > "In civilian equipment, such as computers, the number > of components alone makes miniaturization essential if > the computer is to be housed in a reasonable-sized > building." Electronics Oct. 1, 1957, p. 178 > -- > http://mail.python.org/mailman/listinfo/python-list From intentionally at blank.co.uk Mon Jul 14 19:35:46 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 00:35:46 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> Message-ID: On Mon, 14 Jul 2003 19:17:59 -0400, Roy Smith wrote: >Stephen Horne wrote: >> Ah - but this is also Pythons fault. It has arbitrarily redefined the >> meaning of a mathematics operator - presumably simply because C, C++, >> Java, Basic and others have done this in the past. >> [...] >> Personally, though, I'd go with Pascal on this one. > >Most languages have two "equals" operators, one means assignment, the >other means test for equality. Depending on the language, these are >spelled "=" and "==" or ":=" and "=" (or a few other variations). That's why I referred to Pascal. >The wierd thing is that I don't think either one really matches what a >mathematician means when he writes "=". In math, "=" is neither an >assignment or a test: it's an assertion. 99 out of 100 times, true. But not always - especially in discrete maths. For example, if I write... [forall] x . f(x) = y It's hard to interpret that '=' as an assertion. Similar applies to a range of maths operators. Basically, the way I rationalise it is that when I see what looks like a boolean expression standing on its own, I take it as an assertion that that expression evaluates to true. I'm not saying that has any mathematical validity, but it does seem to cover all cases. So if I see... x = 1 I take it as an assertion that the boolean test 'x = 1' evaluates to true, and from that I can infer the value bound to x (or, in other cases, infer some properties of that value). Or rather I don't - but that's the rationalisation for what I do do. From gmduncan at netspace.net.au Mon Jul 7 03:56:50 2003 From: gmduncan at netspace.net.au (gmduncan) Date: Mon, 07 Jul 2003 17:56:50 +1000 Subject: Python Gurus; "Legend in their own Lunchtime"? Message-ID: <3F0927C2.4000604@netspace.net.au> UK "Private Eye" readers will wink at this. I've been flicking thru Alex Martelli's "Python In a Nutshell" and have been impressed by the authoritive tone , and scope of its contents. An impressive production from a technical point of view, even tho I doubt that anyone could have created it all without help. But am I the only one to feel discomforted by the many Olympian (questionable) judgements he scatters through the code, about every aspect of software development ? A better editor needed ... I also wonder why he never saw fit to mention under "Books and Magazines", Graysons book "Python and TKinter Programming". Martelli needs to say why. Alex - are you there ? - Gary (irritated) From db3l at fitlinxx.com Thu Jul 17 18:33:22 2003 From: db3l at fitlinxx.com (David Bolen) Date: 17 Jul 2003 18:33:22 -0400 Subject: hex to signed integer References: <9j6chvoep7k34fbqutvp364lghnmmohrsj@4ax.com> Message-ID: Tom Goulet writes: > Tim Roberts wrote: > > Tom Goulet wrote: > > >>I want to convert a string of hexadecimal characters to the signed > >>integer they would have been before the statement converted > >>them. How do I do this in such a way that is compatible with Python > >>versions 1.5.2 through 2.4, and not machine-dependent? > > > if hexbit[0] < '8': > > temp = int(hexbit,16) > > else: > > temp = int(long(hexbit,16)-2**32) > > The function takes only one argument in Python 1.5.2. Yes, the base argument was added in later around Python 2.0. An equivalent operation to int(value,base) in Python 1.5.2 and any of the later versions (at least through 2.3 - 2.4 doesn't exist yet) would be the string.atoi(value,base) function. However, as indicated by the above code, both int() and string.atoi() limit their result to a signed integer, so depending on the hexadecimal string it might overflow and result in an exception. So for any sized hexadecimal string, use string.atol(value,base) instead. For example: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> print string.atoi('20',16) 32 >>> print string.atoi('FFFFFFFF',16) Traceback (most recent call last): File "", line 1, in ? File "c:\Python\2.2\lib\string.py", line 225, in atoi return _int(s, base) ValueError: int() literal too large: FFFFFFFF >>> print string.atol('FFFFFFFF',16) 4294967295 >>> print string.atol('%08X' % -1,16) 4294967295 >>> One note - if you end up converting the result of string.atol() with str(), under Python 1.5.2 it will have a trailing "L" but will not have that under any later Python release. Converting it to a string with repr() will have the trailing "L" under all Python releases. -- David From owner-mutt-announce at mutt.org Tue Jul 8 23:54:41 2003 From: owner-mutt-announce at mutt.org (owner-mutt-announce at mutt.org) Date: 9 Jul 2003 03:54:41 -0000 Subject: mutt-announce@mutt.org: Non-member submission from Message-ID: <20030709035441.15812.qmail@ns.gbnet.net> Your submission to the list has been forwarded to the list owner for approval because you do not seem to be on that list. If you want to join the list, send email to , with "subscribe mutt-announce" in the message text (not the subject). From kj at ockey.fake. Mon Jul 21 05:15:26 2003 From: kj at ockey.fake. (kjockey) Date: Mon, 21 Jul 2003 09:15:26 GMT Subject: pythonic malloc Message-ID: I have some simple UDP code that does: s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr) This is OK, except that I'd like to change the text in the middle ("rachel", which is the hostname FWIW), and the NUL padding needs to go out to make the length 25 bytes (so the padding depends on the length of the name). So I could do something like: retpacket = "\xf0\x00\x02\x00"+socket.gethostname() while len(retpacket) < 26: retpacket += "\x00" s.sendto(retpacket, addr) But that feels "wrong". And Python in a Nutshell says its a bad idea - "anti-idiom". Can anyone show me the true path? Brad From abelikov72 at hotmail.com Fri Jul 11 20:51:33 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Sat, 12 Jul 2003 00:51:33 GMT Subject: How to get all IP addresses in python? References: <6cd58b6.0307110715.1bb9bc23@posting.google.com> Message-ID: On Fri, 11 Jul 2003 14:50:00 -0400, "Yun Mao" wrote: >Sorry, this still doesn't work very well on my machine. > >>>> print socket.getaddrinfo(socket.gethostname(), None) >[(2, 1, 6, '', ('127.0.0.1', 0)), (2, 2, 17, '', ('127.0.0.1', 0)), (2, 3, >0, '', ('127.0.0.1', 0))] >>>> > >Any ideas? Thanks! FYI, It works perfectly on my Windows 2000 machine. ... import socket ... print socket.getaddrinfo(socket.gethostname(), None) [(2, 0, 0, '', ('124.181.217.203', 0)), (2, 0, 0, '', ('169.254.25.142', 0)), (2, 0, 0, '', ('169.254.218.201', 0))] ... Good to know too! From mis6 at pitt.edu Tue Jul 29 13:40:56 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 10:40:56 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <2259b0e2.0307290940.49ff417d@posting.google.com> I have posted a recipe with the itertools solution suggested in this thread: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212959 Thanks to everybody who gave feedback! Michele From bkc at Murkworks.com Fri Jul 11 17:23:14 2003 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 11 Jul 2003 17:23:14 -0400 Subject: object instance data to docbook, xml, pdf, etc? References: Message-ID: _ "David Mertz, Ph.D." wrote in message news:lchD/kKkXYHM092yn at gnosis.cx... > Harry George wrote previously: > |We are outputting the instance data, sort of like Gnosis xml_objectify, > |but to docbook DTD. > > You *could* use XSLT to transform the gnosis.xml.pickle output into > DocBook (I'm pretty sure you mean that, objectify goes in the other > direction generic-XML -> python). > > However, I personally find XSLT extremely awkward. If someone doesn't > give you the done-deal, you might find it useful to take > gnosis.xml.pickle and fork it for your desired DocBook/XML output. All > the issues about traversing objects is handled, you should pretty much > be able to just look for the XML tags that get written, and substitute > those as needed. He could modify the xml.pickle code this way, but what if his requirements change in 5 months? I think it's better just to dump the pickle and bite the bullet on xslt sheets for conversion. I use gnosis.xml.pickle's xml output to load dynamic tables in IE (client-side stylesheets convert to html on the fly) and I use a different sheet to generate PDFs with FOP. Oh, and last week I find I also have to output data into Excel compatible form. I haven't decided if I'll write out a CSV. Either directly from the Python objects, or using XSLT to convert the gnosis.xml.pickle output or write to "native Office 2003 XML format". XML can be a pita, but it has paid off for me anyway. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 7 13:50:11 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 07 Jul 2003 19:50:11 +0200 Subject: Apache mod_python and Sessions In-Reply-To: <20030707091923.1f12f872.scpusenet@werbung.schabi.de> References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> <20030707091923.1f12f872.scpusenet@werbung.schabi.de> Message-ID: <3f09b2cf$0$49098$e4fe514c@news.xs4all.nl> Markus Schaber wrote: > python_weblib that does what I need (Additionally, my boss suggested > that we should not use mod_python but CGI instead.) What!? Why!? Any sane explanation why you should go with slow, outdated CGI scripts instead of the nice, fast web server integration of mod_python? --Irmen From a.schmolck at gmx.net Thu Jul 3 17:02:01 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 03 Jul 2003 22:02:01 +0100 Subject: Emacs + py-mode + tkinter problem References: Message-ID: Thomas G?ttler writes: > Tom Locke wrote: > > > Hi All, > > > > I'm having trouble with the python shell within emacs. It's hanging when I > > use tkinter. Setup is: > > > > Windows XP > > emacs 21.3 > > py-mode 4.6 > > > > Recipe: > > From a python-mode buffer, launch the python shell (C-c !), then in the > > shell > > Sorry, I don't know an answer since I only start > the interactive prompt from a terminal. Since I am quite happy > I would like to konw why you want the python interpreter in emacs? > While I can't speak for the OP, how about: - uhm, how do you get code into your interactive session? In python mode you can run selected code on a keypress (even if its indentation doesn't start at 0), whereas last time I looked, cut and pasting of multiline code didn't work *at all* for a stand-alone python shell (because the interactive python shell insists on extra newlines after statements) - debugger integration like automatically landing in the offending source code on exceptions and being able to walk through the code corresponding to the traceback (try C-c -) - to use a real editor, not just for editing code but in the interactive session, too (instead of the crippled readline interface). Ever tried comint-previous-matching-input-from-input on M-p? Better than cursor-up, no? Isearching your output can also be quite useful (and M-z etc. also happen to work, because you're using emacs, not something that feels a bit like it). Maybe too many people are happy with too little (essentially edit/run-whole-program/debug cycles a la C, plus maybe using python interactively as a calculator or to look up documenation). If I had time I'd write a tutorial on using ipython from within emacs for (I think) much more effective interactive development. As it is I still haven't found the time for a reply to a post by David Abrahams on the topic. 'as From dave at nullcube.com Thu Jul 31 22:24:39 2003 From: dave at nullcube.com (Dave Harrison) Date: Fri, 1 Aug 2003 12:24:39 +1000 Subject: setuid and current paths Message-ID: <20030801022439.GA17699@dave@alana.ucc.usyd.edu.au> hi all, Im using the setuid-prog.c script to setuid my cgi script. The C script is chowned to "myuser" (not root, I dont need root access just the access myuser has). However when I do this, the path it executes the script from is not the same dir as the cgi itself. My CGI script uses a dir structure within its own dir, but when I execute it from another dir (via the setuid script) Im not in that dir natively. Ive tried chdir without success, and chroot runs me into a permissions problem. Anyone want to tell me how I _should_ be doing this ? From guettler at thomas-guettler.de Tue Jul 8 06:47:20 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 08 Jul 2003 12:47:20 +0200 Subject: start script automatically References: Message-ID: Tom wrote: > Hi, > > I have a problem because I don't know how to start my script > automatically after a special event happens. > > In detail: I store data from a PLC. Every 30 seconds the data is stored > in a new file. After the file is stored I would like to start my script > that analyzes the data right away. Any help how to do this is deeply > appreciated. Hi, I don't know what PLC is, but why not use an endless loop. Files arrive in a directory called "input" and after processing you move them to a directory called "done". (not tested) while 1: for file in os.listdir("input"): process(file) os.rename(os.path.join("input", file), os.path.join("done", file)) thomas From Juha.Autero at iki.fi Wed Jul 16 08:36:23 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Wed, 16 Jul 2003 15:36:23 +0300 Subject: Waiting for processes to finish under Solaris References: <3F144AB2.10703@dadsetan.com> <3F145C82.6010606@dadsetan.com> Message-ID: <87y8yyeji0.fsf@jautero.no-ip.org> Behrang Dadsetan writes: > It is also a very underdocumented feature.. :)) signal.SIG_DFL (0) is > documented as """SIG_DFL > This is one of two standard signal handling options; it will simply > perform the default function for the signal. For example, on most > systems the default action for SIGQUIT is to dump core and exit, while > the default action for SIGCLD is to simply ignore it. """ > Hopefully it will NOT SIGQUIT it... You are reading wrong documentation. signal.SIG_DFL is a constant for handler parameter of signal.signal. Signal constants are defined as SIG* without underscore. Except of course 0, because it is not a signal. From Linux kill(2) man page: int kill(pid_t pid, int sig); ... If sig is 0, then no signal is sent, but error checking is still performed. Since os.kill will eventually call kill(2) system call, it works the same way. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From peter at engcorp.com Fri Jul 4 14:10:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 14:10:40 -0400 Subject: Python is a gem, you need to keep pushing it .... References: <3F05C138.687F5A06@engcorp.com> Message-ID: <3F05C320.BF195230@engcorp.com> Peter Hansen wrote: > > sismex01 at hebmex.com wrote: > > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > Sent: Viernes, 04 de Julio de 2003 07:42 a.m. > > > > > > delphiro wrote: > > > > > > > [attribution removed... don't do that!] > > > > > Python *is* great but lets not pretend that its a good > > > > > fit for every problem. > > > > > > > > I doubt that (unless you develop hardware drivers). > > > > > > Are you saying that you think Python _is_ a good fit > > > for every problem, excluding only hardware drivers? > > > > > > -Peter > > > > > > > Seems like he is; in my experience Python has been flexible > > enough to fit any problem I've tossed at it. > > As it has for me, but neither you nor I have thrown *every* > problem at it, and the OP appears to be stating that he believes > we would never find Python inadequate, no matter what we threw > at it (exception hardware drivers again). > > As an example, one could argue that embedded systems are not > merely "hardware drivers" (one could also argue that they are, > but I do not), yet we've found Python suitable in only one > of our embedded system products. Thus contradicting myself, of course. :-) What I meant to say was "I know what you mean, since I've found it highly suitable as well, but no one with good experience in computing could reasonably claim it will fit *all* problems except hardware drivers." -Peter From inigoserna at terra.es Sun Jul 13 16:13:33 2003 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: 13 Jul 2003 22:13:33 +0200 Subject: command prompt change dir In-Reply-To: <200307110928.02474.mfranklin1@gatwick.westerngeco.slb.com> References: <200307110928.02474.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: <1058127212.10014.23.camel@inigo.katxi.org> Hello, I think this is the solution midnight commander uses. In lfm [1], I use something similar: I've created next shell function in /etc/bashrc: lfm () { /usr/bin/lfm $*; LFMPATHFILE=/tmp/lfm-$$.path; cd "`cat $LFMPATHFILE`"; rm -f -f $LFMPATHFILE } Before exit, the program writes the directory into a temporal file /tmp/lfm-pid.path, where pid is the process id of lfm, then change the directory. I hope this helps, I?igo [1] http://www.terra.es/personal9/inigoserna/lfm El vie, 11-07-2003 a las 10:28, Martin Franklin escribi?: > On Friday 11 July 2003 07:39, Peter Vestergaard wrote: > > Hi > > Probably a simple question but I have not been able to find out how: > > I want my python script to generate a path based on some simple lookups and > > then change my path so that when the script exits my command prompt (from > > which I launched the script) is standing at this path. The path already > > exists. > > I have tried chdir(path), system('cd '+path) and many others but none > > changes my actual path. > > Hope anyone can help > > Regards, Peter Vestergaard > > I don't think it is possible to change the path of the calling program (in > this case the command prompt you use to start the python script....) > However you could use a shell trick to kind of do what you want:- > > > #!/usr/local/bin/python > # ChangePath script > # invoke from command line like so: > # cd `ChangePath.py` > # > > # simple lookup... > path = "/usr/oracle/" > print path > > > Invoke the above from your command line (xterm or whatever...) > > cd `ChangePath.py` > > I have only tested this on Linux + bash and I would guess this would not work > on Windows... > > > Regards > Martin -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From carsten at gehling.dk Wed Jul 16 10:54:09 2003 From: carsten at gehling.dk (Carsten Gehling) Date: Wed, 16 Jul 2003 16:54:09 +0200 Subject: SV: Choosing the right framework In-Reply-To: <20030716143322.11957.qmail@green.zadka.com> Message-ID: > Fra: python-list-admin at python.org > [mailto:python-list-admin at python.org]P? vegne af Moshe Zadka > Sendt: 16. juli 2003 16:33 > Why, did Apache's reverse proxy module stop working suddenly? Sorry - you're right :-) In fact this is also the way I would configure Zope. > Note, however, that Twisted is *not* a web framework. It has a web > server, but writing in that raw is much like writing raw mod_python > code -- it's often useful, but most of the time, it is the wrong > level of abstraction. Twisted's "official" templating system is > Woven. However, Twisted also works with Quixote and it is quite possible > to adapt other frameworks to it. And lest I forget, webtk[0] > also runs on top of Twisted. Ahh, now I didn't know this - YAFTR (Yet Another Framework To Research....) > It, is, however, still strange to me why you rejected Plone so carelessly > as it *is*, actually, a CMS. Maybe you had good reasons too -- but until > you explain those reasons, it will be hard to guess whether they apply > to other web frameworks. This may be due to pure lazyness. I looked at Plone for 3 days, and still didn't "grasp it". Add to this a heavy burden of work. I may be ignorant of major Plone issues, but here are my main "grudges" against it (please bear in mind that I haven't researched Plone for more than 3 days, and some of my arguments may look plain stupid ;-) : 1) I don't the idea, that the user authentication (login form) to managing the content of the website is visible on the website's pages. 2) I want the content management interface to be similar to the one I currently use in my own CMS. (One frame with a tree structure of the page hierarki, one frame with the page displayed, and content editing forms as popup windows). - Carsten From hat at se-46.wpa.wtb.tue.nl Tue Jul 1 03:55:01 2003 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: Tue, 1 Jul 2003 07:55:01 +0000 (UTC) Subject: I have a list... References: <20030701113915.226ae9bd.agg@astranet.ru> Message-ID: On Tue, 1 Jul 2003 11:39:15 +0400, Damir Hakimov wrote: > Hi, All! > > say, i have a function: > > def f(*b): > print b > return > > then i do: > f(3,4,5) > (3, 4, 5) > > but i have list f=(3,4,5) > f(l) > ((3, 4, 5),) > > how can i call f function to result > f(???(b)) > (3, 4, 5) You mean apply(f,(3,4,5)) ? Albert -- Unlike popular belief, the .doc format is not an open publically available format. From chatralias at aol.com Sun Jul 20 11:31:52 2003 From: chatralias at aol.com (Chatralias) Date: 20 Jul 2003 15:31:52 GMT Subject: Newbie Questions? References: <504413fa.0307200626.3fceb85a@posting.google.com> Message-ID: <20030720113152.09823.00000323@mb-m11.aol.com> >Hail all. Are newbie questions allowed here, or is there a different >Newsgroup for that? Thanks. > The answer is yes and yes. A great place to check out is here. (Taken directly from the Newbies page at python.org without permission - It's almost like living on the edge.) tutor at python.org A low-volume mailing list for folks who want to ask questions regarding how to learn computer programming with the Python language. See http://www.python.org/psa/MailingLists.html#tutor for more info. Ray Rastm2 at aol.com = AOL.COM =yeah go ahead and laugh. From donald_rivard at hotmail.com Wed Jul 23 15:10:37 2003 From: donald_rivard at hotmail.com (Don Rivard) Date: Wed, 23 Jul 2003 15:10:37 -0400 Subject: zope ZMySQLDA Message-ID: zope 2.71b ZMySQLDA 2.08 MySQL-python-0.9.2 mysql 3.23.55NT When I attempt to connect, by creating a Add Z MySQL Database Connection, I set the connection string to database user password, and i keep getting the following error Site Error An error was encountered while publishing this resource. Error Type: AttributeError Error Value: server_capabilities Any ideas why? Don Rivard From bokr at oz.net Tue Jul 22 12:27:02 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2003 16:27:02 GMT Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: On Tue, 22 Jul 2003 08:34:13 +0000 (UTC), Duncan Booth wrote: >bokr at oz.net (Bengt Richter) wrote in news:bfi4ir$t21$0 at 216.39.172.122: > >> I guess the full set of functions might be >> any_true, any_false, all_true, and all_false. >> >> or maybe someone can think of better short phrase? >> > >'all_false(...)' is simply 'not any_true(...)' >'any_false(...)' is 'not all_true(...)' > >So you could get by with just two of these functions, in which case >'any_of', and 'all_of' might be suitable names. > I don't think they're equivalent if they do short-circuiting. Regards, Bengt Richter From tomas at fancy.org Mon Jul 14 19:15:08 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 16:15:08 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> Stephen Horne wrote: > All you have proven is that it is the distinction between types > that get re-bound and those that don't (rather than the use of > references) that is unnecessarily confusing and error prone. As the firestarter (I apologize for the flames that have erupted), I must admit that even I know that this distinction does not exist in Python. There aren't some types that get rebound and others that don't. def fn(arg): local = SOME_GLOBAL local = arg local gets rebound to arg regardless of what the types involved are, period. > The wart remains, even if my description was wrong. And even that > is a dubious claim. I still feel that there's a wart of some sort, but it's not due to any inconsistency in the language, despite what I may have said before (I've been thinking about it a lot over the past few days). > A Python user is interested in how an object behaves - not how it > is internally implemented in the interpreter. Immutable objects > don't behave as references - the internal use of references for > immutable objects is basically a lazy copying optimisation and, > apart from performace and a couple of other technicalities (e.g. > the 'is' operator), has no relevance. Are they really technicalities, though? I mean, a mutable object can be changed. It's the same object, just changed. Immutable objects, however, can't be changed. You can get something that appears like changing it, but it's actually building a new thing and binding the label to that new thing. What I specifically want is a way to have a "second-level binding", e.g. a reference to a reference (assuming that the terminology is correct by saying that all Python variables are references). This is where I see the hole in Python, that there actually is a class of object that is different from everything else; you can bind to anything at all in the language...except references. -tom! From hwlgw at hotmail.com Wed Jul 2 13:01:58 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 2 Jul 2003 10:01:58 -0700 Subject: XML Validation with Python Message-ID: Can you give a commandline example how to do XML Validation (checking against a DTD) with Python? Not with 4Suite or other 3rd party libraries, just the Python standard distribution. I have Python 2.2 but can upgrade to 2.3 beta if needed. I am looking for something like: " $ python validate.py myxmlfile.xml mydtd.dtd " where validate.py contains something like: " import somexmllib import sys # prints 1 if Okay :-) print somexmllib.validate(sys.argv[1], sys.argv[2]) " I am sorry if this is a FAQ or if it is in one of the xml libraries, I just could not figure it out! From alanmk at hotmail.com Fri Jul 4 11:13:13 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 04 Jul 2003 16:13:13 +0100 Subject: Help with xml.parsers.expat please? References: Message-ID: <3F059989.FFBD6E67@hotmail.com> Will Stuyvesant wrote: > There seems to be no XML parser that can do validation in > the Python Standard Libraries. And I am stuck with Python > 2.1.1. until my web master upgrades (I use Python for > CGI). I know pyXML has validating parsers, but I can not > compile things on the (unix) webserver. And even if I > could, the compiler I have access to would be different > than what was used to compile python for CGI. So it didn't work out with xmlproc? Isn't xmlproc a pure python parser that you should be able to drop in and run without compiling anything? > I need to write a CGI script that does XML validation (and > then later also does other things). It does not have to > be complete standards compliant validation but at least it > should check if elements are declared and allowed in > special places in the XML tree. I think you would be much more likely to get constructive help if you posted some examples of the tree structures and data that you're processing. > I tried to understand SAX and DOM but I gave up, and > effbot advises to avoid them anyway. So I am studying > xml.parsers.expat now, but I am stuck. SAX and DOM aren't solutions, they're tools. They are simply different ways to accessing the contents of an XML document. They may or may not be suitable for your problem, depending on a wide variety of considerations. I think the problem needs to be clearly defined before an appropriate solution can be reached. > The program below *does* print information about DOCTYPE > declarations but nothing about the element definitions in > the DTD. I feed it an XML file with a DOCTYPE declaration > like and the DTD is > in the same directory. I also tried inputting the DTD > itself to this program but that doesn't work either > (ExpatError: syntaxerror at the first element definition). > > Please help if you can. > > # file: minimal_validate.py > # > import xml.parsers.expat > > def element_decl_handler(name, model): > print 'ELEMENT definition: ', name, ' model: ', model > > def doctype_decl_handler(doctypeName, systemId, publicId, has_internal_subset): > print 'DOCTYPE declaration: ' > print ' doctypeName: ', doctypeName > print ' systemId: ', systemId > print ' publicId:', publicId > print ' internal subset:', has_internal_subset > > p = xml.parsers.expat.ParserCreate() > > p.ElementDeclHandler = element_decl_handler > p.StartDoctypeDeclHandler = doctype_decl_handler > > import sys > input = file(sys.argv[1]).read() > p.Parse(input) I think you need to do some reading on what SAX does. In summary, it gives you the pieces of an XML document, in a series of function callbacks. You've got to do something with the pieces that you're given. SAX won't solve your problem any more than anything else unless you know what pieces you are receiving, and are doing something with them. One memory efficient way of building up a document in memory is to create a python object to represent every element, and with each "element object" being a (python) attribute of its parent. It's a lot easier than it sounds, and can be read about here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 And you can read about SAX in general here http://www.devarticles.com/art/1/383/2 http://www-106.ibm.com/developerworks/xml/library/x-tipsaxflex.html The latter is a good example from Uche Ogbuji about extracting pieces of a document from a SAX stream, which might be easily adaptable to your problem. But I still think you'd be better to describe the problem as simply as you can here, rather than fumbling around. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From leej at citymutual.com Mon Jul 21 06:49:59 2003 From: leej at citymutual.com (L. A. Jackson) Date: Mon, 21 Jul 2003 11:49:59 +0100 Subject: Python voting demo discussion References: Message-ID: "XML don't really count" Nor should dimpled chads *grin* On 21 Jul 2003 04:30:55 -0500, Ian Bicking wrote: >XML don't really count From bokr at oz.net Wed Jul 23 12:02:44 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Jul 2003 16:02:44 GMT Subject: The global statement References: Message-ID: On Wed, 23 Jul 2003 16:56:08 +0200, Thomas =?ISO-8859-15?Q?G=FCttler?= wrote: >David Hitillambeau wrote: > >> Hi guys, >> As I am new to Python, i was wondering how to declare and use global >> variables. Suppose i have the following structure in the same module (same >> file): >> >> def foo: >> >> >> def bar: >> >> >> >> I want to enable some sharing between the two functions (foo and bar) >> using one global variable in such a way that each function can have read >> and write access over it. > >Hi David, > >global BAD Don't need the above line if you are already in global scope. >BAD=1 > >def foo(): > global BAD > print BAD > >def bar(): > global BAD > print BAD > >foo() >bar() > >If foo and bar are in the same file, >you don't need the "global". > Unless you want to rebind it. Then you need it in order not to get the default behaviour of creating a local within the function. E.g., here are some variations to think about. Note what gets changed and when: >>> BAD = 'global BAD' >>> def baz(): ... BAD = 'local assignment binds locally unless global is specified' ... print BAD ... >>> baz() local assignment binds locally unless global is specified >>> print BAD global BAD >>> def baz(): ... global BAD ... BAD = 'assigned locally, but destination global instead because of "global BAD"' ... print BAD ... >>> print BAD global BAD >>> baz() assigned locally, but destination global instead because of "global BAD" >>> print BAD assigned locally, but destination global instead because of "global BAD" >>> BAD = 'global BAD' >>> def baz(BAD=BAD): ... BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined' ... print BAD ... >>> print BAD global BAD >>> BAD = 'changed global' >>> print BAD changed global >>> baz() global BAD -- local mod to local arg pre-bound to global BAD when baz defined >>> print BAD changed global HTH Regards, Bengt Richter From jjl at pobox.com Sat Jul 26 19:22:04 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 00:22:04 +0100 Subject: Why does Python do this? References: Message-ID: <87fzksc1r7.fsf@pobox.com> Gre7g Luterman writes: [...] > Note the extra space printed when I executed the "print y" command. [...] > So it only seems to happen when you interrupt a print statement with > another print statement during an implicit string conversion. 2.2.1 only does this from the interactive prompt, not from a .py. John From jack at performancedrivers.com Thu Jul 17 11:20:50 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 17 Jul 2003 11:20:50 -0400 Subject: Replacing rexec In-Reply-To: <20030717131402.26541.qmail@green.zadka.com>; from m@moshez.org on Thu, Jul 17, 2003 at 01:14:02PM -0000 References: <87adbd73f1.fsf@pobox.com>, <87adbd73f1.fsf@pobox.com> <20030717131402.26541.qmail@green.zadka.com> Message-ID: <20030717112050.A1168@bitch.nowhere.blah> On Thu, Jul 17, 2003 at 01:14:02PM -0000, Moshe Zadka wrote: > [Aahz] > > require forking the code. Note that it's already too easy to write a > > DoS attack against Python: 100L**100**100 will do it. Conversely, if > > only trusted code is going into the server, there's no need for rexec. > > [John J. Lee] > > I don't see how it's possible to prevent that, whatever language > > you're using. > > Limits on memory and CPU ticks used by untrusted code. > This brand new, cutting edge technology is not yet available, and > LambdaMOO was, of course, a product of Guido misusing the time-machine. > Which doesn't exist itself, either. MUD interpreters [I only know the LPC interpreter first hand] were designed for this from the ground up. A single operation couldn't spin the CPU forever or consume a world's worth of memory. They did this badly. It wasn't possible to crash a MUD but you could bring one to its knees by using LIMIT-1 of every resource every bump. MUDs also have an advantage because the people writing code are hand picked. They have a stake in doing the right thing so they rarely write malicious code. -jack From donn at u.washington.edu Mon Jul 7 18:03:22 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Jul 2003 15:03:22 -0700 Subject: print attitude References: <3F0669B5.679FB505@alcyone.com> <3F09E62C.D1A8D53A@alcyone.com> Message-ID: In article <3F09E62C.D1A8D53A at alcyone.com>, Erik Max Francis wrote: > Donn Cave wrote: > > > Speaking of floats, I believe lists containing floats are the main > > case where people really resist seeing the sense in this - but it's > > easier to call that a wart in float's repr, since they're as bugged > > wherever they see it and in my opinion rightly so. > > Personally, I think the internal difference between str and repr hits > right upon a proper difference: str is for a "reasonable" > human-readable representation, and repr is for as faithful and > informative a representation as possible. These both have their uses > and I approve of the distinction. > > The confusion, in my opinion, comes from the fortuity of when str vs. > repr is used, which is easy to understand once you've been exposed to it > but is very confusing at first. Even for someone who's familiar with > the inaccuracy of floating point, you can very easily see how someone > would be confused and worried about the following code fragment: > > >>> x = 1.4 > >>> print x > 1.4 > >>> print [x] > [1.3999999999999999] Maybe it isn't time to wade back into this, only to repeat ad nauseum the same old discussion. My point is that there is a way to look at str vs. repr that 1) doesn't use utterly ambiguous phrases like "reasonable" or "human-readable", and 2) makes it more or less self-evident that list will repr its contents. For more, see 61-message thread http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=uw1i4nqpl33h.1 l3wpteil4jb0.dlg%4040tude.net&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie% 3DUTF-8%26selm%3Duw1i4nqpl33h.1l3wpteil4jb0.dlg%254040tude.net Donn Cave, donn at u.washington.edu From newsgroups at jhrothjr.com Wed Jul 23 18:53:08 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 23 Jul 2003 18:53:08 -0400 Subject: very Very VERY dumb Question About The new Set( ) 's References: <20030723144732.13232.00000523@mb-m10.aol.com> Message-ID: "Raymond Arthur St. Marie II of III " wrote in message news:20030723144732.13232.00000523 at mb-m10.aol.com... > very Very VERY dumb ? about the new Set( ) 's > > Please be kind and read this like you know I've been up 33-34 hours reading > PEP's but... > > Doc\ref 2.6 Delimiters show's three unused characters "@ $ ?". > @ sort of looks like and sort of sounds like a set an > $ well sort of obvious. > I can imagine that the $ would be confused for money and @ is ugly. > > You folks have prob'ly been all over this. > Even thou I've been using Python since 1.4, I only joined the comp.lang.python > a couple weeks ago so I don't know the flame wars over the Set implimentation. > > Ray St. Marie --- Afraid to sign his name to this one > Rastm2 at aol.bomB Is your question why they didn't add new operators for the set operators, rather than overloading the existing ones? There are two factors. One is that Guido is holding those three characters back for some time when we *really* need them. Sets are still somewhat experimental - if they take off like wildfire they may migrate into the core. Adding operator symbols for something that's in a library doesn't seem like a real good idea. The other issue is that those three characters have no particular relationship to sets, while the Unicode standard contains the actual set operator symbols used in mathematics. When the source script finally becomes Unicode will be the time to talk about expanding the operator set. I'd be very surprised if it happens before 3.0, and very surprised if it isn't one of the major features in that same rather vague 3.0 release. On the other hand, I'm hoping (without much expectation) that we decide that 2.3 will be followed by 3.0. I've got a little list... (with apologies to Gilbert and Sullivan.) John Roth From Chris.Rennert at mdi-oshkosh.com Tue Jul 1 12:15:43 2003 From: Chris.Rennert at mdi-oshkosh.com (Chris Rennert) Date: Tue, 1 Jul 2003 11:15:43 -0500 Subject: remove special characters from line References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> <3F01AECF.965FAADA@hotmail.com> Message-ID: <3f01b363$0$43851$39cecf19@news.twtelecom.net> Thanks guys for the help, As I was waiting for a reply I was trying a few things as well, this is what I ended up doing. I created a list with all the valid characters in in and just did a index check if(line[0] in LIST): That seemed to do exactly what I wanted. Again I thank you for the constructive replies Radovan & Alan. Chris Rennert "Alan Kennedy" wrote in message news:3F01AECF.965FAADA at hotmail.com... > [Chris Rennert] > > > If I have a line like this > > > > ?blah blah blah blah blah > > > > I know I could do a slice like this [1:] to pull everything but the > > special character, but what if I have several lines in a file. > > I am not sure how I would detect a special character like that. I > > would just like to pull everything from those lines (and the special > > character always appears as the first character, but not on every line) > > except for the special characters. > > How about something like this? > > for line in file('myfile.stars'): > print line.lstrip('*') > > Should remove all '*' (even if there is more than one) from the beginnings (but > not the ends) of lines. > > Egor Bolonev wrote: > > > I didn't get what you're talkink about. > > Then what was the purpose of your reply? > > I find it helps keeps the signal noise to ratio of the group down if people only > post when they have something to contribute. > > regards, > > -- > alan kennedy > ----------------------------------------------------- > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/mailto/alan From mwh at python.net Thu Jul 31 06:54:22 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 31 Jul 2003 10:54:22 GMT Subject: keystroke check References: Message-ID: <7h3brvbarwl.fsf@pc150.maths.bris.ac.uk> Wes Fraser writes: > Is there any way to check in a loop to see if at that > given moment in the program, a key on the key board is > being pressed without actually stopping like raw_ipnut > does? The answer to this depends very strongly on the platform you're running on. Cheers, mwh -- I wouldn't trust the Anglo-Saxons for much anything else. Given they way English is spelled, who could trust them on _anything_ that had to do with writing things down, anyway? -- Erik Naggum, comp.lang.lisp From t.leeuwenburg at nothing.bom.gov.au Fri Jul 18 01:23:03 2003 From: t.leeuwenburg at nothing.bom.gov.au (Tennessee James Leeuwenburg) Date: Fri, 18 Jul 2003 15:23:03 +1000 Subject: null pointer exceptions References: <3F17806E.3B9B4F75@alcyone.com> Message-ID: On Thu, 17 Jul 2003 22:06:54 -0700, Erik Max Francis wrote: Certainly I can catch it. However, Java does not require that it be caught itself. I realise it's not great practise to leave these kinds of things in your Java code, but I'm extending someone else's code, and don't really want to back-correct class after class as I find these problems coming up, especially since it doesn't cause Java any hassles. But I might end up having to - I just thought someone might know a neat way of getting around the problem. Cheers, -Tennessee > Tennessee James Leeuwenburg wrote: > >> I have a class which includes adding an ImageIcon. If the required >> graphic >> resource isn't present, there is a NullPointerException. Java doesn't >> care >> - the straight Java program handles it internally and gets on with >> life. >> But when I include it from Python, it explodes. > > A java.lang.NullPointerException is just an exception like anything > else. Can't you just catch it? > > max at oxygen:~/tmp% cat NullCaster.java > import java.lang.*; > > public class NullCaster > { > public static void main(String[] args) > { > Object nullObject = null; > String nullString = (String) nullObject; > nullString.length(); > } > } > max at oxygen:~/tmp% javac NullCaster.java > max at oxygen:~/tmp% jython > Jython 2.1 on java1.4.1 (JIT: null) > Type "copyright", "credits" or "license" for more information. >>>> import java.lang >>>> import NullCaster >>>> try: > ... NullCaster.main([]) > ... except java.lang.NullPointerException, e: > ... print 'oops:', e > ... > oops: java.lang.NullPointerException From theller at python.net Fri Jul 18 06:12:38 2003 From: theller at python.net (Thomas Heller) Date: Fri, 18 Jul 2003 12:12:38 +0200 Subject: Using Unicode scripts References: <3f17c520$0$7194$626a54ce@news.free.fr> Message-ID: "yzzzzz" writes: > Hi, > > I am writing my python programs using a Unicode text editor. The files are > encoded in UTF-8. Python's default encoding seems to be Latin 1 (ISO-8859-1) > or maybe Windows-1252 (CP1252) which aren't compatible with UTF-8. > > For example, if I type print "?", it prints ??. If I use a unicode string: > a=u"?" and if I choose to encode it in UTF-8, I get 4 Latin 1 characters, > which makes sense if the interpreter thinks I typed in u"??". > > How can I solve this problem? > > Thank you > > PS. I have no problem using Unicode strings in Python, I know how to > manipulate and convert them, I'm just looking for how to specify the default > encoding for the scripts I write. Use Python 2.3, and read PEP 263. Thomas From mertz at gnosis.cx Sat Jul 12 01:45:07 2003 From: mertz at gnosis.cx (David Mertz) Date: Sat, 12 Jul 2003 01:45:07 -0400 Subject: What's new with Gnosis Message-ID: At the suggestion of one of my correspondents, I slightly reluctantly implemented an RSS feed for my website/writing. It is perhaps a bit crude so far, but maybe I'll spiff it up. The RSS also has an HTML front to it. If you want to see the latest news about my _Charming Python_ or _XML Matters_ columns, or about other articles (later, perhaps stuff about my book), take a look at: http://gnosis.cx/rss.xml Or http://www.gnosis.cx/publish/whatsnew.html I'm new to this RSS stuff... so let me know (gently) if I've done anything terribly wrong. -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From jack at performancedrivers.com Wed Jul 2 03:22:17 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 2 Jul 2003 03:22:17 -0400 Subject: functors In-Reply-To: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com>; from tomas@fancy.org on Tue, Jul 01, 2003 at 06:25:18PM -0700 References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: <20030702032217.E1055@localhost.localdomain> On Tue, Jul 01, 2003 at 06:25:18PM -0700, Tom Plunket wrote: > How can I create a functor object in Python? > > What I want (being a C++ coder ), is to be able to create an > object that I is callable. The following is my attempt, but it > doesn't work: I would make countdown dumber, and make the call more explicit def countdown(thismany) for (i) in range(thismany): yield False yield True while True: yield False > def Update(self): > while not self.done: > self.countdown.Update() becomes def Update(self): while not self.done: if (self.countdown.next()): self.Callback() # person reading the code knows what happens but if you really want the hidden callback, just change the countdown() def countdown(thismany, call_this): for (i) in range(thismany): yield 69 # ignored by caller anyway call_this() # make the callback while True: yield 42 # more ignored yields But I'm not sure if this is what you really want, the countdown() keeps going even after it has fired. Hence the 'While True: yield False' If you need the callback because you have a whole bunch and can't keep track of each one individually, I'd make a parent class that decrements everyone and pops people after they fire. class Watcher(object): def __init__(self): self.watched = [] self.i = 0 def watch(count, call_this): self.watched.append((self.i+count, call_this)) def decrement(self): self.i += 1 callthese = filter(lambda x:x[0]=i, self.watched) for (dummy, callthis) in callthese: callthis() Just for fun, let's play with itertools from itertools import * def countdown(thismany): return chain(repeat(False, thismany), [True], repeat(False)) or the abusive def countdown(thismany, callthis): def fakeout(): # because "lambda x:yield x()" isn't legal yield callthis() return chain(repeat(None, thismany-1), fakeout(), repeat(None)) and the totally abusive (and totally untested) class Watcher(object): def __init__(self): self.watched = repeat(None) self.curr = 0 def watch(self, count, callthis): def fakeout(): yield callthis() assert(count > self.curr) # new job must fire after the current longest one self.watched = chain(repeat(None, count-1-self.curr), fakeout(), self.watched) self.curr = count def decrement(self): if (self.curr): self.curr -= 1 self.watched.next() Enjoy, -jackdied From peter at engcorp.com Thu Jul 17 09:23:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jul 2003 09:23:22 -0400 Subject: Co-routines References: Message-ID: <3F16A34A.5742F54F@engcorp.com> thewrights at ozemail.com.au wrote: > > I have an application in which I want the users to be able to create python > functions: > > def f1(): > print "1-1" > print "1-2" > print "1-3" > > def f2(): > print "2-1" > print "2-2" > print "3-3" > > and when my application runs, I want to execute these functions in > "lock-step", so that the output looks like: > > 1-1 > 2-2 > 1-2 > 2-2 > 1-3 > 2-3 I think the problem is underspecified. What do you mean by the quoted phrase "lock-step"? Your example includes only simple print statements, which generate output to sys.stdout. What are you really trying to accomplish? Do you want individual bytecodes to be executed one at a time from a series of functions? Do you want any output to be interlaced on a line-by-line basis? Any call to any I/O routine? Need more detail. -Peter From martin at v.loewis.de Mon Jul 14 01:47:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 07:47:40 +0200 Subject: =?iso-8859-1?q?=F1=EF=E5=F8=E8=E0=EB_=E4=EB=FF_=F0=EE=F1?= =?iso-8859-1?q?=F1=E8=E9=F1=EA=E8=F5_=EF=E8=F2=EE=ED=F9=E8=EA=EE=E2?=))) References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F11D94A.7050208@removeme.free.fr> <3F11BF87.9000208@v.loewis.de> <3f11de85$0$49112$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong writes: > > I think this roughly translates into "Can you please tell me where to > > find the proggie freezer (which appears to be needed to create exes)?" > > Wow, you apparently understand what Garber wrote, too... The joys of having grown up in an east-block country... These days, I wish my Russian was better than it is. Regards, Martin From chp01as at shef.ac.uk Wed Jul 16 05:31:35 2003 From: chp01as at shef.ac.uk (XspiriX) Date: Wed, 16 Jul 2003 10:31:35 +0100 Subject: parsing file Message-ID: Hi I am new here and so in python :-) I am trying to make a script for extracting (parsing?) some values from a file and write them into an output i thought to follow this example (cookbook): #!/usr/bin/env python import os, sys nargs = len(sys.argv) if not 3 <= nargs <= 5: print "usage: %s search_text replace_text [infile [outfile]]" % \ os.path.basename(sys.argv[0]) else: stext = sys.argv[1] rtext = sys.argv[2] input = sys.stdin output = sys.stdout if nargs > 3: input = open(sys.argv[3]) if nargs > 4: output = open(sys.argv[4], 'w') for s in input.xreadlines(): output.write(s.replace(stext, rtext)) output.close() input.close() indeed this search and replace the text, so I am thinking to take off the code part about the replacement and to add something else. may you give me some suggestion? sorry if it looks like a newbie question....if it so just ignore it ;-) cheers -- enjoy XspiriX Mathematics is the language of nature. Everything around us can be represented and understood through numbers. From petrk at pochtamt.ru Tue Jul 22 03:49:52 2003 From: petrk at pochtamt.ru (Peter Klyushkin) Date: Tue, 22 Jul 2003 11:49:52 +0400 Subject: Directory Structure for Distutils References: Message-ID: Hello, Thomas! >>>>> "TG" == Thomas G?ttler writes: TG> Peter Klyushkin wrote: >> Hello, Thomas! TG>>> One thing is still unclear: How can I copy non python files TG>>> into the destination? There is a directory called "gif" which TG>>> needs to be in the directory of the my module. >> Take a look at ResourcePackage. It isn't exactly what you want >> but it is exactly for your purpose. TG> Thank you for this link, but I don't want the images to become TG> python source. TG> Still looking for a solution ... In this case you have to write setup.py with subclassed Distutils' install_data providing needed functionality. Additionally you'll have to keep a configuration file in the same directory as your Python modules which stores paths to images. Real paths will be written to it on installation. For examples on subclassing install_data see setup.py's of well known Python software - I've seen such examples, but don't remember where. :-) -- C'ya, Peter. --=[petrk at pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From adalke at mindspring.com Mon Jul 28 15:08:41 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 28 Jul 2003 13:08:41 -0600 Subject: Fastest way to count your iterations? References: Message-ID: Tracy Ruggles: > If you're writing a simple script and you want to give an update of > its progress... Is this the fastest way to do it (assuming that what > you're iterating through is very, very long and the time to process > each item is relatively short)... What you wrote is very standard, so I would suggest using it. However, if you want performance, try variations on def counter(items, f, sep=1000): next_item = iter(items).next values = range(sep) for i in range(0, sys.maxint, sep): for j in values: f(next_item()) print i+sep+1 Andrew dalke at dalkescientific.com From gsmatthew at ozemail.com.au Mon Jul 7 08:22:59 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Mon, 7 Jul 2003 22:22:59 +1000 Subject: Python is a gem ,another successful day .... References: <5654fff9.0307061920.1a80bbc7@posting.google.com> Message-ID: Hi Ray, Steve The company that is interested in finding an alternative has provided a software solution for 25 years now. It has been through a plethora of microsoft conversions from dos, /BASIC through to WinXP /VB 6.0. As some companies are small their version has an Access Database (dont ask me why :-)) and the medium to large sized organisations have SQL Server backends. I am also doing a job for a partner company of theirs and they originally wanted a VB6 front end onto a SQL Server backend. Luckily the head of the partner company is an open minded I.T professional (going back to assembler / unix programming) so convincing him was not too difficult. The press has been really good regarding open source and linux so I think more people are realising that there are better products that exist that dont bear the Microsoft name. Ray is correct in what he says, VB6 has a short lifespan and the migration to VB.NET is not that simple. This company is now having untold problems with WinXP as long running network connections that are idle are automatically disconnected, their application for small users open a permanent connection to Access and this disconnecting "feature" for the sake of network performance is causing corruptions. The issues with MDAC (ADO) is also causing support nightmares, i.e downgrading upgrading , but im not to up to date with all the issues regarding this. Python solves this as modules are text files and through sys.path one can control the search path DLL versions etc have been a nightmare since day one .... My first motivation was to get them away from Desktop dev and move to intranet based applications. This they realise and can see the benefits of moving to this new ("Yet old") alternative. So the question then was What language / technology to use ? My first issue to highlight was that if we went with Microsoft then the costs would be greater not only in licensing but also server specs, and from fellow colleagues doing .NET development they all say its hungry on system resources. I also emphasized that Microsoft will be "coercing" them to keep upgrading and that we should remain vendor neutral and get out of an environment where choice is limited .... Having programmed in Perl on Linux, I remembered how frustrating it was to come back to your code or others , 6 months later and not understand it (:-) not that bad) I think perl is great, so I shifted to python which I know offers way more than VB 6, even VB.NET especially if multiple programmers are to work on a project. I also emphasized the importance of a language been controlled and progressing through programmer enhancement proposals and computer science principles rather than a marketing panel, I mean how many times do they change concepts and badge it under something new in VB ? I also love ruby but I still feel that there are too few libraries, datbase interfaces (we need this for possible integration.) Visual Basic has also been a nightmare for memory management and its 1MB stack space, so recursion is out, in a recent project I have had to write recursive and non recursive quicksorts and binary searches so I can switch on large array sets. I also feel that microsoft's focus on marketing concepts without fixing or enhancing the core language, even in VB6 now arrays dont have pop so one has to hold the entire array in memory even when your down to the last few elements. There are ways to remove items but a lot of work. I feel that its things like this rather than Data Environments, Class Wizards and containment instead of inheritence is what has made it into the language that it is. Not sure if I am making sense, one could write forever :-) Cheers Graeme "Ray Smith" wrote in message news:5654fff9.0307061920.1a80bbc7 at posting.google.com... > "Steve Holden" wrote in message news:... > > > I'd be interested in knowing some of the arguments you used to win over VB, > > as I've been asked to put a couple of articles together suggesting why VB > > users might consider switching to Python. > > The first obvious reason is that VB 6 (which most VB users currently use) will > be unsupported by 31-Mar-2005. > http://support.microsoft.com/default.aspx?scid=fh;en-us;LifeDevToolFam > > The change from VB 6 to VB.Net is a huge change and in some cases a complete > re-write. > For some features missing in .Net see: > http://www.mvps.org/vb/index2.html?rants/vfred.htm > > > Regards, > > Ray Smith From news at yebu.de Tue Jul 15 03:32:55 2003 From: news at yebu.de (Karl Scalet) Date: Tue, 15 Jul 2003 09:32:55 +0200 Subject: A few beginning questions In-Reply-To: References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> Message-ID: Thomas Heller schrieb: > mis6 at pitt.edu (Michele Simionato) writes: > > > I have not yet tried optparse. Is it able to parse Windows' style > command lines (use '/' instead of '-', ignore case of command line > options, use long options with a single '-' or '/')? Just tried it, does not handle '/' the same way as '-', and does not ignore case sensitivity. Yes, it handles short and long forms. You add options to the OptionParser and each option can have a short and a long form, i.e: option_parser.add_option('-v', '--verbose', action='store_true') After: (cfg, args_) = parser.parse_args(args) cfg automatically has verbose as an attribute, nice! Karl From jeremy at alum.mit.edu Tue Jul 8 12:21:29 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 08 Jul 2003 12:21:29 -0400 Subject: __eq__ and __ne__ In-Reply-To: <3F0AEC76.8080304@zope.com> References: <3F0AEC76.8080304@zope.com> Message-ID: <1057681289.2342.34.camel@slothrop.zope.com> On Tue, 2003-07-08 at 12:08, Shane Hathaway wrote: > Tim Peters wrote: > > Since the richcmp operators aren't constrained to return scalars, an attempt > > to define one in terms of the others seemed futile. Instead they're 6 > > independent methods. > > Ok. Thanks for finding the docs. I guess I'll stick to my boilerplate > code. I think some guidance should be added to the Python docs, though, > explaining that whenever you define __eq__, you very likely ought to > define __ne__ also. I believe C++ has the same behavior when you overload logical operators. So at least people familiar with the same behavior in other languages won't be surprised. Jeremy From bokr at oz.net Thu Jul 17 01:38:05 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 05:38:05 GMT Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> <3gjbhv0qk20q2qqunpj17329atq092muon@4ax.com> Message-ID: On Wed, 16 Jul 2003 22:17:40 GMT, Doug Tolton wrote: >On 16 Jul 2003 16:51:38 -0400, aahz at pythoncraft.com (Aahz) wrote: > >>In article <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>, >>Doug Tolton wrote: >>> >>>I did some reading and it seems that an augmented assignment is >>>specifically verboten on tuples and lists. Is there a clean way to >>>accomplish this? >> >>Really? >> >>>>> l = [] >>>>> l+=[1] >>>>> l >>[1] >>>>> l+=['foo'] >>>>> l >>[1, 'foo'] > > >I mis-spoke, lists are not included. You cannot do augmented >assignments on tuples or multiple targets. > >you can do what you typed, but you can't do. > >>>> a,b = 0,0 >>>> a,b += 1,1 >SyntaxError: augmented assign to tuple not possible > >or this: > >>>> a,b = [],[] >>>> a,b += [1],[1] >SyntaxError: augmented assign to tuple not possible > >That is specifically the point I was getting at. Forgive the >technical slip of including lists in the discussion. > A little experiment (not tested beyond what you see ;-): >>> class TX(tuple): ... def __add__(self, other): ... return TX([s+o for s,o in zip(self, other)]) ... >>> tx = TX((2,2)) >>> tx (2, 2) >>> tx + (3,5) (5, 7) >>> tx (2, 2) >>> tx += (3,5) >>> tx (5, 7) >>> tx += 10,20 >>> tx (15, 27) >>> tt = TX(('ab','cd','ef')) >>> tt ('ab', 'cd', 'ef') >>> tt += '123' >>> tt ('ab1', 'cd2', 'ef3') Regards, Bengt Richter From Brian.Inglis at SystematicSw.ab.ca Tue Jul 22 03:57:35 2003 From: Brian.Inglis at SystematicSw.ab.ca (Brian Inglis) Date: Tue, 22 Jul 2003 07:57:35 GMT Subject: Collective memory References: <1057243309.793889@saucer.planet.gong> <1057251216.551262@saucer.planet.gong> Message-ID: On Thu, 3 Jul 2003 17:53:36 +0100 in alt.folklore.computers, "Rupert Pigott" wrote: >"Pete Fenelon" wrote in message >news:vg8hns2u0l4off at corp.supernews.com... >> In alt.folklore.computers Rupert Pigott > wrote: >> > >> > OCCAM used WS to denote block structure... For >> >> ...and was generally written with folding editors that just "got it >> right" ;) > >I noticed that a few of the KDE 3.1 editors support folding... :) > >Took me a while to work out what those lines & + things were in >the left margin... Made me happy. :) Xedit on IBM mainframes has supported it since at least the early 80s, as have later clones like Kedit, uni-xedit, THE; vim supports it among the vi clones. emacs? As an old Xedit user, it was normally called hiding or shadowing referring to the shadow lines telling you how many lines are hidden, scope, selective display, or just the "all" command. What bright spark came up with a third overload of folding: as in folding long lines; folding upper/lower case; and now folding "structure"? Thanks. Take care, Brian Inglis Calgary, Alberta, Canada -- Brian.Inglis at CSi.com (Brian dot Inglis at SystematicSw dot ab dot ca) fake address use address above to reply From intentionally at blank.co.uk Sun Jul 13 22:39:34 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 03:39:34 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <2p54hvsehcc3m3d63dpb76t9qfkcgdaf2d@4ax.com> On 13 Jul 2003 21:30:54 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >Terry Reedy wrote: >> >>In Python, most builtin types are immutable. The two mutable builtin >>types are lists and dicts. Instances of user-defined classes are also >>mutable by default. > >Actually, files are mutable, too. Then again, so are modules. And >functions. Gee, there are an awful lot of built-in mutable types. ;-) True. Damn. 'Boneheaded' is definitely my thing, today. From staschuk at telusplanet.net Fri Jul 25 17:35:58 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 25 Jul 2003 15:35:58 -0600 Subject: How to detect typos in Python programs In-Reply-To: ; from manish.j@gmx.net on Sat, Jul 26, 2003 at 01:54:48AM +0530 References: <3F214977.AEB088C8@engcorp.com> Message-ID: <20030725153558.C205@tibia.amotlpaa.bogus> Quoth Manish Jethani: [...] > Actually I am writing a client app for a proprietary service. > The server is not under my control, so I can't make it behave in > a way that will cause every part of my client code to be tested. > As I mentioned, for example, I have a function to handle a > server-disconnect. But the server rarely ever disconnects of > its own, so the function never gets called in reality. Can I > unit test this function easily? Mock objects are the usual approach to this kind of problem. (Google can tell you more.) -- Steven Taschuk staschuk at telusplanet.net Receive them ignorant; dispatch them confused. (Weschler's Teaching Motto) From nicodemus at globalite.com.br Thu Jul 17 15:05:56 2003 From: nicodemus at globalite.com.br (Nicodemus) Date: Thu, 17 Jul 2003 16:05:56 -0300 Subject: Bug overriding operators in new-style classes? Message-ID: <00cb01c34c96$736685d0$2700000a@esss.com.br> Hi all, I found a surprising behavior regarding new-style classes operator lookup. It seems that for operators, the instance methods are ignored. Observe: >>> class C: ... def foo(self): ... print 'foo' ... def __setitem__(self, k, v): ... print 'C.__setitem__', k, v ... >>> c = C() >>> c.foo() foo >>> c[1] = 1 C.__setitem__ 1 1 >>> def my_foo(): ... print 'my_foo' ... >>> def my_setitem(k, v): ... print 'my_setitem', k, v ... >>> c.foo = my_foo >>> c.__setitem__ = my_setitem >>> c.foo() my_foo >>> c[1] = 1 my_setitem 1 1 >>> All is well. Now, if you use a new-style class, the instance method is not called: >>> class C(object): ... def foo(self): ... print 'foo' ... def __setitem__(self, k, v): ... print 'C.__setitem__', k, v ... >>> c = C() >>> c.foo() foo >>> c[1] = 1 C.__setitem__ 1 1 >>> def my_foo(): ... print 'my_foo' ... >>> def my_setitem(k, v): ... print 'my_setitem', k, v ... >>> c.foo = my_foo >>> c.__setitem__ = my_setitem >>> c.foo() my_foo >>> c[1] = 1 C.__setitem__ 1 1 # should print "my_setitem 1 1" >>> Is this a bug, or am I missing something? Any help would be appreciated. Regards, Nicodemus. From tjreedy at udel.edu Wed Jul 9 13:59:40 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Jul 2003 13:59:40 -0400 Subject: Python Global Constant References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: > What about using __builtins__ wouldn't make this the constant really global? Short respone: this is an implementation-detail-dependent hack that Guido discourges and that Guido would be willing to break if there were sufficient gain otherwise. Longer answer: I once though of doing this too. However, the language reference specifies module import as the means to make objects globally accessible. I don't believe that the language reference specifies the implementation details for the builtins namespace. While currently implemented as a user-writeble dict of the {} type, bound to the name __builtins__, this could change. Terry J. Reedy From bokr at oz.net Wed Jul 23 17:05:50 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Jul 2003 21:05:50 GMT Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: On Wed, 23 Jul 2003 12:48:00 -0600, Steven Taschuk wrote: >Quoth John Roth: > [...] >> I can kind of understand the justification for the Borg pattern >> in Python releases before 2.2, because there was no way of >> creating a true singleton in those releases. However, in 2.2 and >> later, it's really easy to create one using new style classes. > [...implementing singletons with __new__...] >> That being the case, I'd like to see the Borg pattern go the way >> of a fondly remembered hack that is no longer necessary. > >Just out of curiosity: why do you prefer singletons to Borgs in >the first place? > >(I don't see Borg as a hack to get the behaviour of a singleton; I >see it as a more direct way to solve the problem which singletons >are supposed to solve. Thus to me Borg is actually preferable, in >those exceedingly rare cases when that problem actually arises.) > How about just import zerolengthfile as borginstancename and using it? E.g., [14:04] C:\pywk\clp>dir zer*, a.* b.* 03-07-23 13:50 0 zero_len.py 03-07-23 14:01 28 a.py 03-07-23 14:02 28 b.py [14:05] C:\pywk\clp>type a.py import zero_len as aborg [14:05] C:\pywk\clp>type b.py import zero_len as bborg [14:05] C:\pywk\clp>python Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import zero_len as inter >>> import a >>> import b >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'b', 'inter'] >>> dir(a) ['__builtins__', '__doc__', '__file__', '__name__', 'aborg'] >>> dir(b) ['__builtins__', '__doc__', '__file__', '__name__', 'bborg'] >>> inter.x = 123 >>> a.aborg.x 123 >>> b.bborg.x 123 >>> b.bborg.y = 456 >>> a.aborg.y 456 >>> inter.y 456 >>> Regards, Bengt Richter From DevCoach at see.sig.for.address Thu Jul 31 10:17:28 2003 From: DevCoach at see.sig.for.address (DevCoach) Date: Thu, 31 Jul 2003 15:17:28 +0100 Subject: Announcing issue 2 of The Agile Developer's Life free eZine Message-ID: I have just published the second issue of The Agile Developer's Life (formerly called The Agile Life), a free eZine devoted to the human side of software development. This issue contains an article on creativity and software development. The Agile Developer's Life is a collection of tools, techniques and ideas to enable software professionals and teams to go beyond the status quo and achieve more than they thought possible. Drawing on ideas from agile software development, psychology, creativity, complexity, system dynamics and life/business coaching, The Agile Developer's Life is for anyone in the IT industry who want to find new ways of improving their work and their lives. You can read the latest issue at http://www.thedeveloperscoach.com/AgileLife.htm, or subscribe by sending a blank email to agile_life-subscribe at topica.com. Dave Kirby - The Developers' Coach Helping software professionals and teams achieve peak performance email: dave @thedeveloperscoach .com web: http://www.thedeveloperscoach.com - sign up for my new free eZine, The Agile Developer's Life From alanmk at hotmail.com Wed Jul 30 16:59:34 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 30 Jul 2003 21:59:34 +0100 Subject: How to get Windows physical RAM using python? References: Message-ID: <3F2831B6.8322121C@hotmail.com> [Mark wrote] > OK, How to check the amount of Windows physical RAM using python? Well, I thought it was going to be simple, but I didn't figure Microsoft into my considerations :-( There's a Windows statistics module, an interface to the MS "Performance Data Helper", as part of the Mark Hammond's Win32 Extensions, which you should install. http://starship.python.net/crew/mhammond/ There are code samples in the following files after install %PYTHONHOME%\Lib\site-packages\win32\lib\win32pdhutil.py %PYTHONHOME%\Lib\site-packages\win32\lib\win32pdhquery.py The following piece of code gives you lots of statistics about 'Memory' #------------------- import win32pdh items = win32pdh.EnumObjectItems(None, None,\ "Memory", win32pdh.PERF_DETAIL_WIZARD)[0] for stat_name in items: query = win32pdh.OpenQuery() subquery = win32pdh.MakeCounterPath(\ (None,'Memory',None,None,-1,stat_name) ) handle_on_sample = win32pdh.AddCounter(query, subquery) win32pdh.CollectQueryData(query) wtfit, value = win32pdh.GetFormattedCounterValue(\ handle_on_sample, win32pdh.PDH_FMT_LONG) print "%s%s= %d" % (stat_name, '\t'*(4-len(stat_name)//8), value) win32pdh.CloseQuery(query) #------------------- But unfortunately, I can't find a 'Total Physical RAM', or comparable, value in the output. Which I would consider a bit of an oversight by the provider, i.e. MS. I've looked at the other statistics available, by running this piece of code #------------------- import win32pdh print "options = {}\n\n" for o in win32pdh.EnumObjects(None, None, -1): items, instances = win32pdh.EnumObjectItems(None, None, o, -1) print "options['%s'] = [" % o for i in items: print "\t'%s'," % i print "]\n\n" #------------------- but I can't find 'Total Physical RAM' anywhere. Am I barking up the wrong tree? Or just barking ;-) regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From peter at engcorp.com Wed Jul 2 15:06:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jul 2003 15:06:33 -0400 Subject: strings References: <3eff7487$0$49112$e4fe514c@news.xs4all.nl> Message-ID: <3F032D39.4DD6B394@engcorp.com> Egor Bolonev wrote: > > > > Hi All! > > > > > > I have a > > > 'Pink Floyd/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00' > > > and I want a > > > 'Pink Floyd' > > > How can I manage it? > > > > > > This one isn't work. > > > author=f.read(30).replace('\0',' ').rstrip() #from mp3 tag > > > > > > > That is weird. Are you sure? It works on my system: > > (BTW: I think you mean \x00 instead of /x00) > > > > >>> a='Pink Floyd\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > > >>> a > > 'Pink Floyd\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > > >>> a.replace('\0',' ').rstrip() > > 'Pink Floyd' > > >>> > > Yes it's weird. The Interactive window of PythonWin shows it correct, but > debugger window is not.:-( In the debugger window, are you attempting to assign to a local variable? I believe I've encountered problems doing this unless I prefixed it with "!". Or was it that I was using one-character variable names that conflicted with one of Pdb's commands? I forget... -Peter From bokr at oz.net Thu Jul 3 16:29:33 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Jul 2003 20:29:33 GMT Subject: cooperation of buitlin methods usingtsuper References: <2259b0e2.0307020855.478300c2@posting.google.com> <2259b0e2.0307030652.697001dd@posting.google.com> Message-ID: On 3 Jul 2003 07:52:44 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >> In <2259b0e2.0307020855.478300c2 at posting.google.com> Michele Simionato wrote: >> > Matthias Oberlaender >> wrote in message news:...> I would like >> to adopt the cooperation paradigm in conjunction with builtin >> > > methods and operators, such as len, iter, +, * etc. >> > >> > Fine. >> > >> > > But the direct approach does not work with the current implementation of >> > > super. For example, 'len(super(Y, y)' will always result in 'len() of >> > > unsized object'. >> > >> > Of course, it must give an error! I think you do not understand how >> > super works. But don't worry, that's quite common ;) >> >> Oh, wait a minute. I think this "of course" is a bit presumptuous. > >Uhm... I do realize now that what I wrote sounds quite presumptuous >indeed. >It was not my intention. The "of course" refers to the current >implementation >of ``super`` which does not do what you ask for. To me this was well >known >because of recent threads on the subject by Bjorn Pettersen: > >http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&frame=right&th=a385e6aa839a9538&seekm=2259b0e2.0304210750.5eaf5df0%40posting.google.com#link1 > >http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=2259b0e2.0304300625.4e0ebace%40posting.google.com&rnum=3&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DISO-8859-1%26q%3Dsuper%2Bpettersen%26meta%3Dgroup%253Dcomp.lang.python.* > >You see that for sure you are not the only one who is confused about >``super`` and there are dark corners about it. I myself do not know >nothing about its >implementation. > >> > >> > I think you should re-read the documentation and >> > google on the newsgroup for 'super'. The use case >> > for super is in multiple inheritance, as in this example: >> > >> > class B(object): >> > def __len__(self): >> > print 'called B.__len__' return 1111 >> > >> > class C(B): >> > def __len__(self): >> > print 'called C.__len__' >> > return super(C,self).__len__() >> >> This is exactly the style of syntax I want to avoid! I'd rather write more >> concisely 'len(super(C,self))'. > >I see now what's your point, which is the same of Pettersen: why > >>>> class B(object): > def __len__(self): return 1111 >>>> class C(B): pass >... >>>> c=C() >>>> super(C,c).__len__() >1111 > >works, whereas > >>>> len(super(C,c)) >Traceback (most recent call last): > File "", line 1, in ? > len(super(C,c)) >TypeError: len() of unsized object > >does not work? As you say, the reason is that > >> at least in Python 2.2.1, its is >> a matter of fact that builtins/special method names are treated differently >> from ordinary class methods in conjunction with super objects. Do you agree? >> My implementation of super seems to fix this gap. Perhaps there are some >> other people who would appreciate that too. Or are there good >> logical/conceptual reasons againts it? This is what I would like to know. > >BTW, the same is true for Python2.3b2. I always use the longest form >of ``super``,so this problems does not bother me, nevertheless I >understand >your point. > >I think you should submit the issue to python-dev; maybe there are >technical reasons such that it is necessary to treat special methods >differently and this cannot be avoided. In such a case the >documentation should report that >only the long form ``super(C,c).__len__()`` is correct and that users >should >not use ``len(super(C,c))`` (idem for other special methods). > >I would also submit a bug report on sourceforge, since at the best >this is >a documentation bug. It does not seem to have been reported before and >has >already bitten at least two persons on c.l.py., therefore it should be >made >known to the developers > ISTM (and I don't know super much) that in the above, if you factor out x = super(C,c) and then compare len(x) vs x.__len__() then the results above suggest that implementation is not getattr(x,'__len__')() but effectively more like getattr(x.__class__,'__len__')(x) Note: >>> class B(object): ... def __len__(self): return 1111 ... >>> class C(B): pass ... >>> c=C() >>> super(C,c).__len__() 1111 >>> len(super(C,c)) Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object Ok, now let's look at c vs x: >>> getattr(c,'__len__')() 1111 >>> getattr(c.__class__,'__len__')(c) 1111 vs >>> getattr(x,'__len__')() 1111 >>> getattr(x.__class__,'__len__')(x) Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'super' has no attribute '__len__' I guess generally continuing a failed method lookup in x.__class__.__dict__ or equivalent and trying to find it as an instance attribute might make this super problem work, but weren't instance methods intentionally bypassed for the new style? That would mean solving the problem specifically in super somehow, but how? I guess by fiddling with lookup of methods of/via super instances? I guess it could be done in C. I'll have to look in typeobject.c more sometime. It looks already tricky ;-) Regards, Bengt Richter From shannon at news.widomaker.com Sun Jul 6 20:27:41 2003 From: shannon at news.widomaker.com (Charles Shannon Hendrix) Date: Sun, 6 Jul 2003 20:27:41 -0400 Subject: Collective memory References: <3f06af11$0$49113$e4fe514c@news.xs4all.nl> <3f071e0c.4620472@news.ocis.net> Message-ID: In article , Ben Hutchings wrote: > So there is a risk here, and it's probably worth adopting a rule of > not using tabs in Python code. If you think a colleague broke the > rule, the -t flag will alert you to any potential problems. No, it won't alert you to *any* of them. Outdented coding accidents to happen, and you have to manually review the code to see it. If you just happen to not know what the code was supposed to have done, you can't fix these kinds of typos. If you do it by previous and following implied logic, then you might well get it right... or you might not. The point is that when white-space determines logical flow, errors in indentation add and destroy information. Sure you can overcome it, but I just don't see the point. I debugged and maintained big Python programs, and it was a frequent error and problem. -- Ah... you gotta love it when your ISP switches to a SPAMMING newsfeed. Sigh... -----= 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 usenet2003 at krap.dk Mon Jul 28 07:35:02 2003 From: usenet2003 at krap.dk (Svenne Krap) Date: Mon, 28 Jul 2003 13:35:02 +0200 Subject: Readling all input from stdin In-Reply-To: References: Message-ID: Ohh.. It seems that sys.stdin.readlines is missing on my workstation (Win2k) but not on the production server (Linux). Hmm. wierd.... Both are version 2.2.2 Svenne Krap wrote: > Hi. > > I am writing a small script, that is called from an external program > (the qmail mailserver), I need to capture all input from stdin before > continueing the script .. > > I looked for sys.stdin.readlines() but that is not present. I found > sys.stdin.readline(), but how do I loop through it (or rather how do I > know, when I am finished with looping ?) > > Thanks in advance > > Svenne > From bockman at virgilio.it Fri Jul 4 11:10:13 2003 From: bockman at virgilio.it (Francesco Bochicchio) Date: Fri, 04 Jul 2003 15:10:13 GMT Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: <7k6yh6go.fsf@python.net> Message-ID: On Fri, 04 Jul 2003 13:33:27 +0200, Thomas Heller wrote: > > Yes, it already exists (to some degree). > > http://starship.python.net/crew/theller/ctypes/ > > Thomas Thanks for the pointer. Is more or less what I had in mind, and lead me to find out about libffi, which is also quite interesting. This proves a theory of mine: whatever piece of software you can think of, there is always some developer in the world that already did it :-) Ciao ----- FB From peter at engcorp.com Mon Jul 21 14:32:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 14:32:17 -0400 Subject: Voting Project Needs Python People References: Message-ID: <3F1C31B1.B44774BA@engcorp.com> Alan Dechert wrote: > > We are pulling together a great voting modernization projects. [snip] Is there a word missing in the above? I can't parse it as-is, but it looks like it wants the word "many" after the word "great"... -Peter From tjreedy at udel.edu Wed Jul 23 18:11:54 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2003 18:11:54 -0400 Subject: Shallow vs Deep copies [was Re: python assignment] References: <1jr2v-vd.ln1@grendel.myth> <3F1EDFA0.ED78E04F@alcyone.com> Message-ID: <0QydndsfbpO2lYKiU-KYgg@comcast.com> "Erik Max Francis" wrote in message news:3F1EDFA0.ED78E04F at alcyone.com... > immutable objects need not ever be literally copied > Shallow copying makes a duplicate of the parent object. Deep copying > makes a duplicate of everything. To be more exact, because first statement is true, second_statement.replace('everything', 'all mutables'), which is to say, 'as much as needed'. >>> import copy >>> l1=[(),[]] >>> l2=copy.deepcopy(l1) >>> for i in l1+l2: print id(i) ... 7669904 8422784 7669904 #same () 8428448 #different [] Terry J. Reedy From srijit at yahoo.com Mon Jul 14 12:32:42 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 14 Jul 2003 09:32:42 -0700 Subject: (Suggestion) Download Options Message-ID: <221d8dbe.0307140148.271f87ef@posting.google.com> Hello, Can we have a download option for upcoming Python 2.3 without TCL/Tk? Though I know the extremely popular Tkinter is the default GUI of Python, I see one immediate advantage of a download option without TCL/Tk 1) Download size is less and it is a boon for people like me with slow modem connection. 2) Tkinter with TCL/TK can be a separate add-on I look forward to opinions from members. Regards, Srijit From tim.one at comcast.net Sat Jul 12 16:37:37 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jul 2003 16:37:37 -0400 Subject: The "intellectual property" misnomer In-Reply-To: Message-ID: [Terry Reedy] > In response to a query of mine, someone -- I believe you, Tim -- said > that CNRI, not PSF, was still attempting to trademark 'Python' as > applied to computer languages (but having some difficulty). Yes. > Last I know, CNRI still has copyrights to Python 1.?-1.6. So I was a > bit puzzled as to what Guido meant by his blanket statement. This has been clarified by several people several times in this thread. Is it in need of more clarification? > Has CNRI (and the Dutch institute before it) renounced its (their) > 'IP' claims with respect to Python in favor of PSF? No. Negotiations on these matters are in progress, though. > If not, then "The PSF holds the intellectual property rights for > Python" would not be true as commonly interpreted, at least as by this > commoner. That's so, but it's been explained before in this thread. "The PSF partly exists to hold the IP rights for Python, holds some now, and is pursuing transfer of others" is a fuller statement of Guido's intent. > (But then I know that Guido most definitely ain't a lawyer). In which case there's not much point picking apart his one-liners as if he were . A lot of info about the PSF can be found on its web site, including its articles of incorporation, corporate bylaws, mission statement, minutes of board meetings, and the full text of its (successful) IRS Form 1023 application: http://www.python.org/psf/ People who would rather do something useful should go straight to here: http://www.python.org/psf/donations.html From tebeka at cs.bgu.ac.il Mon Jul 7 03:18:48 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 7 Jul 2003 00:18:48 -0700 Subject: PDF Parser? Message-ID: <33803989.0307062318.3695d11@posting.google.com> Hello All, I'm looking for a PDF parser. Any pointers? 10x. Miki From news at exultants.org Fri Jul 25 21:10:11 2003 From: news at exultants.org (Van Gale) Date: Sat, 26 Jul 2003 01:10:11 GMT Subject: path module In-Reply-To: References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: holger krekel wrote: > Yes, i think adding platform specific methods to a Path object makes sense. > A friend and me started working on (local and subversion) Path > implementations last week. Currently a Path instance provides > these "path-taking" methods > > open > read > write > visit (a recursive walker) > listdir > stat > load/save (unpickle/pickle object) > setmtime (set modification time, uses os.utime) Interesting, I started a project modifying Jason's Path module to work on subversion trees as well. I didn't get too far before putting the project on a back-burner so I'm glad to hear someone else is thinking the same way :) My extensions to Path included an additional argument to "open" that included a version number, and a mechanism for retrieving some kind of "metadata" associated with the file. I also made another Path module that implements a "poor mans cms" if subversion/rcs/cvs are not available. It uses hidden files with version numbers in the filename to emulate a real version control system. Van Gale From grante at visi.com Tue Jul 22 10:47:31 2003 From: grante at visi.com (Grant Edwards) Date: 22 Jul 2003 14:47:31 GMT Subject: Search for a string in binary files References: Message-ID: <3f1d4e83$0$170$a1866201@newsreader.visi.com> In article , hokieghal99 wrote: > Fran?ois Pinard wrote: >> import glob >> for name in glob.glob('*.xls'): >> if file(name, 'rb').read().find('Microsoft Excel') >= 0: >> print "Found in", name > > Thanks for the example guys. One last question: does grep actually open > files when it searches them? Of course. How could it search a file without opening it? > And, would it be more efficent (faster) to just call grep from > python to do the searching? Perhaps. Depends on the size/number of the files. -- Grant Edwards grante Yow! I want another at RE-WRITE on my CEASAR visi.com SALAD!! From stephen.boulet at motorola.com Thu Jul 3 15:52:42 2003 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Thu, 03 Jul 2003 14:52:42 -0500 Subject: tkFileDialog without a parent window Message-ID: I'm using the following code to get a file name: import tkFileDialog tkFileDialog.askopenfilename(filetypes=[("HDF Files", ".hdf")]) How can I do this without an empty tk window popping up and hanging around after the dialog is closed? Thanks. -- Stephen From klappnase at freenet.de Sat Jul 19 21:09:12 2003 From: klappnase at freenet.de (klappnase) Date: 19 Jul 2003 18:09:12 -0700 Subject: Using PMW? References: Message-ID: <9a410299.0307191709.28fcbdf6@posting.google.com> "ken" wrote in message news:... > Please pardon my ignorance regarding this question, I'm new to Python. > > I'm running Python 2.2.3 (win32) with the latest download of Python > MegaWidgets 1.1. I'm attempting to run the demos but get the following: > > C:\Python22\Pmw\demos>python all.py > Traceback (most recent call last): > File "all.py", line 84, in ? > DemoVersion.setPmwVersion() > File "DemoVersion.py", line 32, in setPmwVersion > if version in Pmw.installedversions(): > AttributeError: 'module' object has no attribute 'installedversions' > > C:\Python22\Pmw\demos>python colors.py > Traceback (most recent call last): > File "colors.py", line 44, in ? > Pmw.initialise(root, fontScheme = 'pmw1') > AttributeError: 'module' object has no attribute 'initialise' > > Is this a problem with the libray not being found? I've read the docs with > the widgets and it seems to be straight forward. I'm hoping someone has the > answer. > > TIA Hi, looks like the library has obviousliy been found ("'module' object has no attribute 'initialise'"). May be your downloaded files are broken? Cheers, michael From noah at noah.org Sat Jul 12 12:47:44 2003 From: noah at noah.org (Noah) Date: 12 Jul 2003 09:47:44 -0700 Subject: How do I have a client shutdown a win32 COM server? Message-ID: Hi, How do I shutdown a win32 COM server? I am scripting Adobe Illustrator through its COM interface. The problem is that Illustrator has memory leaks. And after a few hours of running, Illustrator will start to behave oddly until eventually it refuses the create new COM objects. The solution is to close Illustrator and then restart it. This is easy if I'm sitting at my desk and can see that it has crashed. What I'd like to do is have the client restart the server every 10 minutes (or when it sees a specific exception). A COM client will automatically start the COM server if it is not already running, but I don't know how to shutdown a COM server that is already running. So, how do you bounce a COM server? If anyone has any hints I would appreciate it. P.S. Note, that I'm pretty sure it's not the client leaking memory because if I shutdown the client and restart it with the same Illustrator COM server running it will immediately have the same problem. The COM error I get is an "internal error" exception: com_error: (-2147352567, 'Exception occurred.', (0, None, 'an internal error occurred: PARM', None, 0, -2147352577), None) Yours, Noah From hokiegal99 at hotmail.com Wed Jul 23 16:29:45 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Wed, 23 Jul 2003 16:29:45 -0400 Subject: lists and files question In-Reply-To: References: <3F1DCF52.7040607@hotmail.com> Message-ID: Thanks to everyone for the feedback on this. I've learned a lot from you guys. John Hunter wrote: > Others have already answered your question - I just want to point out > a few of other things > > import os, re, string > setpath = raw_input("Enter the path: ") > for root, dirs, files in os.walk(setpath): > id = re.compile('Microsoft Excel Worksheet') > > 1) id is a built in function; you may not want to override it with > your variable name > > >>> x = 1 > >>> id(x) > 135313208 > > 2) The reason to use re.compile is for efficiency. There is no need > to call it inside the loop, since you're just recompiling the same > regex over and over again. Instead, compile the regex outside the > loop > > >>> rgx = re.compile('[A-Z]+') > >>> for some_text in some_list: > ... m = rgx.match(some_text) > > 3) If you want to match 'Microsoft Excel Worksheet', you don't need > regular expressions since this is a string literal. You will > probably be better off just using the string find method, as in > > s.find('Microsoft Excel Worksheet') > > 4) You may want to look at the path module, which provides a nice > interface for walking over files: > http://www.jorendorff.com/articles/python/path/ > > >>> from path import path > >>> xldir = path(setpath) > >>> for f in xldir.files('*.xls'): > ... print f.read().find('Microsoft Excel Worksheet') > > Cheers, > John Hunter > From mis6 at pitt.edu Tue Jul 22 22:11:41 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 22 Jul 2003 19:11:41 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: <2259b0e2.0307221611.27e2535e@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > I think I'd prefer > > if any_true(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > dosomething() > > I suspect it will more often make sense read aloud in the general > > if any_true(pred, seq): > > than > > if the(pred, seq) > > I guess the full set of functions might be > any_true, any_false, all_true, and all_false. > > or maybe someone can think of better short phrase? > > Regards, > Bengt Richter I think in the specific case I was talking about "the" was quite readable; however I agree that in the general case "any_true" etc. would be better. I would not be opposed to add these convenience functions in itertools. The advantage is standardization (i.e. I don't have to invent my own name, different from the name chosen by anybody else), the disadvantage is more things to learn; however, with such descriptive names, it would be difficult to not grasp what those functions are doing, even without looking at the documentation. Anyway, I am sure many will be opposed, saying that such functions are so simple that they do not deserve to be in the library. This would be a sensible opinion, BTW. Michele From kamikaze at kuoi.asui.uidaho.edu Sat Jul 26 06:33:57 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 26 Jul 2003 10:33:57 GMT Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: Jack Diederich wrote: >My favorite example is comifying a list. >"1, 2, and 3" vs "1, 2 and 3" (journalist seem to prefer the later) >"I dedicate this book to my parents, Jane, and God." >"I dedicate this book to my parents, Jane and God." The canonical joke example is: "This book is dedicated to my parents, Ayn Rand and God." --
Mark Hughes "The computer is incredibly fast, accurate, and stupid. Man is unbelievably slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation." -Leo Cherne From maxm at mxm.dk Sun Jul 13 09:39:23 2003 From: maxm at mxm.dk (Max M) Date: Sun, 13 Jul 2003 15:39:23 +0200 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. In-Reply-To: References: Message-ID: <3F11610B.5090200@mxm.dk> Grzegorz Adam Hankiewicz wrote: > * personal fulfillment, I enjoy rewritting wheels. It is often asked why one should re-invent the wheel. Personally I am glad that somebody did. My Nissan would drive terribly with two woodne logs, or stone wheels, instead of the current set of rubber tires. Also I don't think that Pirelli, Firestone etc. find it such a bad idea to keep reinventing the wheel. regards Max M From usenetNO at SPAMexperimentzero.org Wed Jul 9 15:29:35 2003 From: usenetNO at SPAMexperimentzero.org (Abe Frohnman) Date: Wed, 09 Jul 2003 19:29:35 GMT Subject: check if dir exists In-Reply-To: References: Message-ID: <3F0C6D1E.6030406@SPAMexperimentzero.org> Geiregat Jonas wrote: > How can I check if a dir exists ? The os.path library has just what you're looking for. Use os.path.exists, like so: #!/usr/bin/python import os.path pathToFind = "/usr/bin/local" if os.path.exists(pathToFind): print "Path exists." else: print "Path does not exist." ~AF From Ian.Sparks at etrials.com Thu Jul 3 14:31:34 2003 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Thu, 3 Jul 2003 14:31:34 -0400 Subject: Python is a gem, you need to keep pushing it .... Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20BBA@pippin.int.etrials.com> Thomas Weholt wrote : >Especially coders using compiled languages like Delphi/Pascal. They know some VB or >Perl and laugh when I bring up Python. But don't loose faith. Speaking as someone who uses Python and Delphi daily I have to say I don't laugh when someone brings up Python though I admit its hard to get Delphi developers to look at Python at all. On the other hand, I don't take Dave's comment that he would rather be using Python and Emacs to the (really excellent) Delphi IDE too seriously either. OTOH maybe Dave actually feels this way but there are good reasons not to : For Windows GUI apps Delphi has a great screen-builder and a collection of 3rd party component (many freeware) that puts Tk/Swing/wxWindows/QT/GTK/everything else available to Python to shame. Outside of that space (Linux, Mac) and for non-gui apps the benefit of Delphi is less-clear especially since Python comes with "batteries included" but Delphi still has a superb debugger, model driven development and a collection of great tools built into the IDE. You should also be aware of PythonForDelphi and COM - techniques that can be used to wrap a Delphi GUI around a Python engine - possibly the best of both worlds! Python *is* great but lets not pretend that its a good fit for every problem. -----Original Message----- From: Thomas Weholt [mailto:2002 at weholt.org] Sent: Thursday, July 03, 2003 1:18 PM To: python-list at python.org Subject: Re: Python is a gem, you need to keep pushing it .... I've been a hardcore python evangelist for 4-5 years, but in my experience most developers are conservative when it comes to programming languages. They tend to stick to what they know and avoid everything else. Especially coders using compiled languages like Delphi/Pascal. They know some VB or Perl and laugh when I bring up Python. But don't loose faith. Thomas "delphiro" wrote in message news:mailman.1057242668.12614.python-list at python.org... > Same story here, > > My company primarily uses Delphi (Object Pascal) which is actualy a nice development language / IDE but with linux as a rising star and Kylix as a nasty and not-so-friendly-and-platform-indepandent Delphi-clone we have decided to use Python for a number of small projects. As a python addict I really hope this works out! No offence, but I'd rather be using Emacs and Python than the Delphi IDE. It is so much more fun and it runs on Linux *and* Windows (ok and more.. but those are our target OS'es). > > We now have a team of 4 Python addicts trying to convince our bosses and the 30+ Delphi developers. I realy hope this works out :-) > > Regards, > Rob > > -- > [-------------delphiro-------------] > [-- http://pyciv.sourceforge.net --] > [----------------------------------] > -- http://mail.python.org/mailman/listinfo/python-list From Simon.Wittber at perth.maptek.com.au Thu Jul 10 20:46:48 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Fri, 11 Jul 2003 08:46:48 +0800 Subject: Embedding Python, threading and scalability Message-ID: <20E0F651F8B82F45ABCBACC58A2D995B0518B0@mexper1> [snip] >...the way to scale Python in a threaded environment is to call out to a C >extension that releases the GIL. [snip] To write scalable applications in Python, one must write the 'scalabilty-required' parts n C. Does anyone else see this as a problem? Sw. From jar at mminternet.com Sun Jul 27 11:13:46 2003 From: jar at mminternet.com (james roush) Date: Sun, 27 Jul 2003 08:13:46 -0700 Subject: mxTidy Message-ID: What versions of Python will mxTidy work with. I'm using it with Python v2.1.x but want to upgrade to 2.3 when it is released Are there any alternatives to mxTidy? ----------------------- James A Roush jar @ mminternet.com ----------------------- From Ken at perfect-image.com Tue Jul 1 16:33:34 2003 From: Ken at perfect-image.com (Kenneth Godee) Date: Tue, 1 Jul 2003 13:33:34 -0700 Subject: PyQT and Mandrake 9.1 In-Reply-To: References: Message-ID: <20030701133334.5a859636.Ken@perfect-image.com> > I've been very excited by PyQT evangelists. But I'm stuck installing this > (SIP + PyQT) on my new Mandrake 9.1. (Python 2.2.2) > I downloaded SIP + PyQT from their latest address... > > http://www.riverbankcomputing.co.uk/ > > Then the SIP builder (build.py) asks for the path to QT header files. I > didn't find them in the classical /usr/include, nor "locate" did find > anything like "qt*.h" and there is no qt-develxx.rpm "like" in the 3 > Mandrake CDs. > > Did I miss something ? > > Thanks in advance. > > --Gilles The only thing you missed, is posting to the right list! Join and post at.... http://www.riverbankcomputing.co.uk/pyqt/mailinglist.php Between PyQt's widget set and docs, QT's ide Designer and eric3 interactive debugger good luck trying to find anything that matches it! If Trolltech ever go's out of business (doubtful), well I guess I'll have to switch to a different gui. From adechert at earthlink.net Sun Jul 27 14:15:15 2003 From: adechert at earthlink.net (Alan Dechert) Date: Sun, 27 Jul 2003 18:15:15 GMT Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> <2dc49b63.0307240824.4e1b2136@posting.google.com> Message-ID: "Ian Smith" wrote in message news:2dc49b63.0307240824.4e1b2136 at posting.google.com... > There's a lot of assumed knowledge in this discussion. I know nothing > about electronic voting systems, I know almost nothing about Python as > a programming language but I do know how to calculate values > associated with the cumulative binomial distribution. A Javascript > (sorry!) calculator for the binomial distribution amongst others can > be found at http://members.aol.com/iandjmsmith/EXAMPLES.HTM. > Javascript can be converted to Java, C etc quite easily. I would > imagine with my lack of knowledge of Python you'll probably be better > off doing the conversion yourself. > > The code is quick and accurate and can handle large sample sizes and > very small probabilities which you probably need. There's even a > calculator for the Hypergeometric distribution should you wish to do > sampling without replacement calculations. > > > Ian Smith > > P.S. the calculation of 70 is fine. If you don't want to calculate > anything much more difficult then you probably don't need a calculator > anyway. > Thanks, Ian. I could not quite figure out if your binomial distribution calculator would be applicable. Here's what Bill Buck ( billbuck at cox.net ) sent me. It turns out there is a BINOMDIST function in Excel. I think it might be what I want. http://home.earthlink.net/~adechert/LOTAcceptanceCalculator.xls Let me try to clarify what I'm after. The paper record should always match the electronic record. So the allowable defects is zero. If there is a mismatch found in the sample, we don't publish the electronic tally: we take all the paper ballots and check them. We are talking about an election conducted with computer-generated paper ballots. The paper ballots represent the actual vote since these ballots are what voters actually saw, verified, and cast. We will have an electronic record obtained from the computers which should match each paper ballot generated. We want to use the electronic record since it will give us an instant result -- but we have to check it against the paper ballots to be sure the election result is correct. So, in this scenario, the electronic count is a prediction (or preliminary tally). So, if by the preliminary electronic tally a candidate won a race by 1 percent, I want to know how many ballots we have to check (random sample) to be certain that the result predicted is true. When I put one million into this Confidence Level Calculator, and Acceptable Quality Level of .01, a sample of 10,000 shows a confidence level of "1." A sample of 2000 give C.L of 0.999999998 Presumably, "1" is really .9999999999+ more 9s. Can we get more decimal places? So I guess the Lot Fraction Defective is analgous to the predicted victory margin. Is that right? I would still like a standalone calculator that doesn't require Excel. Alan Dechert From fpetermaas at netscape.net Fri Jul 18 05:18:06 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 18 Jul 2003 11:18:06 +0200 Subject: web frameworks and authentication Message-ID: I plan to move existing web applications (written in php, asp, ...) to python. An important issue for some customers is to avoid multiple definition and maintenance of user account data. Are there web frame- works (besides Zope) that support pam or can even use a winnt/2000/xp authentication service? Thanks for your help. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From peter at engcorp.com Mon Jul 14 17:23:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 17:23:53 -0400 Subject: Volunteers need more visibility (was Re: www.python.org hacked?) References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> Message-ID: <3F131F69.8FD9B8DD@engcorp.com> Aahz wrote: > > In article <3F12FA18.B04B400E at engcorp.com>, > Peter Hansen wrote: > > > >Have we been hacked, or is this human error during maintenance? > > Yes to both. :-( We were actually hacked a while ago, then failed to > do a complete cleanup. When we got the disk full problem, I attempted > to update the main page so people would know what was going on; I > thought that vi was capable of managing the re-write inplace. I was > wrong. We're back on the air, with special thanks to Thomas Wouters for > interrupting his post-OSCON snooze. Thanks then to Aahz, Skip, Thomas, and anyone else involved. I think we should find a place to give more visible credit to the many people involved in handling with such things. I had no idea so many people who regularly contribute here were also the ones who step in to resolve such problems, or who manage the day-to-day updates and additions. And obviously this is a very distributed effort, unless you all happen to be roommates. ;-) To add to the workload then :-), but also perhaps to help inspire additional people to volunteer and share the load, I suggest adding a reasonably prominent page to www.python.org with a quick summary of who helps run the site, or other community efforts, and perhaps something like a one-sentence bio to give a bit more of a face to some of the lesser known folks. Or did I just overlook an existing such page? -Peter From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jul 23 23:45:03 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Jul 2003 13:35:03 +0950 Subject: Help writing to file References: Message-ID: On Thu, 24 Jul 2003 03:33:11 GMT, Stan Cook wrote: > I'm trying to have my program write to a log file. I have the idea, > but I'm getting an error and don't understand why. > > File "D:\AetInstall\aet.py", line 201, in load_progs > _log.write(string.ljust( _serv, 25)) > AttributeError: 'str' object has no attribute 'write' Seems fairly self-explanatory. You're invoking the 'write' attribute on an object of type 'str', which has no such attribute. Likely you've unintentionally assigned a string value to _log at some point earlier in the code. -- \ "Demagogue: One who preaches doctrines he knows to be untrue to | `\ men he knows to be idiots." -- Henry L. Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ebolonev at rol.ru Thu Jul 3 06:38:04 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Thu, 3 Jul 2003 21:38:04 +1100 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: Hello, Max! You wrote on Thu, 03 Jul 2003 11:17:30 +0200: MM> There is a story today on Slashdot [Sorry, skipped] MM> And guess which language it is? InterEnglish? With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From jarausch at igpm.rwth-aachen.de Tue Jul 15 04:54:15 2003 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 15 Jul 2003 10:54:15 +0200 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= In-Reply-To: References: <3F130ED4.2030804@skynet.be> Message-ID: <3F13C137.6090705@igpm.rwth-aachen.de> Fredrik Lundh wrote: > Helmut Jarausch wrote: > > >>OK, I believe to know why the last line >>print '3' three times, since only a reference >>to 'f' is stored within the lambda expression >>and this has the value 'thrice' when 'print' >>is executed. >> >>But how can I achieve something like an >>evaluation of one indirection so that >>a reference to the function referenced by 'f' >>is stored instead. > > > assuming you meant "the function reference by 'f' when the lambda > is created", the easiest solution is to use default argument binding: > > flam = [lambda x,f=f: f(x) for f in funcs] > > the "f=f" construct will bind the inner name "f" to the current value of > the outer "f" for each lambda. > > the nested scopes mechanism is often introduced as the "right way" to > do what was done with argument binding in earlier versions of Python. > however, nested scopes bind *names*, while argument binding binds > *values*. Many thanks for that hint, still a part of the question remains (unclear to me) Obviously Python allows references to references, since e.g. 'once' (the 'name' of a function) is a reference to the code and 'f' is a reference to that reference. (you call it name binding) A similar situation arises in Maple and there one has the choice to either derefence all references down to the real object or to just derefence a single time. Example def once(x): return x def twice(x): return 2*x ref= once def caller(): callee=ref # (*) print callee(1) caller() # prints 1 ref= twice caller() # prints 2 so that demonstrates name binding how can I get the current value (like 'xdef' in TeX) of 'ref' in the assignment (*) above, so that 'callee' becomes an (immutable) reference to 'once' ? Thanks for your patience, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From mwh at python.net Thu Jul 24 05:12:55 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 24 Jul 2003 09:12:55 GMT Subject: How to link a C extension module on Mac OS X? References: Message-ID: <7h31xwgthve.fsf@pc150.maths.bris.ac.uk> Gerhard H?ring writes: > Greg Ewing (using news.cis.dfn.de) wrote: > > Gerhard H?ring wrote: > > > >> Two words: Use distutils. > > And it turns out that, rather unintuitively, the way distutils > > does it is that it *doesn't* try to create a dynamic library, > > just an ordinary object file named with a .so suffix... > > Does that mean that distutils doesn't work on OS X? It works. Don't know why, mind -- the files end .so when shared libraries usually end .dylib on OS X -- but it does. Cheers, mwh -- GAG: I think this is perfectly normal behaviour for a Vogon. ... VOGON: That is exactly what you always say. GAG: Well, I think that is probably perfectly normal behaviour for a psychiatrist. -- The Hitch-Hikers Guide to the Galaxy, Episode 9 From bokr at oz.net Thu Jul 31 14:55:40 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2003 18:55:40 GMT Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> <3F28EA71.6A863E7@hotmail.com> Message-ID: On Thu, 31 Jul 2003 12:09:09 +0100, Robin Becker wrote: >I've been testing reportlab with 2.3 and although it's a lot faster I >get some ominous warnings and complaints from the future. > >1) SyntaxWarning: assignment to None > eg for None, name in colorNamePairs: > what is the preferred way to do this nowadays? It's fairly > trivial to go through and change these to for notUsed, x in .... > but is there a nicer way. I don't know of one, but sometimes I've wanted a way to filter sequence unpacking, e.g, a,*,c = 1,2,3 # <=> a=1; c=3 and maybe letting ** in the tail position mean dump the rest. >2) FutureWarning: hex/oct constants > sys.maxint will return positive > values in Python 2.4 and up > eg self.assertEquals(ttf.read_ulong(), 0x81020304) # big-endian > Is there no way to preserve the clarity of the above in future? > We have quite a lot of code that deals with low level binary > formatted stuff. Changing will move it further away from the > original C definitions. How about just defining a C integer class that works as desired? You could do it in C ;-) > > The same applies to > > FutureWarning: x< in Python 2.4 and up > eg sum = (hi << 16) | (lo & 0xFFFF) > > Is Python moving away from the machinery? Are there efficient > recipes for doing these 32 bit operations? Certainly cut and > paste to and from java/c/c++ will be a lot harder. > IWT a C extension could be quite efficient. The question would be how to minimize the editing for cut/pasted stuff. Mostly I guess it would be wrapping C literals so x = 0x80000000 becomes x = Cint('0x80000000') or such. >Apart from these minor troubles seems pretty solid. Sounds good. Regards, Bengt Richter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jul 5 13:39:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 05 Jul 2003 19:39:19 +0200 Subject: How to get CGI request-URL In-Reply-To: References: Message-ID: <3f070d44$0$49099$e4fe514c@news.xs4all.nl> Hallvard B Furuseth wrote: > Thanks for the answers. > Glad to be of assistance, but you didn't tell us what the actual solution to your problem was... It is always a good idea to do so because others that have the same problem, and reading the thread, can immediately benefit :-) --Irmen From enrique.palomo at xgs-spain.com Mon Jul 21 05:11:59 2003 From: enrique.palomo at xgs-spain.com (Enrique Palomo) Date: Mon, 21 Jul 2003 11:11:59 +0200 Subject: listening com ports Message-ID: hello all!! can anyone tell me what must i use to listen the com1 and com2 ports and write it to file?? Thanks enrique (Madrid) -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.pollak at gmx.net Wed Jul 2 10:28:07 2003 From: robert.pollak at gmx.net (Robert Pollak) Date: Wed, 02 Jul 2003 16:28:07 +0200 Subject: Mozilla relicensing: Help wanted - Python hacker Message-ID: <3F02EBF7.30706@gmx.net> Let me please point you to , where Gervase Markham from mozilla.org asks for some scripting help. --Robert From sNO_SPAMpinard at zoominternet.net Mon Jul 14 20:08:12 2003 From: sNO_SPAMpinard at zoominternet.net (Steve Pinard) Date: Mon, 14 Jul 2003 20:08:12 -0400 Subject: Which Python Book References: <3F134200.8060708@hotmail.com> Message-ID: <3f134613_6@corp.newsgroups.com> I have not looked at the Python Cookbook, but I'm reading the Nutshell book now (being new to Python myself). The Nutshell book appears to be an excellent reference that you might want to have on your bookshelf. However, as a learning resource, I wouldn't recommend it. I believe it falls into the "Greek" category. It delves into how Python does what it does, and that can be very enlightening. It is not necessary, however, to learn and start using the language. Having said that, there are a couple of FREE resources that I would recommend for learning the language. 1) The Python Tutorial, which comes with the Python download itself, or can be accessed online at www.python.org 2) Dive Into Python (www.diveintopython.org). Mark Pilgrim does an excellent job of showing real working code, then picking apart a line at a time to show what's going on. Perhaps the best part is extensive cross-reference for further reading. I particularly like this style of teaching. Now, having said that, the combination of the free stuff with the Nutshell book might just a unbeatable. (Whew) HTH. -----= 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 tdelaney at avaya.com Sun Jul 20 21:57:13 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 21 Jul 2003 11:57:13 +1000 Subject: [Python-Dev] Python Coding Tools Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D40D3@au3010avexu1.global.avaya.com> > From: Aki Kubota [mailto:akubota at ntsp.nec.co.jp] > > Im new to this mailing list. And Im interested in Python tools. > Stuff you use to make coding easier. like Eclipse for Java. This is not appropriate for Python-Dev, which is for discussion of the development *of* Python, not development *with* python. I have copied your message to the appropriate list - python-list. Tim Delaney From gh at ghaering.de Tue Jul 15 05:04:36 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 15 Jul 2003 11:04:36 +0200 Subject: how to compile python program to linux executable In-Reply-To: <3F13BFF1.2000604@is.lg.ua> References: <3F13BFF1.2000604@is.lg.ua> Message-ID: <3F13C3A4.8050908@ghaering.de> Ruslan Spivak wrote: > Hello. > > Is it possible to convert python program to linux executable program? [...] You can make an executable that contains both your Python script and modules and the interpreter runtime. It's called 'freezing'. The utility for this is in the Python source distribution. There's also Gordon McMillan's Installer that makes the process easier. He offers Linux and Windows versions. Why would you want to do that? There's almost certainly a better solution for your problem, *if* there is any problem in the first place. -- Gerhard From eger at cc.gatech.edu Fri Jul 11 09:55:52 2003 From: eger at cc.gatech.edu (David Eger) Date: 11 Jul 2003 13:55:52 GMT Subject: segfault dup'ing string through C++ (via swig) module Message-ID: I'm trying to make a very simple extension which will return a new copy of a C++ string object to python, and I'm segfaulting in the process. I'm using Python 2.2.2, SWIG 1.3.17 and g++ 3.3. Am I getting something very basic wrong? See code below. -David /* file: dups.cxx */ #include "dups.h" string * dupstring(string s) {return new string(s);} /* file: dups.h */ #ifndef __DUPS_H__ #define __DUPS_H__ #include using namespace std; string * dupstring(string s); #endif /* file: dups.i */ %module dups %{ #include "dups.h" %} /* Convert from C++ --> Python */ %typemap(out) string { $result = PyString_FromString($1.c_str()); } /* Convert from Python --> C++ */ %typemap(in) string { $1 = PyString_AsString($result); } string * dupstring(string); /* file: makefile */ CFLAGS = -gstabs+ -O3 -fpic _dups.so: dups.o dups_wrap.o g++ -shared -o $@ $? %.o: %.cpp g++ -c $(CFLAGS) -o $@ $? %.o: %.cxx g++ -I/usr/include/python2.2 -c $(CFLAGS) -o $@ $? %_wrap.cxx: %.i swig -c++ -python $? clean: rm -f *.o dups_wrap.* *.so dups.py dups.pyc /* file: session_crash */ Python 2.2.2 (#1, Mar 21 2003, 23:40:29) [GCC 3.2.3 20030316 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import dups >>> a = dups.dupstring("foo") Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 16384 (LWP 22607)] 0x0fcc87ec in strlen () from //lib/libc.so.6 (gdb) bt #0 0x0fcc87ec in strlen () from //lib/libc.so.6 #1 0x0fb41324 in _wrap_dupstring (self=0x0, args=0x0) at /usr/include/c++/3.3/bits/char_traits.h:143 #2 0x100ba9e8 in PyCFunction_Call () #3 0x1003c000 in Py_MakePendingCalls () #4 0x1003cd4c in PyEval_EvalCodeEx () #5 0x1003fdcc in PyEval_EvalCode () #6 0x1006cd34 in PyRun_FileExFlags () #7 0x1006c19c in PyRun_InteractiveOneFlags () #8 0x1006bf1c in PyRun_InteractiveLoopFlags () #9 0x1006d984 in PyRun_AnyFileExFlags () #10 0x1000c4c8 in Py_Main () #11 0x1000bf28 in main () #12 0x0fc62da4 in __libc_start_main (argc=1, ubp_av=0x7ffff9f4, ubp_ev=0x0, auxvec=0x7ffffa5c, rtld_fini=0x30026b38 <_rtld_local>, stinfo=0x1000bf18, stack_on_entry=0x7ffff9e0) at ../sysdeps/powerpc/elf/libc-start.c:186 (gdb) From guettler at thomas-guettler.de Mon Jul 21 10:50:19 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 21 Jul 2003 16:50:19 +0200 Subject: Directory Structure for Distutils References: Message-ID: Peter Klyushkin wrote: > Hello, Thomas! > >>>>>> "TG" == Thomas G?ttler writes: > > TG> Thomas G?ttler wrote: >>> Hi! >>> >>> What is the best directory structure for python modules? >>> > TG> One thing is still unclear: How can I copy non python files into > TG> the destination? There is a directory called "gif" which needs > TG> to be in the directory of the my module. > > Take a look at ResourcePackage. It isn't exactly what you want but it > is exactly for your purpose. Hi Peter, Thank you for this link, but I don't want the images to become python source. Still looking for a solution ... thomas From g2h5dqi002 at sneakemail.com Mon Jul 28 21:38:39 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 29 Jul 2003 13:38:39 +1200 Subject: Static typing In-Reply-To: <5627c6fa.0307270537.1afc94d3@posting.google.com> References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> <5627c6fa.0307270537.1afc94d3@posting.google.com> Message-ID: Tayss wrote: > Sort of like when someone asks you to move something to a different > house, and you have no idea how big it is. If you were told, "It's > just a pillow," you know that you don't need to order a huge truck or > take any special precautions. But in Python, you wouldn't have to move the object itself to the new house, only a reference to it! Of course, if it's a mutable pillow, it might not be a good idea to have two people sleeping on it at the same time, in which case you'd want to make a copy. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From piet at cs.uu.nl Sat Jul 12 07:00:34 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 12 Jul 2003 13:00:34 +0200 Subject: Maxmium bufsize using open2? References: Message-ID: As someone else already mentioned, using select is another solution. All solution amount to the fact the input and output to the process are interleaved. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From missive at frontiernet.net Mon Jul 21 17:34:09 2003 From: missive at frontiernet.net (Lee Harr) Date: Mon, 21 Jul 2003 21:34:09 GMT Subject: if information exists on form then use it in cgi References: <2c6431ab.0307211144.4c2f3749@posting.google.com> Message-ID: In article <2c6431ab.0307211144.4c2f3749 at posting.google.com>, lamar_air wrote: > On my web form i have check boxes with the following code: > >St. Kitts Nevis > > when the user submits the form my python cgi retreives each of the > values from the form with code like this for each: > > f=open('C:\My Documents\ABC\boxes', 'w') > > f.write('Boxes') > f.write('\n') Is form a dictionary? How about: if form.has_key('C139') and form['C139'] != '': Also, if you have a bunch of form elements like this, you will probably want to process them in a loop: for k in form.keys(): # may want to sort them first... if k.startswith('C'): # or some other way to identify them... f.write(form[k].value) > if form['C139'].value != '': > f.write(form['C139'].value) > f.write('\n') > > if form['C140'].value != '': > f.write(form['C140'].value) > f.write('\n') > > f.close() > > the problem is if the user doesn't check off all the check boxes on > the form then the if form['C140'].value != '' code errors because > nothing is there. How do i do this? > > Here is the error: > > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > > Traceback (most recent call last): > File "C:\Inetpub\wwwroot\Cgi-bin\Cities2.py", line 175, in ? > if form['C139'].value != '': > File "C:\Python22\lib\cgi.py", line 550, in __getitem__ > raise KeyError, key > KeyError: C139 From peter at engcorp.com Sun Jul 20 00:04:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 00:04:40 -0400 Subject: How to detect user activity - for a screensaver for example. References: Message-ID: <3F1A14D8.54B89804@engcorp.com> Hans Deragon wrote: > > Greetings. > > If I want to write a screensaver for Linux using Python, how can I detect > that the user has not touched the keyboard or mouse for the last 5 mins? Simplest trivial way: check /proc/interrupts for relevant activity... I'm sure there are more standard approaches, but without knowing what they are, or knowing anything about, say, Google ;-), that's the approach I'd take. -Peter From chrisperkins37 at hotmail.com Tue Jul 29 17:52:36 2003 From: chrisperkins37 at hotmail.com (Chris Perkins) Date: 29 Jul 2003 14:52:36 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <2259b0e2.0307290940.49ff417d@posting.google.com> Message-ID: <45228044.0307291352.696b16aa@posting.google.com> mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307290940.49ff417d at posting.google.com>... > I have posted a recipe with the itertools solution suggested in this > thread: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212959 > That's great, but your recipe contains a very serious error - you spelled my name wrong ;) Chris Perkins (not Perking) From glingl at aon.at Tue Jul 29 08:35:12 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue, 29 Jul 2003 14:35:12 +0200 Subject: [Tutor] problems in a python script References: <3F265CDA.9090004@dte.ua.pt> Message-ID: <3F266A00.8010209@aon.at> M?rio Gamito schrieb: > Hi, > > I've downloaded the 30 days trial version of editize and followed the > instructions in http://plone.org/Members/tlynch/HowToIntegrateEditize > to install it. > > Everything runs smoothly until the creation of munge.py as explained > in the above link. I get an error saying > > " Script line 4 > inputvalue = inputvalue.replace("\r", "") > ^ > SyntaxError: invalid syntax" This looks like if this line were indented some (three ?) blanks from the left margin. In Python blanks (or "white space" in general) has syntactic meaning. Therefore in a simple script a simple statement like this assignment MUST NOT be indented. Remove the indentation and things will work. HTH, Gregor > > A curious thing is that when i save it, not only i get the above > error, but also the lines begining with double cardinal (##) are gone!!! > > Also the text refers to "Note: you might need to edit the line calling > munge in wysiwyg_support to reflect the name of your folder where all > the Editize stuff is stored." > > Where is this is done ? > > Thank you in advance for your time and patience. > > Warm Regards, > M?rio Gamito > > > > > munge.py > ----------------------------------------------------- > ## Script (Python) "munge" > ##bind container=container > ##bind context=context > ##bind namespace= > ##bind script=script > ##bind subpath=traverse_subpath > ##parameters=inputvalue > ##title= > > # to guard against files that might contain only > # returns or linefeeds, we will delete each separately > # rather than trying: replace("\r\n", "") > inputvalue = inputvalue.replace("\r", "") > inputvalue = inputvalue.replace("\n", "") > inputvalue = inputvalue.replace("'", "'") > > return inputvalue > ------------------------------------------------------------ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jepler at unpythonic.net Sun Jul 20 21:48:16 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 20 Jul 2003 20:48:16 -0500 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) Message-ID: <20030721014811.GA3858@unpythonic.net> >>> {}[:] = None Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type I'd have expected something like 'TypeError: unslicable type' meaning that you can't slice a dict, not that slice()s aren't hashable. In fact, I wonder why slices *aren't* hashable. I can imagine wanting to write something like the following: class X: # ... def __getitem__(self, idx): if not idx in self._cache: # potentially expire an item and if isinstance(idx, slice): self._cache[idx] = self.calculate_slice_expensively(idx) else: self._cache[idx] = self.calculate_idx_expensively(idx) return self._cache[idx] Jeff From CousinStanley at hotmail.com Tue Jul 15 16:58:09 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 15 Jul 2003 13:58:09 -0700 Subject: String Manipulation References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: | I need a piece of code that takes a string like this | string1 = "aaa/bbb/ccc/dd" and extracts a string containting | the character after the last "/" | | So for this example the result would be "dd" | ... lamar_air ... Here is one way ... >>> str_in = 'aaa/bbb/ccc/dd' >>> >>> list_in = str_in.split( '/' ) >>> >>> last_element = list_in[ -1 ] >>> >>> print last_element dd >>> -- Cousin Stanley Human Being Phoenix, Arizona From andre at netvision.com.br Sat Jul 12 13:22:22 2003 From: andre at netvision.com.br (Andre) Date: Sat, 12 Jul 2003 17:22:22 +0000 Subject: Reading packets from a tun device. Message-ID: <200307121722.22603.andre@netvision.com.br> I'm trying to read packets from a tun device in Python, the code I used for this is the following: f = file( '/dev/tun0', 'r+' ) pkt = f.read( 1500 ) The problem is that the f.read() call doesn't return. When I used a small value in the f.read() call instead of the 1500, like 1 or 5, it did return the first bytes of the packet. I then went to the manuals and found that file() uses stdio's fopen, so I changed my code to make file() not do any buffering, like this: f = file( '/dev/tun0', 'r+', 0 ) pkt = f.read( 1500 ) But the behavior of the program is the same as the one above. What I'm looking for is a way to open a file in Python without using stdio, or a way to read from a tun device using it. I also tried google'ing for another Python program that uses a tun device, but couldn't find any yet, so if you know of a Python program that uses a tun device, that'd be enough for me to figure out what I'm doing wrong. Thank you for reading all this! From mwh at python.net Thu Jul 17 13:50:00 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jul 2003 17:50:00 GMT Subject: Mac OS X, Fink, Python, and web browser References: <2b012c5e.0307151342.e5db114@posting.google.com> Message-ID: <7h3n0fd123r.fsf@pc150.maths.bris.ac.uk> Joe Heafner writes: > Don Hiatt wrote: > > You can change your default web browser to Safari using the preferences > > pane (under internet, I believe). If IDLE_fork uses the default browser > > property then Safari should launch. > > > Hi. > I just double checked and Safari is indeed my system default under System > Preferences -> Internet -> Web. There's no mention of Safari in > webbrowser.py though. IIRC, webbrowser.py uses internet config on the mac, so you certainly should get the default browser. I've had trouble getting with webrowser.py on Mac OS X before now, though, but I didn't dig. Cheers, M. -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From glenfant at NOSPAM.bigfoot.com Fri Jul 4 12:28:49 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Fri, 4 Jul 2003 18:28:49 +0200 Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F04E609.2010500@dadsetan.com> Message-ID: "Behrang Dadsetan" a ?crit dans le message de news: 3F04E609.2010500 at dadsetan.com... > A bit a pitty the message board system is php based.. > > Does anyone know about message board systems written in python? The right question is : "does the web tool comply the requirements ?" Personnally, I prefer phpMySQLadmin to most python stuff in that scope. Despite I prefer programming with Python. --Gilles From dave at pythonapocrypha.com Thu Jul 3 15:08:27 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 3 Jul 2003 12:08:27 -0700 Subject: A story about Python... sort of In-Reply-To: References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <200307031208.27973.dave@pythonapocrypha.com> On Thursday 03 July 2003 10:25 am, Max Khesin wrote: > I am not sure where we disagree. This is exactly my point. The statement > " > Engineering Lessons > ------------------- > 1. C/C++ is no longer a viable development language > " > is pure rubbish. C++ is still great for certain kinds of projects, FWIW, he goes on to say that he's referring to using it for applications level work. > and > there are lots of open-source and proprietary projects to prove this. I > mean, is Linux (or Windows) 'not a viable project'?? Well, again, neither of those are "applications level" projects. He probably could have emphasized that portion of his opinion better. I agree that his position was probably taken a little too strongly, but it does have some merit. For example, I'm a professional developer by trade and by hobby and I stopped using C++ about 2 years ago (except for an occasional Python extension module before ctypes came about) and I have no plans to ever go back because, for me, it is too expensive to develop in C++. If I _must_ drop to a lower-level language temporarily (after exhausting other avenues like Pyrex, Psyco, or even PyInline :) ) I'd be willing to use C a little, or may a C-with-simple-classes style of C++, but I doubt I'll ever use C++ again for much at all, and even then I'll use only the tiniest subset of C++'s features possible. For me the language is too big, has too many pitfalls, and it forces me to manage too many little details. If Python were to become too slow or too weird I'd migrate to another high-level language but life is too short to mess with a language any lower-level than you really need to, and for the most part C++ now falls into that category for me. In that respect I agree with the guy who wrote the article - for me C++ is fading into history just like assembly did once upon a time, and I'm glad. -Dave From aahz at pythoncraft.com Thu Jul 10 13:24:57 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2003 13:24:57 -0400 Subject: does lack of type declarations make Python unsafe? References: Message-ID: In article , David Abrahams wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) writes: >> >> Confronting the Martellibot is like flirting with an encyclopedia, I'd >> rather not do it myself, but I respect those who do, because it >> produces knowledge. > >Yeah, and fun! I'm a little disappointed that Alex disappeared from >this discussion because I thought it was going somewhere interesting >and was looking forward to some more cogent arguments. Any chance of >re-opening it, Alex? I'm referring, in particular, to >http://tinyurl.com/gbq0 Alex has been busy with OSCON and other things; I don't expect him to make many contributions until he's back in Italy and caught up. If you want further discussion, I'd suggest reposting this when he starts posting here again. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From andy47 at halfcooked.com Sun Jul 6 09:30:12 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Sun, 06 Jul 2003 14:30:12 +0100 Subject: AIX + GCC 2.95.3 - Python (2.1 or 2.2) - building the shared library (.so) for python - HOW TO?!? In-Reply-To: <3F056D69.1090705@polbox.com> References: <3F056D69.1090705@polbox.com> Message-ID: hab wrote: > Hi all, [snip description of installing Python from source] > Thanks in advance, > Tom > It might not be what you are looking for, but I've recently installed Python on an AIX box using the rpm available from IBM at; http://www-1.ibm.com/servers/aix/products/aixos/linux/download.html Works like a dream for me. YMMV. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From klapotec at chello.at Thu Jul 31 16:10:47 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 31 Jul 2003 20:10:47 GMT Subject: [Newbie] FAQ? References: Message-ID: On Thu, 31 Jul 2003 13:58:55 -0500, Skip Montanaro wrote: > > Simone>is there a FAQ for this NG? > > Christopher> http://www.faqs.org/faqs/by-newsgroup/comp/comp.lang.python.html > Christopher> Have you heard of Google? > > Simone> sure I did! Pardon... > >Don't apologize too profusely. The dates on the two FAQs listed there (one >for c.l.py and one for c.l.py.announce) are 1996 and 1999, respectively. >The c.l.py FAQ probably is going to be all that useful unless you're a >Python historian. > You're right, I was a bit too fast there... Also in hindsight I sounded a bit rough there, which wasn't my intention. --Christopher From k.robert at gmx.de Sat Jul 26 13:00:06 2003 From: k.robert at gmx.de (Robert) Date: Sat, 26 Jul 2003 19:00:06 +0200 Subject: This application has requested the Runtime to terminate it in an unusual way ? Message-ID: <3f22b3a7$0$30287$9b622d9e@news.freenet.de> On Windows my python 2.2 application (using win32ui GUI, ...) some times simply crashes when I work with the GUI. Tooltips are involved; the app crashes on mouse moves). The GUI-Window disapears and only the following message is yielded (from python-core?) " This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. " what could be the reason ? Robert From adalke at mindspring.com Mon Jul 28 06:46:28 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 28 Jul 2003 04:46:28 -0600 Subject: How to reverse lookup characters in list? References: Message-ID: Keith Jones > import string > string.lowercase > > that gives you a-z, lowercase.. Actually, use 'string.ascii_lowercase' because 'string.lowercase' depends on your locale. On the other hand, for this application, string.lower might be the right thing. Also, the tjland? You need to change the c = c + v into c = (c + v) % len(alphabet) Suppose c is 'z' and v is 2. Then 25 (the position of the 'z') + 2 is 27, which is beyond the list of letters. You need some way to loop around to 0 once you go over the end, and the '%' is the loop-around operator. (It's actually called the mod function.) It also works the other way, so "-1 % 26" loops around to 25. You might find this helpful >>> s = "testing" >>> v = 2 >>> letters = string.ascii_lowercase >>> t = "" >>> for c in s: ... t = t + letters[(letters.index(c)+v)%len(letters)] ... >>> t 'vguvkpi' >>> s = t >>> v = -2 >>> t = "" >>> for c in s: ... t = t + letters[(letters.index(c)+v)%len(letters)] ... >>> t 'testing' >>> With a bit more experience, I think you'll find this also interesting v = 2 # Start by mapping each letter to itself # (There are 256 possible values in an 8-bit character.) encoding_d = {} for i in range(256): c = chr(i) encoding_d[c] = c lc = string.ascii_lowercase for i in range(len(lc)): from_char = lc[i] to_char = lc[(i+v) % len(lc)] encoding_d[from_char] = to_char uc = string.ascii_uppercase for i in range(len(uc)): from_char = uc[i] to_char = uc[(i+v) % len(uc)] encoding_d[from_char] = to_char s = "This is a test." # This is better written as: # t = "".join([encoding_d[c] for c in s]) # but that's something to try out after you learn a # bit more Python. t = "" for c in s: t = t + encoding_d[c] print t # Make a decoding dictionary which is the opposite of the # encoding dictionary decoding_d = {} for from_char, to_char in encoding_d.items(): decoding_d[to_char] = from_char # or as: u = "".join([decoding_d[c] for c in t]) u = "" for c in t: u = u + decoding_d[c] print u With some more experience beyond that, you might write it like this (It uses a very different style and implementation) import string def _r(s, n): # rotate the characters left n positions n %= len(s) # make sure it's properly within range return s[n:] + s[:n] class RotEncoder: def __init__(self, n): from_letters = string.ascii_lowercase + string.ascii_uppercase to_letters = _r(string.ascii_lowercase, n) + _r(string.ascii_uppercase, n) self.encode_table = string.maketrans(from_letters, to_letters) self.decode_table = string.maketrans(to_letters, from_letters) def encode(self, s): return string.translate(s, self.encode_table) def decode(self, s): return string.translate(s, self.decode_table) code = RotEncoder(2) print code.encode("testing") print code.decode(code.encode("testing")) Andrew dalke at dalkescientific.com From danbmil99 at yahoo.com Wed Jul 23 03:44:33 2003 From: danbmil99 at yahoo.com (dan) Date: 23 Jul 2003 00:44:33 -0700 Subject: python assignment References: Message-ID: Ok, thanks for the responses. I think I 'get' it now. However I do think it would be an excellent idea to have a bit of exposition on this subject in the Python tutorial, or perhaps in a separate section. It's not really hard to understand once you realize what's going on, but I suspect it causes no end of confusion for both new programmers and old (those used to langs such as C++). Here's a better example of how a newbie can get confused: >>> a = (1,2) #a is a tuple >>> b = a #b & a now point to same object on heap >>> a += (3,) #tuples are immutable so += returns a new one >>> b == a #b points to old, a points to new False >>> a = [1,2] #a is a list >>> b = a #a & b point to same object again >>> a += [3] #a is mutable, so += mutates it >>> b == a #of course True >>> a = a + [4] #hmm... one *might* think this is eqiv. to a += [4] >>> a == b False #but NOOO!! >>> a [1, 2, 3, 4] >>> b [1, 2, 3] Now that I understand what's happening, it makes sense, but initially this sort of behavior was quite mysterious. -dbm danbmil99 at yahoo.com (dan) wrote in message news:... > without stirring the pot too much -- > > could someone please point me to whatever documentation exists on the > philosophy, semantics, and practical implications of how Python > implements the assignment operator? So far I can't find much useful > in the regular documentation. I understand the basic concept that > names are bound to objects which exist on the heap, but that still > doesn't explain why a = b doesn't _always_ cause a to point to the > same object as b. What determines when the object in question is > copied? What determines when a future maniplulation of the variable > will cause it to point to an object that is already referenced by > another variable? (see code below for an example). > > What I need is an exact and unambiguous algorithm for determining when > an assignment will change the id of the variable (or should I say, > when the evaluation of an expression will cause a new object to be > created). Some of the issues involved can be discerned from the > following session: > > >>> a = 1 > >>> b = a > >>> a is b > True > >>> a += 1 > >>> a -= 1 > >>> a is b > True > >>> a = 1.0 > >>> b = a > >>> a is b > True > >>> a += 1 > >>> a -= 1 > >>> a is b > False > >>> a == b > True From bignose-hates-spam at and-zip-does-too.com.au Fri Jul 11 18:20:48 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 12 Jul 2003 08:10:48 +0950 Subject: The "intellectual property" misnomer References: Message-ID: On Fri, 11 Jul 2003 15:13:43 -0400, Guido van Rossum wrote: > The PSF holds the intellectual property rights for Python Ugh. Please don't propagate this ridiculous, meaningless term. It's used to refer to a wide range of greatly disparate legal concepts; to use it as a single term implies that there's some unifying "intellectual property" principle joining them together, which is a falsehood. If the PSF holds the copyright to Python, please say that. If the PSF holds patents which cover Python, please say that. If the PSF owns the trademark for Python, please say that. If the PSF has trade secrets in Python, please say that. But please *don't* muddy the water by saying the PSF holds "the intellectual property rights" for Python. That says nothing useful -- it doesn't help determine which of the above fields of law are applicable -- and only promotes the idea that all these different fields of law are part of a whole, which they are definitely not. It also encourages another falsehood: that of considering intellectual objects as property. This is something which many people who use Python would disagree with strongly. -- \ "Why should I care about posterity? What's posterity ever done | `\ for me?" -- Groucho Marx | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From tzot at sil-tec.gr Wed Jul 2 05:14:04 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 02 Jul 2003 12:14:04 +0300 Subject: Date issue Win98 vs NT References: Message-ID: On Wed, 02 Jul 2003 03:50:10 GMT, rumours say that "Stan Cook" might have written: >Has anyone else had this or a similar problem and is there a workaround? >This piece of code: >from time import gmtime, strftime >_log = _log + "\\" + strftime("%m%d%y", gmtime()) + ".log" >produces a file with the name 'today's date.log' on NT, but creates a file >called 'tomorrow's date.log' on Windows 98. I would really like to know >why this happens. Any help offered is very much appreciated. Are you by any chance in Austin, Texas? I could guess that first you tried this code in Windows NT, and later rebooted to Windows 98. Running your code on Windows 98 happened after 6pm, your local time. By that time, I think it is already tomorrow in Greenwich, England (which is what gmtime provides). Try localtime instead (assuming your timezone is set correctly both in NT and 98). -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From just at xs4all.nl Wed Jul 2 06:38:02 2003 From: just at xs4all.nl (Just) Date: Wed, 02 Jul 2003 12:38:02 +0200 Subject: Assign to True / False in 2.3 References: <3F02ADD3.6047F561@alcyone.com> Message-ID: In article <3F02ADD3.6047F561 at alcyone.com>, Erik Max Francis wrote: > Culley Angus wrote: > > > I was a little suprised to find that I could assign a value to 'True', > > and 'False' without warning though, and was wondering if this is > > deliberate. > > This is true of pretty much all Python features. The only special > dispensation goes to None, which is a warning now (in the 2.3 beta): Actually, at some point there was a warning for True and False as well, but it was taken out because there is plenty of code out there like this: try: True, False except NameError: True, False = 1, 0 (I'm not entirely sure, it can also be that there never was a warning in place, but it was discussed.) Just From aahz at pythoncraft.com Fri Jul 11 10:33:47 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 10:33:47 -0400 Subject: Embedding Python, threading and scalability References: Message-ID: In article , Simon Wittber (Maptek) wrote: > >To write scalable applications in Python, one must write the >'scalabilty-required' parts n C. > >Does anyone else see this as a problem? Not particularly. Most threading at the application level is done for one or more of three purposes: * Allowing background work and fast response in a GUI application * Scalable I/O * Autonomous sections of code for algorithmic simplicity (e.g. simulations) Python does quite well at all three out of the box (the second because all standard Python I/O modules release the GIL, as do most 3rd-party extensions that deal with I/O (e.g. mxODBC)). The only thing Python doesn't do is computational threading, and Python's overhead makes it a poor choice for that purpose. Finally, there are so many distributed computing solutions that multiple processes are a viable technique for managing computational threading. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From http Sun Jul 20 21:57:04 2003 From: http (Paul Rubin) Date: 20 Jul 2003 18:57:04 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> Message-ID: <7x8yqstzf3.fsf@ruckus.brouhaha.com> "Alan Dechert" writes: > You make a lot of good points. As I understand it, Canada administers > national, province, and local elections separately. They happen at > different times and are conducted by different entities. The U.S. is one of > very few where you see federal, state, and local contests on the same > ballot. The US does not have federal contests. All elections for federal office are actually state contests. That includes Presidential elections, which are a bunch of state contests for slates of electors from the individual states. That all the elections are state contests and not federal ones is one of the reasons it's hard to impose uniform national standards on how the elections are run. From jjl at pobox.com Mon Jul 21 09:45:17 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Jul 2003 14:45:17 +0100 Subject: Python scripting with Paint Shop Pro 8.0 References: <87d6g4wzu7.fsf@pobox.com> Message-ID: <87oezoq9hu.fsf@pobox.com> Marc Wilson writes: [...] > The documentation is, er, sketchy. The manual refers you to a non-existant > folder on the CD, and the Python content is referred to as the "Python > Scripting Engine", which suggests it may not be a full implementation. If I > have to install Python separately, so be it. I'll look for the .pyd file > and see if there a suspiciously-named executable there as well. The fact that it's embedded doesn't necessarily mean that you can't import it from outside the running application, but it may well not be possible. Worth a try, though. As I said in an email, don't forget COM -- maybe one of those .py files you have is just a wrapper around a COM automation interface. The "Python for Windows extensions" (aka win32all) is what you need for most COM stuff. John From hokiegal99 at hotmail.com Fri Jul 18 18:16:05 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Fri, 18 Jul 2003 18:16:05 -0400 Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> Message-ID: <3F1871A5.3020702@hotmail.com> Thanks again for the help Andy! One last question: What is the advantage of placing code in a function? I don't see how having this bit of code in a function improves it any. Could someone explain this? Thanks! Andy Jewell wrote: > On Friday 18 Jul 2003 2:33 am, hokiegal99 wrote: > >>A few questions about the following code. How would I "wrap" this in a >>function, and do I need to? >> >>Also, how can I make the code smart enough to realize that when a file >>has 2 or more bad charcters in it, that the code needs to run until all >>bad characters are gone? > > > It almost is ;-) > > >>For example, if a file has the name >>">chars out of the file name. >> >>The passes look like this: >> >>1. >2. -bad*mac\file becomes -bad-mac\file >>3. -bad-mac\file becomes -bad-mac-file >> >>I think the problem is that once the program finds a bad char in a >>filename it replaces it with a dash, which creates a new filename that >>wasn't present when the program first ran, thus it has to run again to >>see the new filename. > > > No, the problem is that you're throwing away all but the last correction. > Read my comments below: > > import os, re, string > bad = re.compile(r'%2f|%25|[*?<>/\|\\]') #search for these. > print " " > setpath = raw_input("Path to the dir that you would like to clean: ") > print " " > print "--- Remove Bad Charaters From Filenames ---" > print " " > for root, dirs, files in os.walk(setpath): > for file in files: > badchars = bad.findall(file) # find any bad characters > newfile = file > for badchar in badchars: # loop through each character in badchars > # note that if badchars is empty, this loop is not entered > # show whats happening > print "replacing",badchar,"in",newfile,":", > # replace all occurrences of this badchar with '-' and remember > # it for next iteration of loop: > newfile = newfile.replace(badchar,'-') #replace bad chars. > print newfile > if badchars: # were there any bad characters in the name? > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,file) > os.rename(oldpath,newpath) > print oldpath > print newpath > print " " > print "--- Done ---" > print " " > > > wrt wrapping it up in a function, here's a starter for you... "fill in the > blanks": > > > -------8<----------- > def cleanup(setpath): > # compile regex for finding bad characters > > # walk directory tree... > > # find any bad characters > > # loop through each character in badchars > > # replace all occurrences of this badchar with '-' and remember > > # were there any bad characters in the name? > > -------8<----------- > > To call this you could do (on linux - mac paths are different): > > -------8<----------- > cleanup("/home/andy/Python") > -------8<----------- > > hope that helps > -andyj > > From guettler at thomas-guettler.de Mon Jul 21 05:35:36 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 21 Jul 2003 11:35:36 +0200 Subject: Directory Structure for Distutils Message-ID: Hi! What is the best directory structure for python modules? I want to install a script called pyla into /usr/bin/pyla The script pyla imports several methods and classes from a module called pyla. Up to would like to do it like this pyla/ pyla/setup.py pyla/dist (created by distutils) pyla/pyla/__init__.py # This should be in site-packages/pyla pyla/pyla/foo.py pyla/pyla # Script for /usr/bin cannot be called like this # because directory pyla exists. Would be nice if there was a "prefered" directory strucuture in the documentation of distutils. This should include doc/, man/, etc/, ... What does your directory strutures look like? thomas From thewrights at ozemail.com.au Thu Jul 17 09:07:36 2003 From: thewrights at ozemail.com.au (thewrights at ozemail.com.au) Date: Thu, 17 Jul 2003 23:07:36 +1000 Subject: Co-routines Message-ID: I have an application in which I want the users to be able to create python functions: def f1(): print "1-1" print "1-2" print "1-3" def f2(): print "2-1" print "2-2" print "3-3" and when my application runs, I want to execute these functions in "lock-step", so that the output looks like: 1-1 2-2 1-2 2-2 1-3 2-3 If I were using prolog I'd write a meta-interpreter; with lisp/scheme I might use macros and do some source-code transformation. What's the most Pythonic way to do this? If I assume that each statement in the function bodies occupy only one physical line, I could read the user functions in, and output them to a new file, interspersing "yield"s. If, quite reasonable, a user spans a statement over more that one line: def f3(): d = { "a" : "One string", "b" : "Another string" } print d then I'm in the "parsing python" game. (I recall the malevolent and wicked ternary operator example that was posted here which fiddled with function source code in the metaclass... I'm still picking up pieces of my brain from the floor) I'd be very grateful for suggestions. Is the compiler module my friend? I would love to end up with: while 1: try: for f in function_list: f.next() except StopIteration: print "wow!" Thanks Chris Wright From justinjohnson at fastmail.fm Wed Jul 9 13:00:30 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Wed, 09 Jul 2003 11:00:30 -0600 Subject: process.py problems In-Reply-To: <20030709123628.66ACA3771B@www.fastmail.fm> References: <20030708153117.127C0326C0@www.fastmail.fm> <20030708094057.C9520@ActiveState.com> <20030708210829.B3BBE3886D@www.fastmail.fm> <20030708170131.C13603@ActiveState.com> <20030709123005.C0B58374AF@www.fastmail.fm> <20030709123628.66ACA3771B@www.fastmail.fm> Message-ID: <20030709170030.51BDE37470@www.fastmail.fm> I guess this really is a problem. I found that it sometimes hangs on p.stdout.read(). >>> p = process.ProcessOpen("cleartool lsvob -s") >>> p.stdout.read() '\\import_test\n\\pvob\n\\vob\n\\adminvob\n\\adminvob2\n' >>> p = process.ProcessOpen("cleartool lsview -l") >>> p.stdout.read() *** just hangs here *** On Wed, 09 Jul 2003 06:36:28 -0600, "Justin Johnson" said: > Never mind the part about commands hanging.... that appears to be > related to something else in my code. I think your process stuff is > working fine for .exe commands. :-) > > So just the dir command is failing now. > > On Wed, 09 Jul 2003 06:30:05 -0600, "Justin Johnson" > said: > > After replacing my process.py I still get an error with the dir command > > (see below). > > > > I'm getting some wierd results with normal .exe commands though. > > Commands that don't have much output come back just fine, but commands > > that have more output, even if they don't take long to run necessarily, > > seem to get stuck and just hang, never returning. > > > > E:\ccase\python\uhg\uht>python > > ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on > > Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import process > > >>> p = process.ProcessOpen("dir") > > process: info:ProcessOpen.__init__(cmd='dir', mode='t', cwd=None, > > env=None) > > process.res: info:[11054544] ProcessOpen._start(): create child stdin: > > <_FileWra > > pper: file:None fd:3 os_handle:> > > process.res: info:[11054544] ProcessOpen._start(): create child stdout: > > <_FileWr > > apper: file:None fd:4 os_handle:> > > process.res: info:[11054544] ProcessOpen._start(): create child stderr: > > <_FileWr > > apper: file:None fd:5 os_handle:> > > process: debug:_whichFirstArg: first='dir', rest='' > > Traceback (most recent call last): > > File "", line 1, in ? > > File "process.py", line 1118, in __init__ > > self._startOnWindows() > > File "process.py", line 1289, in _startOnWindows > > cmd = _fixupCommand(cmd, self._env) > > File "process.py", line 516, in _fixupCommand > > cmd = _whichFirstArg(cmd, env) > > File "process.py", line 325, in _whichFirstArg > > candidate = which.which(first) > > File "which.py", line 251, in which > > raise WhichError("Could not find '%s' on the path." % command) > > which.WhichError: Could not find 'dir' on the path. > > >>> > > > > >>> p = process.ProcessOpen("cleartool lsvob -l") > > process: info:ProcessOpen.__init__(cmd='cleartool lsvob -l', mode='t', > > cwd=None, > > env=None) > > process.res: info:[18469440] ProcessOpen._start(): create child stdin: > > <_FileWra > > pper: file:None fd:3 os_handle:> > > process.res: info:[18469440] ProcessOpen._start(): create child stdout: > > <_FileWr > > apper: file:None fd:4 os_handle:> > > process.res: info:[18469440] ProcessOpen._start(): create child stderr: > > <_FileWr > > apper: file:None fd:5 os_handle:> > > process: debug:_whichFirstArg: first='cleartool', rest='lsvob -l' > > process: debug:_SaferCreateProcess(appName=None, > > cmd='"C:\\Program > > Files\\Rational\\ClearCase\\bin\\cleartool > > .EXE" lsvob -l', > > env=None, > > cwd=None) > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > process: info:_registerprocess(process= > 0x0119D2 > > 40>) > > ***** It doesn't return here ***** > > > > > > On Tue, 8 Jul 2003 17:01:32 -0700, "Trent Mick" > > said: > > > > > > Yup, process.py is expected a which.py <1.0. Crappy. I need to put up a > > > new process.py. To work around in it in your current build you need to > > > changes process.py's usages of which.which() to expect a single hit > > > instead of a list of a all hits. In other words, which.which() changed > > > from: > > > >>> which.which("python") > > > ["C:\\Python22\\python.exe", "C:\\Python21\\python.exe", ...] > > > to: > > > >>> which.which("python") > > > "C:\\Python22\\python.exe" > > > > > > This is a little bit of a pain to do though. I have attached an untested > > > process.py that should have this fixed. I apologize for the informalness > > > of this. I'll try to get a new process.py version up on > > > when I get a chance. > > > > > > Cheers, > > > Trent > > > > > > > > > [Justin Johnson wrote] > > > > Thanks for the reply! > > > > > > > > which 1.0.2 > > > > > > > > Here's the log output with the dir command > > > > ----------------------- > > > > process.res: info:[18392288] ProcessOpen._start(): create child stdin: > > > > <_FileWra > > > > pper: file:None fd:3 os_handle:> > > > > process.res: info:[18392288] ProcessOpen._start(): create child stdout: > > > > <_FileWr > > > > apper: file:None fd:4 os_handle:> > > > > process.res: info:[18392288] ProcessOpen._start(): create child stderr: > > > > <_FileWr > > > > apper: file:None fd:5 os_handle:> > > > > process.res: info:[18392288] ProcessOpen.__del__() > > > > process: info:[18392288] ProcessOpen.close() > > > > process: info:[18392288] ProcessOpen: closing stdin (<_FileWrapper: > > > > file:None fd > > > > :3 os_handle:>). > > > > process: debug:[18400496] _FileWrapper.close() > > > > process: debug:[18400496] _FileWrapper.close: close handle > > > > process: debug:[18400496] _FileWrapper.close: closing handle raised > > > > process: debug:[18400496] _FileWrapper.close: done closing handle > > > > process: info:[18392288] ProcessOpen: closing stdout (<_FileWrapper: > > > > file:None f > > > > d:4 os_handle:>). > > > > process: debug:[18400720] _FileWrapper.close() > > > > process: debug:[18400720] _FileWrapper.close: close handle > > > > process: debug:[18400720] _FileWrapper.close: closing handle raised > > > > process: debug:[18400720] _FileWrapper.close: done closing handle > > > > process: info:[18392288] ProcessOpen: closing stderr (<_FileWrapper: > > > > file:None f > > > > d:5 os_handle:>). > > > > process: debug:[18403024] _FileWrapper.close() > > > > process: debug:[18403024] _FileWrapper.close: close handle > > > > process: debug:[18403024] _FileWrapper.close: closing handle raised > > > > process: debug:[18403024] _FileWrapper.close: done closing handle > > > > process: debug:[18400720] _FileWrapper.close() > > > > process: debug:[18400496] _FileWrapper.close() > > > > process: debug:[18403024] _FileWrapper.close() > > > > ---------------- > > > > > > > > I also get the following results running commands that are in my path... > > > > ------------------ > > > > g`"apper: file:None fd:5 os_handle:> > > > > process: debug:_SaferCreateProcess(appName=None, > > > > cmd='C lsview -s', > > > > env=None, > > > > cwd=None) > > > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > > > > > process.res: info:[18680944] ProcessOpen.__del__() > > > > process: info:[18680944] ProcessOpen.close() > > > > process: info:[18680944] ProcessOpen: closing stdin (<_FileWrapper: > > > > file:None fd > > > > :3 os_handle:>). > > > > process: debug:[18696880] _FileWrapper.close() > > > > process: debug:[18696880] _FileWrapper.close: close handle > > > > process: debug:[18696880] _FileWrapper.close: closing handle raised > > > > process: debug:[18696880] _FileWrapper.close: done closing handle > > > > process: info:[18680944] ProcessOpen: closing stdout (<_FileWrapper: > > > > file:None f > > > > d:4 os_handle:>). > > > > process: debug:[18696832] _FileWrapper.close() > > > > process: debug:[18696832] _FileWrapper.close: close handle > > > > process: debug:[18696832] _FileWrapper.close: closing handle raised > > > > process: debug:[18696832] _FileWrapper.close: done closing handle > > > > process: info:[18680944] ProcessOpen: closing stderr (<_FileWrapper: > > > > file:None f > > > > d:5 os_handle:>). > > > > process: debug:[18699984] _FileWrapper.close() > > > > process: debug:[18699984] _FileWrapper.close: close handle > > > > process: debug:[18699984] _FileWrapper.close: closing handle raised > > > > process: debug:[18699984] _FileWrapper.close: done closing handle > > > > process: debug:[18696832] _FileWrapper.close() > > > > process: debug:[18696880] _FileWrapper.close() > > > > process: debug:[18699984] _FileWrapper.close() > > > > --------- > > > > > > > > > > > > > > -- > > > Trent Mick > > > TrentM at ActiveState.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From skip at pobox.com Thu Jul 24 16:00:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jul 2003 15:00:01 -0500 Subject: easy way to remove nonprintable chars from string In-Reply-To: <2b012c5e.0307241138.177e5c8c@posting.google.com> References: <2b012c5e.0307241138.177e5c8c@posting.google.com> Message-ID: <16160.15041.404075.457250@montanaro.dyndns.org> Don> Is there an easy way to remove multiple non-printable (e.g. "not Don> strings.printable") from a string? Perhaps something like Don> foo.replace(list_of_nonprintables, '') if it only existed? :-) Check out the string module's translate function. Skip From fredrik at pythonware.com Thu Jul 17 02:44:50 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2003 08:44:50 +0200 Subject: Regular expression help References: Message-ID: David Lees wrote: > I forget how to find multiple instances of stuff between tags using > regular expressions. Specifically I want to find all the text between a > series of begin/end pairs in a multiline file. > > I tried: > >>> p = 'begin(.*)end' > >>> m = re.search(p,s,re.DOTALL) > > and got everything between the first begin and last end. I guess > because of a greedy match. What I want to do is a list where each > element is the text between another begin/end pair. people will tell you to use non-greedy matches, but that's often a bad idea in cases like this: the RE engine has to store lots of back- tracking information, and your program will consume a lot more memory than it has to (and may run out of stack and/or memory). a better approach is to do two searches: first search for a "begin", and once you've found that, look for an "end" import re pos = 0 START = re.compile("begin") END = re.compile("end") while 1: m = START.search(text, pos) if not m: break start = m.end() m = END.search(text, start) if not m: break end = m.start() process(text[start:end]) pos = m.end() # move forward at this point, it's also obvious that you don't really have to use regular expressions: pos = 0 while 1: start = text.find("begin", pos) if start < 0: break start += 5 end = text.find("end", start) if end < 0: break process(text[start:end]) pos = end # move forward From jbar at lf1.cuni.cz Thu Jul 3 08:12:27 2003 From: jbar at lf1.cuni.cz (Jiri Barton) Date: Thu, 03 Jul 2003 14:12:27 +0200 Subject: How to setup webserver for Python References: Message-ID: <3f041dac@shknews01> It is actually 'Options' not 'Option' Try: echo 'Options +ExecCGI' >.htaccess in the console and see. http://httpd.apache.org/docs/howto/cgi.html HTH, Jiri From alanmk at hotmail.com Sat Jul 19 10:59:16 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 19 Jul 2003 15:59:16 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <3F195CC4.D426E416@hotmail.com> Martin v. Loewis >> So what do you think about this message?: >> >> ???????????????? >> >> Look Ma, no markup. And not every character uses two bytes, either. >> And I can use Umlauts (??????) and Arabic (????????.????????????) >> if I want to. Florian Schulze wrote: > And [it displays properly on] Opera (7.11). > I would also like to know what's the trick. The final point I'd like to make [explicit] is: nobody had to ask me how or why my xml snippet worked: there were no tricks. Nobody asked for debugging information, or for reasons why they couldn't see it: everyone saw/heard/felt it. Thus saving me a large amount of (time|effort|embarassment)+, helping people perceive what I was saying, or apologising to those that it slipped past. One person, Bengt, said that he couldn't see it, but posted another piece of very similar markup, i.e. (ht|x)ml, that worked for him and everybody else. simple-and-universally-interchangable-encodings-and-structures-are-a-honking-great-idea:-let's-do-more-of-those-ly y'rs. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mertz at gnosis.cx Tue Jul 15 12:41:48 2003 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 15 Jul 2003 12:41:48 -0400 Subject: [Announce] Gnosis Utils 1.1.0 Message-ID: [Announce] Gnosis Utils 1.1.0 This release contains enhancements to gnosis.xml.objectify. Added _XO_.__repr__ method to make nodes print in a nicer, more compact fashion. Added ._seq attribute to node objects to support structure preserving convenience functions. Specifically, older versions of gnosis.xml.objectify lost information about mixed content and the order of children. E.g., >>> xml = 'Mixed content is good' >>> obj = XO(xml,EXPAT).make_instance() >>> obj.PCDATA, obj.i.PCDATA, obj.b.PCDATA (u'Mixed is', u'content', u'good') We had no way of knowing where inside the and the occur, nor even which child element occurs first. Now we can recover that information: >>> from gnosis.xml.objectify import content, children >>> content(obj) [u'Mixed ', , u' is ', ] >>> children(obj) [, ] Sequence information and convenience methods are NOT SUPPORTED (yet?) for the DOM parser, only for EXPAT! Changed default parser to EXPAT. If you have relied on the special attribute ._XML that the DOM parser attaches to nodes, you will now need to explicitly specify DOM as the parser used. However, the new sequence functions pretty well handle the job pyobj._XML used to do (in a different way). Some newer versions of PyXML report CDATA as #cdata-section nodes rather than as #text. We deal with it either way now. It may be obtained at: http://gnosis.python-hosting.com/Gnosis_Utils-1.1.0.tar.gz (this URL is different from usual since my main site was slashdotted, and I'm worried about my monthly bandwidth limit; I'll copy the file to its regular home next month). Try it out, have fun, send feedback! David Mertz (mertz at gnosis.cx) Frank McIngvale (frankm at hiwaay.net) ------------------------------------------------------------------------ BACKGROUND: Gnosis Utilities contains a number of Python libraries, most (but not all) related to working with XML. These include: gnosis.indexer (Full-text indexing/searching) gnosis.xml.pickle (XML pickling of Python objects) gnosis.xml.objectify (Any XML to "native" Python objects) gnosis.xml.validity (Enforce validity constraints) gnosis.xml.indexer (XPATH indexing of XML documents) [...].convert.txt2html (Convert ASCII source files to HTML) gnosis.util.dtd2sql (DTD -> SQL 'CREATE TABLE' statements) gnosis.util.sql2dtd (SQL query -> DTD for query results) gnosis.util.xml2sql (XML -> SQL 'INSERT INTO' statements) gnosis.util.combinators (Combinatorial higher-order functions) gnosis.util.introspect (Introspect Python objects) gnosis.magic (Multimethods, metaclasses, etc) ...and so much more! :-) From steve at ferg.org Fri Jul 4 11:37:41 2003 From: steve at ferg.org (Stephen Ferg) Date: 4 Jul 2003 08:37:41 -0700 Subject: Python is a gem, you need to keep pushing it .... References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: Absolutely! Gotta keep pushing! If you get into a situation where a presentation -- to management, or to other programmers -- would be useful, I've created what I hope will be a helpful resource -- the Python Slideshow Presentations page: http://www.ferg.org/python_presentations/index.html -- Steve Ferg From GavinT at ResMed.com.au Thu Jul 17 20:08:17 2003 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Fri, 18 Jul 2003 10:08:17 +1000 Subject: ps in windows Message-ID: He, He, Gerhard has evolved he used to say ----snip---- Btw. I knew it was possible, but still was using a search engine to quickly find the link. The http://google.com keywords I used were "python windows process list". -- Gerhard ----snip---- windows vs win32 subtle ;-) (Yes I have to much time on my hands this morning). Alternatively Jeff, you can go have a look at the great Australian, Mark Hammond's (if only he was a Queenslander) Windows Programming with Python or on his starship pages (follow the links from the Python.org homepage. Regards Gavin -----Original Message----- From: Gerhard H?ring [mailto:gh at ghaering.de] Sent: Friday, 18 July 2003 9:58 AM To: python-list at python.org Subject: Re: ps in windows Jeff Sandys wrote: > Not really a Python question except I will use Python to write the > script. > > I have several Windows98SE PCs and a Linux PC on a home network. > I want the Linux PC running a cron job to query the Windows PCs to find > out what programs they are running. > Any pointers on how to do this? If I had this problem what I'd do is go to http://groups.google.com/ and search for the keywords "python win32 list processes" ;-) -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From bokr at oz.net Sun Jul 13 13:00:11 2003 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2003 17:00:11 GMT Subject: Python - if/else statements References: Message-ID: On Sun, 13 Jul 2003 16:40:39 +1200, dmbkiwi wrote: >On Sun, 13 Jul 2003 03:59:53 +0000, Bengt Richter wrote: > [...] >> BTW, since you uploaded it, is there an URL for it? > >http://www.kdelook.org/content/show.php?content=6384 > I get a tar file, but winzip thinks it's broken. Usually it handles them fine. 03-07-13 09:34 507,442 6384-weather_liquid_py-0_7_2_tar.tar [ 9:51] C:\pywk\clp\dmbkiwi>lsm *tar 3912fe9836d69ec9004da899e08e352e 6384-weather_liquid_py-0_7_2_tar.tar That's the MD5 digest, same as from (in case you want to check against a known good you have): [ 9:52] C:\pywk\clp\dmbkiwi>python D:\Python22\Tools\Scripts\md5sum.py 6384-weather_liquid_py-0_7_2_tar.tar 3912fe9836d69ec9004da899e08e352e 6384-weather_liquid_py-0_7_2_tar.tar Regards, Bengt Richter From martin_a_clausen at hotmail.com Wed Jul 23 06:52:21 2003 From: martin_a_clausen at hotmail.com (Mars) Date: 23 Jul 2003 03:52:21 -0700 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <764b8294.0307230252.4014eb82@posting.google.com> Thanks guys - as I thought - basic stuff I had gotten wrong. Regards, Martin From me at privacy.net Wed Jul 30 11:55:51 2003 From: me at privacy.net (Heather Coppersmith) Date: 30 Jul 2003 11:55:51 -0400 Subject: changing the List's behaviour? References: Message-ID: On Wed, 30 Jul 2003 17:36:12 +0200, Peter Otten <__peter__ at web.de> wrote: > Heather Coppersmith wrote: >>> class DefaultList(list): >>> def __init__(self, sequence=[], default=None): > list.init(self, sequence) >> >> That's asking for trouble. That mutable default argument for >> sequence is evaluated at class definition-time, and all instances >> of DefaultList created without a sequence argument will end up >> sharing one list. >> >> Do this instead: >> >> class DefaultList( list ): >> def __init__( self, sequence = None, default = None ): >> if sequence is None: >> sequence = [ ] >> >>> list.__init__(self, sequence) > I can see the trouble only if the sequence argument is used to initialize a > member, e.g. > def __init__(self, seq=[]): > self.seq = seq # bad, multiple instances may share one list > However, in the DefaultList case, sequence is never changed. > So I don't see what can go wrong. Am I overlooking something? > - Peter Oops, my mistake. ;-) Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From fredrik at pythonware.com Thu Jul 10 13:18:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jul 2003 19:18:43 +0200 Subject: Deleting specific characters from a string References: <1057847111.3f0d77471178b@mcherm.com> Message-ID: Michael Chermside wrote: > RE's are NOT renown for their speed when doing simple character > replacement, deletion or insertion on strings. But _I_ haven't timed > it either, so I'm going to shut up now. I rewrote the re.sub implementation for 2.2, making it about 10 times faster for cases like this (compared to the 2.1 version). if you precompile the regexp, p.sub(text, "") is nearly as fast as the translate method under 2.3. ymmv. From gh at ghaering.de Sun Jul 20 15:38:58 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 20 Jul 2003 21:38:58 +0200 Subject: "Pure Python" MySQL module like Net::MySQL In-Reply-To: References: Message-ID: <3F1AEFD2.6090707@ghaering.de> Ravi wrote: > Gerhard H?ring wrote: > > > >> Is there any particular reason why you'd need such a beast instead of >> just using MySQLdb? >> > I'm developing for cell phones/PDA's using Jython, because Java is > available. Yet, a proper C compiler is not, so libmysql cannot be > compiled. I will see if I can put a wrapper on the Java MySQL connector > to make it accessible in Jython. No need for that, just download zxJDBC :) -- Gerhard From hans at deragon.biz Sat Jul 5 11:24:26 2003 From: hans at deragon.biz (Hans Deragon) Date: 5 Jul 2003 08:24:26 -0700 Subject: Red Hat 9, Python and Glade - a mixure not working? Message-ID: Greetings. Total newbie to Glade here. I created an interface using glade-2 and I want to use it with my python program. Following is what I wrote (test prg): ------------------------- #!/usr/bin/python import gtk import gtk.glade import sys def on_button4_clicked(source=None, event=None): sys.exit(); gtk.glade.XML('project3.glade') xml.autoconnect({ 'on_button4_clicked': on_button4_clicked }) gtk.main() ------------------------- Now when I am running it, I get the following error: ------------------------- (run2.py:11714): GLib-GObject-CRITICAL **: file gobject.c: line 1002 (g_object_get): assertion `G_IS_OBJECT (object)' failed (run2.py:11714): GLib-GObject-CRITICAL **: file gobject.c: line 1002 (g_object_get): assertion `G_IS_OBJECT (object)' failed Erreur de segmentation ------------------------- I am running redhat 9 with the lastest updates and glade-2. Anybody has a clue how to get it running? Is there a python program that comes in one of RH 9 packages that makes use of glade? I could use it as an example. Regards, Hans Deragon From megalith at btinternet.com Thu Jul 24 15:46:24 2003 From: megalith at btinternet.com (Gordon Chapman) Date: 24 Jul 2003 12:46:24 -0700 Subject: Regex: Limiting Scope without capturing results Message-ID: <173ef463.0307240355.cf896bb@posting.google.com> Right, this has had me scratching my head for a while. I want to limit the scope of an OR without using ()s as I don't want to capture that specific result, I'm trying to split a multistatement line up into a series of single statement lines, the multi statement line is of the format; Surface "/work/master/shaders/surface/surface_s07b" "color VAR_EYE_COL1_TINT" [ 0.239215686275 0.2 0.2 ] "color VAR_EYE_COL2_TINT" [ 0.4 0.301960784314 0.25 ] "color VAR_EYE_COL3_TINT" [ 0.749019607843 0.749019607843 0.701960784314 ] "color VAR_TEX_TINT" [ 0.0 0.0 0.0 ] "color diff_shadow_colour" [ 0 0 0 ] "color diff_tint" [ 1 1 1 ] "color env_sea_colour" [ 0.03 0.08 0.02 ] "color rim_shadow_colour" [ 0 0 0 ] "color rim_tint" [ 1 1 1 ] "color spec_shadow_colour" [ 0 0 0 ] "color specmap_filter" [ 1 1 1 ] "color specmap_shadow_colour" [ 0 0 0 ] "color surface_colour" [ 1 1 1 ] .... Now I have a pattern that kinda works fine when I use p.split with capture parentheses, the first match is the complete string, but then it gives me substring matches like "color", then the param name, then the value, when all I want is the first string; p = re.compile('\s+(\"(string|float|color)\s(\S+)\"\s\[\s*([0-9. ]+|\"\S*\")\s+\])') Obviously I can just ignore the extraneous information, but I'd rather come up with a neater way to do it (taking the easy way out also rather defeats the purpose of this as an academic exercise :) If I remove the ()s around the string|float|color match it stops matching anything, so is there an alternative to these ? Or a way of telling them to limit the scope of the match without capturing the result ? Thanks. G. From martin at v.loewis.de Sun Jul 13 05:09:54 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 13 Jul 2003 11:09:54 +0200 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: "John Roth" writes: > The OP's question revolved around ***which*** code page was > being used internally. Windows uses Unicode. That's not the same > question as what code set Python uses to attempt to translate Unicode > into a single byte character set. Yes and no. What Windows uses is largely irrelevant, as Python does not use Windows here. Instead, it uses the Microsoft C library, in which environment variables are *not* stored in some Unicode encoding, when accessed through the _environ pointer. > As to more difficult, as I said above, I haven't perused the source, > so I can't comment on that. If I had to do it myself, I'd probably > start out by always using the Unicode variant of the Windows API > call, and then check the type of the arguement to environ() to determine > which to pass back. I'm not sure whether or not I'd throw an exception > if the actual value couldn't be translated to the current SBCS code. Notice that os.environ is not a function, but a dictionary. So there is no system call involved when retrieving an environment variable. Instead, they are all precomputed. > On reading this over, it does sound a bit more strident than my > responses usually do, but I will admit to being irritated at the > assumption that you need to read the source to find out the > answer to various questions. If the question is "how does software Foo do something", the *only* reliable way is to read the source. You may have a mental model that may allow you to give an educated guess how Foo *might* do something. In this case, your educated guess was wrong, that's why I referred you to the source. Regards, Martin From jjl at pobox.com Mon Jul 14 20:51:54 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Jul 2003 01:51:54 +0100 Subject: The ASPN compiler References: <4868482a.0307141418.a45699e@posting.google.com> Message-ID: <87smp8d32t.fsf@pobox.com> clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) writes: [...] > Well, folks, I actually went off and read the paper. In spite of the > declaration of success at the end of the paper, the project appears to > have been just an academic proof of principle exercise. The compiler > is too slow to be of practical use and not much of the much of the [...] Since all they wanted to demonstrate was that "the .NET runtime and Intermediate Language were capable of supporting the language", I think somebody should have told Microsoft about this guy called Turing. With great foresight , he proved that the .NET runtime *is* capable of supporting Python, which should have saved Mark & Greg all that hard work. <0.5 wink> John From bignose-hates-spam at and-benfinney-does-too.id.au Tue Jul 29 22:26:07 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 30 Jul 2003 12:16:07 +0950 Subject: Convert a number to it name... References: Message-ID: On 29 Jul 2003 19:31:47 -0700, Mauro Baraldi wrote: > Someone can help how to convert a number to [words]. Found on my first Google search: -- \ "Yesterday I told a chicken to cross the road. It said, 'What | `\ for?'" -- Steven Wright | _o__) | Ben Finney From rnd at onego.ru Wed Jul 9 15:53:14 2003 From: rnd at onego.ru (Roman Suzi) Date: Wed, 9 Jul 2003 23:53:14 +0400 (MSD) Subject: Guido.moves_to(California) ? Message-ID: Reading PythonDev I've just found this GvR: """ Last night at OSCON I announced that I am moving to California. I have accepted a new job at Elemental Security, a security software startup in San Mateo. You may have heard of one of the founders, Dan Farmer, who is the (co-)author of several well-known free security checking programs: Satan, Titan and The Coroner's Toolkit. ... """ I was not very surprised to hear that, but I wonder if it means new licenses coming: >>> license() Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.2 2.1.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2.1 2.2 2002 PSF yes 2.2.2 2.2.1 2002 PSF yes 2.3 2.2.2 2002-2003 PSF yes Good luck to Guido! Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From bokr at oz.net Tue Jul 29 01:48:49 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 05:48:49 GMT Subject: pretty printing graphs References: <2259b0e2.0307281530.218400ae@posting.google.com> Message-ID: On 28 Jul 2003 16:30:03 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >"Scherer, Bill" wrote in message news:... > >Hey "dot" is great! I didn't know about it before readin your post. > >In a very short time I came out with the following recipe to draw >Python inheritance hierarchies (which I post since it is pretty >short and useful ;): > Well, here's the version with connectors: ====< pptree.py >=============================================== # pptree.py v 0.01 -- 20030728 22:20:17 bokr class TextBox: def __init__(self, text): self.text = text lines = text.splitlines() self.bb = len(lines)+2, max(map(len, lines))+2 # rows,cols bounding box def __str__(self): return self.text class Node: PageHeight = 6*11; PageWidth = 78 def __repr__(self): return ''%self.textBox.text.splitlines()[0] def treebb(self): # tree bb incl this node childMaxHeight, childTotWidth = 0, 0 for child in self.children: h, w = child.treebb() childMaxHeight = max(childMaxHeight, h) childTotWidth += w ret = childMaxHeight+self.textBox.bb[0], max(childTotWidth, self.textBox.bb[1]) return ret def __init__(self, textBox): self.textBox = textBox self.children = [] def boxlines(node, boxHeight, boxWidth): oh, ow = node.textBox.bb # this node top text box bb th, tw = node.treebb() # minimal child tree bb incl text box at top render = ['']*boxHeight ofmt = '|%%%ds|'% (ow-2) render[0] = ('+'+'-'*(ow-2)+'+').center(boxWidth) iLine=1 for line in node.textBox.text.splitlines(): render[iLine] = (ofmt%line).center(boxWidth) iLine += 1 render[iLine] = render[0] iLine += 1 if node.children: availSepSpaces = boxWidth - tw nch = len(node.children) sep = nch>1 and availSepSpaces//nch or 0 childBoxes = [] for child in node.children: chh, chw = child.treebb() childBoxes.append(child.boxlines(boxHeight-oh-1, sep and chw+sep or boxWidth)) cbhs = map(len, childBoxes); assert max(cbhs)==min(cbhs) # all child boxes same ht # do connector line (with wasteful repetition) conn = ''.join(['+'.center(sep and child.treebb()[1]+sep or boxWidth) for child in node.children]) conn = conn.center(boxWidth) first = conn.find('+'); last = conn.rfind('+') conn = conn[:first] + conn[first:last].replace(' ','-') + conn[last:] center = '+'.center(boxWidth).find('+') # whatever the alg is conn = list(conn); conn[center]='|'; conn = ''.join(conn) render[iLine] = conn for iChildline in xrange(cbhs[0]): iLine += 1 render[iLine] = ''.join( [childBox[iChildline] for childBox in childBoxes] ).center(boxWidth) for iLine in range(boxHeight): if not render[iLine]: render[iLine] = ' '*boxWidth return render def __str__(self): return '\n'.join(self.boxlines(self.PageHeight, self.PageWidth)) def showInPage(self, pageHeight=6*11, pageWidth=78): return '\n'.join(self.boxlines(pageHeight, pageWidth)) def test(height,width): # dimensions of chart # Example hierarchy O = object class F(O): pass class E(O): pass class D(O): pass class G(O): pass class C(F,D,G): pass class B(E,D): pass class A(B,C): pass def explore(cls, tree): node = Node(TextBox(cls.__name__)) tree.children.append(node) for b in cls.__bases__: explore(b, node) root = Node(TextBox('root')) explore(A, root) print print root.children[0].showInPage(height, width) if __name__ == '__main__': import sys; args = sys.argv[1:] height = args and int(args.pop(0)) or 20 width = args and int(args.pop(0)) or 60 test(height,width) ================================================================ Results: first 50 wide, then 90 [22:54] C:\pywk\clp>pptree.py 20 50 +-+ |A| +-+ +-------------|----------+ +-+ +-+ |B| |C| +-+ +-+ +----|----+ +--------|--------+ +-+ +-+ +-+ +-+ +-+ |E| |D| |F| |D| |G| +-+ +-+ +-+ +-+ +-+ | | | | | +------+ +------+ +------+ +------+ +------+ |object| |object| |object| |object| |object| +------+ +------+ +------+ +------+ +------+ [22:54] C:\pywk\clp>pptree.py 20 90 +-+ |A| +-+ +-----------------------|--------------------+ +-+ +-+ |B| |C| +-+ +-+ +---------|---------+ +---------------|---------------+ +-+ +-+ +-+ +-+ +-+ |E| |D| |F| |D| |G| +-+ +-+ +-+ +-+ +-+ | | | | | +------+ +------+ +------+ +------+ +------+ |object| |object| |object| |object| |object| +------+ +------+ +------+ +------+ +------+ The code is pretty hacky, but I wanted to show the art ;-) BTW, TextBox can accept a multiline string, and finds the bounding box (without trimming blanks). Regards, Bengt Richter From imbosol at aerojockey.com Thu Jul 24 19:00:45 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 24 Jul 2003 23:00:45 GMT Subject: very Very VERY dumb Question About The new Set( ) 's References: <20030723144732.13232.00000523@mb-m10.aol.com> <3f205d3c.745868662@news.blueyonder.co.uk> Message-ID: Alan Gauld wrote: > On 23 Jul 2003 18:47:32 GMT, rastm2 at aol.commorespam (Raymond > Arthur St. Marie II of III ) wrote: > >> Doc\ref 2.6 Delimiters show's three unused characters "@ $ ?". >> @ sort of looks like and sort of sounds like a set an >> $ well sort of obvious. >> I can imagine that the $ would be confused for money and @ is ugly. > > Since I detest any thought of prefix symbols to indicate type(as > per Perl etc) but have no visibility of these debates, I'll throw > in my suggestion and done a flameproof suit! > > Since both dictionaries and Sets require unique members/keys, > why not use the dictionary braces but without the key/value > syntax. So: > > mySet = {1,2,3,4} > > Which is illegal for a dictionary but would be OK for a Set. > It also just happens to be the same delimiters used in math > for sets... > > Just a thought before I go to bed! :-) +1 if Python's parser could handle it (which seems dubious). -- CARL BANKS From donhiatt at acm.org Tue Jul 15 17:42:20 2003 From: donhiatt at acm.org (Don Hiatt) Date: 15 Jul 2003 14:42:20 -0700 Subject: Mac OS X, Fink, Python, and web browser References: Message-ID: <2b012c5e.0307151342.e5db114@posting.google.com> Joe Heafner wrote in message news:... > Hi. > I'm running Mac OS X (10.2.6), Fink 0.5.3, Python2.2 and all requisite > Could someone please tell me where and how to get IDLE_fork to use Safari > (1.0)? You can change your default web browser to Safari using the preferences pane (under internet, I believe). If IDLE_fork uses the default browser property then Safari should launch. Cheers, don From phil at riverbankcomputing.co.uk Wed Jul 30 04:43:03 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 30 Jul 2003 09:43:03 +0100 Subject: PyQt Help and Advice In-Reply-To: References: Message-ID: <200307300943.03118.phil@riverbankcomputing.co.uk> On Wednesday 30 July 2003 1:27 am, Keith Jones wrote: > On Wed, 30 Jul 2003 00:18:32 +0100, Phil Thompson wrote: > > To correct one misconception... > > > > PyQt was first released on November 1st 1998. There have been 34 releases > > in all. The next release, including support for Qt v3.2.0, will be around > > August 12th. It isn't new. > > > > Phil > > Phil, > > Any idea when Qt3.2 will have noncommercial support in windows? That's a question for Trolltech. I would certainly expect Qt v4 to be released first. Phil From nagylzs at freemail.hu Fri Jul 11 13:39:37 2003 From: nagylzs at freemail.hu (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Fri, 11 Jul 2003 19:39:37 +0200 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <7xk7ap3j6z.fsf@ruckus.brouhaha.com> <3F0EE2E1.1C30CEA4@hotmail.com> Message-ID: <3F0EF659.2020100@freemail.hu> > > > > >>My suggestion is to >>authenticate the cookies with a cryptographic checksum and verify the >>authentication before deserializing the cookies. That's probably the >>simplest approach. Keeping session info on a multi-process server (or >>worse, a multi-server network) needs some kind of concurrent storage >>mechanism. >> >> > >Paul, > >Do you mean transmit the checksum to the client with the cookie? And >check that they match when the cookie and checksum come back? > >Or is the checksum stored on the server, in some form of lookup >dictionary keyed by some user session identifier? > I think he wanted to write a digital signature instead. Right? Laci 1.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From andy at wild-flower.co.uk Fri Jul 18 08:46:17 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 18 Jul 2003 13:46:17 +0100 Subject: scanf string in python In-Reply-To: References: Message-ID: <200307181346.17148.andy@wild-flower.co.uk> On Friday 18 Jul 2003 8:39 am, J?rgen Cederberg wrote: > lehrig wrote: > > lehrig wrote: > >>I have a string which is returned by a C extension. > >> > >>mystring = '(1,2,3)' > >> > >>HOW can I read the numbers in python ? > > > > Now I have done it like this: > > tmp = mystring[1:-1] > > tmplist = string.split(tmp,',') > > x = int(tmplist[0]) > > y = int(tmplist[1]) > > z = int(tmplist[2]) > > > > But there should be a more convenient solution. > > Hi, > > some have suggested map, exec and re's. I came up with this list > comprehenion > > >>> mystring = '(1,2,3)' > >>> mynumbers = [int(i) for i in mystring[1:-1].split(',')] > >>> mynumbers > > [1, 2, 3] > > regards > Jorgen Cederberg what about: x,y,z=eval(mystring) ??? see: >>> x,y,z=eval(mystring) >>> x,y,z (1, 2, 3) >>> x 1 >>> y 2 >>> z NOTE: this could introduce exploitable behaviour if you can't guarantee that the string is *only* going to contain a tuple of nembers... think about what could happen if the c code returned 'ReallyNastyFunc()' instead of "(1,2,3)"... :-(. As long as you can guarantee the value won't be 'dangerous' you'll be ok. hth -ndyj From drs at ecp.cc Wed Jul 9 03:40:27 2003 From: drs at ecp.cc (drs) Date: Wed, 09 Jul 2003 07:40:27 GMT Subject: Deleting specific characters from a string References: Message-ID: "Behrang Dadsetan" wrote in message news:begfb3$7j6$1 at online.de... > Hi all, > > I would like deleting specific characters from a string. > As an example, I would like to delete all of the '@' '&' in the string > 'You are ben at orange?enter&your&code' so that it becomes > 'benorange?enteryourcode'. > > So far I have been doing it like: > str = 'You are ben at orange?enter&your&code' > str = ''.join([ c for c in str if c not in ('@', '&')]) > > but that looks so ugly.. I am hoping to see nicer examples to acheive > the above.. you can use the replace method of the string object >>> 'You are ben at orange?enter&your&code'.replace('@', '').replace('&', '') 'You are benorange?enteryourcode' -d From jorgencederberg at hotmail.com Fri Jul 18 03:39:54 2003 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Fri, 18 Jul 2003 09:39:54 +0200 Subject: scanf string in python In-Reply-To: References: Message-ID: lehrig wrote: > lehrig wrote: > > >>I have a string which is returned by a C extension. >> >>mystring = '(1,2,3)' >> >>HOW can I read the numbers in python ? > > > Now I have done it like this: > tmp = mystring[1:-1] > tmplist = string.split(tmp,',') > x = int(tmplist[0]) > y = int(tmplist[1]) > z = int(tmplist[2]) > > But there should be a more convenient solution. Hi, some have suggested map, exec and re's. I came up with this list comprehenion >>> mystring = '(1,2,3)' >>> mynumbers = [int(i) for i in mystring[1:-1].split(',')] >>> mynumbers [1, 2, 3] regards Jorgen Cederberg From max at alcyone.com Mon Jul 14 21:04:40 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 18:04:40 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> Message-ID: <3F135328.89C1F89C@alcyone.com> Roy Smith wrote: > The wierd thing is that I don't think either one really matches what a > mathematician means when he writes "=". In math, "=" is neither an > assignment or a test: it's an assertion. Right. In fact, when a mathematician really does mean rebinding, they use an operator decidely unlike =, often :=, <-, <=, or some other similar ASCIIzation. The equals sign in mathematics does not mean the same thing it does in modern programming languages. It's just something that one has to deal with early on or be forever annoyed. It's arguable that the Pascal family has the most mathematics-like operations for equality and assignment here, but really it's just a semantic issue of knowing which operator means what. One can even get used to things like % means string formatting if one really tries :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Does the true light / Of love come in flashes \__/ Sandra St. Victor From grobinson at transpose.com Wed Jul 2 15:41:48 2003 From: grobinson at transpose.com (Gary Robinson) Date: Wed, 02 Jul 2003 15:41:48 -0400 Subject: Signal-handling question Message-ID: In some code we're writing we're making an assumption, and I'd like to confirm that the assumption is valid. Suppose a signal arrives while a file is being written, and the signal handler explicitly raises a SystemExit exception. My understanding is that the C-level I/O code will continue and the signal won't be processed until the end of the atomic python interpreter instruction that invoked that C code. Then, the signal handler is executed, including the SystemExit. Are we guaranteed that there are no circumstances under which any more file I/O will be carried out by the interrupted code after the signal handler is invoked? That is, are we guaranteed that the SystemExit raised by the signal handler will immediately terminate the interrupted call to write()? The answer seems to be "obviously YES" but I need to be sure so I thought it was worth asking. Thanks-- --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From intentionally at blank.co.uk Wed Jul 16 15:41:54 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 20:41:54 +0100 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: <747bhv8r2h398bv121seft4spukd6bcsug@4ax.com> On 16 Jul 2003 05:18:48 GMT, bokr at oz.net (Bengt Richter) wrote: >>Copies are only made when they are needed. The lazy copy optimisation, >>in other words, still exists. >(BTW, don't get hung up on this part, ok? Skip forward to the ==[ code part ]== >below if you're going to skip ;-) > >Ok, so the copy happens at b[2]=4 right? This is still useless copying >if the holder of the "a" reference *wants* to have it as a continuing >reference to the same single shared list. And you can program that in C++ >if you want to, and you presumably would. Except now you have to create pointer variable. If you want to share a single object, you need an explicit way to do it. Let me use an analogy from a discussion held elsewhere but on a related subject. In Algol and Fortran were among the earliest high level languages. There were, I believe, called 'third generation' (assembler as opposed to machine code being the second generation). Hence the name of 'forth' (which was supposed to be ever higher level, though IMO it is a lower level language) and also the term '4GL' that was heavily used for languages like SQL at one time. Anyway, Algol and Fortran apparently (I didn't know this until today) *always* used call-by-reference. So why is it that all C parameters are call-by-value (though the value may be a pointer) and Pascal parameters are call-by-value by default? This is new to me - my first experiences of C and Pascal was at an age when the whos-language-is-better rows were about Pascal providing call-by-reference. To me, the distinction is that C is lower level - closer to what you'd do in assembler or machine code - whereas Pascal is higher level. You can pass pointers in Pascal to achieve the same goal as a 'var' parameter, but 'var' better expresses why you are doing it. I had assumed, therefore, that there had been a natural progression from low-level assembler - that earlier high level languages would either be like C or like Pascal, depending on just how high level they are. But that's not true. Algol and Fortran both used call-by-reference, and that somewhat established tradition was rejected when C and Pascal were being developed. Why the rejection? On a point of principle. When parameters are call-by-reference by default, it allows accidental side-effects. Sometimes, functions change parameters that callers aren't expecting them to change. When changing one identifier can affect another by default, errors can happen. There are tools for doing this explicitly. They are called pointers or references. > >Ok now how would you handle the case of multiple copies of that pointer variable? >Make it "smart" so that you get copy-on-write of what it points to? That's the discussion >we're having about the first level of Python references, ISTM. Easy enough. Reference counting for the object keeps track of how many variables are currently using it as their value. Assign to as many variables as you like - all you get is all those variables referencing one object with a higher reference count. Before modifying the object, you check the reference count. If greater than one, you need to make a copy. Pointer/reference objects have to point to the 'variable' rather than the object. Access the object through that, and they are then guarenteed to access the correct object that they were associated with. Pointers and references don't increment the reference count as they are not supposed to get copies. ASCII art warning... +---+ +-------+ +---------------+ | x |--->| x var |----->| object : RC=2 | +---+ +-------+ +---------------+ ^ +---+ +-------+ | | y |--->| y var |----+ +---+ +-------+ ^ | +---+ +-------+ +-------------------+ | z |-->| z var |-->| ptr object : RC=1 | +---+ +-------+ +-------------------+ Garbage collection continues to work as it already does, having nothing to do with the new reference count in the object. The intermediate 'variable' thing means that even if the original variable goes out of scope, the pointer can still refer to it - and a new variable created with the same name doesn't have to re-use the old variable thingy. This involves an extra layer of indirection compared with Python at the moment. It would involve a (small) performance hit as a result. But there is no copying of the object unless the copy is needed. >>C++ uses exactly this kind of approach for the std::string class among >>others. Copy-on-write is a pretty common transparent implementation >>detail in 'heavy' classes, including those written by your everyday >>programmers. Does that mean C++ is slower that Python? Of course not! >> >It could be, if the unwanted copying was big enough. No, it can't. It *never* creates an unnecessary copy. That is the whole point of lazy copying. >I'm a bit disappointed in not getting a comment on class NSHorne ;-) I *know* that you can use a class to get pointer behaviour. The issue of pointers becomes important if you don't get that behaviour because of copy-on-write. >Does this give names in ns the "variable" semantics you wanted? Is there any difference >other than "semantic sugar?" Explaining the difference, if any, will also clarify what >you are after, to me, and maybe others ;-) The issue is what happens by default. From fredrik at pythonware.com Fri Jul 4 05:03:37 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Jul 2003 11:03:37 +0200 Subject: Tkinter Image Button Bug References: Message-ID: Russell E. Owen wrote: > I think you are running into a common Tkinter pitfall (it is an > intentional design decision, but I do not recall the argument for it): quick version: the Tkinter interface layer doesn't know the Tk-level type for all option, you can use images in lots of places, the layer cannot tell the difference between an image and a string (image objects don't have to inherit from Tkinter.Image), the semantics of the Tk image delete operation is rather weird (Tk uses reference counting, so it knows that the image is still in use, so if someone tries to delete an image that is still being used, the image won't go away -- but the contents are cleared; it's like "del mylist" would always do "mylist[:] = []" before decrementing the reference count, just for fun), this whole mess was hidden by a bug in an earlier version of Python, and changing this behaviour would break too much stuff. it's like mutable default arguments; you'll only make this mistake once. > I am almost certain it suffices to assign b._iconref = icon (_iconref > being an attribute that the Label b is not likely to already have). absolutely. From mcherm at mcherm.com Thu Jul 17 14:14:05 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 17 Jul 2003 11:14:05 -0700 Subject: Co-routines Message-ID: <1058465645.3f16e76dc10ae@mcherm.com> Chris Wright wants a way to execute python code one-line-at-a-time so he can run multiple functions "in lockstep". I don't have an answer, but I have the START of an approach. Michael Sparks is ahead of me here (see his excellent answer http://mail.python.org/pipermail/python-list/2003-July/173694.html), but for a different approach try this: G:\>python ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): ... print '1-1' ... print '1-2' ... print '1-3' ... >>> import dis >>> dis.dis(f.func_code) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 ('1-1') 9 PRINT_ITEM 10 PRINT_NEWLINE 11 SET_LINENO 3 14 LOAD_CONST 2 ('1-2') 17 PRINT_ITEM 18 PRINT_NEWLINE 19 SET_LINENO 4 22 LOAD_CONST 3 ('1-3') 25 PRINT_ITEM 26 PRINT_NEWLINE 27 LOAD_CONST 0 (None) 30 RETURN_VALUE Here we can SEE the code, and it's nicely broken into lines by the SET_LINENO bytecode. What I'd LIKE to do now is to somehow go from f.func_code (a code object) to a Python list of bytecodes. Then we could easily split the list on SET_LINENO codes, intersperse with calls to other functions, and sew it all up into a larger list. Then we would just need to exec those bytecodes, and BINGO... problem solved. But I don't know how to convert a code object into a list of bytecodes, nor how to convert it back to a code object so I can pass it to exec. Any better gurus able to enlighten me? -- Michael Chermside From hokiegal99 at hotmail.com Sat Jul 5 18:10:02 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 05 Jul 2003 18:10:02 -0400 Subject: Calculating Year, Month and Day of Life In-Reply-To: References: Message-ID: <3F074CBA.80505@hotmail.com> Ian Bicking wrote: > On Sat, 2003-07-05 at 12:48, hokiegal99 wrote: > >>Hello, >> >>I am a funeral director trying to write a small program that calculates >>the number of years, months and days a person has lived by entering the >>year, month and day of their birth. This is what I have so far: > > > You might want to look at mxDateTime, or Python 2.3's datetime module, > which will probably provide functions to make this calculation > significantly easier -- counting days in years, adjusting for leap > years, etc. Well, that's if you want to be exact, which may not really > be important. > > Ian This is a good point. I want to be within the correct year, month and day, but if I'm off by a few hours it won't matter. From my calculations, the average year is 365.25 days long (with a leap year every 4 years) so that makes the avergae month 30.4375 days long. Do you see any problem with doing it this way? From delphiro at zonnet.nl Fri Jul 4 04:51:43 2003 From: delphiro at zonnet.nl (delphiro) Date: Fri, 4 Jul 2003 10:51:43 +0200 Subject: Python is a gem, you need to keep pushing it .... In-Reply-To: <41A1CBC76FDECC42B67946519C6677A9A20BBA@pippin.int.etrials.com> References: <41A1CBC76FDECC42B67946519C6677A9A20BBA@pippin.int.etrials.com> Message-ID: <20030704105143.74e0a3d8.delphiro@zonnet.nl> > On the other hand, I don't take Dave's comment that he would rather be using Python and Emacs to the (really excellent) Delphi IDE too seriously either. OTOH maybe Dave actually feels this way but there are good reasons not to : I guess you mean my (delphiro) comment. As a daily Delphi user I do like the Delphi IDE but the Emacs editor is way better than the editor that comes with the Delphi IDE. > For Windows GUI apps Delphi has a great screen-builder and a collection of 3rd party component (many freeware) that puts Tk/Swing/wxWindows/QT/GTK/everything else available to Python to shame. Well, part of that is true.. you can drag and drop almost any possible component on a form and start working. This takes more time in Pyhton (in my case with wxPython) but I don't think Python should be 'ashamed' for its 3rd party tools. As for my private project I use scipy for calculations and graphical output (and even the option to save the output as pdf!). I have not seen any freeware component for Delphi with the same possibilities. As for the GUI part I start the design using Boa Constructor which also has a nice way to implement events and use the boa output in Emacs to get things useful. Easy does it, though I must admit that the GUI part will develop faster with the Delphi IDE (rough guess, about 2-3 times in development speed). Once the GUI development is done and the 'actual' work starts I find Python easier to use and faster in development time than Delphi. I mean.. try creating a dynamic list that contains a integer, function, another list, a string etc. just in one line. > Outside of that space (Linux, Mac) and for non-gui apps the benefit of Delphi is less-clear especially since Python comes with "batteries included" but Delphi still has a superb debugger, model driven development and a collection of great tools built into the IDE. I certainly agree about the debugger though I realy doubt if using Emacs with its build in debugger is so much slower once you get used to it. > Python *is* great but lets not pretend that its a good fit for every problem. I doubt that (unless you develop hardware drivers). Rob -- [-------------delphiro-------------] [-- http://pyciv.sourceforge.net --] [----------------------------------] From pyth at devel.trillke.net Sat Jul 26 03:50:45 2003 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 26 Jul 2003 09:50:45 +0200 Subject: path module In-Reply-To: <1059185020.28092.11625.camel@lothlorien>; from ianb@colorstudy.com on Fri, Jul 25, 2003 at 09:03:40PM -0500 References: <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> <20030725203322.P6906@prim.han.de> <1059160667.28096.10876.camel@lothlorien> <20030725215602.Q6906@prim.han.de> <1059185020.28092.11625.camel@lothlorien> Message-ID: <20030726095045.T6906@prim.han.de> Ian Bicking wrote: > On Fri, 2003-07-25 at 14:56, holger krekel wrote: > > > The multiple walk methods would only be a shortcut anyway. Again, they > > > might be difficult in a situation like a URL where directory and file > > > are intermingled (and maybe ReiserFS 4...?) -- which maybe is okay, a > > > urlpath object simply wouldn't implement that walker. > > > > Yep, URL pathes have no notion of directories and files. Thus a general > > URL path can't have a 'listdir' method and thus we can't recurse. > > You can easily special case it for Apache's "Indexes" view, though :-) > > WebDAV does, though, doesn't it? But you can still edit the directory > resource, so it gets overloaded. WebDAV's use of GET is messed up. I am not very familiar with the low-level details of WebDAV but i think determining if something is a directory is done by a PROPGET command. cheers, holger From abbeflabbe at InospamIhotmail.com Fri Jul 18 01:19:35 2003 From: abbeflabbe at InospamIhotmail.com (Linkages) Date: Fri, 18 Jul 2003 05:19:35 GMT Subject: gui Message-ID: a good GUI for linux ? bye linkages From sandskyfly at hotmail.com Fri Jul 4 10:20:11 2003 From: sandskyfly at hotmail.com (Sandy Norton) Date: 4 Jul 2003 07:20:11 -0700 Subject: Least used builtins? Message-ID: Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> len(dir(__builtins__)) 86 >>> Python 2.3b2+ (#43, Jul 4 2003, 04:54:22) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> len(dir(__builtins__)) 125 >>> Apparently these were added between py152 and py23: ['help', 'UnicodeTranslateError', 'StopIteration', 'SyntaxWarning', 'unicode', 'enumerate', 'unichr', 'basestring', 'DeprecationWarning', 'UnicodeError', 'copyright', 'sum', 'ReferenceError', 'OverflowWarning', 'dict', 'bool', 'True', 'FutureWarning', 'NotImplemented', 'file', 'zip', 'object', 'TabError', 'credits', 'UnicodeEncodeError', 'UnicodeDecodeError', 'super', 'IndentationError', 'False', 'RuntimeWarning', 'license', 'classmethod', 'UserWarning', 'PendingDeprecationWarning', 'iter', 'UnboundLocalError', 'Warning', 'staticmethod', 'property','WindowsError'] I know there some plans to reduce the number of builtins in some future version of python (Python 3.0?): So which builtins do you least use? Pesonally, I don't think I've ever used the following: intern, buffer, coerce cheers, Sandy From skip at pobox.com Wed Jul 9 14:02:53 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 9 Jul 2003 13:02:53 -0500 Subject: LOADING DATA INTO ARRAYS In-Reply-To: <200307100147.05841.skchim0@engr.uky.edu> References: <200307100147.05841.skchim0@engr.uky.edu> Message-ID: <16140.22733.468173.643296@montanaro.dyndns.org> satish> I am trying to collect the following data in X,Y,Z arrays as satish> following: satish> 1.00000000000000 0.00000000000000D+000 0.00000000000000D+000 satish> 0.932113519778473 0.362166241174114 0.00000000000000D+000 satish> 0.737671227507627 0.675160099611485 0.00000000000000D+000 ... satish> The error I am getting after the compilation is as follows: satish> xval,yval=string.split(line) satish> ValueError: unpack list of wrong size That's because the string.split() operation yields a list containing three values per line, not two, and you're trying to assign those three values to only two variables. If you don't want the third field you can discard it a couple ways: # only assign the first two items xval,yval=string.split(line)[0:2] or # assign the third item to a dummy variable xval,yval,dummy=string.split(line) Skip From jdhunter at ace.bsd.uchicago.edu Tue Jul 29 09:53:27 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 29 Jul 2003 08:53:27 -0500 Subject: pretty printing graphs In-Reply-To: (bokr@oz.net's message of "29 Jul 2003 02:07:14 GMT") References: Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> How about (I added a name in the first node line for Bengt> debugging, and boxing): (code follows output). Not tested Bengt> much ;-) Thanks Bengt - that looks great. You really should be on the payroll. I won't have time until tonight to wrap my head around your code, but I think I'll add a to_dot method to the Node class which generates dot output, so I can use your ascii output for day-to-day stuff, and then go to dot for publication quality. Thanks all for the suggestions, JDH From lol at lolmcNOSPAM.com Fri Jul 4 16:58:48 2003 From: lol at lolmcNOSPAM.com (Rogue 9) Date: Fri, 04 Jul 2003 21:58:48 +0100 Subject: Newbie problems with class imports Message-ID: <3f05ea73@shknews01> Hi All, I have a small problem in a program I'm developing and could do with some guidance as to how I resolve it. The hierachy of my program is as follows: 1)The toplevel package is called oop_lb 2)Beneath oop_lb are 3 packages - analysis,process and tests I am using the very excellent unittest module to help me to create a program that is as bug free as I can make it and the tests are as you cn guess in the tests package mentioned above. I have developed several modules which reside in the process package and succesfully created tests in the tests package which ensure the code does what I intended.When I moved on to the analysis package however,things went a bit wonky as the modules in this package called classes which resided in the process package and when using the import statements to make them available I found that either I could get the oop_lb module to run with one set of import statements but the tests I wrote would not recognise the modules from process in the import statements and produced the following type of error: Traceback (most recent call last): File "CalculateMedianTest.py", line 14, in ? import oop_lb.analysis.CalculateMedian File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 14, in ? from process import GetDraw ImportError: No module named process This occurs with the following import statement in the CalculateMedian.py module from process import GetDraw If I change this to import oop_lb.process.GetDraw then the test program will work but the oop_lb.py file fails with the following error Traceback (most recent call last): File "oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 13, in ? import oop_lb.process.GetDraw File "/home/lol/disk/python/lotto/oop_lb/oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file ImportError: cannot import name CalculateMedian So.....my problem is that I can't seem to find the proper way to import the modules to satisfy both the testing modules in the oop_lb.tests package and also allow oop_lb.py to run without import errors. I apologise for the length of the post and any ambiguities I may not have managed to clear up whilst proff reading this before posting. Thanks,Lol -- Remove NOSPAM from my email address to use it,please. From eichin at metacarta.com Tue Jul 22 15:59:52 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 22 Jul 2003 15:59:52 -0400 Subject: pythonic malloc References: <7g1xwjqujm.fsf@pikespeak.metacarta.com> Message-ID: <7g7k6a5o3r.fsf@pikespeak.metacarta.com> > Now I just have a question about portability. Will this break on a > big-endian box? That is, does: read struct.__doc__, it explains about endianness in detail (in particular, that's what the "<" at the beginning is all about.) From peter at engcorp.com Thu Jul 10 14:21:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 14:21:04 -0400 Subject: replace value of a specific position References: Message-ID: <3F0DAE90.6C656C7E@engcorp.com> Tom wrote: > > I want to replace a specific part of a string. I tried replace but this > doesn't work the way I want it, because it checks and replaces all > values and not the position (index). > > t = '010010101001001110100101010111' > t = t.replace(t[5], '2') > > This is just a bad example of what I tried. It produces this output: > > 212212121221221112122121212111 > > But I wanted: > > 010012101001001110100101010111 Try this instead: >>> t = '010010101001001110100101010111' >>> import array >>> x = array.array('c', t) >>> x array('c', '010010101001001110100101010111') >>> x[5] = '2' >>> x.tostring() '010012101001001110100101010111' -Peter From exarkun at twistedmatrix.com Tue Jul 8 00:18:58 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Tue, 8 Jul 2003 00:18:58 -0400 Subject: PyIrc module In-Reply-To: <200307072005.17077.shalehperry@comcast.net> References: <20030707225250.7171.qmail@cs06.tgv.net> <200307072005.17077.shalehperry@comcast.net> Message-ID: <20030708041846.GA3315@intarweb.us> On Mon, Jul 07, 2003 at 08:05:17PM -0700, Sean 'Shaleh' Perry wrote: > On Monday 07 July 2003 15:52, sylvain HELLEGOUARCH wrote: > > Hello everyone, > > > > This is my first message round here :) > > > > Well, my message is more or less an announcment of my pyirc module for > > Python (uh uh surprise this is the right place :)). > > > > This module tries to implement both RFC 1459 and 2812 about IRC protocol. > > I've decided to code my own module as Python has a lack of IRC ones. > > Generally speaking, either they are not up-to-date anylonger or they are > > written for a specific GUI. > > > > not to downplay your work, but have you looked at Twisted? > http://twistedmatrix.com/products/twisted > Forget Twisted: http://python-irclib.sourceforge.net/ http://sourceforge.net/projects/pyirclib/ http://sk.nvg.org/python/irc_uninett/ http://tarken.lyrical.net/programming/python/irclib_py.php http://linux.duke.edu/projects/kibot/contents/doc/kibot/kibot.irclib.html But hey, I guess everyone's entitled to write at least one IRC library... Jp PS - Not to downplay etc -- It is practically impossible to teach good programming style to students that have had prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration. -- Dijkstra From blunck at gst.com Tue Jul 29 11:09:34 2003 From: blunck at gst.com (Christopher Blunck) Date: 29 Jul 2003 08:09:34 -0700 Subject: How to properly package/distribute a pure python module? References: <5ab0af73.0307281045.6cb13cfe@posting.google.com> Message-ID: <1147e466.0307290709.34b2461@posting.google.com> MatthewS at HeyAnita.com (Matt Shomphe) wrote in message news:<5ab0af73.0307281045.6cb13cfe at posting.google.com>... > Are there any guidelines for packaging a pure python module? > Specifically, say I have a set of 10 functions, all of varying > behaviors (no unifying theme to bind them together into clear > subsets), that I would like to make available to others. What is the > best structure for the distributed module? A single file called > "functions.py" that people can put in "site-packages"[1]? A > subdirectory called "MyFunctions" with an "__init__.py" and the > "functions.py" files[2]? Or should the functions be broken out into > individual files[3]? > > I'm sure it depends on some other factorsbut are there general rules > for constructing a nice, logical package for others to use? > > [1] site-packages/functions.py (from functions import f1) > [2] site-packages/MyFunctions/functions.py, __init__.py (from > MyFunctions.functions import f1) > [3] site-packages/MyFunctions/__init__.py, f1.py, f2.py, f3.py (from > MyFunctions.f1 import f1) Do a google search for the distutils module. For examples, look at any python project (ZSI or SOAPpy for example), and take a look at the setup.py. The gist of it is that you define a setup.py module that defines which modules are to be included in the distro. A user, when they download your tarball, goes into your directory and (as root): "python setup.py install". Once you have your app in distutils compatible format, you can use distutils to generate .exe installs, rpm installs, tarball downloads, etc etc etc. So definitely take a look at distutils. :) -c From mauro.baraldi at bol.com.br Tue Jul 29 22:31:47 2003 From: mauro.baraldi at bol.com.br (Mauro Baraldi) Date: 29 Jul 2003 19:31:47 -0700 Subject: Convert a number to it name... Message-ID: Hello World ! Someone can help how to convert a number to it name. Well I'll explain... 11 -> leven. 48 -> forty eight. Something like it. Thanks []s Mauro From garberch at yandex.ru Sun Jul 13 13:32:04 2003 From: garberch at yandex.ru (Garber) Date: 13 Jul 2003 10:32:04 -0700 Subject: =?ISO-8859-1?B?8e/l+Ojg6yDk6/8g8O7x8ejp8ero9SDv6PLu7fno6u7iKSkp?= Message-ID: <37d6f77c.0307130932.1e3adf0d@posting.google.com> ?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? exe-???? ?????????). From jepler at unpythonic.net Sun Jul 20 08:48:23 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 20 Jul 2003 07:48:23 -0500 Subject: Tk mainloop() In-Reply-To: References: Message-ID: <20030720124819.GA20780@unpythonic.net> Use the 'after' method of widgets. This program increments the counter in the label about once a second. from Tkinter import * def update_and_requeue(): v.set(v.get() + 1) t.after(1000, update_and_requeue) t = Tk() v = IntVar(t) l = Label(t, textvariable=v); l.pack(side="top") b = Button(t, command=t.destroy, text="Close"); b.pack(side="top") t.after(1000, update_and_requeue) t.mainloop() From mcfletch at rogers.com Tue Jul 1 22:42:24 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 01 Jul 2003 22:42:24 -0400 Subject: whitespace and ?asc()? In-Reply-To: <3F02086D.9010300@ihug.co.nz> References: <3F02086D.9010300@ihug.co.nz> Message-ID: <3F024690.70901@rogers.com> Ray Tomes wrote: > Hi all > > I am totally new to python. On the whole I really like the design of > the language and after just one day may be considered a convert. Yay! > I was trying to find out the exact definition of whitespace so I went > to look at strings.whitespace to find out which chars were whitespace, > and found 9, 10, 11, 12, 13, 32 which according to my ancient ascii > chart are TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? FormFeed (FF) if my memory serves. Doing: print '\x0c' # hexidecimal 12 also prints an FF in PythonWin, so seems likely that's it. > Also, in trying to find the ASCII (or is it ANSI) values for > characters I could not find the reverse function for chr() [in BASIC > it is asc()]- can someone please tell me what reverses chr()? ord(character) in Python. Note that unichr() is also reversed by ord, very tricky function that ord :) . > I had to do this yucky thing to decode whitespace ... Ick, off to the dungeons with you! ;) HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From kevino at tulane.edu Tue Jul 22 16:27:49 2003 From: kevino at tulane.edu (Kevin Ollivier) Date: Tue, 22 Jul 2003 13:27:49 -0700 Subject: Zlib problem on Windows XP?? Message-ID: Hi all, When using the latest Python 2.2.x releases as well as the Python 2.3 betas and rc1 on Win XP, I cannot import zlib. When I try, I get an error about the dynamic module not having an 'initzlib' symbol. The strange thing is that this problem seems to be XP-specific - on Windows 2K I do not get this error. I've installed Python 2.2.3 on two XP machines with the same results. I installed the latest beta on one of the machines, but the results were the same. (Haven't tried RC1 yet.) Does anyone else see this problem? I thought it was something I had done at first, but I haven't built Python myself and the error occurs right after installation, so I'm stuck as to what could be happening. Thanks! Kevin From tzot at sil-tec.gr Sun Jul 27 17:41:39 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 28 Jul 2003 00:41:39 +0300 Subject: Checking whether bool is a type References: <3F2442B2.E660E97@jandecaluwe.com> Message-ID: <5jh8iv893mvl1mvst0u2i4qb05sm8egovj@4ax.com> On Sun, 27 Jul 2003 23:22:58 +0200, rumours say that Jan Decaluwe might have written: >In my application I need to know whether bool is >available as a type (in Python2.3) or not. I just >realized I can use the following: >>> type(bool) is type You might like to do this as an alternative: def bool_is_type(): try: return isinstance(bool, type) except NameError: return 0 to catch older python versions as well. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From skip at pobox.com Mon Jul 7 15:45:42 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jul 2003 14:45:42 -0500 Subject: single/double quote escape interpolation In-Reply-To: References: Message-ID: <16137.52710.881156.657585@montanaro.dyndns.org> Simon> I was just wondering why python doesn't make a distinction Simon> between single and double quotes - a bit like Perl does. In most instances it's helpful because you can avoid extra escapes, e.g.: "why don't we drop by the pub and quaff a few?" instead of 'why don\'t we drop by the pub and quaff a few?' There are also triple-quoted strings using """ and ''' as the string delimiters. They mostly just make it easy to create multi-line string literals, but they can also be used to avoid backslashes: '''Maury said, "Why don't we drop by the pub and quaff a few?"''' Simon> Obviously I realise there are no dollar signs so you can't Simon> intrpolate a varaible in a string. You can interpret variables, the mechanism is just slightly different: "why don't we drop by the $where and $dowhat a few?" for Perl, vs. "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict for Python. Somedict is a dictionary having keys "where" and "dowhat" (at minimum). The most common "somedict"s are probably "locals()" and "globals()" though you can easily construct your own or take them from different contexts, like SQL query results. Simon> This is fine, but having to remember to put an r in front of Simon> regex's is really annoying and it would be great if you could Simon> jsut use single quotes instead to interpolate slashes properly Simon> etc. (ie only escape them once). I find having to run to the Camel book every other day more annoying. ;-) I can never remember what all the qx, qw, etc stuff means. Skip From michael at foord.net Sat Jul 12 11:25:50 2003 From: michael at foord.net (Fuzzyman) Date: Sat, 12 Jul 2003 16:25:50 +0100 Subject: The ASPN compiler References: Message-ID: <2k30hv4t88n5iu7nj5g3e55gd275rumf7i@4ax.com> On Sat, 12 Jul 2003 02:21:33 +0200, Gerhard H?ring wrote: >Fuzzyman wrote: >> What's the score on this (the ASPN python compiler) > >There was a proof-of-concept implementation of a Python compiler for the >.NET platform done by ActiveState and sponsored by Microsoft. > >> - is it a true >> compiler for python ? > >Read the whitepaper, available on the ActiveState site. > Done that - its not entirely clear - any chance you could answer the question...... >> - what does it output - binary or C++ for .NET >> framework............ > >Read the whitepaper, available on the ActiveState site. > Done that - its not entirely clear - any chance you could answer the question...... >> if the latter then it could be very cool as it >> may work with the PocketPC 2003 SDK.... for producing binaries for >> PDAs from python... cool... > >Forget it. Instead what you probably want is a Python implementation for >Windows CE 3.0. There is one. Not for the SH3 processor... doesn't produce binaries. > >> (I'm sure my terminology is way out of line here... sorry) >> >> Does it work yet ? > >Read the whitepaper, available on the ActiveState site. > >RTFM. STFW. etc. :-P > >-- Gerhard ATFQ :-) Fuzzyman --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera http://www.voidspace.org.uk Where Headspace Meets Cyberspace Cyberpunk and Science Resource Site Exploring the worlds of Psychology, Spirituality, Science and Computing -- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz http://www.learnlandrover.com From jjl at pobox.com Tue Jul 8 10:47:49 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Jul 2003 15:47:49 +0100 Subject: COM Programming References: <6308fa3f.0307080220.5889317b@posting.google.com> Message-ID: <87y8z9f52i.fsf@pobox.com> tom.bradshaw at zytek.co.uk (TB) writes: [...] > Also has anybody got any references to more info about Python using > COM? The O'Reilly book by Hammond and Robinson (one of the COM chapters is free to download). John From zephyr01 at alltel.net Wed Jul 2 22:58:30 2003 From: zephyr01 at alltel.net (Hans Nowak) Date: Wed, 02 Jul 2003 22:58:30 -0400 Subject: Question regarding naming convention In-Reply-To: <1057062415.13616.0@doris.uk.clara.net> References: <1056988215.49928.0@iris.uk.clara.net> <1057062415.13616.0@doris.uk.clara.net> Message-ID: michael wrote: > Both of the above seem to overcomplicate the syntax. Of the two, I > prefer the second, but I'm sure I've read on c.l.py that the > from..import.. version is not a preferred way of doing things. > > Is there no way to write a class, such that the statement: > > import MyClass > > would dynamically import the MyClass class from MyClass.py ? > > It just surprises me that there isn't a neater way around this, as > Python seems to encapsulate most everything else in a simple way. Not sure if this is what you're after, but: >>> def importobj(name): mod = __import__(name) obj = getattr(mod, name) globals()[name] = obj # import the StringIO object from the StringIO module >>> importobj('StringIO') # is it in the global namespace? yes: >>> dir() ['StringIO', '__builtins__', '__doc__', '__name__', 'importobj'] Putting something into globals() is a bit of a kludge, though. You're probably better off using from x import x. Cheers, From vze4rx4y at verizon.net Wed Jul 16 15:44:29 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 16 Jul 2003 19:44:29 GMT Subject: __eq__ and __ne__ References: Message-ID: > [Tim] > >>>> Since the richcmp operators aren't constrained to return scalars, > >>>> an attempt to define one in terms of the others seemed futile. > >>>> Instead they're 6 independent methods. > > [Shane Hathaway] > >>> Ok. Thanks for finding the docs. I guess I'll stick to my > >>> boilerplate code. I think some guidance should be added to the > >>> Python docs, though, explaining that whenever you define __eq__, > >>> you very likely ought to define __ne__ also. Okay, I added it to the docs. Raymond Hettinger From fredrik at pythonware.com Wed Jul 16 10:53:00 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2003 16:53:00 +0200 Subject: tkinter: Better Traceback References: Message-ID: Thomas G?ttler wrote: > Is there a way to get a better traceback in tkinter? > It would be nice to see the line number of the last line > of "my" code. > > Exception in Tkinter callback > Traceback (most recent call last): > File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", > line 1299, in __call__ > args = apply(self.subst, args) > File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", > line 1035, in _substitute > e.height = getint(h) > ValueError: invalid literal for int(): ?? it's not a bug in your code, it's an incompatible change in Tk 8.4.2, which uses "??" to represent an "undefined integer". either upgrade your Tkinter (Python 2.3 contains a workaround), or down- grade your Tk to 8.4.1 or earlier (or link Tkinter against Tk 8.3.x). From http Thu Jul 10 22:12:36 2003 From: http (Paul Rubin) Date: 10 Jul 2003 19:12:36 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> Message-ID: <7xk7ap3j6z.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > > Because now you need a mechanism to store the session info on the > > server, and you might want it to work across multiple load-balanced > > servers that fail over to one another, etc. > > That's far superior to presenting the opportunity to exploits in the > first place, in my opinion. Depending on the contents of the contents > of that cookie, what you suggest may not be a problem at all (depending > on how critical the data contained therein is). I'm not sure what you're saying here. My suggestion is to authenticate the cookies with a cryptographic checksum and verify the authentication before deserializing the cookies. That's probably the simplest approach. Keeping session info on a multi-process server (or worse, a multi-server network) needs some kind of concurrent storage mechanism. I don't see a robust, secure, low-overhead way to do that with out-of-the-box Python. Any suggestions? From Stephen.C.Waterbury at nasa.gov Wed Jul 23 16:16:38 2003 From: Stephen.C.Waterbury at nasa.gov (Stephen C. Waterbury) Date: Wed, 23 Jul 2003 16:16:38 -0400 Subject: Problem with pyOpenSSL and Python2.3c Message-ID: I'm trying to get pyOpenSSL to work with Python 2.3c on Red Hat 9, but there seems to be a Python C API incompatibility. I assume this just means that a new version of pyOpenSSL is needed for Python 2.3 -- is that correct? - Steve. From gregbrunet at NOSPAMsempersoft.com Mon Jul 21 15:06:42 2003 From: gregbrunet at NOSPAMsempersoft.com (Greg Brunet) Date: Mon, 21 Jul 2003 14:06:42 -0500 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: Hi Marc: "Marc Wilson" wrote in message news:kl3lhvgh5iillo5g9jvff92qkc8i2022nm at 4ax.com... > I've just got Paint Shop Pro 8.0, and the functionality of the old > ImageRobot add-on has been replaced with the new Python Scripting. Thanks for mentioning PSP 8's support of Python. I have an older copy that I haven't updated for a while, and this scripting capability is an update worthwhile making! > What I'm trying to determine is: can I run these scripts from a command-line > invocation? I want to use the scripts to automatically convert files as > they arrive, uploaded onto a website, not interactively. I just DL'd an eval copy also, and a couple of thoughts. 1) Duncan's already pointed out the file association, so it looks like that's an easy way to ensure that the Python script is handled properly by PSP. 2) Python was installed there for me. You should see "python22.dll" in your [C:\Program Files\Jasc Software Inc\Paint Shop Pro 8] (or appropriate) directory. There shold also be a [\Python Libraries] subdirectory with other required files. 3) Interestingly, I can't find any sign of a JascApp.* file anywhere. I would expect to see a PYC or PYD given the Import command, but being a relative newbie myself, don't have a good understanding of how this could be. But, hey - it seems to work, so I won't complain. 4) I would expect that for btach processing you would also pass the file to process at the command shell, but they do seem to offer some extra help for batch processing (the "Processing all the files in a directory" section on page 26 of the script.pdf manual (available at their website if you've only got all the HTML documentation from the CD) I agree that the Docs could be a bit more helpful! 5) Of course the messages showing off PIL have opened my eyes to how easy it is to use that - and Python is LOTS easier than Perl IMHO. -- Greg From martin at v.loewis.de Sun Jul 13 18:01:28 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 00:01:28 +0200 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: Stephen Horne writes: > >This just isn't true. The C++ assignment operator is not at all like > >the Python assignment statement. Python variables are not like C++ > >variables, no surprise assignment is different too. If you used > >languages outside of C++ and its like (e.g., Pascal), you would find > >Python's behavior common. [...] > The ability to change part or all > of a value in-place has nothing to do with whether that value is > referenced using a pointer or whatever in computer theory - any link > between pointers/references and mutability should be related to the > implementation of the language - not the semantics. So you think "assignment" is about "changing values"? This is the case in C and C++, but not the case in Java (atleast for objects), and Python. In Python, assignment changes variables, not values. This is something fundamentally different. In Python (and many other languages), variables are independent of their value (and vice versa). Variables are *associated* with a value, instead of *being* that value. Then, assignment changes that association - not the value itself. > So much for dropping out of the discussion, but I hate it when people > make false claims about my beliefs, making me out to be ignorant, when > it is *not* *me* who is missing the point. I'm uncertain what your point is, however, I do observe that computer theory has a different view of what assignments are than what I think your view is. Regards, Martin From mis6 at pitt.edu Thu Jul 17 08:16:50 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 17 Jul 2003 05:16:50 -0700 Subject: [OT] sentances with two meanings References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> Message-ID: <2259b0e2.0307170416.e2bc998@posting.google.com> JanC wrote in message news:... > mis6 at pitt.edu (Michele Simionato) schreef: > > > Now, Latin had to verbs for "to know": "scire" and "cognoscere". > > And "cognovisse". (I still have a latin dictionary too... :) Huh? "cognovisse" cannot be a verb, what would be the paradigma? Michele From skip at pobox.com Mon Jul 28 15:44:06 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 14:44:06 -0500 Subject: Fastest way to count your iterations? In-Reply-To: References: Message-ID: <16165.32006.801791.56445@montanaro.dyndns.org> Tracy> [ is the modulus operator the quickest way to find out if you're Tracy> really at the 1000th item? ] I would certainly hope it's fast enough. If it's not, you probably have more serious performance issues to consider. It's what I use in my progress module. Visit http://www.musi-cal.com/~skip/python/ and search for "progress". Skip From mcfletch at rogers.com Fri Jul 18 08:48:44 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 18 Jul 2003 08:48:44 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? Message-ID: <3F17ECAC.30104@rogers.com> Hi all, I'm working on a base meta-type for a plug-in system, and I'd really like to use the same rich-descriptor objects as I've used everywhere else in the system. Basically these are descriptors that intercept x.name, do various transformations, and then store the values in the instance dictionary. Unfortunately: >>> type(t).pluginRole Traceback (most recent call last): File "", line 1, in ? File "p:\properties\basicproperty\basic.py", line 231, in __get__ return self.getDefault( client ) File "p:\properties\basicproperty\basic.py", line 256, in getDefault setattr( client, self.name, value ) File "p:\properties\basicproperty\basic.py", line 283, in __set__ self._setValue( client, value ) File "p:\properties\basicproperty\basic.py", line 151, in _setValue client.__dict__[ self.name ] = value TypeError: object does not support item assignment which would seem to suggest that the only way to use the regular descriptors would be to do the (annoying) '_'+name thing so that there's a proliferation of names in the class (which I *really* don't want). So, does anyone have a pattern which allows setting an attribute on a class which doesn't go through the setattr machinery (i.e. can be used within a descriptor)? What I'm using right now (adding a "_PlugIn__properties" dictionary) feels a little hackish, (though it does work): class PlugIn( type ): """Meta-class for plug-in classes""" def __new__( cls, name, bases, dictionary): dictionary['_PlugIn__properties'] = {} new = super( PlugIn, cls).__new__( cls, name, bases, dictionary) return new especially as it requires that I sub-class each and every descriptor-type I want to use with plugins... not a huge deal, they're built to make that easy, but it seems inelegant to be creating an extra __dict__ just because the built-in one is marked as non-assignable save through the built-in setattr mechanism. Basically, I'd love to find a method "simple_setattr" which allows the setting on the class w/out triggering the property I'm trying to implement. Always-looking-for-elegance-even-when-it-already-works, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From max at alcyone.com Sun Jul 6 22:36:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 06 Jul 2003 19:36:16 -0700 Subject: anything new on the ternary operator? References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> Message-ID: <3F08DCA0.3EED47A4@alcyone.com> Russell Reagan wrote: > What is superior about using the proposed ternary operator instead of > using > the 'and' and 'or' operators to simulate inline logic? Because the and/or technique doesn't quite work. Instead of rehashing this topic again, I'd recommend you check out the PEP 308 on the conditional operator which goes through all the details: http://www.python.org/peps/pep-0308.html -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ She glanced at her watch ... It was 9:23. \__/ James Clavell From rmunn at pobox.com Fri Jul 18 14:41:58 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 18 Jul 2003 18:41:58 GMT Subject: String Manipulation References: Message-ID: Batista, Facundo wrote: [snip 243 lines] Ew. Your followup was nicely informative, but your newsreader turned a nice, short six-line post into a 243-line monstrosity. Could you please turn off HTML posting and go easy on everyone else's bandwidth? Thanks! -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From jan.reinmueller at regwest.sbs.de Tue Jul 8 10:09:44 2003 From: jan.reinmueller at regwest.sbs.de (Jan Reinmüller) Date: Tue, 8 Jul 2003 16:09:44 +0200 Subject: Pyton Modul Message-ID: Hi, I am working at the moment with the semnet.py modul. Did anybody know what exactley the modul is doing? Maybe someone has a good practical example for me. Thanks in advance. Marcel From gsmatthew at ozemail.com.au Fri Jul 18 23:55:44 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Sat, 19 Jul 2003 13:55:44 +1000 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: <9j3Sa.319$vD1.15038@nnrp1.ozemail.com.au> ok so code like this is perfectly safe def run(self): while 1: job = queue.get() __processjob() thanks "Cliff Wells" wrote in message news:mailman.1058582130.2101.python-list at python.org... > On Fri, 2003-07-18 at 18:29, Graeme Matthew wrote: > > ok still a bit confused sorry .... first attempt at a thread pool > > > > Am I correct in saying that each thread runs in a continious loop > > Yes. > > > each thread calls queue.get. The get method will block and not return > > anything until an item is placed into it. When an item is placed into > > it, one of the threads will get assinged a job i.e the first one that > > happens to be in use during the cycle ? > > I think you have the idea, but I'm not sure (your terminology escapes me > a bit toward the end). What happens is each thread blocks waiting for > something to be placed on the queue. When something is put on the > queue, one of the available threads (i.e. one that is blocking on > queue.get() rather than processing a job). Only a single thread will be > woken for each item that is put on the queue. It isn't knowable which > thread that will be. > > > The job is returned to the thread, it runs with the job and does all > > the processing then returns and calls queue.get again and waits for a > > job to become available ? > > Yes. > > > When placing a job via Queue.put() one must acquire a lock place it > > and then release it > > No. The locking semantics are internal to the Queue object. Do not > concern yourself with it. It simply works. Do not attempt to put locks > around it. > > > Am i aslo correct in saying that queue is actually doing the blocking > > and controls which thread gets the job ? > > In a sense (that is, for practical purposes). How it is done internally > by the interpreter isn't important. > > > Lastly, sorry for all the questions, surely the CPU usage is the same > > when the queue is waiting for jobs and when the threads are polling as > > theyre all in one process anyway > > The threads are asleep while waiting. They don't consume any CPU. The > queue doesn't "wait" for jobs (that is, it doesn't loop, poll or > otherwise consume any CPU time), when you call queue.put() it is a > method call on an object, not a thread. > > > Am i getting this or am i way off :-) > > Just a little way off ;) > > Regards, > > Cliff > > -- > My only regret is that I ever was born > -Swans > > From egbert.list at hccnet.nl Sun Jul 27 04:55:28 2003 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Sun, 27 Jul 2003 10:55:28 +0200 Subject: Tools for reading Dr Dobb's Python-URL Message-ID: <20030727085528.GA1056@mirk.lan> What is _the_ tool for reading Dr. Dobb's Python-URL, I mean not only seeing the url's, but opening them as well ? I have made a python-script which handles it reasonably well, but someone must have invented a better wheel before me. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From peter at engcorp.com Mon Jul 21 14:27:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 14:27:10 -0400 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: <3F1C307E.1A00BBD0@engcorp.com> Marc Wilson wrote: > > Groovy. I may become a Python convert. *sigh* I've not finished learning > perl yet, and now I've got a new shiny toy. :) Excellent! You have much less to _un_learn then. :-) From andymac at bullseye.apana.org.au Wed Jul 30 06:41:57 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 30 Jul 2003 20:41:57 +1000 (EST) Subject: -shared option in distutils In-Reply-To: <20030730051157.GA28595@dave@alana.ucc.usyd.edu.au> References: <20030730051157.GA28595@dave@alana.ucc.usyd.edu.au> Message-ID: <20030730204011.U70595@bullseye.apana.org.au> On Wed, 30 Jul 2003, Dave Harrison wrote: > Im compiling on solaris 9 and am having problems with the linking (I > loathe solaris these days ;-), and if I call gcc by hand and remove the > -shared flag and replace it with -G it works. > > But I just cant find where I need to change this in the distutils > package for my install of python2.1.1. > > Where can I find it ? Grepping the source suggests unixccompiler.py contains the magic you seek. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From grante at visi.com Thu Jul 24 10:34:21 2003 From: grante at visi.com (Grant Edwards) Date: 24 Jul 2003 14:34:21 GMT Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> Message-ID: <3f1fee6d$0$169$a1866201@newsreader.visi.com> In article , Leopold Faschalek wrote: >> How does one do raw Ethernet under Win32? Ultimately, I want >> to do it in a Python program, but if somebody can point me to a >> clue on how to do it from C, I could probably figure out the >> rest. > the new winsock2.h supports more socket types: > /* > * Types > */ > #define SOCK_STREAM 1 /* stream socket */ > #define SOCK_DGRAM 2 /* datagram socket */ > #define SOCK_RAW 3 /* raw-protocol interface */ > #define SOCK_RDM 4 /* reliably-delivered message */ > #define SOCK_SEQPACKET 5 /* sequenced packet stream */ > > so you have only to define 3 as type in the socket() call I've seen vague references to this in some FAQs but could never find out if it actually worked or how to specified what Ethernet protocol you wanted to receive on the socket. -- Grant Edwards grante Yow! The PINK SOCKS were at ORIGINALLY from 1952!! But visi.com they went to MARS around 1953!! From spam at magnetic-ink.dk Mon Jul 28 02:16:02 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Mon, 28 Jul 2003 06:16:02 +0000 (UTC) Subject: How to reverse lookup characters in list? References: Message-ID: <3f24bfa2-27e5c5a1-a047-466d-99ab-bc4d01f01b42@news.szn.dk> Keith Jones wrote: > If you must ahve a list, you can do > > [a for a in string.lowercase] > > to get a list of characters from a to z. Or simply "list(string.lowercase)". // Klaus -- ><> unselfish actions pay back better From lists at gregfortune.com Sun Jul 27 11:26:17 2003 From: lists at gregfortune.com (Greg Fortune) Date: Sun, 27 Jul 2003 08:26:17 -0700 Subject: eric3, pyqt, qscintilla - guru needed. References: Message-ID: <31SUa.3521$Jk5.2639815@feed2.centurytel.net> It sounds like qscintilla was either not detected during the compile process of PyQt or the library is not available. My guess would be that the .so files did not get copied into the correct place. Check $QTDIR/lib for libqscintilla.so.2. If it's not there, go back into the directory in which you unpacked qscintilla and copy all the .so files into $QTDIR/lib. If $QTDIR isn't set, look for the lib directory in the folllowing places: /usr/lib/qt/lib /usr/local/lib/qt/lib /usr/qt/lib Also, make sure that the qt versions match up when you are looking. If in doubt, check all qt/lib directories you find. Finally, if all that looks good, start the PyQt compile process again and make sure it detects and enables qscintilla support. Greg Fortune Fortune Solutions reh wrote: > Have installed on Redhat 9.0 in the following order; > > Qscintilla > sip > PyQt > > When I install eric3 (python install.py), I get this error; > Sorry, please install QScintilla and/or reinstall > PyQt with QScintilla support. > > It seems the errors occurs in the install.py file at: > from qtext import QextScintilla > > From qtext.py, I have typed in at the python prompt; > >>> import libsip # ok here > >>> from qt import QWidet # ok here > >>> from qt import QObject # ok here > >>> from qt import QPrinter # ok here > >>> import libqtextc # error here > Traceback (most recent call last): > File "", line 1, in ? > ImportError: libqscintilla.so.2: cannot open shared object file: No such > file or directory > >>> > > Been through all readme files, tried just about everything. > Anyone have an idea what's wrong. > From skip at pobox.com Tue Jul 8 09:33:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 08:33:58 -0500 Subject: path module In-Reply-To: References: <1057655734.3738.7.camel@lothlorien> Message-ID: <16138.51270.256713.554899@montanaro.dyndns.org> Just> I find overloading / unneccesary, since it's not like you'll have Just> to write Just> a.join(b).join(c).join(d) Just> but rather Just> a.join(b, c, d) Just> which I don't think is all that bad. Yes, but a/b/c/d is nicely analogous to Unix pathname syntax. Skip From martin at v.loewis.de Sun Jul 6 03:17:11 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 06 Jul 2003 09:17:11 +0200 Subject: tp_base, tp_basesize, and __slots__ instance __class__ reassignment In-Reply-To: References: Message-ID: Jp Calderone wrote: > Can anyone enlighten me? The test doesn't recognize the addition of arbitrary same slots. Instead, it only looks for the __dict__ slot and the weakrefs slot. If any additional slots have been added to either subclass, the classes are considered different. To test whether just these two slots have been added in lock-step, you check 1. the dictoffset is the same for both classes, and it follows immediately the base slots, or neither class has a dictoffset. 2. the weakrefs offset is the same for both classes, and it follows immediately the dictoffset (or the base slots if there was no dictoffset). 3. there are no additional slots Now, this *could* be generalized to treating to classes the same if they have the same user-defined slots. If you want to do that, looking at the size is not sufficient - you also have to verify that the slot names and offsets are the same, lock-step-wise. HTH, Martin From jjl at pobox.com Tue Jul 15 17:15:54 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Jul 2003 22:15:54 +0100 Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> Message-ID: <87smp7biet.fsf@pobox.com> bhahn at spam-spam.g0-away.com (Brendan Hahn) writes: > duncan at rcp.co.uk wrote: > >"Colin S. Miller" wrote: > >To "take someone in" means to trick or deceive them. > > "take in" can also mean to observe. But "take someone in" never means that. It really is a wonder that we manage to communicate this way... John From FBatista at uniFON.com.ar Tue Jul 15 17:18:02 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 15 Jul 2003 18:18:02 -0300 Subject: String Manipulation Message-ID: Better: >>> orig = "aaa/bbb/ccc/dd" >>> orig.split('/')[-1] 'dd' . Facundo #- -----Mensaje original----- #- De: Batista, Facundo [mailto:FBatista at uniFON.com.ar] #- Enviado el: Martes 15 de Julio de 2003 6:03 PM #- Para: Python-List (E-mail) #- Asunto: RE: String Manipulation #- #- #- #- >>> orig = "aaa/bbb/ccc/dd" #- >>> orig.split('/')[orig.count('/')] #- 'dd' #- >>> #- #- #- . Facundo #- #- #- #- #- #- -----Mensaje original----- #- #- De: lamar_air at hotmail.com [mailto:lamar_air at hotmail.com] #- #- Enviado el: Martes 15 de Julio de 2003 5:23 PM #- #- Para: python-list at python.org #- #- Asunto: String Manipulation #- #- #- #- #- #- I need a piece of code that takes a string like this string1 = #- #- "aaa/bbb/ccc/dd" and extracts a string containting the #- #- character after #- #- the last "/" #- #- #- #- So for this example the result would be "dd" #- #- #- #- like this: #- #- for i=0; string1.right(i) != '/'; i++ #- #- #- #- result = string1.mid(i, string1.length()) #- #- #- #- but in python. #- #- -- #- #- http://mail.python.org/mailman/listinfo/python-list #- #- #- #- -- #- http://mail.python.org/mailman/listinfo/python-list #- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From p-abel at t-online.de Wed Jul 2 01:35:08 2003 From: p-abel at t-online.de (Peter Abel) Date: 1 Jul 2003 22:35:08 -0700 Subject: __del__ not working with cyclic reference? References: Message-ID: <13a533e8.0307012135.3554e42c@posting.google.com> janeaustine50 at hotmail.com (Jane Austine) wrote in message news:... > I have some code using singleton pattern. The singleton instance > is shared as a class variable. The problem is that the singleton > instance is not cleared automatically. > > Following is a simplified version that shows the problem: > > -------- > #foobar.py > class FooBar: > def __del__(self): > print "FooBar removed" > > FooBar.foobar=FooBar() Doen't understand what you're doing here. For me you define a classvariable named **foobar** which is bound to an instance of class **FooBar**. > -------- > > c:\python23>python foobar.py > > c:\python23> > > It doesn't print anything. > > Why is this so? Due to the cyclic reference? Isn't python's gc > supposed to treat it? What singleton idiom is recommended > otherwise? > For me the following works: >>> class FooBar: ... def __del__(self): ... print "FooBar removed" ... >>> foo=FooBar() >>> del foo FooBar removed >>> > Thanks > > Jane Regards Peter From gregbrunet at NOSPAMsempersoft.com Tue Jul 1 23:20:06 2003 From: gregbrunet at NOSPAMsempersoft.com (Greg Brunet) Date: Tue, 1 Jul 2003 22:20:06 -0500 Subject: Howto: extract a 'column' from a list of lists into a new list? References: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Message-ID: "Bengt Richter" wrote in message news:bdspmf$leq$0 at 216.39.172.122... > Or you can take advantage of zip: > > >>> fields = [ > ... ('STOCKNO', 'C', 8, 0), > ... ('DACC', 'C', 5, 0), > ... ('DEALERACCE', 'C', 30, 0), > ... ('D-ACCRTL', 'C', 9, 0), > ... ('D-ACCCST', 'C', 9, 0) > ... ] > >>> zip(*fields)[0] > ('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST') > > Or a list of all the columns of which only the first was selected above: > >>> zip(*fields) > [('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST'), ('C', 'C', 'C', 'C', 'C'), (8, 5, 30 > , 9, 9), (0, 0, 0, 0, 0)] > > Since zip gives you a list of tuples, you'll have to convert if you really need a list version > of one of them: > > >>> list(zip(*fields)[0]) > ['STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST'] Bengt: This looks great - but something isn't quite working for me. If I type in the stuff as you show, the zip function works, but if I use the values that I get from my code, it doesn't. Here's what I get in a sample session: #------------------------------------ >>> ff=dbf('nd.dbf') >>> ff.Fields() [('STOCKNO', 'C', 8, 0), ('DACC', 'C', 5, 0), ('DEALERACCE', 'C', 30, 0), ('D_ACCRTL', 'C', 9, 0), ('D_ACCCST', 'C', 9, 0), ('DEC', 'N', 10, 2)] >>> zip(*ff.Fields()) Traceback (most recent call last): File "", line 1, in ? TypeError: zip argument #1 must support iteration #------------------------------------ Where the "dbf" invoices the _init_ for the dbf class which opens the file & reads the header. As part of that, the fields are placed in a class variable, and accessed using the Fields() method. At first I wasn't sure of what the '*' did, but finally figured that out (section 5.3.4-Calls of the Language Reference for anyone else who's confused). After puzzling it through a bit, I believe that Fields() is causing the problem because it's not really a list of tuples as it appears. Rather it's a list of dbfField objects which have (among others) the following 2 methods: class dbfField: #---------------------------------------- def __init__(self): pass #---------------------------------------- def create (self, fldName, fldType='C', fldLength=10, fldDec=0): # (lot's of error-checking omitted) self._fld = (fldName, fldType, fldLength, fldDec) #---------------------------------------- def __repr__(self): return repr(self._fld) #---------------------------------------- def __getitem__(self,key): """ Return by position or item name """ if type(key) is IntType: return self._fld[key] elif type(key) is StringType: ukey = key.upper() if ukey=="NAME": return self._fld[0] elif ukey=="TYPE": return self._fld[1] elif ukey=="LENGTH": return self._fld[2] elif ukey=="DEC": return self._fld[3] What I was trying to do, was to use the _fld tuple as the main object, but wrap it with various methods & properties to 'safeguard' it. Given that can I still use zip to do what I want? (Egor & Max's list comprehension solution works fine for me, but the zip function seems especially elegant) I read in the library reference about iterator types (sec 2.2.5 from release 2.2.2), and it looks like I could get it to work by implementing the iterator protocol, but I couldn't find any sample code to help in this. Any idea if there's some available, or if this is even worth it. Better yet, is there a way for me to accomplish the same thing in a simpler way? It's likely that I'm 'brute-forcing' a solution that has gotten to be a lot more complex than it needs to be. Certainly if the field definitions were in a simple tuple (which it is internally), zip would work, but then it seems that I would lose the encapsulation benefits. Is there a way to achieve both? Thanks again, -- Greg From bokr at oz.net Tue Jul 29 19:05:42 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 23:05:42 GMT Subject: Bottleneck: easy obscurity "encryption" via xor References: <3f26f477$0$49098$e4fe514c@news.xs4all.nl> Message-ID: On Wed, 30 Jul 2003 00:25:59 +0200, Irmen de Jong wrote: >Tino Lange wrote: > >> It turns out not to be quick at all. I really didn't expect this to be >> a bottleneck, but it takes quite some time. > >>> return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, _salt = salt: operator.xor(ord(char), _salt), str), "") > >Running this on a large string builds up a huge list of ints, >that you are converting to chars and then concatenating them >together using +... this creates a HUGE number of temporary >string objects. >The usual pattern of fast string joining is: > >''.join(list-of-fragments) > >So first try: > > return ''.join(map(lambda char, _salt = salt: chr(operator.xor(ord(char), _salt)), string)) > >This runs MUCH faster already. > >But the version I'd recommend is: > >def xorcrypt(string, salt = 255): def xorcrypt(s, salt = 255): # better name choice, even though string module may not be used > if salt <0 or salt> 255: > raise "Invalid salt! Must be 0<=salt<=255!" > return ''.join( [ chr(ord(c) ^ salt) for c in string ] ) return s.translate(''.join([chr(ic^salt) for ic in xrange(256)])) > >because >1) salt must be 0..255 not only <=255 >2) forget about map & lambda, use a list comprehension. forget about list comprehension, use str.translate ;-) > >That implementation runs about 20 times faster than your original one; >0.11 seconds for 100 Kb source data. (python 2.3) > s.translate ought to a good deal faster yet ;-) Regards, Bengt Richter From bokr at oz.net Tue Jul 15 03:17:52 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2003 07:17:52 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> Message-ID: On Tue, 15 Jul 2003 04:28:21 +0100, Stephen Horne wrote: >On Mon, 14 Jul 2003 16:15:08 -0700, Tom Plunket >wrote: [...] >> >>Are they really technicalities, though? I mean, a mutable object >>can be changed. It's the same object, just changed. Immutable >>objects, however, can't be changed. You can get something that >>appears like changing it, but it's actually building a new thing >>and binding the label to that new thing. > >Yes. But the thing being changed *is* an object, *not* a value. Values >are always immutable - basic fact of mathematics. Too many words that I don't understand ;-/ Ok. There seem to be some entities you call "values" and some you call "variables." > >Variables in mathematics are bound to values. I think Python should be >implemented in a way that respects that. Now you are apparently saying that there is at least one relationship possible between "variables" and "values" -- namely being "bound." How do we know that a given "variable" is "bound" to a given "value?" I guess one way would be to introduce the idea of an ordered pair, produced say by a constructor "Pair", and also a set of ordered pairs defined as the binding set. Then if Pair(variable,value) is in the binding set, we can say variable and value are bound. Note that this is entirely abstract; representation is a separate matter. "variable" is a single entity, presumably belonging to the set of possible variables. > >Whether you use objects to represent values, or whether you use some >kind of symbolic representation is an implementation detail which >should be transparent to the user unless the user specifically >requests to deal with the object or whatever. > Now we apparently have a recognizably different entity "object" which I'd like to know the meaning of, not to mention some kind of relations "object"<->"represent"<->"value" and "symbol"<->"represent"<->"value." To start, I would propose that all the words should refer to some abstract entities or relationships, and then that we carefully consider various concrete representations that may be put in correspondence, perhaps also in terms of a set of ordered pairs. I'm too tired right now though ;-/ >If I type... > >>>> a = [1, 2, 3] >>>> b = a > >Then in my mind, the point is that both variables get bound to the >value '[1, 2, 3]'. Ok, I infer that your take "a" and "b" to represent "variables." And you are proposing that "'[1, 2, 3]'" represents a "value", and that the first statement creates a binding. say (a, '[1 2, 3]') in the binding set. The second statement will presumably produce another binding (b, ) in the binding set. Now that means we have to decide what "a" evaluates to in "b = a." If it's just a, we get the binding (b, a) but that would say that variables can be part of the set of possible values (i.e., variables per se, not e.g. string representations). That's not how it works, though. Evaluating a implies finding its associated value in a (variable,value) pair in the binding set. So the new binding should be (b, '[1, 2, 3]') -- i.e., the same identical value as bound to a. So far this is just how python works. > >The fact that the binding to values might be implemented using binding >to the same object at this point should be, to me, a low level detail. > >If I now type... > >>>> b[2] = 4 > >Then the variable b should now be bound to the value '[1, 2, 4]'. That >is the whole point of what I've done. However, the fact that it was >achieved by modifying a part of an object is an implementation detail. >It should not affect the *value* bound to the variable a. In other Aha. Maybe "variable" is a misnomer that you should not use when reading python assignment statements. E.g., say "alias" instead, and read "b=a" as "b is now an alias for the same entity as a is an alias for." The syntax is like an optical illusion that can be seen more than one way, and you are projecting a non-python view onto the syntax, which is interfering with seeing the other view ;-) >words, a new object should be created at that point - a copy of the That's a "should" for another language, it's not what Python is designed to do. >original - which would then be modified. That way, the mathematical >concept of variables being bound to values would be respected. > Why don't you respect the possibility of a language that is *designed* to deal with entities and relationships in ways you are not used to? ;-) >This is not difficult to achieve. The implementations of the C++ The difficulty is not really relevant. It's not a goal for this language ;-) >standard library that I've seen use exactly the same copy-on-write >mechanism for strings. This method implements a lazy copying >optimisation without violating the concept of variables being bound to >values. That is, the hidden use of pointers or references in the >std::string class is an implementation detail that you don't have to >worry about as a programmer. The programmer worries about the >application - not the low level details of the implementation of the >language or library. > >But, like I said before, this isn't about imitating C++. It's about >respecting the common definitions of 'variable', 'value' etc from There you go again ;-) I could as well say that it's about "respecting" that Python is not designed to do what you are used to and thus does not use "assignment" the way you are used to, most likely because it doesn't really have "variables" in the sense that you are used to. Why assume because some notion isn't used that it means disrespect? If you read "variable" where you should be reading "alias" perhaps you are misconstruing what you are reading, and are merely uncomfortable because the mental model you are using to organize your perceptions doesn't fit. It's like saying a python should respect accepted ideas of locomotion and have legs, because everything you're used to that moves on the ground has legs ;-) >mathematics and computer science - something that people do seem to >intuitively expect until the Python way is beaten into them. You mean until the burn-in from their first over-repeated viewpoint exposure fades ;-) > >To me, 'Pythonic' expresses 'doing the right thing'. In this case, in >my view, Python does the wrong thing and expects everyone to get used Expand your set of views. I think you will find one where you will see Python as doing the right thing, for the most part. ;-) >to it. Regards, Bengt Richter From owski at hotmail.com Mon Jul 14 19:22:18 2003 From: owski at hotmail.com (Adam Ruth) Date: Mon, 14 Jul 2003 23:22:18 +0000 (UTC) Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Message-ID: <20030714172215452-0600@news.xmission.com> I started to write a response, and then I realized that it would be pointless. We're just gonna have to be happy in each other's ignorance. Our skulls are too thick for each other's arguments. I'm gonna stick with the idea that we're both wrong. Even-though-your-more-wrong-erly yours, Adam Ruth From JensRie at gmx.de Fri Jul 11 01:56:53 2003 From: JensRie at gmx.de (Jens Riedel) Date: Fri, 11 Jul 2003 07:56:53 +0200 Subject: Zope problem: objectValues('Folder') References: Message-ID: <3F0E51A5.3060600@gmx.de> Craig Funk schrieb: > The objectValues() will only return a list of the folders if it is called > from with a DTML Method. If you are calling it from within the context of a > Document it will not work. The method is called within the context of the > folder so everything is fine. That is why it would work in > standard_html_header. However a Document has it's own context. > > Craig Thanks, that was it! regards, Jens From gh at ghaering.de Mon Jul 21 18:23:28 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 22 Jul 2003 00:23:28 +0200 Subject: [OT] SCO is Going After End Users In-Reply-To: <4868482a.0307211336.4ca9493a@posting.google.com> References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: <3F1C67E0.7070805@ghaering.de> Russ Salsbury wrote: > ComputerWorld says that SCO is going to charge Linux end users a > license fee for "the opportunity to run Linux legally." > > Lots of companies will pony up. > > I realize that this is OT, Then please keep it to the appropriate groups. I'm sick and tired of "news" about SCO's alleged claims. > but SCO's action strikes at the heart of > Open Source. Somebody with the right patents can try to tax or shut > down the rest of us, regardless of the validity of their claims. [...] That may be so in the US. In Germany, SCO is not allowed to spread their FUD any further for the time being: http://www.golem.de/0305/25730.html (German) I'm too lazy to find an English translation for you. Please let's keep this stuff off list. SCO is gaining way too much attention already. And this is all they want: increase their stock value/hope to be bought out. Explicit Reply-To set if you fell you need to discuss this further with me. Otherwise EOD from my side. -- Gerhard From frobozz_electric at hotmail.com Mon Jul 7 11:06:31 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 7 Jul 2003 15:06:31 GMT Subject: Gathering variable names from within a function. References: <2259b0e2.0307050511.55253683@posting.google.com> Message-ID: This will seem excessive, but it`s a little hack I`ve been playing with. WARNING: It`s incomplete, and, in general, it should probably *not* be used. Still, here it is, if you`re interested: import inspect class ThisResolutionError(Exception): pass def this(): "returns the function object that calls it" # get calling function's name from outer frame fname = inspect.currentframe(1).f_code.co_name frameno = 2 func = None while func is None: # search the outer frames for a reference to this function try: func = inspect.currentframe(frameno).f_locals.get(fname, None) frameno += 1 except ValueError: # reached end of call stack raise ThisResolutionError, "could not resolve %s"%fname return func # return this function object 'this()' can be used to get hold of the function that you're currently in; you may then manipulate or inspect that function as you please. for example: def modvars(arg1, arg2): "records it's own modified variables" var1 = arg1 var2 = arg2 var3 = arg1+arg2 this().__dict__ = vars() print this().__doc__ return var3 modvars(1,2) print modvars.__dict__ # OUTPUT: # records it's own modified variables # {'arg1': 1, 'arg2': 2, 'var1': 1, 'var3': 3, 'var2': 2} 'this()' appears to work for functions, including nested functions, but it does not work for bound/unbound methods, or functions stored in a dictionary (yet). For instance, you can do the following: def f(): def g(): print "g says 'Hello'" this().g = g print f.g print f.g() # # g says 'Hello' But you can't do this: def f(): def g(): "g says 'Hello'" print this().__doc__ this().g = g print f.g() # ThisResolutionError: could not resolve g Anyway, it's still pretty neat to be able to grab hold of a function, from inside itself, and work with it. Sean From intentionally at blank.co.uk Sun Jul 13 23:43:07 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 04:43:07 +0100 Subject: anything like C++ references? References: Message-ID: On 13 Jul 2003 20:18:25 -0500, Ian Bicking wrote: >I think, then, that Stephen maybe wants to do something like: > >>>> a = ref(1) >>>> b = a >>>> b is a >True >>>> a + 2 >3 >>>> a = 5 >>>> b >5 > >And so on. This is all quite doable in Python (implementation of ref >left to the reader), except for the "a = 5" part. Instead you'd have to >do something like "a.set(5)". Even though it is doable, of course, it's >by way of clever hacks. Well, during the 'debate', that's the basic idea that involved - except that I'd use explicit pointer-dereferencing syntax. Imagine, for instance, changing all assignments and other 'copying' to use a copy-on-write system. Then add a pointer type and a 'newcopyof' operator. And nick the C-style prefix '*' for dereferencing and add '&' as a 'make a pointer to this object' operator (absolutely NOT a physical memory address). >>> a = 5 >>> b = a >>> b is a False >>> a = &5 >>> b = a >>> *b is *a True >>> a = &5 >>> b = newcopyof a # could be "b = &(*a)" in principle >>> *b is *a False >>> a = BadPtr >>> b = *a Traceback (most recent call last): File "", line 11, in ? BadDeref: pointer does not reference a valid object >>> a = *1 Traceback (most recent call last): File "", line 12, in ? TypeError: object doesn't support dereference operator No need for a 'delete' equivalent because of garbage collection. No possibility of referencing a bad pointer as there is no way to create a bad pointer - except, of course, for the explicit BadPtr (or whatever) which throws an exception if dereferenced. >The problem that Stephen is not appreciating is that this sort of >reference implies that "a" is a typed variable -- of type "pointer", >somehow implicitly declared when it was initially assigned a ref >object. (He's not alone, because just a little while ago someone >proposed a way to overload the meaning of "=", to achieve largely the >same functionality) No - I'm aware of the issue. When people use lists to fake pointers, they already need explicit notation to tell Python what they are doing. I'd just rather go back to having explicit pointers, though implemented in a way which is appropriate to scripting languages and which eliminates the major reliability issues of C-like pointer mechanisms. Using this approach, I don't need to declare variable types but I do need to be explicit about when I'm using pointed-to-values and when I'm using the pointers themselves. Self-dereferencing pointers might also be nice in some ways, but with serious problems. In C++, binding to the referenced object is done in the declaration. That can't happen in Python, so a different method would be needed - a special assignment operator, probably. That then leads to the fundamental flaw. This couldn't be used to do what, in C++, it does best - mimicking what Pascal calls 'var' parameters. If there were a 'procedure' abstraction, distinct from 'function', I might be happy for all parameters to be implicitly dereferenced pointers - I'd be happy being unable to change the pointer in this case (in fact I'd like it enforced) - to get var parameter like behaviour. There are nasty subtleties, though (what if someone creates a pointer to the parameter, for instance - can it be used to change the supposedly fixed pointer?). The C-like approach of just passing a pointer as the expected parameter type has the advantage of simplicity if nothing else. >Anyway, that's my attempt at empathy with Stephen, if not agreement. If >he is wanting something other than what I've described, he should give >other examples, because code examples are better than words. I hope I've explained, now. It wasn't in my mind when I started out, but it would certainly be a way to solve what I see as serious problems. A realistic change for Python? - I doubt it. It could be technically feasable, perhaps (a 'from future' thing adding copy-on-write and the new operators etc) but interaction with past modules would create problems. And with my very limited understanding of Python internals, I'm sure I'm missing much bigger problems. Not to mention that at this point, the change would probably be so fundamental as to actually create a new language. This does, however, give an alternative that *could* have been plausible (in a parallel universe, perhaps), and which would not have resulted in certain common problems that do occur now. From joerg.maier at rz.uni-mannheim.de Sun Jul 27 17:54:18 2003 From: joerg.maier at rz.uni-mannheim.de (=?ISO-8859-15?Q?J=F6rg?= Maier) Date: Sun, 27 Jul 2003 23:54:18 +0200 Subject: python on windos os.popen and standart in and out Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hy, i want remote ls via shh from a windows machine. after starting the command via # stdoutssh = os.popen('/path/to/ssh.exe user at host ls -al ~' -+' 2>&1', 'r') i have the possibility to watch the standart output in the pipe, but i cant give the password. when giving 'w' as second parameter, i just can write, but not read. ssh is installed by cygwin. i dont want to use ssh-keys, because user shold be able to use the program on different machines without much key-copying. thank you for every advice. regards, joerg - -- Hi I am a signature virus. Please copy me to your .signature file to help me spread. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2-rc1-SuSE (GNU/Linux) iD8DBQE/JEoOTYj8eXbs1acRAt6VAJ9YIDo6Busujj3TAun34t7kXG0VaQCfa4Bv /I9/X+GUl3QjNw+xN2vOigY= =qE1P -----END PGP SIGNATURE----- From rastm2 at aol.commorespam Wed Jul 23 14:47:32 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 23 Jul 2003 18:47:32 GMT Subject: very Very VERY dumb Question About The new Set( ) 's Message-ID: <20030723144732.13232.00000523@mb-m10.aol.com> very Very VERY dumb ? about the new Set( ) 's Please be kind and read this like you know I've been up 33-34 hours reading PEP's but... Doc\ref 2.6 Delimiters show's three unused characters "@ $ ?". @ sort of looks like and sort of sounds like a set an $ well sort of obvious. I can imagine that the $ would be confused for money and @ is ugly. You folks have prob'ly been all over this. Even thou I've been using Python since 1.4, I only joined the comp.lang.python a couple weeks ago so I don't know the flame wars over the Set implimentation. Ray St. Marie --- Afraid to sign his name to this one Rastm2 at aol.bomB From anton at vredegoor.doge.nl Sat Jul 5 06:49:33 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 05 Jul 2003 12:49:33 +0200 Subject: getting a submatrix of all true References: Message-ID: John Hunter wrote: >>>>>> "Bengt" == Bengt Richter writes: > Bengt> Brute force seems to work on this little example. Maybe it > Bengt> can be memoized and optimized and/or whatever to handle > Bengt> your larger matrix fast enough? > >Thanks for the example. Unfortunately, it is too slow even for >moderate size matrices (30,10). I've been running it for over two >hours for a 30x10 matrix and it hasn't finished. And my data are >1000x100! I posted a somewhat long version before (inspired by Bengts idea) but I remembered an easier way to generate all combinations, and also I noticed that there is freedom in choosing to analyze rows or columns, which can be computationally advantageous. Below is a version that depends mostly on 2**N where N is the smallest of those two values. Unfortunately 2**100 is still way to big a number, but my code can now routinely solve 100x15 matrices ... >Last night, I began to formulate the problem as a logic statement, >hoping this would give me an idea of how to proceed. But no progress >yet. But I have come to the conclusion that with P ones, brute force >requires 2^P combinations. With 1000x100 with 5% missing that gives >me 2^5000. Not good. IMO it depends (except for the amount time spent in copying data of course) on the smallest of the number of rows or columns, so that's 2**100 in this case. Maybe for some matrices, your number is preferable? >Thanks for your suggestion, though. If you have any more thoughts, >let me know. I hope you don't mind me following this too :-) Nice problem, and I'm not so sure about my math as I sound above, if anyone can prove me right or wrong I'd be happy anyway ... Anton --- class ScoreMatrix: def __init__(self, X): n1,n2 = len(X),len(X[0]) if n2 highscore: mi,highscore = i,sc sc,rows,cols = highscore print "maximum score: %s" %(sc) print "index of this score: %s" %(mi) print "tabledata:" for i,r in enumerate(X): for j,c in enumerate(r): if i in rows and j in cols: print c, else: print 'x', print if __name__=='__main__': test() From gh at ghaering.de Sat Jul 12 22:06:17 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 13 Jul 2003 04:06:17 +0200 Subject: Any pure-python relational databases? In-Reply-To: <8XZPa.12712$Hb.219315@news4.e.nsc.no> References: <2a897f11.0307121143.4a37113b@posting.google.com> <8XZPa.12712$Hb.219315@news4.e.nsc.no> Message-ID: <3F10BE99.7070307@ghaering.de> Thomas Weholt wrote: > "Wayne Pierce" wrote: [...] >>>2) Any kind of relational DBMS written in pure python that'll run on >>>1.5.2? >> >>While not relational, have you looked at Metakit? >> >>http://www.equi4.com/metakit/python.html > > Relational *and* simple install with good Python module; SQLite => > http://www.sqlite.org/ First, PySQLite is not pure Python, it needs to be compiled against the SQLite engine. Second, PySQLite currently requires Python >= 2.1 and will require Python >= 2.2 in the 0.5 branch which I'll start eventually. I'd be willing to make a backport to 1.5.2 if somebody pays me. But something as little fun as this I won't do for free :-P -- Gerhard From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 7 08:02:34 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 07 Jul 2003 12:02:34 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 7) Message-ID: QOTW: "Confronting the Martellibot is like flirting with an encyclopedia, I'd rather not do it myself, but I respect those who do, because it produces knowledge." -- Anton Vredegoor "Python and Java are not diametrically opposed religions that must fight to the death in jihad, despite the existence of loonies favoring exactly that. They solve different problems; sometimes in similar ways, sometimes not." -- Mark Hughes Discussion ---------- Michael Chermside explains what assignment in Python means, and how this conflicts with a proposed change of the assignment 'operator'. Bengt Richter adds another twist to this discussion about overloading the assignment operator (which is a statement, really). Geoff Howland discusses issues related to the use of Python executables for source code secrecy, instead of speed increase. Erik Max Francis explains the difference in output of printing an element as part of a list and printing the element itself. Mirko Zeibig shows that "bound method" objects can be used for callback functions, or "functors". Erwin Andreasen explains that buffering is why a python script with multiple threads can seem to execute the same 'print' multiple times. David Bolen adds insight to the question "when is unit-testing bad?", regarding elements that we think are hard to unit-test. Bengt Richter shows how to use zip to transpose a list to get a list of columns (apparently inspired by a Martellibot post). Tkinspect is a kind of debugger that allows one to diagnose a Tkinter process "from the outside". Announcements ------------- Python 2.3beta2, the second beta release of Python 2.3. Pyro 3.3 beta, an advanced and powerful Distributed Object Technology system written entirely in Python. 4Suite 1.0a3, a comprehensive platform for XML and RDF processing, with base libraries and a server framework. DNSpython 1.0.0, a DNS toolkit for Python. Eric 3.2, a full featured Python IDE that is written in PyQt using the QScintilla editor widget. PyKota 1.12, a complete Print Quota and Accounting Software Solution for CUPS and LPRng. PyQt 3.7, a comprehensive set of Python bindings for Trolltech's Qt GUI toolkit. PyRex 0.8.1, a language for writing Python extension modules. SQLObject 0.4, SQLObject is an object-relational mapper supporting Postgres, MySQL, and SQLite. Scratchy 0.6, an Apache log parser and HTML report generator. Announcements ------------- PyRex 0.8, a language for writing Python extension modules. M2Crypto 0.11, a crypto and SSL toolkit for Python. PythonCAD 8th release, a CAD package written in Python. DocUtils 0.3, a system for processing plaintext documentation (reStructuredText markup). Scratchy 0.4, an Apache log parser and HTML report generator. ClientForm 0.0.10 and 0.1.3a, a Python module for handling HTML forms on the client. SCons 0.90, a software construction tool (build tool, or make tool). Twisted 1.0.6, an event-driven networking framework for server and client applications. David Mertz, our own Lulu, presents Twisted to a wider audience. TTFQuery 0.2.4, builds on the FontTools module to allow you to query TTF font-files for metadata and glyph outlines. ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From aahz at pythoncraft.com Sun Jul 20 09:44:24 2003 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2003 09:44:24 -0400 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: In article , Marc Wilson wrote: > >I'm a complete Python newbie, though I know at least one regular in >here. :) Hi, Marc! >What I'm trying to determine is: can I run these scripts from a >command-line invocation? I want to use the scripts to automatically >convert files as they arrive, uploaded onto a website, not >interactively. Don't know PSP, but normally this kind of facility would be made available through an importable module. If that's not an option, check to see whether PSP allows specifying a script on the command line; presumably their embedded Python permits you to exit PSP. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From g2h5dqi002 at sneakemail.com Fri Jul 18 02:25:32 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 18 Jul 2003 18:25:32 +1200 Subject: list() coercion In-Reply-To: References: Message-ID: Ian Bicking wrote: > I'm not clear on how that will help...? > > It already does have an __iter__ method, but it returns a separate > iterator. It turns out that it won't help. I had thought that calling __len__ would only happen if there were no __iter__ method, but that seems not to be the case. The only thing I can think of at the moment is not to do list(x) at all, but list(iter(x)) instead. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From deets_noospaam at web.de Sun Jul 27 12:24:21 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2003 18:24:21 +0200 Subject: multithreading-problem Message-ID: Hi, I expirienced strange problems when using the module threading: class Bar: def __init__(_, arg): _.arg = arg def work(_): while 1: print _.arg def foo(arg): b = Bar(arg) b.work() for i in xrange(4): thread = threading.Thread(target=lambda : foo(i)) thread.start() What I'd expect would be a sequence of prints like this 1 2 3 4 1 3 4 2 What I actualy get is this: 1 4 4 4 4 1 4 4 4 Placing a time.sleep(3) after the thread.start() fixed things. So it appears that the curried lambda passed as target is somehow a reference equal for all four invocations. The used python is 2.2.. Regards, Diez From bokr at oz.net Thu Jul 3 00:25:40 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Jul 2003 04:25:40 GMT Subject: getting a submatrix of all true References: Message-ID: On Wed, 02 Jul 2003 14:16:57 -0500, John Hunter wrote: > >I have a largish data set (1000 observations x 100 floating point >variables), and some of the of the data are missing. I want to try a >variety of clustering, neural network, etc, algorithms on the data, >and to keep life simple I want to reduce the dimensions of the matrix >so that I have no missing values, since not all the algorithms are >able to handle them and there is sufficient redundancy in the >variables that I can afford to lose some. > >I am currently using a hack that works, but it makes me wonder if >there is an optimal solution. I define optimal as the removal of rows >and columns such that there are no missing values and >max(numRows*numCols). > >My current approach is to drop rows (observations) that have more than >some prespecified number of missing variables, and then drop the >columns (variables) of the reduced data set that have any missing >values. I chose the threshold for dropping a row by eyeballing the >distribution of number of missing variables per observation, pick a >number on the low end of the distribution, and dropping the rows that >exceed the threshold. > >Another way of formulating the question: for a sparse boolean matrix >(sparse on True), what is the optimal way to remove rows and columns >so that the total number of elements in the matrix is maximal and >there are no True values left. > > >Example: > > 0 0 0 > 0 0 0 candidate sub matrix has 12 elements > 0 0 0 > 0 0 0 > >1 0 0 0 1 >0 0 0 0 0 0 0 0 0 0 >0 0 0 0 0 0 0 0 0 0 candidate submatrix has 15 elements >0 0 0 0 0 0 0 0 0 0 >0 0 1 0 0 > > 0 0 > 0 0 candidate submatrix has 8 elements > 0 0 > 0 0 > >I want to programatically extract the 15 element matrix If I understand your original optimality definition, that would be suboptimal. I.e., how about the 16-element matrix? (x's mark the corresponding zeroes) 1 0 0 0 1 x x 0 x x x x 0 x x x x 0 x x x x 1 x x Or do they have to be adjacent? > >Following the approach described above, I get the desired answer in >the example below, though this is a hack solution and I have the >feeling there is a better one. > > from Numeric import nonzero, array, take, sum > > X = array([[1, 0, 0, 0, 1], > [0, 0, 0, 0, 0], > [0, 0, 0, 0, 0], > [0, 0, 0, 0, 0], > [0, 0, 1, 0, 0]]) > > goodObsInd = nonzero(sum(X,1)<2) # observations with < 2 missing variables > X = take(X, goodObsInd) # drop the bad > > goodVarInd = nonzero(sum(X)==0) # variables with no missing data > X = take(X, goodVarInd, 1 ) # drop the bad variables > > print X > Brute force seems to work on this little example. Maybe it can be memoized and optimized and/or whatever to handle your larger matrix fast enough? ====< submatrix.py >================================ X = [ [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0] ] def optimrcs(mx, rows=[], cols=[]): if not rows or not cols: return 0,[],[] maxscore = 0 for r in rows: if not mx[r].count(1): continue for c in cols: if not mx[r][c]: continue # eval column submatrix vs row submatrix colsxthis = cols[:]; colsxthis.remove(c) colscore, rset, cset = optimrcs(mx, rows, colsxthis) if colscore>maxscore: maxscore, maxrows, maxcols = colscore, rset, cset rowsxthis = rows[:]; rowsxthis.remove(r) rowscore, rset, cset = optimrcs(mx, rowsxthis, cols) if rowscore >= maxscore: maxscore, maxrows, maxcols = rowscore, rset, cset if not maxscore: return len(rows)*len(cols), rows, cols return maxscore, maxrows,maxcols if __name__ == '__main__': score, rowsel, colsel = optimrcs(X, range(5), range(5)) print 'Score = %s, rows = %s, cols = %s' % (score,rowsel,colsel) print for r in range(5): row = X[r] for c in range(5): if r in rowsel and c in colsel: print '<%s>'% row[c], else: print ' %s '% row[c], print ==================================================== Running it results thus: [21:24] C:\pywk\clp>submatrix.py Score = 16, rows = [1, 2, 3, 4], cols = [0, 1, 3, 4] 1 0 0 0 1 <0> <0> 0 <0> <0> <0> <0> 0 <0> <0> <0> <0> 0 <0> <0> <0> <0> 1 <0> <0> Regards, Bengt Richter From norproaj at yahoo.com Tue Jul 8 17:15:52 2003 From: norproaj at yahoo.com (Dianne Combs) Date: Tue, 8 Jul 2003 14:15:52 -0700 (PDT) Subject: Advocate Media/The Northeast Progressive Advocate Journal/San Francisco Bay Message-ID: <20030708211552.19262.qmail@web60006.mail.yahoo.com> Dear Online Reader or Editor ... If you could ... please take a look at our new online treeless edition newspapers, The Northeast Progressive Advocate-Journal and our sister newspaper the San Francisco Bay Gazette, which are produced exclusively by our joint staffs to serve the Northeast and West Coast areas - with additional non-mainline media perspective. News stories and columns are researched, thoughtful and blend politics with society, regional and local topics, etc. - in the tradition of the premier monthly magazines and the cosmopolitan newspapers. We do accept ads and subscription requests for online weekly e-mail links to the latest edition - so please take advantage of these services, provided your interest justifies it. Here are the following online links to the newspapers... www.norprogaj.com ... www.sfbaygazette.co-inc.com Again, if you feel its appropriate, please take advantage of our ad service - a competitive rate sheet is available upon request. Online subscription requests are also currently offered at $5.00 USD a month to help support our activities as truly progressive publications - committed to providing factual news and stories that just do not appear on the local or for that matter the national scene. We truly appreciate your time and let others know about it ... The Northeast Progressive Advocate-Journal. ... thanks again ... Walter Harry Combs, Editor-in-Chief Dianne Combs, Features Editor & Ads/Subscriptions Contact norproaj at yahoo.com or sfbaygazette at yahoo.com (9a-5p EDT - Phone) (518) 793-8501 (24/7 Fax/Phone-Voicemail) (360) 252-673 __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From tdelaney at avaya.com Thu Jul 24 20:55:56 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 25 Jul 2003 10:55:56 +1000 Subject: recognizing empty iterators Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D4785@au3010avexu1.global.avaya.com> > From: Michele Simionato [mailto:mis6 at pitt.edu] > > BTW, the fact that an empty iterator is True is somewhat strange, > considering that [],() and "" are False; on the other hand, generic > objects are True, so the point can be debated ... It is impossible to know, in the general case, if an iterator is empty. The primary reason for this is that many iterators are destructive e.g. file iterators. A wrapper iterator can be used around a destructive iterator that caches information, but that's about the best you can do unless the iterator is resettable. An iterator may in fact be conceptually empty at one instant, then the next instant not be empty... All it is possible to know is if an iterator has been exhausted *for now* - and that is if it raises StopIteration. Technically this does not mean that the iterator is permanently exhausted - it could start returning values at a later date, but this would be very confusing to people ;) Tim Delaney From jdhunter at ace.bsd.uchicago.edu Tue Jul 8 12:57:36 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 08 Jul 2003 11:57:36 -0500 Subject: ftp a file by date and name match In-Reply-To: <1001ff04.0307080629.7ef1e277@posting.google.com> (bobx@linuxmail.org's message of "8 Jul 2003 07:29:14 -0700") References: <1001ff04.0307080629.7ef1e277@posting.google.com> Message-ID: >>>>> "Bob" == Bob writes: Bob> I am trying to get the latest file from an ftp site that Bob> matches a pattern and is the latest one. I have it in Perl Bob> and would like to see the Python version for comparison. Here's analogous code to filter a list of filenames using a regex in python. For simplicity, I'll just make up the list of filenames rather than get them from some ftp server import re, sys files = ['20021203.somename.x86.exe', '20030103.somename.x86.exe', '20030503.somename.x86.exe', 'README',] matches = [fname for fname in files if re.match('\d{8}.*x86.exe', fname)] matches.sort() # sort to get the most recent last if len(matches)==0: print 'No file matched' sys.exit() # byebye recent = matches[-1] # get the last element of the list Note if you assume the file list is already ordered lexographically and don't need to sort, and don't want to check for the no match condition, and like tight, hard to read perl code, you could just do everything in one line, though this is frowned upon by python fans. recent = [fname for fname in files if re.match('\d{8}.*x86.exe', fname)][-1] Now we have the filename of the most recent match, and can proceed to fetch it from the ftp server. Here's some example code to log into an ftp server, change dir, and fetch a file in binary mode. Again, I'll just make up a filename from ftplib import FTP recent = 'welcome.msg' # an example file for testing ftp = FTP() # connect to host, default port ftp.connect('ftp.gnu.org') ftp.login('ftp', 'jdhunter at ace.bsd.uchicago.edu') #user, pass ftp.cwd('/pub') # get the most recent file and store it on the local sys with same name ftp.retrbinary('RETR %s' % recent, file(recent, 'wb').write) All done. All you have to do now is get a listing of files from your favorite ftp server and glue the two pieces together. Here are the docs for the ftplib module (part of the standard library) http://python.org/doc/current/lib/module-ftplib.html Perhaps you'll join the ranks of the converted? JDH From pinard at iro.umontreal.ca Mon Jul 21 22:27:11 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 21 Jul 2003 22:27:11 -0400 Subject: Flat file to associative array. In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE8D426D@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE8D426D@au3010avexu1.global.avaya.com> Message-ID: [Delaney, Timothy C (Timothy)] > > From: Alex [mailto:bogus at antispam.com] > > > > What would be the best way to convert a flat file of products into > > a multi-dimensional array? The flat file looks like this: > > > > Beer|Molson|Dry|4.50 > > Beer|Molson|Export|4.50 > > Shot|Scotch|Macallan18|18.50 > > Shot|Regular|Jameson|3.00 > Have you tried any of the CSV/DSV (delimiter-separated libraries). They > may be overkill, but you may also be able to get a 1 or 2 line solution > out of them. Python does not directly have multi-dimensional arrays deep down, but by using a tuple as index, we get the feeling and effect of a multi-dimensional array. Going without such libraries makes a longer solution, 4 lines maybe :-) Here is an untried proposal. dictionary = {} for line in file('FLAT-FILE-NAME'): fields = line.split('|') dictionary[tuple(fields[:-1])] = fields[-1].rstrip() -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From i at mindlace.net Wed Jul 9 00:02:19 2003 From: i at mindlace.net (emf) Date: Tue, 08 Jul 2003 21:02:19 -0700 Subject: regexp and filenames In-Reply-To: References: Message-ID: <2147483647.1057698139@[10.0.1.2]> --On 8 Tuesday, July 2003 20:24 -0400 hokiegal99 wrote: > I have a bit of a problem that I think Python can solve, but I need a > bit of direction. I'm replacing 12 Macs with PCs. Macs allow > characters in filenames that Windows does not, specifically the > following: > > : * ? " < > | / \ > > I would like to write a script that searches through a directory for > filenames that contain any of the aboved listed characters and > replaces them with a - (the minus sign). > > I'm familiar with regexp, but I've only used it in Python to act on > the contents of a file, not filenames in a directory. Any pointers on > how to approach this are welcome! > This should do the trick. You can steal walk from 2.3 and use it in 2.2 with hardly any modifications, if you're using 2.2. import os, re # | and \ have to be escaped; # the r prefix on the string keeps it from being a huge escape: badcharset = re.compile(r'[*:?"<>/\|\\]') for root, dirs, files in os.walk('/'): #or however you spell root on your mac for file in files: badchars = badcharset.findall(file) newfile = '' for badchar in badchars: newfile = file.replace(badchar,'-') if newfile: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) Hope that helps, ~mindlace http://mindlace.net From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 2 16:47:32 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2003 22:47:32 +0200 Subject: Suggesting for overloading the assign operator In-Reply-To: References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <3f0344e2$0$49115$e4fe514c@news.xs4all.nl> Bengt Richter wrote: > Hm, it just occurred to me that one could have yet another form of sugar > [ It's now later, and I think this may be more than sugar ;-) ] > to help with this, by treating the dot operator slightly more symmetrically, > like, e.g., '+'. [...lots of interesting examples...] > f.readlines() > > would effectively become > > readlines.__rgetattribute__(f)() > > if there were no readlines method on f, and this could > wrap f on the fly to provide the missing readlines method. My head spins... I don't know if I should consider these ideas very powerful -- or very evil... My guts tell me that this could be very powerful indeed. However my intuition tells me that there is a big catch about this, but I don't know what it is yet... :-P --Irmen From shellegouarch at programmationworld.com Mon Jul 7 18:52:50 2003 From: shellegouarch at programmationworld.com (sylvain HELLEGOUARCH) Date: Mon, 07 Jul 2003 22:52:50 GMT Subject: PyIrc module Message-ID: <20030707225250.7171.qmail@cs06.tgv.net> Hello everyone, This is my first message round here :) Well, my message is more or less an announcment of my pyirc module for Python (uh uh surprise this is the right place :)). This module tries to implement both RFC 1459 and 2812 about IRC protocol. I've decided to code my own module as Python has a lack of IRC ones. Generally speaking, either they are not up-to-date anylonger or they are written for a specific GUI. My module is far from being perfect right now but it provides : - an easy way to connect/disconnect from any servers (damn those servers which don't respect RFC rules !!!!) - a way to join/part channels - a way to send private messages as well as notices - a way to ask the servers for some info (admin,stats,trace command for instance) - a way to ask a client for some info - almost full CTCP/DCC support (DCC chat/send/get are supported) ... Everything is done with modules included in Python 2.2.2 which means that you don't need extra modules. I've written two clients demos to show how it works. One with PyGtk 2 and the other with PyQt (3.6). I've planned to write a Zope product as soon as possible. The drwaback right now is mainly the lack of documentation. I must do some code clean-up as well. But the module works. You can find more info here : http://pyirc.tuxfamily.org/ http://freshmeat.net/projects/pyirc/ Please try it and help to improve it. Im' not a Python guru so I guess there are some different ways to do what I've done so let me know. Bye for now. - Sylvain Hellegouarch From nospam at mega-nerd.com Thu Jul 17 05:25:13 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Thu, 17 Jul 2003 09:25:13 GMT Subject: Linux - python vs sh References: Message-ID: <3F166B4B.C51AAC2E@mega-nerd.com> Krisztian Kepes wrote: > > Hi ! > > I want to list my rpm database to file with this: > But how I get the rpm's output in my py program ? > list= rpm -qa import commands, string [status, rpmoutput] = commands.getstatusoutput('rpm -qa') rpmlist = string.split (rpmoutput, '\n') Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ Q. What is the difference between Jurassic Park and Microsoft? A. One is an over-rated high tech theme park based on prehistoric information and populated mostly by dinosaurs, the other is a Steven Spielberg movie. From paul.m at speakeasy.net Thu Jul 31 19:30:31 2003 From: paul.m at speakeasy.net (Paul M) Date: Thu, 31 Jul 2003 19:30:31 -0400 Subject: Plotting points with DISLIN In-Reply-To: References: Message-ID: Bob Perlman wrote: > Hi - > > I've been getting good results using the DISLIN data plotting package > with Python. But I've been unable to plot points instead of curves. > Can someone tell me how to turn off the between-points interpolation? > And if there is a way to do it, is there a way to change the style of > points plotted? > > Thanks, > Bob Perlman Hi Bob, For a slightly more pythonic wrapper around DISLIN see: http://kim.bio.upenn.edu/~pmagwene/disipyl.html --Paul From ianb at colorstudy.com Fri Jul 25 22:03:40 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 21:03:40 -0500 Subject: path module In-Reply-To: <20030725215602.Q6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> <20030725203322.P6906@prim.han.de> <1059160667.28096.10876.camel@lothlorien> <20030725215602.Q6906@prim.han.de> Message-ID: <1059185020.28092.11625.camel@lothlorien> On Fri, 2003-07-25 at 14:56, holger krekel wrote: > > The multiple walk methods would only be a shortcut anyway. Again, they > > might be difficult in a situation like a URL where directory and file > > are intermingled (and maybe ReiserFS 4...?) -- which maybe is okay, a > > urlpath object simply wouldn't implement that walker. > > Yep, URL pathes have no notion of directories and files. Thus a general > URL path can't have a 'listdir' method and thus we can't recurse. > You can easily special case it for Apache's "Indexes" view, though :-) WebDAV does, though, doesn't it? But you can still edit the directory resource, so it gets overloaded. WebDAV's use of GET is messed up. And we should specify HTTP, of course, since FTP does have a notion of directories, and possibly other URL methods would as well. But this is a digression... Ian From max at alcyone.com Wed Jul 16 15:37:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 16 Jul 2003 12:37:16 -0700 Subject: anything like C++ references? References: <1058377188.3f158de4a3a51@mcherm.com> Message-ID: <3F15A96C.D557570C@alcyone.com> Moshe Zadka wrote: > On Wed, 16 Jul 2003, Michael Chermside wrote: > > > stuff[i] = newComplexObject(i++, "name", "fred") > > I'm not entirely sure that C code is not undefined. I think it > is, but it could be that I'm mistaken and that "=" is a "sequence > point". > It's a variant on the old > > a[i]=i++ > > thing. The problem here is that it's not certain what happens first -- > the a[i] (evalating to an lvalue) or i++. Assignments are definitely not sequence points. But function calls are. So the code is well-defined, and is equivalent to = newComplexObject(i++, "name", "fred"); stuff[i] = ; (Presuming, of course, newComplexObject is a function call. If it were implemented as a macro then that'd be something else.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Everybody's playing the game / But nobody's rules are the same \__/ Florence, _Chess_ From dave at pythonapocrypha.com Sat Jul 12 22:15:36 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 12 Jul 2003 20:15:36 -0600 Subject: anything like C++ references? In-Reply-To: <1058050617.28466.279.camel@lothlorien> References: <000301c348c7$3c501980$21795418@dell1700> <1058050617.28466.279.camel@lothlorien> Message-ID: <200307122015.36808.dave@pythonapocrypha.com> On Saturday 12 July 2003 04:56 pm, Ian Bicking wrote: > On Sat, 2003-07-12 at 17:45, Brian Quinlan wrote: > > > void change(int& i) > > > { > > > i++; > > > } > > > > The idiomatic way to write this code in python would be: > > > > def change(val): > > return val + 1 > > To be more specific, you would achieve the same effect with: > > def change(val): > return val + 1 > i = change(i) > > As opposed to the C++ where you'd do: > > change(i) // no assignment needed > > > There is no direct Python equivalent to the C++ function, for all sorts > of reasons (most of them very deliberate). Your response above (that the normal thing to do in Python is just return the modified value) made me wonder if most people are asking about pass-by-reference not because they want pass-by-reference, but because in C it's generally a nuisance to return stuff from functions, especially multiple values, so you end up learning about pointers and/or pass-by-reference. IOW, if you could erase the influence of previous languages would this FAQ become "how can I return multiple things from a function" more often than it would become "how can I modify an object from inside a function"? -Dave From vze4rx4y at verizon.net Mon Jul 14 22:12:51 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 15 Jul 2003 02:12:51 GMT Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <3F130ED4.2030804@skynet.be> Message-ID: [Helmut Jarausch] > > OK, I believe to know why the last line > > print '3' three times, since only a reference > > to 'f' is stored within the lambda expression > > and this has the value 'thrice' when 'print' > > is executed. > > > > But how can I achieve something like an > > evaluation of one indirection so that > > a reference to the function referenced by 'f' > > is stored instead. [effbot] > assuming you meant "the function reference by 'f' when the lambda > is created", the easiest solution is to use default argument binding: > > flam = [lambda x,f=f: f(x) for f in funcs] > > the "f=f" construct will bind the inner name "f" to the current value of > the outer "f" for each lambda. > > the nested scopes mechanism is often introduced as the "right way" to > do what was done with argument binding in earlier versions of Python. > however, nested scopes bind *names*, while argument binding binds > *values*. This is an excellent explanation of what was being demonstrated. Raymond Hettinger From rastm2 at aol.commorespam Sun Jul 27 00:57:10 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 27 Jul 2003 04:57:10 GMT Subject: Loading and executing an arbitrary Python script from within Python References: <20030726094624.15169.00000599@mb-m13.aol.com> Message-ID: <20030727005710.05032.00000550@mb-m26.aol.com> >Dustin: shares his code with us: >def run(self): > while self.threads: > for g in self.threads: > try: > g.next() > except StopIteration: > self.threads.remove(g) > Hi Dustin, I can't help, because I'm confused by this section of code. Particularly "g.next( )" in the try statement. Did I get the concept wrong about using a generater in a try section? Is this code legal anyone? Or does this only pertain to the yeild statement in a try. Ray St.Marie Rastm2 at aol.com From bgailer at alum.rpi.edu Sat Jul 5 11:58:47 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 05 Jul 2003 09:58:47 -0600 Subject: Frustration with spurious posts. In-Reply-To: <5E982A0C1799274AAD22EE21DE6373DD0392D593@cbibipnt08.hc.bt. com> Message-ID: <5.2.1.1.0.20030705095656.01a4e060@66.28.54.253> Does anyone know why we keep getting these posted to the list. Is there a way to stop it? Undeliverable: Re: Movie At 03:56 PM 7/5/2003 +0100, postmaster at bthub01.bt.com wrote: >Your message > > To: N.Winton at axion.bt.co.uk > Subject: Re: Movie > Sent: Sat, 5 Jul 2003 15:59:01 +0100 > >did not reach the following recipient(s): > >N.Winton at axion.bt.co.uk on Sat, 5 Jul 2003 15:56:09 +0100 > The recipient name is not recognized > The MTS-ID of the original message is: >c=gb;a=bt;p=bt;l=CBIBIPNT0803070514563GAHP1WW > MSEXCH:IMS:EXCHANGE:BTHUB01:CBIBIPNT08 3550 (000B09B6) 550 5.1.1 >... User unknown Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From bokr at oz.net Fri Jul 25 10:21:18 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 14:21:18 GMT Subject: file.close() References: <7xhe5b82ip.fsf@ruckus.brouhaha.com> Message-ID: On 25 Jul 2003 00:54:38 -0700, Paul Rubin wrote: [...] >I think a much better solution would involve a language extension, >maybe a macro in some hypothetical macro extension for Python. E.g. > > with f = open(frob): > [do stuff with f] > >could be equivalent to: > > f = open(frob) > try: > [do stuff with f] > finally: > f.done() # calls f.close() > del f > >"done" here is a generic method that gets called on exiting a "with" >block. First reaction == +1, but some questions... 1) Is f.done() really necessary? I.e., doesn't an explicit del f take care of it if the object has been coded with a __del__ method? I.e., the idea was to get the effect of CPython's immediate effective del on ref count going to zero, right? 2) how about with two files (or other multiple resources)? with f1,f2 = file('f1'), file('f2'): [do stuff with f1 & f2] What is the canonical expansion? f1 = file('f1') try: f2 = file('f2') try: [do stuff with f1 & f2] finally: del f2 # leaving f2.done() to f2.__del__ finally: del f1 # ditto-like or ?? Also, what about the attribute version, i.e., ob.f = file(frob) try: [do stuff with ob.f] finally: del ob.f # calls f.__del__, which calls/does f.close() I.e., ob.f = something could raise an exception (e.g., a read-only property) *after* file(frob) has succeeded. So I guess the easiest would be to limit the left hand side to plain names... Note that that restriction does not apply e.g. to a for loop construct: >>> class SE(object): ... def _setp(self, val): print 'Side effect:', val ... p = property(None,_setp) ... >>> se = SE() >>> for se.p in range(5): pass ... Side effect: 0 Side effect: 1 Side effect: 2 Side effect: 3 Side effect: 4 Regards, Bengt Richter From fredrik at pythonware.com Wed Jul 2 06:37:23 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Jul 2003 12:37:23 +0200 Subject: arbitrary long integer aritmetics References: <20030702101213.GE21059@frobozz> Message-ID: Andrew Bennetts wrote: > I also note that your Python 2.2 does arithmetic differently to mine: > > $ python2.2 > Python 2.2.2 [etc etc] > >>> 2147483647 * 2147483647 * 2147483647 > 9903520300447984150353281023L file my example under "cut and paste errors". From hwlgw at hotmail.com Thu Jul 3 13:55:14 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 3 Jul 2003 10:55:14 -0700 Subject: XML Validation with Python References: <3F042045.C5CB0248@hotmail.com> Message-ID: > [Alan Kennedy ] > The only pure python validating parser is Lars Garshol's "xmlproc", > which is a part of pyxml (a "third-party" optional extension). You can > read the documentation for xmlproc here > > http://www.garshol.priv.no/download/software/xmlproc/ > > and the bit about validating on the command line is here > > http://www.garshol.priv.no/download/software/xmlproc/cmdline.html > > Is there any reason why it has to be in the base distribution? > Because I want to use it from a cgi script written in Python. And I am not allowed to install 3rd party stuff on the webserver. Even if I was it would not be a solution since it has to be easy to put it on another webserver. But of course: if there is a validating parser written completely in Python then I can use it too! If it runs under Python 2.1.1, that is (that is what they have at the website). I will investigate this www.garshol.priv.no link you gave me, thank you. From tim.one at comcast.net Tue Jul 22 22:46:56 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 22 Jul 2003 22:46:56 -0400 Subject: python assignment In-Reply-To: Message-ID: [dan] > without stirring the pot too much -- > > could someone please point me to whatever documentation exists on the > philosophy, semantics, and practical implications of how Python > implements the assignment operator? It's too simple to explain <0.5 wink>. Fredrik does a good job here: http://effbot.org/zone/python-objects.htm > So far I can't find much useful in the regular documentation. I > understand the basic concept that names are bound to objects > which exist on the heap, but that still doesn't explain why a = b > doesn't _always_ cause a to point to the same object as b. That's because a = b does always cause a to point to the same object as b. If you think you found a case where that's not true, you're missing something. > What determines when the object in question is copied? The rule that the object in question is never copied. There are no exceptions to this. Copying an object requires invoking some method of the object, or applying some function to the object. For example, d.copy() returns a (shallow) copy of a dict d, and L[:] returns a (shallow) copy of a list L. > What determines when a future maniplulation of the variable > will cause it to point to an object that is already referenced by > another variable? (see code below for an example). Phrase that more precisely, and it will answer itself . Seriously, I don't know what you're asking there. > What I need is an exact and unambiguous algorithm for determining when > an assignment will change the id of the variable Variables don't have ids, but objects do. Assignment never changes the id of an object. > (or should I say, when the evaluation of an expression will cause a > new object to be created). Expressions may or may not create new objects, but assignment isn't an expression in Python (assignment is a statement), and an assignment never creates a new object. > Some of the issues involved can be discerned from the > following session: > >>>> a = 1 >>>> b = a >>>> a is b > True That one is necessarily True. Immediately after a = b and assuming b is bound to *something*, a is b always returns True. The history and type of the object bound to b makes no difference. >>>> a += 1 >>>> a -= 1 >>>> a is b > True That one isn't defined. It could just as well return False. Which it returns is an implementation detail, and may vary across implementations of Python (including across Python releases). >>>> a = 1.0 >>>> b = a >>>> a is b > True As above, that was necessarily True. >>>> a += 1 >>>> a -= 1 >>>> a is b > False And again that one isn't defined. It could just as well return True, and depends on implementation details. >>>> a == b > True That one is fuzzy, because floating-point arithmetic is involved, and that's subject to roundoff errors. Note that x += y isn't *just* an assignment statement, it's syntactic sugar for the assignment x = x.__iadd__(y) Whether the __iadd__() method of an object returns a pre-existing object, or returns a new object, isn't defined in general. It's up to each type's implementation of __iadd__ to decide what it wants to do. As an internal optimization, the __iadd__ method of some immutable types chose to return pre-existing objects *when that's convenient* for them. It would be very unusual (because bad design) for the __iadd__ method of a mutable type to return a pre-existing object, though. From martin at v.loewis.de Sun Jul 13 18:18:34 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 00:18:34 +0200 Subject: Reloading nested modules References: Message-ID: Andy Jewell writes: > Does anyone know of a way to dynamically reload all the imported > modules of a client module? You could iterate over sys.modules and invoke reload for all of them. Regards, Martin From justinjohnson at fastmail.fm Thu Jul 3 09:11:58 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Thu, 03 Jul 2003 07:11:58 -0600 Subject: win32service problems Message-ID: <20030703131158.26AD537CBF@www.fastmail.fm> Hello, I created an NT service using win32service. This service runs as a particular user on the domain and accepts connections to run commands on the server. The service is working great on most of the servers I have, but on one server it fails to start, with the following error message. --- Error starting service: The service did not respond to the start or control request in a timely fashion. --- And I get the following dumped to the event logs... --- Timeout (30000 milliseconds) waiting for the Twisted ClearCase Service service to connect. --- The Twisted ClearCase Service service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion. --- However, when I install the service without specifying my domain level user it starts fine. Also when I start it in debug mode it works fine. I checked the local policy settings to make sure the domain level user has the same rights as he has on my other servers and there is no difference. Does anyone have any ideas why this is happening? Also, do you know of anywhere I can look to get better debug info, or to debug using my domain level user? Thanks much. -Justin From hokiegal99 at hotmail.com Fri Jul 11 15:13:01 2003 From: hokiegal99 at hotmail.com (Tubby Tudor) Date: Fri, 11 Jul 2003 15:13:01 -0400 Subject: call one python script from within another Message-ID: What is the best way to call one python script from within another python script? For example: one.py finishes succesfully and calls two.py which finishes OK and then calls three.py Thanks guys! From peter at engcorp.com Mon Jul 7 16:45:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 16:45:43 -0400 Subject: Is there any solution in PYTHON? References: Message-ID: <3F09DBF7.8B4470B6@engcorp.com> A wrote: > > I have a program that downloads some web pages. Sometimes there is a poor internet > connection and my script freezes( hangs) and does not download ALL pages. > Is there any solution how to test if the program works and if not re-start it from the point > where it stopped? > Or simply how to download ALL pages eventhough there is a timeout connection( can be > of any value)? I would think (not that I do this kind of thing often) that there would be a better program than the one you are using, which can suck down all files in a site *and* handle timeouts, which is obviously a pretty common problem. Or is there a reason you want to use Python specifically? Sounds more like make-work to me. -Peter From andymac at bullseye.apana.org.au Mon Jul 14 06:25:05 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 14 Jul 2003 20:25:05 +1000 (EST) Subject: PyVariant anyone In-Reply-To: <3f125990$1_2@mk-nntp-2.news.uk.tiscali.com> References: <3f125990$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <20030714201823.R33711@bullseye.apana.org.au> [posted & mailed] On Mon, 14 Jul 2003, Paul Keating wrote: > I need to call a C++ DLL from Python, for which I'm planning to use > boost.python. But the DLL has been written to a VBA interface, and this > means it expects to get variable length arrays as Windows Variants instead > of lists or tuples. > > Anyone know how to construct a convincing Windows Variant in Python? I've been able to do so with Thomas Heller's ctypes module, but I've not got as far as dealing with arrays. However, if you're going to use boost.python then I'd infer that you're already using some C++ so it would be much easier to do the conversion at the C++ interface level - my understanding is that a VARIANT is a C structure, which for arrays points at another structure, which in turn gives the number & type of elements and a pointer to the actual calloc()ed array data. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From ark at acm.org Sun Jul 13 13:51:36 2003 From: ark at acm.org (Andrew Koenig) Date: Sun, 13 Jul 2003 17:51:36 GMT Subject: The definition of an object in Python References: <94af9c5a.0307130919.1ab63400@posting.google.com> Message-ID: Avi> Wesley says that every Python object must possess the following Avi> three characteristics: 1) an identity, which can be retrieved Avi> by the function id(); 2) a type, which can be retrieved by Avi> the function type(); and 3) a value. Avi> But when I do the following Avi> mystring = 'hello' Avi> print mystring.id() Avi> print mystring.type() Avi> Python complains that mystring does not possess the attributes Avi> id and type. type and id are functions, not methods. >>> mystring = 'hello' >>> print mystring.id() # using id as a method doesn't work Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'id' >>> print id(mystring) # using id as a function does 1456272 >>> print type(mystring) # ditto for type -- Andrew Koenig, ark at acm.org From gumuz at looze.net Fri Jul 25 08:02:44 2003 From: gumuz at looze.net (Guyon Morée) Date: Fri, 25 Jul 2003 14:02:44 +0200 Subject: (Eclipse/TruStudio) Re: I am so impressed References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> Message-ID: <3f211b92$0$8296$4d4ebb8e@news.nl.uu.net> did you install both packages from TruStudio? you have to download the trustudio framework & the python devtools be sure you've unzipped the files correctly in th plugin folder of eclipse "deelan" wrote in message news:hu5rfb.7qn.ln at news1.interplanet.it... > Guyon Mor?e wrote: > > > I've been looking for a nice python editor for a while. I was using a great > > general purpose editor called EditPlus. It did the job pretty good.... > > > > I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com > > and it's great! > after your suggestion i've downloaded both eclispe and trustudio. > eclipse starts flawlessy but i cannot see any trace of trustudio > python extensions. BTW eclipse runs smoothly on my office P4 1.4GHz, 512MB. > > there's should be some reference to python support > in the IDE, right? something lile "new file --> python", > or "new project --> python project", actually i only see > java related stuff. > > following the website instructions i've just unzipped trustudio zip > files (2) into eclipse folder (they actually installs under "plug-ins" > folder). i've restarted eclipse a couple of times, but nothing > changed > > any thoughts? > > later, > deelan > > -- > goldicus1970 AT yahoo.it > http://www.deelan.com/ > > > > > From ratman at nmt.edu Sun Jul 13 18:33:17 2003 From: ratman at nmt.edu (Jason Trowbridge) Date: 13 Jul 2003 15:33:17 -0700 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: Message-ID: <8f35dab2.0307131433.36b64e0@posting.google.com> Okay, without looking at anybody else's answers, using the docs, or trying out the examples. This is straight from the head, cold. Act I 's' is a list, and you can't lookup the resulting indice of the sequence using the brackets. A s.index( 'a') would be valid. As for why the exception isn't caught: There is a missing tuple there. The following would work: except (IndexError, TypeError): The way it is currently given would only catch IndexError exceptions. The exception instance would then be bound to the TypeError name. Act II The type of msg is always type instance, because it is a class instance. The actual class is held under the msg.__class__ attribute. Act III I believe that you need to call Exception.__init__(self) in your constructor. When the string representation of the exception is printed, it use's Exception.__str__() (maybe Exception.__repr__(). I forget which one the traceback shows). Since the instance hasn't been initialized properly, that function can't print out its information. Act IV This has to do with string exceptions. I'm not sure how a specific string exception can be caught. In any case, this is part of the reason to stay away from string exceptions. Additionally, string exceptions are scheduled to eventually disappear from the language. Act V Without looking at the docs, I'd say that KeyError is derived from the LookupError class. Exceptions are supposed to be listed most-specific to least specific, which translates to child classes before parent classes here. Hmm, time to look at the answers other people have given, and find how badly off I am! _ () () Jason Trowbridge | "There has been a coup. The Mac ( ' .~. Generic Programmer | users are liberating the printers." \ = o = | --Schlake ---"`-`-'"---+ ratman at nmt.edu | From sketerpot at chase3000.com Mon Jul 14 14:30:35 2003 From: sketerpot at chase3000.com (Peter Scott) Date: 14 Jul 2003 11:30:35 -0700 Subject: training for newbies References: Message-ID: <659f82ff.0307140637.53c573a2@posting.google.com> > > do you know any sites with free programs for newbies, which will help me in > > progress? i know that only way to develop is writing programs, but in my > > book i don't have programs to write, only questions.. > > Check out http://www.uselesspython.com and Python Cookbook at > http://aspn.activestate.com I can't recommend the Python Cookbook enough. Get the book if you can afford it. The discussions are great, giving you real understanding of the things being discussed. There is a world of difference between good python code and bad python code, and the python cookbook is a great way to learn good python style: by example and discussion. If you want programs to write, here are some ideas: A web spider, which should support the robots exclusion protocol (see the robotparser module in the standard library, ). Try extracting a list of images. Something that takes an URL to an RSS file and spits out an HTML file. You can also turn this into a CGI script if you like. This should be good practice for error handling, since not all RSS files have the same information. Some have Slashdot-style articles, with a headline, an article summary, and a link. Some just have a date and a paragraph about the author's cat. For extra credit, try making a module for generating HTML output (preferably valid HTML 4.01 or XHTML 1.0---with a seperate module, you just code the support once, and never worry about validity again). If you make an extra layer on top of that, you could generate output in more formats, like LaTeX. This is probably overkill, but you did say that you wanted programs to write. :-) Have fun, and good luck! From abelikov72 at hotmail.com Wed Jul 9 13:22:17 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Wed, 09 Jul 2003 17:22:17 GMT Subject: Python vs PHP References: Message-ID: On 9 Jul 2003 06:20:24 GMT, ngps at netmemetic.com (Ng Pheng Siong) wrote: >According to Afanasiy : >> Python web development is fragmented. > >www.waferproject.org: > > Wafer is a research project which compares the many open source web > application frameworks which are available using a common example > application. This research project is designed to compare the application > frameworks on a level field by specifying an example application so that > the application features become irrelevent and the merits of each > framework becomes the focus. > >Java ones only. I explore and often create the feature lists of platforms through common ground example applications in all my evaluations, web related or not. It would be nice to have a Python equivalent. Unfortunately, for now I need to just get started on some things myself rather than convince a bunch of other people to do the same. I suppose this could be the best way to show so many of the factors I've been listing for months which are apparently invisible. I'm sure people agree with me, but they do not participate in Usenet, and are very busy being important. I can also imagine any sort of attempt at comparison, like a benchmark, or the infamous language shootout, would be absolutely ridiculed. I personally consider them fairly useful, but most do not and I am wary of spending so much time on something which would eventually, or perhaps not so eventually, devolve into personal attacks. From bokr at oz.net Sat Jul 26 15:11:53 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 19:11:53 GMT Subject: How safe is modifying locals()? References: Message-ID: On Sat, 26 Jul 2003 14:49:41 +0200, Stefan Schwarzer wrote: >Hi Paul > >Paul Paterson wrote: >> This is a very interesting (and Pythonic) approach, thanks for >> suggesting it! This is certainly what I would try to do if I were >> writing the code from scratch. It may be possible to construct a >> "namespace" type object which gets passed to the function. > >I think the most common way to make a namespace in Python is > >class my_namespace: pass >... >my_namespace.a = 'foo' >my_namespace.b = 'bar' > >Such namespaces are very similar to dictionaries: > >my_namespace = {} >... >my_namespace['a'] = 'foo' >my_namespace['b'] = 'bar' > >but the first approach is a bit more readable. > >If you need many containers, you could use: > >class Container: > pass > >c1 = Container() >c2 = Container() >... >c1.foo = 'foo' >c2.foo = 'bar' > >Of course, if you have a better name for your container, that's even >better. Think of Ian's Point example. :-) > Nice summary. Just to round it out, we could add using the type builtin. I.e., type(cname, bases, cdict) works to create an instant class (new type), and this can be used for some interesting alternative spellings, e.g., A one-off name space object: >>> nso = type('',(),{})() >>> nso <__main__. object at 0x007AC1E0> BTW, funny that you can have a '' class name this way ;-) (I wonder if it can trigger a bug?) >>> `nso.__class__.__name__` "''" >>> nso.x = 123 >>> vars(nso) {'x': 123} Anyway, if you want to initialize some default name bindings in the form of class variables, you can do that simply, even in the one-off one-liner, e.g., >>> nso = type('',(),{'x':123, 'y':'wye'})() >>> nso.x, nso.y (123, 'wye') Note that they are class attributes ("variables"), not instance attributes, though: >>> nso.x = 'instance attribute' # shadows class attr >>> nso.x 'instance attribute' >>> del nso.x # but can be unshadowed >>> nso.x 123 If you want to generate a cdict for class attributes by calling some function, you could, e.g., >>> nso = type('',(),(lambda **kw:kw)( ... x = 456, ... y = 'wye', ... etc = 'and so forth' ... ))() Of course, that's a pretty silly substitute (other than the '' vs 'nso' class name) for >>> class nso(object): ... x = 456 ... y = 'wye' ... etc = 'and so forth' ... >>> nso = nso() but it does show a function (lambda **kw:kw) being called to generate the cdict. Checking results: >>> nso.x 456 >>> nso.x, nso.y, nso.etc (456, 'wye', 'and so forth') >>> vars(nso.__class__).keys() ['__dict__', '__module__', 'etc', 'y', 'x', '__weakref__', '__doc__'] BTW, I find it useful to use vars(foo).keys() rather than dir(foo) to avoid inherited stuff. Of course, if you bind the class to a name instead of instantly ()'ing it, note >>> ClassAlias = type('ClassName',(),{}) >>> ClassAlias doesn't match very well, and >>> ClassName = type('ClassName',(),{}) >>> ClassName is a silly substitute for >>> class ClassName(object): pass ... >>> ClassName Even if you don't bind the name locally, it is bound to the instance as inst.__class__.__name__, so it may be a good idea to call type with a reasonable name as the first param, not ''. Hm, got to rambling again ;-/ Regards, Bengt Richter From lamar_air at hotmail.com Mon Jul 21 15:44:54 2003 From: lamar_air at hotmail.com (lamar_air) Date: 21 Jul 2003 12:44:54 -0700 Subject: if information exists on form then use it in cgi Message-ID: <2c6431ab.0307211144.4c2f3749@posting.google.com> On my web form i have check boxes with the following code: St. Kitts Nevis when the user submits the form my python cgi retreives each of the values from the form with code like this for each: f=open('C:\My Documents\ABC\boxes', 'w') f.write('Boxes') f.write('\n') if form['C139'].value != '': f.write(form['C139'].value) f.write('\n') if form['C140'].value != '': f.write(form['C140'].value) f.write('\n') f.close() the problem is if the user doesn't check off all the check boxes on the form then the if form['C140'].value != '' code errors because nothing is there. How do i do this? Here is the error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: Traceback (most recent call last): File "C:\Inetpub\wwwroot\Cgi-bin\Cities2.py", line 175, in ? if form['C139'].value != '': File "C:\Python22\lib\cgi.py", line 550, in __getitem__ raise KeyError, key KeyError: C139 From abcdebl2nonspammy at verizon.net Wed Jul 30 01:35:02 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Wed, 30 Jul 2003 05:35:02 GMT Subject: Thank you developers for 2.3 Message-ID: Flawless install and it ran my very simple minded (try not to laugh) nested loop integer arithmetic benchmark twice as fast as 2.2.3 version 2.3 5.04 sec version 2.2.3 9.77 sec import time def speedTest(N): t1 = time.time() k = 0 for i in xrange(N): for j in xrange(N): k += (i+j) t2 = time.time() return t2-t1 print speedTest(3000) david lees From naren at trillium.com Thu Jul 17 14:37:11 2003 From: naren at trillium.com (Narendra C. Tulpule) Date: 17 Jul 2003 11:37:11 -0700 Subject: Recursion in compile() References: <781faf41.0307161629.6295618b@posting.google.com> Message-ID: <781faf41.0307171037.142956f6@posting.google.com> Steven Taschuk wrote in message news:... > Quoth Narendra C. Tulpule: > > is there any way to allow recusrion in compile()? Something like: > > > > src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \ > > '\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n' > > cobj = compile(src_code, 'myfile', 'exec') > > eval(cobj) > > This works fine for me -- it prints 479001600 as expected, on both > 2.2.2 and 2.3b1. What is the problem you're seeing? Sorry, you're right, it does work for me. I was trying something like cobj = compile('eval(src_code)', ...) eval(cobj) And that complains about syntax error (because I am trying to define a function within eval string?) From sav at ulmen.mv.ru Sat Jul 19 09:34:10 2003 From: sav at ulmen.mv.ru (Alexander Semenov) Date: Sat, 19 Jul 2003 17:34:10 +0400 Subject: __getitem__ and arguments References: <10eb079f.0307190110.30deb5b9@posting.google.com> Message-ID: <3f1948d6@post.ulj.menatepspb.com> Hello, KanZen! ??>>>> a[1, 2, 3] K> 1 K> For __getitem__() the arguments become a tuple. I can't seem to find K> this in the language spec. Can anybody explain this to me? Python doesn't have multidimension arrays. It has only sequences and dicts which consist from values indexed by keys. When you write a[1,2,3] python always see a[key] where key=(1,2,3). Tuples created automaticly where neccessary. Try "return 1, 2, 3" or "a,b,c = 1, 2, 3" statements. With best regards, Alexander Semenov. From postmaster at 127.0.0.1 Sat Jul 12 10:11:19 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Sun, 13 Jul 2003 02:11:19 +1200 Subject: Any pure-python relational databases? Message-ID: Hi, I've been looking for some way to operat a relational database on a 3rd party web server. The server runs Python 1.5.2, and does not have the MySQL-python module, (nor does it have libmysqlclient), which means I can't just talk to MySQL. The web host is my client's choice, not mine, and there's very little prospect of getting them to upgrade their python or install mysql-python. Is there: 1) Any pure-python interface to MySQL? or 2) Any kind of relational DBMS written in pure python that'll run on 1.5.2? All help appreciated. Cheers David From rimbalaya at yahoo.com Tue Jul 1 13:10:26 2003 From: rimbalaya at yahoo.com (Rim) Date: 1 Jul 2003 10:10:26 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <2259b0e2.0307010328.1e1b4a04@posting.google.com> Message-ID: <6f03c4a5.0307010910.35ca3158@posting.google.com> mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307010328.1e1b4a04 at posting.google.com>... > rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0306301931.3f15fbb7 at posting.google.com>... > > Hi, > > > > I have been thinking about how to overload the assign operation '='. > > Notice that you can always override __setattr__ ... Thanks. I have noticed that already, but it does not give me what I want. What do you think about providing a statement to assign values without assigning type? '=' statement assigns value and type ':=' statement assigns value ony Rim From dholth at fastmail.fm Mon Jul 14 18:22:05 2003 From: dholth at fastmail.fm (Daniel Holth) Date: Mon, 14 Jul 2003 22:22:05 GMT Subject: Embedding Python in a plugin Message-ID: Hello! I am trying to embed Python into an xmms plugin using Debian/unstable/i386, gcc 3.3.1 and Python 2.2.3+. The plugin is a shared library loaded by xmms. The plugin is dynamically linked with the python library. Running scripts works but when I try to import python extensions I get these kinds of errors: Traceback (most recent call last): File "", line 1, in ? File "/home/dholth/lib/python2.2/site-packages/xmmspy.py", line 12, in ? import time ImportError: /usr/lib/python2.2/lib-dynload/time.so: undefined symbol: PyExc_IOError I'm using all the compiler options I can find! /bin/sh ./libtool --mode=link gcc -Wall -I/usr/include/xmms -I/usr/include/gtk-1.2 -I/usr/include/glib-1.2 -I/usr/lib/glib/include -g -O2 -I/usr/include/python2.2 -I/usr/include/glib-1.2 -I/usr/include/python2.2 -g -O2 -I/usr/include/python2.2 -o libxmmspy.la -rpath /usr/lib/xmms/General -module -avoid-version -Xlinker -export-dynamic xmmspy.lo -lstdc++ -lpython2.2 -L/usr/lib -L/usr/X11R6/lib -lgtk -lgdk -rdynamic -lgmodule -lglib -ldl -lXi -lXext -lX11 -lm -lxmms ... including "-Xlinker -export-dynamic" as suggested by distutils. How do I embed Python in an application where the main application has no knowledge of Python, only the dynamically loaded plugin does? Which programs do this already? Thanks a heap, Daniel Holth http://dingoskidneys.com/ From intentionally at blank.co.uk Wed Jul 16 16:02:21 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 21:02:21 +0100 Subject: anything like C++ references? References: <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com> Message-ID: On 16 Jul 2003 07:24:30 +0200, Heiko Wundram wrote: >If you encapsulate your data correctly (have classes handle data that >belongs together, and not pass it round in parts), everything works out >great, at least for me. And I guess there's nothing more important than >thinking about proper data-encapsulation before starting a project. The pointer thing was raised in the context of a larger discussion. It *would* be necessary if another change was made (don't worry, it won't happen). From bogal2 at comcast.net Tue Jul 15 14:25:54 2003 From: bogal2 at comcast.net (BogAl) Date: Tue, 15 Jul 2003 13:25:54 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: Thanks for the reply, John.... > I think not; path should contain a list of *directories*, not *files* > -- Windows is silently ignoring the non-existence of directories > called "C:\WINDOWS\SYSTEM\python22.dll" etc. For some reason, I misunderstood that; glad you cleared that up for me! > Rephrasing Bernard's question: do you have those 3 files in > directories that are listed in your system path? OK, I do now. > After a normal Python installation, you would expect to have > c:\Python22 in your path, and Python22.dll in that directory. python22.dll ended up in C:\WINDOWS\SYSTEM instead; don't know why. C:\PYTHON22 never ended up in the PATH. The csv module's still not working; I'll respond to your reply in the other subthread. BogAl From paulpaterson at users.sourceforge.net Sun Jul 27 00:51:11 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sun, 27 Jul 2003 04:51:11 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: <3TIUa.107401$XV.6252339@twister.austin.rr.com> Bengt Richter wrote: > On Sat, 26 Jul 2003 15:20:24 GMT, Paul Paterson wrote: > > >>Stefan Schwarzer wrote: >> >> >>>Hi Paul >>> >>>Paul Paterson wrote: >>> >>> >>>>This is a very interesting (and Pythonic) approach, thanks for >>>>suggesting it! This is certainly what I would try to do if I were >>>>writing the code from scratch. It may be possible to construct a >>>>"namespace" type object which gets passed to the function. >>> >>> >>>I think the most common way to make a namespace in Python is >> >> >> >>Thanks, the bare namespace class is essentially what I am going to try. >> >> >>>Of course, if you have a better name for your container, that's even >>>better. Think of Ian's Point example. :-) >> >>I think you may have missed my original post; I am writing a generic VB >>to Python converter so generating good names based on code intent would >>be pretty tough! Perhaps in v2.0 ;) >> >>My current thinking is (for the orignal example of changing one >>variable, 'y' but not another, 'x'), >> >>class Namespace: pas >> >># ByVal arguments passed directly, ByRef via a namespace >>def change(x, byrefs): >> x = x + 1 >> byrefs.y = byrefs.y + 1 >> >>ns = Namespace() # The local namespace >>ns.x = 0 >>ns.y = 0 >>change(ns.x, ns) >># Now ns.x = 0, ns.y = 1 >> > > This looks readable, to me ;-) > > But it is not pointer semantics, since you have to know the name for y inside change. For my application this is always the case ... but sometimes treating the problem as harder than it really is leads to a solution that is better than you would get otherwise! > It will be nice and fast if you can use the above, but if not, in some cases, class NSP > below will let you use it just like Namespace above, though with pointer features if > you need them. > > I just wanted to throw in here that the namespace approach will also let you > use properties (there's a handy builtin to create them from accessor methods, > or you can instantiate them from your own descriptor classes) as your > byrefs "variables" if you like. > > You just have to mane the NameSpace class inherit from object, to make it > a new-style class. Then you can add properties either right in the class definition > or later by setting class attributes , e.g., > A namespace for variables also gives you the potential to define methods for the name space > itself. Here is an example with a name space that has an internal pointer class and lets > you create "pointers" to the "variables" in the namespace, using ns[vname] syntax, which > goes to the __getitem__ method of the class to make a "pointer" (__slots__ hopefully just > makes pointer instances better optimized): > > >>> class NSP(object): > ... """NSP defines name space with "pointer" creation via p = ns[vname]""" > ... class Ptr(object): > ... """Ptr instance holds ns ref and vname for access to ns.vname""" > ... __slots__ = 'ns', 'vname' > ... def __init__(self, ns, vname): self.ns=ns; self.vname=vname > ... def __getitem__(self, i): > ... """typical: x=p[:]""" > ... return getattr(self.ns, self.vname) > ... def __setitem__(self, i, v): > ... """Typical: p[:] = x""" > ... setattr(self.ns, self.vname, v) > ... def __delitem__(self, i): > ... """Typical: del p[:] # deletes what's pointed to""" > ... delattr(self.ns, self.vname) > ... def __getitem__(self, name): > ... """Make "pointer." Typical: p2x = ns['x']; p2x[:] => ns.x""" > ... return self.Ptr(self, name) > ... > >>> ns = NSP() > >>> ns.x = 123 > >>> ns.y = 456 > >>> def change(x, py): > ... x = 'new x?' > ... py[:] = 'new via py[:]' > ... > >>> ns.x > 123 > >>> ns.y > 456 > >>> change(ns.x, ns['y']) # on the fly &y > >>> ns.x > 123 > >>> ns.y > 'new via py[:]' > >>> To my eye, the [:] or [0] spelling of this makes the code look more complex than necessary, but I think you are on to something because if you spell it, def change(x, y): x = 'new x' y.update('new y') with the relevant changes to the Ptr class then it could certainly grow on me. The things I like are, - no new variable names in the 'change' function so it looks similar to the original code - the mechanism for propogating changes to the caller scope is explicit - 'y' can be passed on to another function if needed and things are still clear eg, def change(x, y): x = 'new x' change2(y) def change2(y): y.update('deep change in y') To do this using the original namespace approach gets a little tricky because you have to merge the namespaces as you go. The pointer idea flattens that structure. > I'm not necessarily recommending any of the above, but I thought it might give you some ideas.. > There is definitely a performance hit in px[:] (or better, px[0]) vs byref.x to consider. > > Anyway, I thought properties and descriptors might also come in handy somewhere in your quest ;-) This is certainly food for thought. My main criteria is this: I don't want to translate clearly written code in an ugly language (VB) into ugly code in a clear language (Python). If this happens I might as well pack up and go home! So I will trade speed for clarity almost always because someone can always optimize clear code later. Thanks for these thoughts and the time it took to post them, they really made me think! (I mean that in a good way, of course ;) ) Paul From buzzard at urubu.freeserve.co.uk Mon Jul 14 21:28:09 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 15 Jul 2003 02:28:09 +0100 Subject: bug in my code? Message-ID: Greetings. I am struggling to track down what I presume is a bug in my code. The trouble is that it only raises its head occasionally. I have managed to prune the code to the following: shutTest.py -------------------------------------------------------- import cPickle def test2(iterations): for i in range(iterations): try: f = file('C:\\Python22\\(2, 2, 2, 3, 4).shu', 'r') try: dependencies, nodes = cPickle.load(f) finally: f.close() except IOError: pass ---------------------------------------------------------------- Calling the function with a suitable argument (say, 100) doesn't usually pose a problem. The file is opened OK and the data unpickled. But occasionally (or usually if I call the function with 1000 as argument) I get the all too common, on Windows, 'The instruction at {some memory address} referenced memory at {some other (and on one occasion the same) memory address}. The memory could not be "read".' I just tried to run the function in the interactive window and got the following traceback. Traceback (most recent call last): File "", line 1, in ? File "shutTest.py", line 9, in test2 dependencies, nodes = cPickle.load(f) cPickle.UnpicklingError: invalid load key, 'a'. where the 'a' has a grave accent over it. I'm guessing that the previous crashes have corrupted the file? Is there any reason why my code should have caused the crashes, or is this just Windows 2000? The crashes don't seem to be totally random as they always occur in this section of code. BTW I am using Python 2.2.2, and I had the crashes in PythonWin, IDLE and the interactive window. TIA. Duncan From skip at pobox.com Sun Jul 27 10:52:59 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 27 Jul 2003 09:52:59 -0500 Subject: code coverage tool with emacs integration? In-Reply-To: <87u198ree4.fsf@pobox.com> References: <87u198ree4.fsf@pobox.com> Message-ID: <16163.59211.574952.985573@montanaro.dyndns.org> John> Anybody know of one? John> Actually, I have a feeling that emacs understands a standard John> format for errors, which would make it really easy to implement John> this by having the coverage tool print results in that format -- John> anybody know where to find the details? compilation-error-regexp-alist. The simplest format to remember is filename:linenumber:message I'm not sure what you're after though. Code coverage tools generally emit annotated listings, not compiler-like output. What would you like it to do, emit file:line:msg info for the start of each run of lines which weren't covered? How would you get any context showing you what lines in the region had been executed at least once? Skip From florian.proff.schulze at gmx.net Thu Jul 17 18:53:29 2003 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Fri, 18 Jul 2003 00:53:29 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: On Fri, 18 Jul 2003 00:33:38 +0200, Martin v. Loewis wrote: > So what do you think about this message?: > > ???????? > > Look Ma, no markup. And not every character uses two bytes, either. > And I can use Umlauts (???) and Arabic (???.????) if I want to. > > I don't know for whom this renders well, but I guess MSIE5+, NS6+ > and Mozilla 1+ are good candidates - without the need for saving > things into files. And Opera (7.11). I would also like to know what's the trick. Florian From gtewalt at earthlink.net Wed Jul 2 10:42:51 2003 From: gtewalt at earthlink.net (gt) Date: 2 Jul 2003 07:42:51 -0700 Subject: Newbie advice for string fromatting Message-ID: O.k., four days into playing with python and I have a little problem that I would like to get some feedback on. ( as far as the best way to go about it ) Basically, just a little Mad-Libs type script. Something like: libs = ["adverb", "noun", "verb", "tool"] words = {a:j, n:j, v:j, t:j} for x in libs: print "Enter a ", x, ": ", words[j] = raw_input() print "The %s %s %s with a %s." % (a, n, v, t) What is the most efficient way to do something like this? From justinjohnson at fastmail.fm Wed Jul 9 08:36:28 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Wed, 09 Jul 2003 06:36:28 -0600 Subject: process.py problems In-Reply-To: <20030709123005.C0B58374AF@www.fastmail.fm> References: <20030708153117.127C0326C0@www.fastmail.fm> <20030708094057.C9520@ActiveState.com> <20030708210829.B3BBE3886D@www.fastmail.fm> <20030708170131.C13603@ActiveState.com> <20030709123005.C0B58374AF@www.fastmail.fm> Message-ID: <20030709123628.66ACA3771B@www.fastmail.fm> Never mind the part about commands hanging.... that appears to be related to something else in my code. I think your process stuff is working fine for .exe commands. :-) So just the dir command is failing now. On Wed, 09 Jul 2003 06:30:05 -0600, "Justin Johnson" said: > After replacing my process.py I still get an error with the dir command > (see below). > > I'm getting some wierd results with normal .exe commands though. > Commands that don't have much output come back just fine, but commands > that have more output, even if they don't take long to run necessarily, > seem to get stuck and just hang, never returning. > > E:\ccase\python\uhg\uht>python > ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on > Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import process > >>> p = process.ProcessOpen("dir") > process: info:ProcessOpen.__init__(cmd='dir', mode='t', cwd=None, > env=None) > process.res: info:[11054544] ProcessOpen._start(): create child stdin: > <_FileWra > pper: file:None fd:3 os_handle:> > process.res: info:[11054544] ProcessOpen._start(): create child stdout: > <_FileWr > apper: file:None fd:4 os_handle:> > process.res: info:[11054544] ProcessOpen._start(): create child stderr: > <_FileWr > apper: file:None fd:5 os_handle:> > process: debug:_whichFirstArg: first='dir', rest='' > Traceback (most recent call last): > File "", line 1, in ? > File "process.py", line 1118, in __init__ > self._startOnWindows() > File "process.py", line 1289, in _startOnWindows > cmd = _fixupCommand(cmd, self._env) > File "process.py", line 516, in _fixupCommand > cmd = _whichFirstArg(cmd, env) > File "process.py", line 325, in _whichFirstArg > candidate = which.which(first) > File "which.py", line 251, in which > raise WhichError("Could not find '%s' on the path." % command) > which.WhichError: Could not find 'dir' on the path. > >>> > > >>> p = process.ProcessOpen("cleartool lsvob -l") > process: info:ProcessOpen.__init__(cmd='cleartool lsvob -l', mode='t', > cwd=None, > env=None) > process.res: info:[18469440] ProcessOpen._start(): create child stdin: > <_FileWra > pper: file:None fd:3 os_handle:> > process.res: info:[18469440] ProcessOpen._start(): create child stdout: > <_FileWr > apper: file:None fd:4 os_handle:> > process.res: info:[18469440] ProcessOpen._start(): create child stderr: > <_FileWr > apper: file:None fd:5 os_handle:> > process: debug:_whichFirstArg: first='cleartool', rest='lsvob -l' > process: debug:_SaferCreateProcess(appName=None, > cmd='"C:\\Program > Files\\Rational\\ClearCase\\bin\\cleartool > .EXE" lsvob -l', > env=None, > cwd=None) > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > process: info:_registerprocess(process= 0x0119D2 > 40>) > ***** It doesn't return here ***** > > > On Tue, 8 Jul 2003 17:01:32 -0700, "Trent Mick" > said: > > > > Yup, process.py is expected a which.py <1.0. Crappy. I need to put up a > > new process.py. To work around in it in your current build you need to > > changes process.py's usages of which.which() to expect a single hit > > instead of a list of a all hits. In other words, which.which() changed > > from: > > >>> which.which("python") > > ["C:\\Python22\\python.exe", "C:\\Python21\\python.exe", ...] > > to: > > >>> which.which("python") > > "C:\\Python22\\python.exe" > > > > This is a little bit of a pain to do though. I have attached an untested > > process.py that should have this fixed. I apologize for the informalness > > of this. I'll try to get a new process.py version up on > > when I get a chance. > > > > Cheers, > > Trent > > > > > > [Justin Johnson wrote] > > > Thanks for the reply! > > > > > > which 1.0.2 > > > > > > Here's the log output with the dir command > > > ----------------------- > > > process.res: info:[18392288] ProcessOpen._start(): create child stdin: > > > <_FileWra > > > pper: file:None fd:3 os_handle:> > > > process.res: info:[18392288] ProcessOpen._start(): create child stdout: > > > <_FileWr > > > apper: file:None fd:4 os_handle:> > > > process.res: info:[18392288] ProcessOpen._start(): create child stderr: > > > <_FileWr > > > apper: file:None fd:5 os_handle:> > > > process.res: info:[18392288] ProcessOpen.__del__() > > > process: info:[18392288] ProcessOpen.close() > > > process: info:[18392288] ProcessOpen: closing stdin (<_FileWrapper: > > > file:None fd > > > :3 os_handle:>). > > > process: debug:[18400496] _FileWrapper.close() > > > process: debug:[18400496] _FileWrapper.close: close handle > > > process: debug:[18400496] _FileWrapper.close: closing handle raised > > > process: debug:[18400496] _FileWrapper.close: done closing handle > > > process: info:[18392288] ProcessOpen: closing stdout (<_FileWrapper: > > > file:None f > > > d:4 os_handle:>). > > > process: debug:[18400720] _FileWrapper.close() > > > process: debug:[18400720] _FileWrapper.close: close handle > > > process: debug:[18400720] _FileWrapper.close: closing handle raised > > > process: debug:[18400720] _FileWrapper.close: done closing handle > > > process: info:[18392288] ProcessOpen: closing stderr (<_FileWrapper: > > > file:None f > > > d:5 os_handle:>). > > > process: debug:[18403024] _FileWrapper.close() > > > process: debug:[18403024] _FileWrapper.close: close handle > > > process: debug:[18403024] _FileWrapper.close: closing handle raised > > > process: debug:[18403024] _FileWrapper.close: done closing handle > > > process: debug:[18400720] _FileWrapper.close() > > > process: debug:[18400496] _FileWrapper.close() > > > process: debug:[18403024] _FileWrapper.close() > > > ---------------- > > > > > > I also get the following results running commands that are in my path... > > > ------------------ > > > g`"apper: file:None fd:5 os_handle:> > > > process: debug:_SaferCreateProcess(appName=None, > > > cmd='C lsview -s', > > > env=None, > > > cwd=None) > > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > > > process.res: info:[18680944] ProcessOpen.__del__() > > > process: info:[18680944] ProcessOpen.close() > > > process: info:[18680944] ProcessOpen: closing stdin (<_FileWrapper: > > > file:None fd > > > :3 os_handle:>). > > > process: debug:[18696880] _FileWrapper.close() > > > process: debug:[18696880] _FileWrapper.close: close handle > > > process: debug:[18696880] _FileWrapper.close: closing handle raised > > > process: debug:[18696880] _FileWrapper.close: done closing handle > > > process: info:[18680944] ProcessOpen: closing stdout (<_FileWrapper: > > > file:None f > > > d:4 os_handle:>). > > > process: debug:[18696832] _FileWrapper.close() > > > process: debug:[18696832] _FileWrapper.close: close handle > > > process: debug:[18696832] _FileWrapper.close: closing handle raised > > > process: debug:[18696832] _FileWrapper.close: done closing handle > > > process: info:[18680944] ProcessOpen: closing stderr (<_FileWrapper: > > > file:None f > > > d:5 os_handle:>). > > > process: debug:[18699984] _FileWrapper.close() > > > process: debug:[18699984] _FileWrapper.close: close handle > > > process: debug:[18699984] _FileWrapper.close: closing handle raised > > > process: debug:[18699984] _FileWrapper.close: done closing handle > > > process: debug:[18696832] _FileWrapper.close() > > > process: debug:[18696880] _FileWrapper.close() > > > process: debug:[18699984] _FileWrapper.close() > > > --------- > > > > > > > > > > -- > > Trent Mick > > TrentM at ActiveState.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From http Mon Jul 21 11:52:10 2003 From: http (Paul Rubin) Date: 21 Jul 2003 08:52:10 -0700 Subject: "Pure Python" MySQL module like Net::MySQL References: <7xk7advy4c.fsf@ruckus.brouhaha.com> <87fzl0q82k.fsf@pobox.com> Message-ID: <7xy8yr3mj9.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > In any case, MySQL *isn't* in the same league as Oracle or PostgreSQL, > is it? You and I might not think so, but MySQL Corp's marketroids like to say that it is. Therefore you'd think they'd document the wire protocol. Although, it's possible that Oracle and PostgreSQL also don't document their own protocols. But that would just mean Oracle and PostgreSQL aren't really high-class databases either ;-). From ulope at gmx.de Tue Jul 8 17:57:29 2003 From: ulope at gmx.de (Ulrich Petri) Date: Tue, 8 Jul 2003 23:57:29 +0200 Subject: doublequotes in regexp 1.5.2 - zope/externalmethod References: Message-ID: "Florian Konnertz" schrieb im Newsbeitrag news:bed11r$ssr$05$1 at news.t-online.com... > Hi, > > I have to do a little script for an old zope website running on > python1.5.2 and have a regexp problem. > > (for those who know zope: I have to change all stx links in a dtml doc > to html which is not done for any reason. It's an old zope (2.3.2) :( > python is 1.5.2 I tried with string.find, but i get a "string object > has no atribute 'find'" error - find is documented for python-1.5.2 :-/ > So i guesses i have to use an External Method where i can use re.) > In python 1.5.2 you have to use: import string s="blah pattern blah" pos = string.find(s, "pattern") for Zope this would be: HTH Ciao Ulrich From bokr at oz.net Wed Jul 2 05:04:13 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Jul 2003 09:04:13 GMT Subject: Howto: extract a 'column' from a list of lists into a new list? References: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Message-ID: On Tue, 01 Jul 2003 20:07:58 -0500, John Hunter wrote: >>>>>> "Bengt" == Bengt Richter writes: > > >>>> zip(*fields) > >That is amazingly helpful. I've often needed to transpose a 2d list, >(mainly to get a "column" from an SQL query of a list of rows) and >this is just the trick. > >I recently wrote a function to "deal" out a list of MySQLdb results, >where each field was a numeric type, and wanted to fill numeric arrays >with each column of results > >With your trick, eg, for a list of results from three numeric fields, >I just have to do: > > a1, a2, a3 = map(array, zip(*results)) > That looks neat. But it isn't really "my" trick (whatever that means ;-). Anyway, IIRC, I learned it from a Martellibot post some time back ;-) Regards, Bengt Richter From peter at engcorp.com Tue Jul 15 10:18:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 10:18:59 -0400 Subject: Sio serial module install problem with ActiveState References: Message-ID: <3F140D53.DC7677B3@engcorp.com> Gary Richardson wrote: > > [snip] > > > BTW, this serial printer is apparently pretty much a 'dump > > and go' type device - the only thing the printer seems to > > be capable of returning is a 4-byte error code after a special > > error report command is sent to the printer - other than that, > > all of the data and commands seem to move downstream only, > > with no return from the printer expected. Is Sio overkill for > > this, i.e. is there some incredibly simple "open a serial port > > under Win32 for write only" command I'm missing in the basic > > Python stuff? > > I've written a pretty simple serial I/O module that will do what you want. > Email me directly if you would like a copy. The benefit of the PySerial library is that it's cross-platform, available without emailing you, fully documented, and most important of all: if you find problems, you can fix them and everyone else benefits. Maybe you can contribute those parts of your own library which are better than PySerial to the PySerial project and we can avoid a proliferation of serial libraries in Python. Or put the file on a web page somewhere and we can all poke away at it, learn from it, and maybe incorporate the best parts into PySerial. -Peter From bokr at oz.net Mon Jul 28 11:06:25 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 15:06:25 GMT Subject: CGI "download" prompt? References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> <77dd287a.0307250619.7c2ec441@posting.google.com> Message-ID: On Fri, 25 Jul 2003 16:45:19 +0200, =?ISO-8859-1?Q?Gerhard_H=E4ring?= wrote: >Daniel Orner wrote: >>>Try setting the Content-Type: header to something other than text/html, >>>such as: application/octet-stream [...] > >Erhm. Let's suppose you want to send an RTF file and have the browser >pop up a save dialog with a certain filename preconfigured: > >Then send these headers: > >Content-Type: application/rtf >Content-Disposition: attachment; filename=mydocument.rtf > I wonder if an ordinary HTML page with a link to a second HTML page could be changed to have a javascript link in the first that would effectively prefix Content-Disposition on the second page without changing the latter. Wondering if you'd tried it, and found a way that avoids downloading into an array before the save-as dialog comes up (I am just speculating that might be part of one way it could be done). Regards, Bengt Richter From alan.gauld at btinternet.com Tue Jul 22 02:49:15 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Jul 2003 06:49:15 GMT Subject: good python book References: <3f1cbbda_6@news.athenanews.com> Message-ID: <3f1cdce3.516224491@news.blueyonder.co.uk> On 22 Jul 2003 00:21:46 -0400, anonymous at coolgroups.com wrote: > i'm looking to start learning python. could someone > recommend a good beginner's book for me? Depends. Are you new to programming or just new to the Python language? If the latter you should just use the official tutor that comes with Python and save your money for one of the more advanced books and/or references. If you are a complete beginner there are lots of online tutors but only a couple of books. 1) Ivan Van Lanningham's "Teach Yourself Python in 24 Hours" 2) The Deitel's "Python How to Program" 2) My "Learn to Program using Python" The focus of each is slightly different. Check out the newbies page on the Python web site for more info. I'd recommend trying a web tutor first then buying something like Learning Python or Core Python... HTH, Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From peter at engcorp.com Wed Jul 23 08:59:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jul 2003 08:59:52 -0400 Subject: [OT] RE: Possible use of Python for a voting machine demo project -- your feedback requested References: <1ED4ECF91CDED24C8D012BCF2B034F13026F8E3D@its-xchg4.massey.ac.nz> <1ED4ECF91CDED24C8D012BCF2B034F130212AB7C@its-xchg4.massey.ac.nz> Message-ID: <3F1E86C8.1631855C@engcorp.com> Andrew Dalke wrote: > > Skip Montanaro: > > Stranger things have happened here... > > For example, here in New Mexico, in Southwest US, if there is a tie in > an election then it's broken by a game of chance, like poker or dice. > Every few years there's a tie for a local election which is resolved this > way. > > Were electronic voting pushed even more, would that mean we > would end up resolving it with video poker? I hope not. There's > something visceral about the two candidates, meeting in front of > the county courthouse, at noon, mumuring "draw", and playing a > game of Hi-Low. ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ "Draw", in reference to the aforementioned tie vote, of course. ;-) From postmaster at 127.0.0.1 Wed Jul 16 08:46:05 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Thu, 17 Jul 2003 00:46:05 +1200 Subject: tkinter References: <3114992.1058316065@dbforums.com> Message-ID: On Wed, 16 Jul 2003 00:41:05 +0000, sprmn paused, took a deep breath, then came out with: > > does anyone know of any sites with good tutorials on tkinter on them? http://www.astro.washington.edu/owen/TkinterSummary.html http://www.pythonware.com/library/tkinter/introduction/index.htm http://www.astro.washington.edu/owen/ROTKFolklore.html On the strength of the above 3 links, I switched from wxWindows to tkInter. In contrast with a lot of Tkinter doco which pushes you into learning Tk, these pages explain Tkinter in a very pythonic manner and make it very accessible. Enjoy! From ebolonev at rol.ru Tue Jul 1 11:27:02 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Wed, 2 Jul 2003 02:27:02 +1100 Subject: remove special characters from line References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Message-ID: Hello, Chris! You wrote on Tue, 1 Jul 2003 10:03:37 -0500: CR> If I have a line like this CR> ?blah blah blah blah blah CR> I know I could do a slice like this [1:] to pull everything but the CR> special character, but what if I have several lines in a file. CR> I am not sure how I would detect a special character like that. I CR> would just like to pull everything from those lines (and the special CR> character always appears as the first character, but not on every line) CR> except for the special characters. CR> I hope I have enough detail for someone to help me. CR> Thanks in advance, I didn't get what you're talkink about. With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From aahz at pythoncraft.com Wed Jul 30 18:40:30 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Jul 2003 18:40:30 -0400 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> Message-ID: In article , John Machin wrote: > >So ... could we please change that to "much kudos"? Nope. Kudos is a mass noun, but it's a discrete mass noun. So you need to say "many kudos". This bit of pedantry is brought to you by "much kudo about nothing". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From dlarnold at west.com Wed Jul 16 16:02:15 2003 From: dlarnold at west.com (Don Arnold) Date: 16 Jul 2003 13:02:15 -0700 Subject: <> and != References: <3F154B63.3060503@hotmail.com> <3F154BBD.2060304@hotmail.com> <3jlahv8o1fcu2j0oij2p31c32nftnb3er8@4ax.com> <3F155B6D.8000205@hotmail.com> Message-ID: <609dd410.0307161202.32e47c3e@posting.google.com> Duncan Booth wrote in message news:... > hokiegal99 wrote in > news:3F155B6D.8000205 at hotmail.com: > > > Thank you, that is what I thought. What's the reason for having two > > symbols mean the same thing? > > > Originally Python only had '<>' for the not-equal comparison. Version 0.9.3 > added a bunch of C like syntax, such as C's shifting and masking operators. > It also added C style '==' and '!=' comparison operators. The original '<>' > remains valid for backwards compatibility. Out of curiosity, what was the original operator for the equality comparison? From Scott.Daniels at Acm.Org Fri Jul 25 09:34:01 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 25 Jul 2003 06:34:01 -0700 Subject: possible error in socketmodule / asyncore on win32 In-Reply-To: References: Message-ID: <3f2131ca$1@nntp0.pdx.net> Garth wrote: ... What looks at first glance like a good bug report.... > > Not really sure where to report this so I'm posting here. > > This is all against 2.3c1 > > (Cheers to all for a wicked language.) > > Garth > The way to help out is to go through the hassle of filing a bug report on SourceForge: Either go to http://www.python.org and click to bugs (Special Topics has: Beginners_Guide Topic_Guides Python_Project: _bugs_, _patches_, ....) If you are feeling terribly confident that you know the exact fix, you could click on patches instead. The bugs link is here: http://sourceforge.net/tracker/?group_id=5470&atid=105470 The pain is that you will need a SourceForge ID to submit a bug or patch, but the process of getting one is not really horrid. CLick on the please log in part and do the dance. They don't generate much trash mail as far as I can tell. Now posting a good email address in comp.lang...., that can get you reams. -Scott David Daniels Scott.Daniels at Acm.Org From staschuk at telusplanet.net Mon Jul 21 21:10:58 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 21 Jul 2003 19:10:58 -0600 Subject: UserDict -> dict, reasons for migrating existing code In-Reply-To: ; from andreas.kuntzagk@mdc-berlin.de on Mon, Jul 21, 2003 at 11:02:52AM +0200 References: Message-ID: <20030721191058.B1960@tibia.amotlpaa.bogus> Quoth Andreas Kuntzagk: [...] > what would be the reasons to migrate existing code from the use of > UserDict() to dict()? (UserString ...) What would be reasons against? > Reasons I can think of: > pro: > - Speed Improvement because of a level of indirection less > - UserDict can become deprecated > > con: > - Code not working whith older python > - cost of migrating large codebase > > Do you know other reasons? I think there are still some issues with subclassing the built-in types, but I've no idea what they are. (Hopefully somebody more knowledgeable will comment.) Your thought that a dict subclass might be faster than a UserDict subclass is plausible, but I'd strongly suggest doing some timing experiments before doing any large migration under that assumption. Otherwise, I think you've said everything. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From tismer at tismer.com Wed Jul 2 12:08:18 2003 From: tismer at tismer.com (Christian Tismer) Date: Wed, 02 Jul 2003 18:08:18 +0200 Subject: My Big Dict. In-Reply-To: <94974e1a.0307020532.1cb19956@posting.google.com> References: <20030702073735.40293ba2.christophe.delord@free.fr> <94974e1a.0307020532.1cb19956@posting.google.com> Message-ID: <3F030372.10804@tismer.com> Paul Simmonds wrote: ... I'm not trying to intrude this thread, but was just struck by the list comprehension below, so this is about readability. > If this is a problem, use a combination of count and index methods to > find the first, and use slices. For example, if you don't mind > two-lined list comps: > > d=dict([(l[:l.index('!')],l[l.index('!')+1:-1])\ > for l in file('test.txt') if l.count('!')]) With every respect, this looks pretty much like another P-language. The pure existance of list comprehensions does not try to force you to use it everywhere :-) ... compared to this: ... > d={} > for l in file("test.txt"): > try: i=l.index('!') > except ValueError: continue > d[l[:i]]=l[i+1:] which is both faster in this case and easier to read. About speed: I'm not sure with the current Python version, but it might be worth trying to go without the exception: d={} for l in file("test.txt"): i=l.find('!') if i >= 0: d[l[:i]]=l[i+1:] and then you might even consider to split on the first "!", but I didn't do any timings: d={} for l in file("test.txt"): try: key, value = l.split("!", 1) except ValueError: continue d[key] = value cheers -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From duncan at NOSPAMrcp.co.uk Fri Jul 18 10:57:35 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 18 Jul 2003 14:57:35 +0000 (UTC) Subject: Co-routines References: Message-ID: wrote in news:g7xRa.305$fF.9914 at nnrp1.ozemail.com.au: > I have an application in which I want the users to be able to create > python functions: > > def f1(): > print "1-1" > print "1-2" > print "1-3" > > def f2(): > print "2-1" > print "2-2" > print "3-3" > > and when my application runs, I want to execute these functions in > "lock-step", so that the output looks like: > > 1-1 > 2-2 > 1-2 > 2-2 > 1-3 > 2-3 Does this do what you want? Given an input string: SOURCE = """\ def f1(): print "1-1" for ch in ('a', 'b', 'c'): print "1-2",ch print "1-3" def f2(): print "2-1" print "2-2" print "2-3" """ it produces: 1-1 2-1 1-2 a 2-2 1-2 b 2-3 1-2 c 1-3 N.B. It executes all top-level functions in the input, interleaving statements. If a function calls another function, the called function will be executed at full speed. A function could call another function 'line at a time' by wrapping it's generator in for loop, but it would have to be explicit. ----- begin steplock.py ----- # Execute functions in steplock import symbol, token from symbol import * from token import * import parser import compiler import types class Atom: def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def pretty(astList): res = [] el = astList[0] if el in symbol.sym_name: res.append(Atom(symbol.sym_name[el])) elif el in token.tok_name: res.append(Atom(token.tok_name[el])) else: res.append(el) for el in astList[1:]: if isinstance(el, (list, tuple)): res.append(pretty(el)) else: res.append(el) return type(astList)(res) def printAst(ast, depth=2): if not isinstance(ast, (list, tuple)): ast = ast.tolist() import pprint pp = pprint.PrettyPrinter(depth=depth) pp.pprint(pretty(ast)) class TreeWalker: def __init__(self): pass def dovisit(self, node): t = node[0] nodetype = "default" if t in symbol.sym_name: nodetype = sym_name[t] elif t in token.tok_name: nodetype = tok_name[t] fname = "visit_" + nodetype if hasattr(self, fname): return getattr(self, fname)(node) return self.visit_default(node) def visit_default(self, node): # Visit an otherwise boring node. res = [ node[0] ] for child in node[1:]: if isinstance(child, (list, tuple)): res.append(self.dovisit(child)) else: res.append(child) return tuple(res) class TopWalker(TreeWalker): def __init__(self): self.generators = [] def visit_file_input(self, node): newnodes = self.visit_default(node) assert newnodes[-1][0] == 0 and newnodes[-2][0] == 4 newnodes = newnodes[:-2] + tuple(self.generators) + newnodes[-2:] return newnodes #def visit_stmt(self, node): # printAst(node, depth=255) # return self.visit_default(node) def visit_funcdef(self, node): self.generators.extend(MakeGenerator(node)) return node YIELD_STMT = (stmt, (simple_stmt, (small_stmt, (flow_stmt, (yield_stmt, (NAME, 'yield'), (testlist, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, (power, (atom, (NAME, 'None')))))))))))))))))), (NEWLINE, '') )) def MakeGenerator(funcdefnode): funcname = funcdefnode[2][1] newfuncname = funcname + '_generator' suite = funcdefnode[-1] walker = FunctionWalker() newsuite = walker.dovisit(suite) NewFunc = (funcdef, (NAME, 'def'), (NAME, newfuncname)) + funcdefnode[3:-1] + (newsuite,) NewFunc_stmt = (stmt, (compound_stmt, NewFunc)) #return (NewFunc_stmt, ) ASSIGN_stmt = (stmt, (simple_stmt, (small_stmt, (expr_stmt, (testlist, (symbol.test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr,(term, (factor, (power, (atom, (NAME, funcname)), (trailer, (DOT, '.'), (NAME, 'generator'))))))))))))))), (EQUAL, '='), (testlist, (symbol.test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr,(term, (factor, (power, (atom, (NAME, newfuncname))))))))))))))))), (NEWLINE, ''))) DEL_stmt = (stmt, (simple_stmt, (small_stmt, (del_stmt, (NAME, 'del'), (exprlist, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, (power, (atom, (NAME, newfuncname))))))))))))), (NEWLINE, ''))) return (NewFunc_stmt, ASSIGN_stmt, DEL_stmt) class FunctionWalker(TreeWalker): def visit_funcdef(self, node): return node # Ignore nested functions! def visit_suite(self, node): #print "Visiting suite of %d children" % (len(node)-1) res = [ node[0] ] for el in node[1:]: if el[0] == stmt: if el[1][0] == compound_stmt: res.append(self.dovisit(el)) else: res.append(el) res.append(YIELD_STMT) else: res.append(el) return tuple(res) def test(): SOURCE = """\ def f1(): print "1-1" for ch in ('a', 'b', 'c'): print "1-2",ch print "1-3" def f2(): print "2-1" print "2-2" print "2-3" """ ast = parser.suite(SOURCE) astList = ast.totuple(1) walker = TopWalker() newList = walker.dovisit(astList) code = parser.sequence2ast(newList) namespace = { '__builtins__': __builtins__ } exec code.compile('dummy.py') in namespace functions = [ namespace[key].generator() for key in namespace if isinstance(namespace[key], types.FunctionType) ] while functions: for f in functions[:]: try: f.next() except StopIteration: functions.remove(f) if __name__=='__main__': test() ----- end steplock.py ----- -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gh at ghaering.de Fri Jul 18 05:51:18 2003 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Fri, 18 Jul 2003 11:51:18 +0200 Subject: Unicode question In-Reply-To: <3F17C0C3.6040309@ghaering.de> References: <65m1yubd.fsf@python.net> <3F17C0C3.6040309@ghaering.de> Message-ID: <3F17C316.3060702@ghaering.de> Gerhard H?ring wrote: > Ricardo Bugalho wrote: >> On Fri, 18 Jul 2003 02:07:13 +0200, Gerhard H?ring wrote: >> >>>> Gerhard H?ring writes: >>>> >>>>>>>> u"???" >>>>> >>>>> u'\x84\x94\x81' >>>>> [this works, but IMO shouldn't] > [...] > You'll get warnings if you don't define an encoding (either encoding > cookie or BOM) and use 8-Bit characters in your source files. These > warnings will becomome errors in later Python versions. > > It's all in the PEP :) I feel like an idiot now :-( I do get the warnings when I run a Python script, but I do not get the warnings when I'm using the interactive prompt. So it's all good (almost). Why not also produce warnings at the interactive prompt? -- Gerhard From bignose-hates-spam at and-benfinney-does-too.id.au Fri Jul 25 01:40:53 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 Jul 2003 15:30:53 +0950 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> Message-ID: On 25 Jul 2003 07:18:15 +0200, Martin v. L?wis wrote: > rimbalaya at yahoo.com (Rim) writes: >> So what problem is the new.instancemethod() trying to solve? > > It has no side effects on the class it is an instancemethod of. So what side effects (i.e. what problem) is the new.instancemethod() trying to solve? -- \ "I spent a lot of money on wine and women, and like a fool I | `\ squandered the rest." -- Benny Hill | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From tim at lesher.ws Wed Jul 9 14:00:53 2003 From: tim at lesher.ws (Tim Lesher) Date: 9 Jul 2003 11:00:53 -0700 Subject: Detecting user activity in Python References: Message-ID: Stefan Behrens wrote in message news:... > I rather doubt that such functionality is in Python itself, i.e. > can be used platform independently. So in that case, has anyone > examples of how to do that in native C++ for Windows and Linux? For native windows, you can install a systemwide mouse hook and a systemwide keyboard hook (in a .DLL). When you receive a mouse or keyboard message, reset a timer, then pass it to the next hook in the chain. You can get more information (and samples) from msdn.microsoft.com. From claird at lairds.com Sat Jul 19 23:06:12 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 20 Jul 2003 03:06:12 -0000 Subject: Calling tcl from python and viceversa References: <453d10b2.0307190828.3c576f15@posting.google.com> Message-ID: In article , dan wrote: >funny -- first look at the board and it's right on subject. > >I'm trying to write an app that does some cool stuff with sound >samples, using tkSnack. But I'm stuck on a simple question -- how do >I insert some of my own code into the tkInter mainloop? I need the >sequencer to run in the background while the UI is up. > >Forgetting about snack for the moment, how do I run _any_ >non-event-driven code while my Tk widgets are active? (for instance, >animation in one window while menus are still available). I can't >find any demos that show this sort of behavior. > >All the Tk examples I've seen set up the widgets and run >root.mainloop(). I can't for the life of me figure out what code this >call invokes, but it won't return until a quit command or some such >action is initiated by the user. TCL docs say that Tk_mainloop calls >tcl_DoOneEvent() in a dead loop until a quit flag is set, or something >like that. > >My best guess is that I'm supposed to set up another thread to do my >stuff, and send messages to the Tkinter thread that trigger Tk events, >or something like that. But the Tkinter docs are so sketchy I can't >really get a handle on how to do it. Any help or pointers would be >appreciated. . . . In Tcl-think, one just lives with the "dead loop". There is no "non-event-driven code". Tcl-ers go about as far as anyone with this model. "[A]nimation in one window while menus are still available"? The conventional Tcl response is, "make the animation event-driven". I know how unaes- thetic that will seem to most readers; study for its full, native expression. Tcl has added thread support over the last few years--but not in the standard distribution. I've never seen a Tkinter over a threading Tcl; I don't know how well it works. Maybe it's just what you're after. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From mwh at python.net Thu Jul 31 06:51:11 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 31 Jul 2003 10:51:11 GMT Subject: Exceptions as New Style Classes References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: <7h3fzknas1w.fsf@pc150.maths.bris.ac.uk> Steven Taschuk writes: > Quoth Andrew: > > To satisfy my curiosity I was wondering if anyone knew if this > > behaviour was intentional? > > Is there a specific reason why exceptions are not allowed to be new > > style classes? > > It is intentional. > > There are two difficulties with allowing new-style classes as > exception types. Ideas exist for dealing with them, but at the > moment none of them as been implemented. They have, in PyPy! (which doesn't do old-style classes at all, at present). IIUC, Guido thought what PyPy does would be sensible enough for CPython, but I don't know what the timeframe might be. Cheers, mwh -- This is not to say C++ = bad, Lisp = good. It's to say C++ = bad irrespective of everything else. -- Alain Picard, comp.lang.lisp From maxm at mxm.dk Thu Jul 10 06:23:06 2003 From: maxm at mxm.dk (Max M) Date: Thu, 10 Jul 2003 12:23:06 +0200 Subject: Python vs PHP In-Reply-To: References: <3F0D2827.4070501@mxm.dk> Message-ID: <3F0D3E8A.3080204@mxm.dk> Ganesan R wrote: >>>>>>"Max" == Max M writes: > >>>Python web development is fragmented. > >>Ahem ... How os Python web development fragmented? Most of it probably >>takes place in the Zope world. > > > How about the fact if you want something simpler than Zope you cannot point > to a single framework and say use this one? That's right. But without a framework, you are about on par with PHP. Only with a better language and better libraries. regards Max M From dmbkiwi at yahoo.com Fri Jul 11 22:27:33 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sat, 12 Jul 2003 14:27:33 +1200 Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 01:58:13 +0000, Bengt Richter wrote: > On Sat, 12 Jul 2003 11:16:12 +1200, dmbkiwi wrote: > >>On Fri, 11 Jul 2003 20:33:19 +0000, Bengt Richter wrote: >> >>> On Sat, 12 Jul 2003 07:34:18 +1200, dmbkiwi wrote: >>> >> >> >>Thanks for helping me with this. >> >> >>>>def meterClicked(widget, meter, button): >>>> #print "meterclick" >>>> global dayshow, daypicrem, ddon, ddcon, buttonpressed >>> # these globals -- where do they come from? What module? # Note that each >>> module has its own globals, so is are there different modules # that think >>> they're sharing globals but really aren't? There are ways to solve that, # >>> but first, is that relevant? >> >>They don't come from a module, they come from different functions within >>the script. To be honest, I don't think I've ever quite understood >>globals, so I insert them where I think they should go - probably quite >>incorrecly. Will this matter? > It could. It depends. A script or a file (extension may vary, .py, .pyc, etc) that's imported > is like a big room with a single cork bulletin board. Think of that bulletin board as > the script's or module's global name space. It's where name tags can be tacked up with names > associated with objects. You can think of the objects themselves as balloons attached to > the name tags by strings (the houses have no roofs, so all the balloons occupy space > someplace high up outside ;-) > > Note that according to this model, when you assign x=y what you > are doing is finding the y-labled tag and following its string to the associated object-balloon > and tying a new string to that same balloon, and then attaching that new string to a > new tag labeled x and tacking this new tag on an appropriate bulletin board, resulting in > two tags and their strings leading to the same object-balloon. > > Functions are like play houses inside the big room, and they each have their own > bulletin boards inside, which is each function's local namespace. > > If you write "global xxx" inside a function, you are saying that when you are in that > playhouse, you will not use the inside private bulletin board for name tags labeled xxx, > but you will instead reach out and use the bulletin board in the big room. So xxx=123 > means create an integer object-balloon with 123 value and make a tag labeled xxx and > tie a string from the 123 balloon to that tag, and then reach out and tack the tag to the > bulletin board in the big room. > > When you leave the playhouse, its inside bulletin board is cleared of name tags (and the > strings detached). When you enter again, you start with a clean inside board with only > name tags matching the formal parameter names (if any). If the last string is detached, > it is grabbed by a balloon collector, who pops it to make sure there is always space in > the sky for new balloons. Kind of ;-) > > If you don't write "global xxx" inside the function, the rules for name tags labeled > xxx are different according to whether there's any code _anywhere_ in the function > that tacks up that name tag (e.g., assigns to that name) or whether the code just > looks for an existing tag (i.e., just uses it in an expression). > > If there's an assignment anywhere, it's an error to try to use it in an expression > before the assignment. A legal assignment tacks the tag to the inside bulletin board. > The balloon and string part is the same story wherever the tag goes. > > If there's no assignment, then the only other ordinary way it can be on the inside bb > is if it is a parameter name, or it got tacked there by some other code that tacks name tags, > like def foo... will make a foo name tag (the string goes to a function object), or class Bar... > which would make a Bar name tag with string to a class object. Those are the main ways. > > If the name tag is not on the inside bb, it could still be on an enclosing playhouse's > bulletin board (it is now possible to nest playhouses, not just have them all in the big room. > If the name tag is not found on the bb of the immediately enclosing playhouse, it could be on > the bb of yet another enclosing playhouse, and so on, until if it is not found on the bb of > the big common room, it's a name error. > > BTW, the name-tag end of strings can also be tied to some balloons, which may have special > eyelets taped to them. E.g., tuple-balloons come in variations according to how many fixed > eyelets they have for attaching strings to other balloons. In the case of tuples, the eyelets > are single-use. You can't cut and re-tie a single string, you have to make a new tuple-balloon > and tie what strings you want there. If you cut the last string to a tuple-balloon, the > baloon collector will grab it and eventually cut all the strings and pop the tuple-balloon, > maybe right away. He may have secret deals with balloon makers for recycling material, but > that's his business. List-ballons allow eyelet re-use, and also adding or removing eyelets. > But every eyelet must have a string leading to some balloon, even if it is the None balloon. > Crikey, thanks for putting in the time to explain that. >> >>> >>> # Second, are the globals accessible from multiple threads? Are you seeing >>> hard-stuck errors or blue-moon errors? >> >>Now my newbiness will be evident. Multiple threads? I am not consciously >>creating threads. Should I? Does python automatically create multiple >>threads? What are hard-stuck/blue-moon errors? > You shouldn't have multiple threads unless you made them on purpose or used some > module that did it without your knowing. It should be prominent in the docs if so, though. > Hard-stuck/blue-moon is not technical terminology ;-) I meant, do you get the error > every time the code is executed, or only once in a blue moon. Hard-stuck (as far as I know). >> >>> >>>> if (meter == mainpic) and (button == 1): >>> # always here? >> # yes >>>> if ddcon == 0: >>> # and here ? >> # yes >>>> if ddon == 1: >>> # and here? >> # no > # so at least one if didn't just 'fall through'! >>>> deleteDayDetail(widget, dayshow) >>>> karamba.redrawWidget(widget) >>>> createCurrentDetail(widget) >>>> karamba.redrawWidget(widget) >>>> else: >>> # never here, you're saying, right? >> # always here > # very very weird. What evidence are you interpreting to come to these conclusions? I've put print statements in the script to ensure the script is doing what I think it's doing. These were removed for the purpose of posting to this group. >>> # >>>> else: >>> # never here either, right? >> always here > # again weird**n That's why I'm here. >>> # >>> # get here though? >> # yes >>>> buttonpressed = 1 >>>> > If that is really happening, I wonder if you are somehow executing code from a different version > or have some kind of mixed-up installation. Or are using incompatible extension modules? > Do you have multiple versions installed? what are your versions, and what sym links are there? > And what are the #! lines of your script(s)? One point that I may not have made clear is that I'm not experiencing this behaviour personally with my set up. It is other people using this script who are reporting this behaviour. The difficulty I'm having is that it's very hard to debug a problem you're not having. I've sent versions of the script to these people, with print statements at appropriate points to ensure that the script is doing what I think it's doing (in terms of going wrong for them), and from the output they send back, the interpreter is definitely ignoring the else statement and ploughing through them, even though, it's also executed the corresponding if statement. >>> I used tabs above to line up (maybe ;-) with your text, but maybe you >>> should run your code through tabnanny or something to check for consistent >>> usage. I never use tabs (though I use the tab key and gvim puts in 4 space >> >>Tabs seem to be fine in the actual code - I think it's the word wrapping >>in either your/my newsreader that is causing problems, but your tab >>positioning is correct. >> >>> indentation for me ;-) so I haven't used the tab checkers, but you might >>> benefit, perhaps. >> >>I'm using kate here under KDE/linux. It has syntax highlighting for python, and >>seems to deal with tabs nicely. >>> >>>>What these users are experiencing is that this portion of code is being >>>>processed, and evaluating all if statements as true, however, as you can >>>>see, they cannot all be true each time this function is called. Their >>>>versions of python also ignore the else construct. >>>> > Their versions? Does that mean you are trying to run extensions or .pyc code > with different version interpreters? That shouldn't work. Python source (.py) > should work, unless an old interpreter runs into a new feature it doesn't know about. See above. "Their version" means the user's version, not my version, or multiple versions. > >>>>Can anyone shed any light on what might be going on with these users? >>>> >>> I'd check on the globals and threading issues first. Then see about >>> building a mousetrap. >> >>Why would these affect the interpretation of the if/else. Seems to me, >>that if the if statement evaluates to true, then the else statement should be >>ignored. However, it appears that for these users, python is just > Sure, I didn't really believe what I was reading, I guess. Sorry. I thought > the condition data was getting clobbered, not the condition machinery. > >>ploughing right on through, and running the else statement also. Or am I >>missing something. What is a mousetrap? > By mousetrap I meant some test code inserted to trap the problem mouse, metaphorically speaking. > >> >>Any further help would be greatly appreciated. > I guess version clash or some installation corruption looks most likely from here. > Gotta go... > > Regards, > Bengt Richter Thanks anyway. IF you have any other thoughts, let me know. -- Regards Matt Suffering alone exists, none who suffer; The deed there is, but no doer thereof; Nirvana is, but no one is seeking it; The Path there is, but none who travel it. -- "Buddhist Symbolism", Symbols and Values From webmaster at fordweb.ca Wed Jul 23 15:04:24 2003 From: webmaster at fordweb.ca (HostDomains.ca- A Division of FordWeb.Inc) Date: Wed, 23 Jul 2003 13:04:24 -0600 Subject: help... Message-ID: <000a01c3514d$3bbed680$6c00a8c0@ab.hsia.telus.net> we get the following error message when we try to login to our control panel for ensim....can you help key Traceback (innermost last): File C:\Program Files\Zope\lib\python\ZPublisher\Publish.py, line 162, in publish File C:\Program Files\Zope\lib\python\ZPublisher\BaseRequest.py, line 427, in traverse File .\base\AccessControl\CommonAccessControl.py, line 235, in validate (Object: RoleManager) File .\base\AccessControl\CommonAccessControl.py, line 296, in _authenticate (Object: RoleManager) File .\published\webhost\WebHostAccessControl.py, line 78, in userAuthenticate (Object: RoleManager) File .\base\serverman\current\registrymgr.py, line 54, in value2dict NameError: key -------------- next part -------------- An HTML attachment was scrubbed... URL: From bvdpoel at kootenay.com Fri Jul 18 14:20:55 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Fri, 18 Jul 2003 11:20:55 -0700 Subject: Using Python as script extension Message-ID: <3f183aee_1@dns.sd54.bc.ca> I'm looking for some suggestions on a project I'm working at these days... I've written my program "Musical MIDI Accompaniment (MMA)" which parses a text file and generates MIDI output. I've written this in Python, and all works very nicely. See http://www.kootenay.com/~bvdpoel/music.html Now, I am thinking that adding variables and conditional (if/then/else) possiblities to MMA scripts might be a good thing. If I want to do this I see several possible routes: 1. Add the code to maintain and set variables to my existing code. This always seems to end up being a lot more work than one plans. Certainly, adding a command like "Set MyVariable 123" is simple enought, but then the next thing you know one will be adding math, etc. 2. Somehow having Python handle the dirty stuff. I guess that my "Set MyVariable 123" could be passed along to Python with an eval or exec. However, I'm not sure how much help this would be since we still end up with having to write code to handle if/then/else. 3. Somehow turn my MMA scripts into python scripts and extend python to generate the stuff which my program originally set out to produce. This would involve a major rewrite of my own code and most likely send my exsiting MMA scripts into the dumpster... And I'm sure I'm missing yet another solution. I'd really appreciate some thoughts and/or ideas on how I might approach this. Thanks. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From logistix at cathoderaymission.net Tue Jul 15 11:22:49 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 15 Jul 2003 08:22:49 -0700 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <3c91a864.0307150722.7ebfb569@posting.google.com> "Allison Bailey" wrote in message news:... > > Then, I get errors when I try the following: > sh = wb.worksheets(1) After running makepy, your methods become case sensitive. They are case insensitive before makepy. You probably need 'wb.Worksheets(1)' From tjreedy at udel.edu Tue Jul 22 22:26:51 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2003 22:26:51 -0400 Subject: python assignment References: Message-ID: <_SOdnaZDbr7xb4CiXTWJjw@comcast.com> "dan" wrote in message news:fbf8d8f2.0307221659.1dd1ac77 at posting.google.com... > without stirring the pot too much -- > > could someone please point me to whatever documentation exists on the > philosophy, semantics, and practical implications of how Python > implements the assignment operator? Go to Google.com and search their c.l.py for 'assignment' during the last 6 months. > I understand the basic concept that > names are bound to objects which exist on the heap, but that still > doesn't explain why a = b doesn't _always_ cause a to point to the > same object as b. But is *does*!!! > What determines when the object in question is copied? The programmer, by explicitly coding a copy operation. Assignment *never*, that I can think of, creates a new object by itself. Name = object *always* binds name to object in the appropriate namespace. > What I need is an exact and unambiguous algorithm for determining when > an assignment will change the id of the variable Variables do not have ids, only Pyobjects. >(or should I say, when the evaluation of an expression will cause > a new object to be created). Entirely separate issue. Names in expressions always evaluate to an existing object. Attributes and collection item retrievals usually do. Non-method operations usually do not. > Some of the issues involved can be discerned from the following session: I am beginning to think that Python newbies should not be told about id() and 'is' until they have learned enough to not misinterpret the results. > >>> a = 1 > >>> b = a > >>> a is b > True Correct, for the reason you think. > >>> a += 1 > >>> a -= 1 > >>> a is b > True Correct, but probably not why you think. For immutable types, two copies are the same as one copy, so the interpreter free to reuse an existing object of the same value as needed rather than allocate a redundant duplicate. CPython does this for commonly used small ints, >>> import sys >>> sys.getrefcount(1) 50 #49 internal, 1 from the function call but this is an implementation detail newbies should not worry about (except out of idle curiosity -- which I had also ;-). If you really are curious, repeat the above with -2, -1, 99, 100, 101. Also, experiment with 'a', 'aa', and 'a a'. > >>> a = 1.0 > >>> b = a > >>> a is b > True Same as example one. > >>> a += 1 > >>> a -= 1 > >>> a is b > False Correct, CPython does not preallocate any floats. > >>> a == b > True Numbers compare by numerical value, independent of type: >>> 0 == 0L == 0.0 == 0.0+0.0j 1 Terry J. Reedy From aahz at pythoncraft.com Wed Jul 9 16:22:28 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2003 16:22:28 -0400 Subject: Guido.moves_to(California) ? References: Message-ID: In article , Roman Suzi wrote: > >I was not very surprised to hear that, but I wonder if it means >new licenses coming: Nope. Now that there's an independent organization (the PSF) to hold Python's intellectual property, there's no reason (and almost no chance) of any further major changes to the Python license. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From Mark.Fenbers at noaa.gov Sat Jul 5 08:07:24 2003 From: Mark.Fenbers at noaa.gov (Mark Fenbers) Date: Sat, 05 Jul 2003 08:07:24 -0400 Subject: Bewildered graphs Message-ID: <3F06BF7C.8DC6A978@noaa.gov> I am investigating Python for the sake of ultimately generating hydrographs (such as this: http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) on-the-fly from a web server cluster. I have not used Python previously and do not yet know if Python is very useful for this or if I am wasting my time. Quite frankly, I am a little bewildered. Not only is there Python, but there are many extention modules which cloud up my view as to what I will need. There's Scientific Python, which sounds promising, but there's also SciPy which in itself has gnuplot, xplt and plt modules. I know enough about gnuplot to know that it won't meet my needs because I need to be able to shade regions above certain values such as done in yellow on the example hydrograph (the link above). It also doesn't have many font options or the ability to place an image such as the NOAA logo. Can someone kindly guide me as to what I would most likely need to replicate the graph shown via the link above? Mark -------------- next part -------------- A non-text attachment was scrubbed... Name: Mark.Fenbers.vcf Type: text/x-vcard Size: 333 bytes Desc: Card for Mark Fenbers URL: From alf at fayauffre.org Thu Jul 31 12:54:46 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Thu, 31 Jul 2003 16:54:46 +0000 (UTC) Subject: .setdefault() References: Message-ID: Tino Lange a ?crit : > I just realized that .setdefault *always* executes the second > argument - even if it's not necessary, because the requested item in > the first argument exists. Since setdefault is a method, this is coherent with Python's standard behaviour: method and function arguments are always evaluated before the method is called. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From adechert at earthlink.net Sun Jul 20 20:44:01 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 00:44:01 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xllus94t8.fsf@ruckus.brouhaha.com> Message-ID: "A.M. Kuchling" wrote in message news:K_idnV09hdycrYaiRTvU2Q at speakeasy.net... > On 20 Jul 2003 16:06:11 -0700, > Paul Rubin <> wrote: > > one another. Otherwise the ballot would be a voting receipt, > > something that a good voting system should not provide. Search for > > "receipt-free voting" in Google to see what a big problem this is for > > computerized systems. > > On the other hand, given the ready availability of cellphones with digital > cameras, even in a paper-based system you can now make your own voting > receipt while you're still in the voting booth. Not clear what can be done > about this... perhaps you'll have to hand in your cellphone when voting, and > go through an X-ray system to prove you don't have it. > Right. This receipt problem is way overblown. If we really thought this was a big problem, absentee voting would be illegal. There are problems with absentee voting but then look at Oregon -- they have gone to vote-by-mail entirely. There are always going to be some risks but we have to make them manageable. Alan Dechert From anton at vredegoor.doge.nl Fri Jul 4 18:24:01 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 05 Jul 2003 00:24:01 +0200 Subject: getting a submatrix of all true References: Message-ID: John Hunter wrote: >Another way of formulating the question: for a sparse boolean matrix >(sparse on True), what is the optimal way to remove rows and columns >so that the total number of elements in the matrix is maximal and >there are no True values left. After having read Bengts code (and scraping the parts of my exploded head from the floor) and after later getting the hint about the size of the problem being 2**N, it finally dawned on me that the problem would be related to getting all possible combinations of a range. The following code has the advantage that it generates solutions by index, for example "M[i]" returns the score and the row and column information for index i. (note that is not the same as finding the optimal solution, but it still could be handy to be able to generate a specific one by index) However for small matrices it is possible to do exhaustive searching with "max(M)". Maybe if this would be combined with some heuristic algorithm it would be better (genetic algorithm?) Code below (needs Python 2.3, very lightly tested), I hope this helps, Anton class Combinations: def __init__(self,n,k): self.n,self.k,self.count = n,k,self.noverk(n,k) def __getitem__(self,index): #combination number index if index > self.count - 1: raise IndexError res,x,rest = [],self.n,index for i in range(self.k,0,-1): while self.noverk(x,i) > rest : x -= 1 rest -= self.noverk(x,i) res.append(x) return res def noverk(self,n,k): return reduce(lambda a,b: a*(n-b)/(b+1),range(k),1) class AllCombinations: def __init__(self,n): self.n, self.count = n, 2**n def __getitem__(self,index): #combination number index for all k in combinations(n,k) if index > self.count - 1: raise IndexError n,rest = self.n,index for k in range(n+1): c = Combinations(n,k) if rest - c.count < 0: return c[rest] rest -= c.count class ScoreMatrix: def __init__(self, X): self.AC = AllCombinations(len(X)) self.X = X def __getitem__(self,i): #score selected rows and columns by index rows = self.AC[i][::-1] if rows: Y = [self.X[i] for i in rows] Z = [(i,z) for i,z in enumerate(zip(*Y)) if 1 not in z] cols = [i for i,z in Z] score = sum(map(len,[z for i,z in Z])) return score,rows,cols else: return 0,[],[] def test(): X = [ [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], ] M = ScoreMatrix(X) sc,rows,cols = max(M) print sc for i,r in enumerate(X): for j,c in enumerate(r): if i in rows and j in cols: print c, else: print 'x', print if __name__=='__main__': test() output: 16 x x x x x 0 0 x 0 0 x x x x x 0 0 x 0 0 0 0 x 0 0 0 0 x 0 0 From staschuk at telusplanet.net Wed Jul 16 22:13:24 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 20:13:24 -0600 Subject: Recursion in compile() In-Reply-To: <781faf41.0307161629.6295618b@posting.google.com>; from naren@trillium.com on Wed, Jul 16, 2003 at 05:29:08PM -0700 References: <781faf41.0307161629.6295618b@posting.google.com> Message-ID: <20030716201324.D656@tibia.amotlpaa.bogus> Quoth Narendra C. Tulpule: > is there any way to allow recusrion in compile()? Something like: > > src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \ > '\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n' > cobj = compile(src_code, 'myfile', 'exec') > eval(cobj) This works fine for me -- it prints 479001600 as expected, on both 2.2.2 and 2.3b1. What is the problem you're seeing? -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From adalke at mindspring.com Sun Jul 13 17:12:12 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 13 Jul 2003 15:12:12 -0600 Subject: Newbie with sort text file question References: Message-ID: Bob Gailer: > [Pipeline] Huh. Hadn't heard of that one before. Thanks for the pointer. (And overall, nice post!) > The Python version: Some stylistic comments > input = file('c:\input.txt') Since 'input' is a builtin, I use 'infile'. That's only a preference of mine. For the OP, you'll need 'c:\\input.txt' because the '\' has special meaning inside of a string so must be escaped. > fruits = {} # a dictionary to hold each fruit and its count > lines = input.readlines() > for line in lines: Since you are using Python 2.2 (later you use "if fruit in fruits", and "__in__" support for dicts wasn't added until Python 2.2, I think, and the 'file' usage is also new), this is best written as for line in input: > fruit = line.split('_', 1)[0] > if fruit in fruits: > fruits[fruit] += 1 # increment count > else: > fruits[fruit] = 1 # add to dictionary with count of 1 Here's a handy idiom for what you want fruits[fruit] = fruits.get(fruit, 0) + 1 > output1 = file('c:\output1.txt', 'w') > for key, value in fruits.items(): > output1.write("%s occurs %s\n" % (key, value)) > output1.close() > output2 = file('c:\output2.txt', 'w') > output2.write("Total occurrences is %s\n" % len(lines)) > output2.close() That's missing some sorts, so I don't think it meets the OP's requirements. How about this? infile = open("input.txt") lines = [] counts = {} for line in infile: lines.append(line) fruit = line.split("_", 1)[0] counts[fruit] = counts.get(fruit) + 1 # Sort by name. Since "_" sorts after any letter, this means # that "plum_" will be placed *after* "plumbago_", which # is probably not what you want. Left as an exercise :) lines.sort() outfile = open("output1.txt") for line in lines: outfile.write(line) outfile.close() # Print counts from highest count to lowest count_data = [(n, fruit) for (fruit, n) in counts.items()] count_data.sort() outfile = open("output2.txt") total = 0 for n, fruit in count_data: outfile.write("%s occurs %s\n" % (fruit, n)) total += n outfile.write("\nTotal occurances: %s\n" % total) outfile.close() Andrew dalke at dalkescientific.com From bignose-hates-spam at and-zip-does-too.com.au Sun Jul 6 22:35:00 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Mon, 07 Jul 2003 02:35:00 GMT Subject: anything new on the ternary operator? References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> Message-ID: On Mon, 07 Jul 2003 02:13:15 GMT, Russell Reagan wrote: > What is superior about using the proposed ternary operator instead of > using the 'and' and 'or' operators to simulate inline logic? The "cond and expr1 or expr2" does not always function as expected for a ternary if-then-else operator. The PEP for the ternary operator explains: "A common way to emulate an if-then-else expression is: and or However, this doesn't work the same way: it returns when is false! See FAQ 4.16 for alternatives that work -- however, they are pretty ugly and require much more effort to understand." FAQ 4.16 is here: -- \ "I wish I had a dollar for every time I spent a dollar, because | `\ then, yahoo!, I'd have all my money back." -- Jack Handey | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From rreagan at attbi.com Mon Jul 7 23:33:32 2003 From: rreagan at attbi.com (Russell Reagan) Date: Tue, 08 Jul 2003 03:33:32 GMT Subject: A story about Python... sort of References: Message-ID: "John J Lee" wrote: > A Google result (appropriately enough, given the origin of > the name Google) suggested 10**120 10**120 is the estimate of "paths", or "games", not "positions". The estimate of unique positions is 10**40, give or take. I don't recall whether that figure includes illegal positions that could never exist in a legal game of chess. From spock at telerama.com Tue Jul 29 13:49:17 2003 From: spock at telerama.com (Matt Newcomb) Date: 29 Jul 2003 10:49:17 -0700 Subject: Jython + propertyChangeListener?!?! Message-ID: <40cdba6.0307290949.2df33f17@posting.google.com> G'day, Hi. I'm new to jython/python and am trying to interface a jython script with some java code that produces property change events. Here's the jython code: import sys; from javax import swing; from java.beans import PropertyChangeListener; from gov.nasa.gsfc.irc.instrument import InstrumentModelProvider; class irchooks(PropertyChangeListener): def propertyChange(self, e): print "Property Change:"; print e; print self; def __init__(self): self.modelProvider = InstrumentModelProvider.getInstance() self.model = self.modelProvider.getInstrument("Detector") print "Sample Rate: " print self.model.getFramePeriod(); self.model.addPropertyChangeListener(self); print "Generate a property change event" self.model.setFramePeriod(0.215); Then when I try running this code from the application ( via the bean scripting framework ), I keep getting these errors: Sample Rate: 0.001 Traceback (innermost last): File "", line 37, in ? File "", line 33, in __init__ TypeError: propertyChange() too many arguments; expected 1 got 2 Exception in backgrounded command procedure: PropertChangeTest exception from JPython: Traceback (innermost last): File "", line 37, in ? File "", line 33, in __init__ TypeError: propertyChange() too many arguments; expected 1 got 2 : Traceback (innermost last): File "", line 37, in ? File "", line 33, in __init__ TypeError: propertyChange() too many arguments; expected 1 got 2 Huh? Any ideas? Thanks. Matt Newcomb Yerkes Observatory 373 W. Geneva St. Williams Bay, WI 53191 From abcdebl2nonspammy at verizon.net Thu Jul 17 00:27:23 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Thu, 17 Jul 2003 04:27:23 GMT Subject: Regular expression help Message-ID: I forget how to find multiple instances of stuff between tags using regular expressions. Specifically I want to find all the text between a series of begin/end pairs in a multiline file. I tried: >>> p = 'begin(.*)end' >>> m = re.search(p,s,re.DOTALL) and got everything between the first begin and last end. I guess because of a greedy match. What I want to do is a list where each element is the text between another begin/end pair. TIA David Lees From wiebke.paetzold at mplusr.de Thu Jul 31 07:16:06 2003 From: wiebke.paetzold at mplusr.de (Wiebke Pätzold) Date: Thu, 31 Jul 2003 13:16:06 +0200 Subject: regular expression Message-ID: Hi all, I wrote a little program. Here it is: import sys import Mk4py db = Mk4py.storage("c:\\datafile.mk",1) vw = db.view("people") def func(row): try: if row.Nachname[0:1]=='G': return 1 else: return 0 except AttributeError: return 0 vf = vw.filter(func) for r in vf: print vw[r.index].Nachname,vw[r.index].Kongressbereich I create a database that contains a table. 'Nachname' and 'Kongressbereich' are special fieldnames. This program can search for a special letter. In my example it is 'G'. and the search takes place in 'Nachname'. Mow I want to use regular expression. So that I can limit my search. For example: I can search for Ge and it is not relevant wich letters follow Could somebody help me with this task? Wiebke From mis6 at pitt.edu Tue Jul 22 22:11:50 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 22 Jul 2003 19:11:50 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: <2259b0e2.0307221611.51d6ff27@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > I think I'd prefer > > if any_true(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > dosomething() > > I suspect it will more often make sense read aloud in the general > > if any_true(pred, seq): > > than > > if the(pred, seq) > > I guess the full set of functions might be > any_true, any_false, all_true, and all_false. > > or maybe someone can think of better short phrase? > > Regards, > Bengt Richter I think in the specific case I was talking about "the" was quite readable; however I agree that in the general case "any_true" etc. would be better. I would not be opposed to add these convenience functions in itertools. The advantage is standardization (i.e. I don't have to invent my own name, different from the name chosen by anybody else), the disadvantage is more things to learn; however, with such descriptive names, it would be difficult to not grasp what those functions are doing, even without looking at the documentation. Anyway, I am sure many will be opposed, saying that such functions are so simple that they do not deserve to be in the library. This would be a sensible opinion, BTW. Michele From jordan at krushen.com Mon Jul 21 04:43:55 2003 From: jordan at krushen.com (Jordan Krushen) Date: Mon, 21 Jul 2003 01:43:55 -0700 Subject: httplib\urllib attributes problem In-Reply-To: <006001c34f07$03bb0760$6700a8c0@inet43> References: <005201c34f05$e273da60$6700a8c0@inet43> <006001c34f07$03bb0760$6700a8c0@inet43> Message-ID: On Sun, 20 Jul 2003 23:36:44 +0200, Bobbie wrote: > hmmm. > But doesn't that apply to the suggested "opener.addheaders = []" change > as > well ? That would go in your code, not in urllib2.py. You have control over when your code changes, and if you ship a package to other users, this would still be able to override their libraries, too. J. From cookedm+news at physics.mcmaster.ca Sat Jul 19 20:21:11 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sat, 19 Jul 2003 20:21:11 -0400 Subject: distutils.core not in Debian python2.2 package References: Message-ID: At some point, Kent Tenney wrote: > Howdy, > > I did; > # apt-get install python2.2 > > # python > Python 2.2.1 > ... > >>> > > then checked docutils out of CVS > and did; > > docutils# python ./setup.py install > > ImportError: No module named distutils.core > > How do I install distutils? Install the python2.2-dev package. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From schull at digitalgoods.com Tue Jul 15 01:30:56 2003 From: schull at digitalgoods.com (Jon Schull) Date: 14 Jul 2003 22:30:56 -0700 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> <3F0E136A.6222F201@engcorp.com> <2621b014.0307140819.6ec99736@posting.google.com> <3F13034D.19A4C65@engcorp.com> Message-ID: <2621b014.0307142130.6e49ea6d@posting.google.com> Peter Hansen wrote in message news:<3F13034D.19A4C65 at engcorp.com>... > > If this is merely a "local webserver interface", then it should bind > to localhost only. Well, maybe this is how the question should be phrased. How best to securely and reliably "bind to localhost only" (spoof-proofly, etc.)? From lists at gregfortune.com Tue Jul 22 15:07:46 2003 From: lists at gregfortune.com (Greg Fortune) Date: Tue, 22 Jul 2003 12:07:46 -0700 Subject: Installing lots of packages Message-ID: I've got a whole bunch of package dependencies in the programs I develop. Mainly, they are generic libraries/utilities I've written that are needed by most of the programs I write. The biggest problem I've had with python's packaging system is that I end up needing to install every library package on each machine I install my programs on. It's even worse when I go through an upgrade... Is there any way to create something like a "meta-package"? ie, can bundle a whole bunch of packages together under a single installer? I'm working on both Windows and Mac so the tools need to support both platforms. Does anything exist for this purpose? Thanks, Greg Fortune Fortune Solutions From gerard.sookahet at artenum.com Sat Jul 19 13:54:20 2003 From: gerard.sookahet at artenum.com (Gerard Sookahet) Date: Sat, 19 Jul 2003 19:54:20 +0200 Subject: Calling tcl from python and viceversa In-Reply-To: <453d10b2.0307190828.3c576f15@posting.google.com> References: <453d10b2.0307190828.3c576f15@posting.google.com> Message-ID: Carlos P. wrote: > Hi! > I want to call tcl from python and python from tcl. The big picture is > that I?m writing an application GUI with tcl/tk and application logic > with python, so at least I want to call python events from the tk GUI. > I have read about _tkinter and tkapp.call although I couldn?t find any > detailed documentation. And, anyway, that seems to work in one > direction (python->tcl) but I don?t know how to make it work in the > other (tcl->python). > Thank you, > Carlos Hello, I have found an hint in the Tcl Wiki about Tclpython: http://mini.net/tcl/5630 May be this will help you a little. Gerard Sookahet From bogal2 at comcast.net Tue Jul 15 14:54:14 2003 From: bogal2 at comcast.net (BogAl) Date: Tue, 15 Jul 2003 13:54:14 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: Thanks for the reply, John.... > I would suggest that you > (1) Remove all your copies of csv.pyd > (2) Install the csv module properly by following the instructions on > Dave's website (i.e. briefly, you unpack the distribution into a > directory, and then run setup.py) I tried this first; went to the suggested alternative second. Here's what happens when I run setup.py: C:\Python22\Lib\site-packages\csv> python.exe C:\PYTHON22\LIB\SITE-P~1\CSV\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 > (3) If you still have a problem, post a message that shows > (a) what version of Windows you are running > (b) what version of Python > (c) your windows path > (d) your Python path (import sys; print sys.path) > (e) what you get when you run Python (at the DOS command line!!) with > -v and try to import the csv module > (f) what the MS depends utility says about > C:\Python22\Lib\site-packages\csv.pyd > > Another thought: I found I had a python22.dll (dated Oct 2002, must be > from Python 2.2.2) in my c:\WINNT\system32 directory and one dated May > 2003 (must be from Python 2.2.3) in my c:\Python22 directory ... don't > know how that happened; puzzling ... I've killed off the older one. > You might like to search python22.dll *AND* msvcrt.dll and ensure that > you are using the latest. > > HTH, > John From ebolonev at rol.ru Fri Jul 4 03:19:36 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 18:19:36 +1100 Subject: enumerate example Message-ID: Hello, All! Any useful example for enumerate, please. With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From delphiro at zonnet.nl Fri Jul 4 08:46:57 2003 From: delphiro at zonnet.nl (delphiro) Date: Fri, 4 Jul 2003 14:46:57 +0200 Subject: Kylix reality (was: Python is a gem, you need to keep pushing it ....) Message-ID: <20030704144657.60f8f5dc.delphiro@zonnet.nl> > How is Kylix "nasty and not-so-friendly"? I > generally think of it as rather polished and > useful. We (the company I work for) have a lot of problems with Kylix. On RedHat 9 debugging threads crashes Kylix, on Debian Woody the C++ compiler crashes with any compilation and there are more crashes, even on 'certified' linux disrtibutions. It just seems like Borland only supports older Linux distributions and does not want to release patches for newer RedHat / Suse / Mandrake releases. Apart from that I think it should work on *any* linux distribution not just the 'major' ones. The IDE also is kind of sloppy (based on Wine) and feels akward when you are used to the Delphi IDE (there seems to be a slight delay between a keypress and the action that should happen, even on a PIII-900). Personaly I think the Kylix IDE could improve a lot if the code was native. Don't get me wrong, I think it is great that Borland takes linux seriously and compiled Kylix applications run perfectly but the product needs a lot of polishing before becoming as smooth as it is for the Windows platforms. Rob From hp at rentec.com Tue Jul 29 18:39:30 2003 From: hp at rentec.com (HP) Date: 29 Jul 2003 15:39:30 -0700 Subject: urlretrieve a file whose name has spaces in it Message-ID: <10caf2e2.0307291439.33d9fcc3@posting.google.com> I am using urllib.urlretrieve() to download a file from a web site. THe trouble is that the file name has spaces in it, such as "string string1 foo.doc". The statement: urllib.urlretrieve("http://website.com/path/string string1 foo.doc", "local_file"); produces local_file which contains the following one line: ErrorThe parameter is incorrect. What is the correct way of specifying the this file in urlretrieve() ? thanks HP From janeaustine50 at hotmail.com Tue Jul 1 22:37:50 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 1 Jul 2003 19:37:50 -0700 Subject: __del__ not working with cyclic reference? Message-ID: I have some code using singleton pattern. The singleton instance is shared as a class variable. The problem is that the singleton instance is not cleared automatically. Following is a simplified version that shows the problem: -------- #foobar.py class FooBar: def __del__(self): print "FooBar removed" FooBar.foobar=FooBar() -------- c:\python23>python foobar.py c:\python23> It doesn't print anything. Why is this so? Due to the cyclic reference? Isn't python's gc supposed to treat it? What singleton idiom is recommended otherwise? Thanks Jane From skip at pobox.com Wed Jul 30 15:31:38 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jul 2003 14:31:38 -0500 Subject: Upgrading python In-Reply-To: References: Message-ID: <16168.7450.873745.526233@montanaro.dyndns.org> Stephen> I guess that I had in mind a move from 2.2.2 to 2.2.3. What's Stephen> the rule for a minor upgrade like this? I'd actually be more careful there than if I was just installing 2.3. I'd uninstall 2.2.2, then install 2.2.3. I'd also rummage back through the folders containing third-party stuff (stuff which winds up in site-packages) and reexecute python setup.py clean python setup.py install Skip From richmond at ev1.net Sat Jul 12 11:36:49 2003 From: richmond at ev1.net (Charles Richmond) Date: Sat, 12 Jul 2003 15:36:49 GMT Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: <3F10466E.19E34A7E@ev1.net> Walter Bushell wrote: > > Charles Richmond wrote: > > > int *p, x, y; > > > > then: > > > > y = x/*p; > > > > is quite different from: > > > > y = x / *p; > > > > The first way, "/*" will begin a comment...the second way, > > you get the integer "x" divided by the integer pointed to by "p". > > Ouch!! That is one reason code coloring is *important*. > > I remember working in Fortran and being confused why the compiler was > not accepting the if statement, 'til we looked at the cards and saw it > was a "1F" statement. > In the later part of our IBM/370 assembly language class, a girl was running the program she wrote for her assignment. One statement did *not* seem to do anything. She spend at least 30 minutes trying to figure out what was wrong. Turns out that there was a "*" in column one, and the statement was really a comment...and generated *no* code. This happened because she was punching her program on good ole' 80 column cards, in a student environment where many people used the same keypunch machines. Often people would pick up the "blank" cards and stick them back in the input hopper for the keypunch. It was easy to miss the "*" punched in column one, because the upper left corner of the cards was sliced off by design. So the unlucky girl just happened to get a card that *already* had a "*" in column one, when she punched up her program. Instant bug... Another favorite beginner mistake was punching code past column 72 in FORTRAN IV. Sometimes, if you were unlucky, the FORTRAN code would make sense *without* the part beyond column 72. Of course, the results would *not* be what was expected. -- +----------------------------------------------------------------+ | Charles and Francis Richmond richmond at plano dot net | +----------------------------------------------------------------+ From pythonguy at Hotpop.com Wed Jul 16 13:48:46 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 16 Jul 2003 10:48:46 -0700 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> <3f15132a$0$13797$4d4ebb8e@news.nl.uu.net> Message-ID: <84fc4588.0307160948.1481804b@posting.google.com> Avid quizzers tend to answer a quiz sequentially. I dont expect a good percentage to do a 'look-ahead'. Anyway for anybody reasonably aware of the language the first question is a walk-through. Only from the 2nd onwards, it is a challenge, it at all it is. ~Anand "Guyon Mor?e" wrote in message news:<3f15132a$0$13797$4d4ebb8e at news.nl.uu.net>... > I spotted one funny 'mistake' .... the first question asks the name of the > inventor of python. > the second one gives you the answer :) > > > > > "Anand Pillai" wrote in message > news:84fc4588.0307152253.20858619 at posting.google.com... > > Hi Pythonistas, > > > > I have placed a quiz on Python on the trivia site www.funtrivia.com. > > Here is the link. > > > > http://www.funtrivia.com/quizdetails.cfm?id=139672 > > > > Looks like it is the first quiz on Python on this site. > > > > Please try it out if you like quizzing. > > Let me know if there are any factual errors. > > > > Thanks > > > > ~Anand From robin.cull at pace.co.uk Tue Jul 22 11:06:28 2003 From: robin.cull at pace.co.uk (Robin Cull) Date: 22 Jul 2003 08:06:28 -0700 Subject: Iterating order of dict.items() Message-ID: <16469f07.0307220706.5e2fe1e4@posting.google.com> In a script I am writing, when I iterated over the items in a dict using: for x,y in mydict.items(): doSomethingWith(x,y) The order the items comes out in appears to be undefined. I would have thought that without any other sorting that the items would just come out in the order that the dict was defined in, so: mydict = {"one": 1, "two": 2, "three": 3, "four": 4} would yield values: x | y ------+-- one | 1 two | 2 three | 3 four | 4 However the order appears to be random say three, four, one, two for example So, is the order of dict.items() defined? If so, what is that order? Is there any way to control the order my dict is iterated over? Thanks a lot. Cheers, Robin From david at kharmakhameleon.com Tue Jul 29 01:01:59 2003 From: david at kharmakhameleon.com (David Connell) Date: 28 Jul 2003 22:01:59 -0700 Subject: Mod_Python and ExpatPy Message-ID: <32e181f9.0307282101.551c51a8@posting.google.com> I'm porting a mod_python / XML app that has been running in Apache 1.3 and I am running into trouble with Apache 2.0. Specifically, I'm getting a restricted execution mode error when I import the ExpatPy piece. Any body know what, why or how to fix? Thanks! From ulope at gmx.de Tue Jul 22 15:13:16 2003 From: ulope at gmx.de (Ulrich Petri) Date: Tue, 22 Jul 2003 21:13:16 +0200 Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88) References: Message-ID: "Ames Andreas (MPA/DF)" schrieb im Newsbeitrag news:mailman.1058894315.10480.python-list at python.org... > Hello, > > during execution of an assignment statement like > > x = y > x = z # <-- > > is y's reference count decremented (and therefore its __del__ possibly > called) *before* x is bound to z (or is z bound to x, I don't know the > correct wording) or *afterwards*? No. 1. its not y's reference count that gets (possibly) decremented but the-object-y-points-to 2. in this example noting will be decremented since y never goes out of scope. Just by assining y to x you dont "invalidate" y. Ciao Ulrich From Simon.Wittber at perth.maptek.com.au Tue Jul 1 03:58:44 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Tue, 1 Jul 2003 15:58:44 +0800 Subject: what has happened to the list? Message-ID: <20E0F651F8B82F45ABCBACC58A2D995B032AC4@mexper1> I've never seen it this quiet before... Can anyone shed any light? From mcfletch at rogers.com Mon Jul 28 13:51:41 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 28 Jul 2003 13:51:41 -0400 Subject: Toronto Pythonistas, PyGTA meeting is tomorrow (Tuesday) @ 8pm Message-ID: <3F2562AD.6090105@rogers.com> Regular place. You can find more details here... http://web.engcorp.com/pygta/wiki/NextMeeting Don't forget! Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mike at nospam.com Thu Jul 24 18:11:46 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 24 Jul 2003 15:11:46 -0700 Subject: not able to run References: Message-ID: Joe Kmoch wrote: > I've tried to install python2.2 on our Solaris 8 system using the > package available on the sunfreeware.com site. When I try to run > python I get the following: > > # ls -al python2.2 > -rwxr-xr-x 1 bin bin 4902360 Feb 17 20:44 python2.2 > # python2.2 > ld.so.1: python2.2: fatal: libstdc++.so.5: open failed: No such file > or directory > Killed Take ftp://ftp.sunfreeware.com/pub/freeware/sparc/8/libgcc-3.3-sol8-sparc-local.gz which includes the files and links libgcc_s.so libstdc++.a libstdc++.so libstdc++.so.5.0.4 libgcc_s.so.1 libstdc++.la libstdc++.so.5 sparcv9 ./sparcv9: libgcc_s.so.1 libstdc++.a libstdc++.so libstdc++.so.5.0.4 libgcc_s_sparcv9.so libstdc++.la libstdc++.so.5 Since these files are part of the gcc package, you may not need to install it if you already have gcc 3.3 installed. This package is created because some programs will not run without these libraries - installs in /usr/local/lib. Mike From tim at lucurum.com Thu Jul 3 17:39:33 2003 From: tim at lucurum.com (Tim Fitzpatrick) Date: Thu, 03 Jul 2003 22:39:33 +0100 Subject: Problems with BILINEAR/BICUBIC filters in PIL Message-ID: <3F04A295.6060704@lucurum.com> Hi all I'm fairly new to Python with PIL and I'm having some problems with the BILINEAR/BICUBIC filters when rotating and transforming images. If I use resize() with NEAREST, BILINEAR and BICUBIC I can clearly see the difference in the filters. But if I use rotate() or transform() then there is no difference, and they all look like NEAREST filtering. Any ideas as to what I am doing wrong? I am testing with a simple, small BMP image, so the mode is RGB. I'm running Python 2.2.2 on Windows with PIL 1.1.4. Help appreciated, Tim From danbmil99 at yahoo.com Sun Jul 20 10:32:38 2003 From: danbmil99 at yahoo.com (dan) Date: 20 Jul 2003 07:32:38 -0700 Subject: Tk mainloop() References: Message-ID: re my prev response -- sleep() doesn't 'allow Tkinter thread to run', but it might be necessary to let some system services or something run in the background. Actually I'm going to take it out and see what happens. Just calling youroot.update() should be enough to let Tkinter do its thing. quick comment: if Py is indeed going to take over the world of programming, which I for one applaud, it needs to get its threading stuff together. Seems pretty funky right now. Also Tk is nice but a C-level native set of GUI commands that work across platforms but use platform-native calls would be a great improvement. Just my 2c -dbm "Petr Evstratov" wrote in message news:... > Hi, I have a question: how do you execute an arbitrary function in Tk fooBar.mainloop()? > > I need to change the contents of a label every second, but I think I will also use some other functions as well... > > I hope that someone will answer my question, because I have been looking for an answer for 3 days, asking people, searching Google... and still have not found anything useful... > > Thanks, Pete From mhammond at skippinet.com.au Tue Jul 15 02:36:34 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 15 Jul 2003 16:36:34 +1000 Subject: PyVariant anyone In-Reply-To: <3f125990$1_2@mk-nntp-2.news.uk.tiscali.com> References: <3f125990$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: Paul Keating wrote: > I need to call a C++ DLL from Python, for which I'm planning to use > boost.python. But the DLL has been written to a VBA interface, and this > means it expects to get variable length arrays as Windows Variants instead > of lists or tuples. > > Anyone know how to construct a convincing Windows Variant in Python? If you can link against pythoncom.dll, there are public functions there for it. Mark From yzzzzz at netcourrier.com Fri Jul 18 06:00:00 2003 From: yzzzzz at netcourrier.com (yzzzzz) Date: Fri, 18 Jul 2003 12:00:00 +0200 Subject: Using Unicode scripts Message-ID: <3f17c520$0$7194$626a54ce@news.free.fr> Hi, I am writing my python programs using a Unicode text editor. The files are encoded in UTF-8. Python's default encoding seems to be Latin 1 (ISO-8859-1) or maybe Windows-1252 (CP1252) which aren't compatible with UTF-8. For example, if I type print "?", it prints ??. If I use a unicode string: a=u"?" and if I choose to encode it in UTF-8, I get 4 Latin 1 characters, which makes sense if the interpreter thinks I typed in u"??". How can I solve this problem? Thank you PS. I have no problem using Unicode strings in Python, I know how to manipulate and convert them, I'm just looking for how to specify the default encoding for the scripts I write. From Scott.Daniels at Acm.Org Sun Jul 27 19:24:38 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 27 Jul 2003 16:24:38 -0700 Subject: multithreading-problem In-Reply-To: References: <3f243632$1@nntp0.pdx.net> Message-ID: <3f245f36@nntp0.pdx.net> Diez B. Roggisch wrote: > Ah, ok. That makes sense. Where do I find this curry-function, only in the > book? It appears not to be a standard function. Bottom of my message before, just type it in. (or go to ActiveState for the class-based version). The cookbook site: http://aspn.activestate.com/ASPN/Python/Cookbook/ The curry recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 -Scott Example of use in IDLE (followed by code): >>> from my_util import curry >>> def f(a,b,c): return a*b+c >>> g = curry(3) >>> assert g(2,1) == 7 == f(3,2,1) >>> file: my_util.py from __future__ import nested_scopes def curry(*_args, **_kwargs): """curry(f,)() == f(, ) (roughly). keyword args in the curry call can be overridden by keyword args in the later call; curry can be used to change defaults. """ def result(*__args, **__kwargs): if _kwargs and __kwargs: kwargs = _kwargs.copy() kwargs.update(__kwargs) else: kwargs = _kwargs or __kwargs return _args[0](*(_args[1:]+__args), **kwargs) return result From anton at vredegoor.doge.nl Thu Jul 10 05:53:43 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 10 Jul 2003 11:53:43 +0200 Subject: A story about Python... sort of References: Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote: >Hmmm. So, if the universe is open and contains an infinite >amount of matter, then we could solve chess eventually, >but we might have to wait a while for the limits of the >observable universe to expand sufficiently... IMO it all depends on the amount of low hanging fruit in the universe. For example if at some early stage in the game the Queen could be captured cleanly, the rest would be just minor details, unless some careless move would give the game away of course. For example at the department of informatics in Maastricht, there was someone (Victor Allis IIRC) who had a habit of inviting people in a most friendly and convincing way into his "torture chamber" where one could play a game of "gobang" or "four in a row" or something like that (it's a long time ago, I'm not sure about the details anymore) against an innocent looking computer program. As time went by the program got stronger and stronger and the faces of the people leaving the room got more and more somber. Winning a game just resulted in the program not making the same mistake next time :-) In the end he managed to prove that the program was invincible, not because he could generate the whole game tree, but because he could maneuver the game into some position that was always winnable for the computer. Anton From robin.cull at pace.co.uk Wed Jul 30 18:58:38 2003 From: robin.cull at pace.co.uk (Robin Cull) Date: 30 Jul 2003 15:58:38 -0700 Subject: Is there a standard module library function to access /etc/passwd or /etc/group References: <16469f07.0307300416.351ba776@posting.google.com> Message-ID: <16469f07.0307301458.59e73736@posting.google.com> Heather Coppersmith wrote in message news:... > On 30 Jul 2003 05:16:43 -0700, > robin.cull at pace.co.uk (Robin Cull) wrote: > > > ... Something that gives access to the C standard libarary > > functions get[pw|group]ent(), for example ... > > Right out of the table of contents of Python's Library Reference: > > 8.2 pwd -- The password database > 8.3 grp -- The group database Those'll be the ones! :) > > When all else fails, read the manual.... ;-) I assure you I did, in fact it baffles me that I missed "pwd" in the global module index when I was scanning for "passwd". Then I went off on a complete tangent and started looking through "os" and "posix" for some reason. A case of "can't see the wood for the trees" I think! I'll look harder next time ;) Cheers, Robin From tjreedy at udel.edu Thu Jul 31 15:56:24 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2003 15:56:24 -0400 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> <3f28e998$0$49107$e4fe514c@news.xs4all.nl> Message-ID: <4V2dnfpICor06bSiXTWJiQ@comcast.com> "Irmen de Jong" wrote in message news:3f28e998$0$49107$e4fe514c at news.xs4all.nl... > Ben Finney wrote: > > Or 'totally mega kudos, d00dZ' depending which decade you're living in. > > rather, "Thanx 2 all developers 4 ur 1337 c0D1ng Skilzz!!!" Not being (001 with 1337speak, I googled '1337' and found this site (#12) that deigned to explain: http://www.1337-online.com/whatis1337.php From ben at dadsetan.com Thu Jul 3 22:27:21 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Fri, 04 Jul 2003 03:27:21 +0100 Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> Message-ID: <3F04E609.2010500@dadsetan.com> A bit a pitty the message board system is php based.. Does anyone know about message board systems written in python? Ben. Kyle Babich wrote: > I have just opened pyBoards.com, a community for Python programmers. > Please stop by and check it out. > > http://www.pyBoards.com > > Tell me what you think, > Kyle From newgene at bigfoot.com Mon Jul 28 12:53:26 2003 From: newgene at bigfoot.com (newgene) Date: 28 Jul 2003 09:53:26 -0700 Subject: howto redirect stdout/stderr into a wxPython textctrl? Message-ID: Hi, group, I guess it is a simple question for you, but it puzzles me for a while. I use a wxTextCtrl in my application for output result and any exception msg. I know I can add new msg onto wxTextCtrl by WriteText() method. But I have a function imported from another module and in this function all results are output by "print". I am wondering if I can redirect stdout and stderr into the wxTextCtrl object, so that all output from that function will be shown up on wxTextCtrl box and I don't need modify the current code for that function. Thank you. Chunlei From hwlgw at hotmail.com Thu Jul 17 11:53:23 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 17 Jul 2003 08:53:23 -0700 Subject: IMAP examples References: Message-ID: > > I can't seem to find any decent examples on how to use the > > IMAPLIB module. the docs aren't that sophisticated > > unfortunately.... the cookbook entry comes close, but i'd > > like to know if someone knows some nice examples somewhere. > > [Tony Meyer] > What do you mean by decent? > > Spambayes (http://spambayes.org) has an IMAP filter, which is an example of > using imaplib. Whether it's decent or not, well... ;) I think he means by decent examples: - concise - clear - showing general useful usage - showing peculiar usage in the case of warts Looking into the (not concise) spambayes code for an example how to use IMAP is *not* like looking at a decent example. It is more like a last resort. Also looking at the Python Cookbook examples doesn't help much because they are either not concise or too simplistic or etc. Designing decent examples is hard work. From http Fri Jul 11 14:16:22 2003 From: http (Paul Rubin) Date: 11 Jul 2003 11:16:22 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <7xk7ap3j6z.fsf@ruckus.brouhaha.com> <3F0EE2E1.1C30CEA4@hotmail.com> Message-ID: <7x7k6pvsi1.fsf@ruckus.brouhaha.com> Nagy L?szl? Zsolt writes: > >Or is the checksum stored on the server, in some form of lookup > >dictionary keyed by some user session identifier? > > > I think he wanted to write a digital signature instead. Right? I used "cryptographic checksum" in a broad sense. More specifically the suggestion is to use a secret-key authentication code like HMAC-MD5. From skip at pobox.com Tue Jul 15 22:56:07 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jul 2003 21:56:07 -0500 Subject: Library for pop over ssl? In-Reply-To: References: Message-ID: <16148.48839.42687.918488@montanaro.dyndns.org> >> Hi, I know of poplib, which does what I need except that it doesn't >> support SSL encryption. imaplib has SSL-support. But I want it with >> pop3. Is there a library available that does this or do I have to >> implement it myself? JanC> You can always use stunnel to SSL-ize a "normal" protocol... JanC> Doesn't stunnel only work for servers? Skip From jdhunter at ace.bsd.uchicago.edu Tue Jul 15 16:55:39 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 15 Jul 2003 15:55:39 -0500 Subject: String Manipulation In-Reply-To: <2c6431ab.0307151223.4173c4ee@posting.google.com> (lamar_air@hotmail.com's message of "15 Jul 2003 13:23:09 -0700") References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: >>>>> "lamar" == lamar air writes: lamar> I need a piece of code that takes a string like this lamar> string1 = "aaa/bbb/ccc/dd" and extracts a string lamar> containting the character after the last "/" One good way to do this is to split the string on the '/' character, which creates a list of strings >>> string1 = "aaa/bbb/ccc/dd" >>> parts = string1.split('/') >>> parts ['aaa', 'bbb', 'ccc', 'dd'] Now you just want to get the last element of this list; python allows you to index with -1 to get the last element, -2 to get the second to last, etc... >>> parts[-1] 'dd' JDH From intentionally at blank.co.uk Tue Jul 15 01:31:08 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 06:31:08 +0100 Subject: anything like C++ references? References: <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> <3F138ADC.4BF9DB3A@alcyone.com> Message-ID: On Mon, 14 Jul 2003 22:02:20 -0700, Erik Max Francis wrote: >Stephen Horne wrote: > >> True enough. The issue of how assignment is represented is trivial and >> unimportant in the scheme of things. > >Then I retract (or at least soften) my earlier comment; I thought you >were suggesting that it was a significant issue. No need - any confusion is my fault. When I first made the point, I should have made it clear that I was being overpedantic and not really serious. Looking back, the point I made about '+' in particular should not have been made - at least not without a healthy dose of smileys or something. Sorry. I hope no offense was caused. From matthias.oberlaender at VOID.daimlerchrysler.com Mon Jul 28 02:44:37 2003 From: matthias.oberlaender at VOID.daimlerchrysler.com (Matthias Oberlaender) Date: 28 Jul 2003 06:44:37 GMT Subject: Low resolution of cpu times returned by getrusage Message-ID: My problem is that cpu times returned by getrusage seem to be rounded to 10 ms units (so also does time.clock). I never noticed such a low resolution in previous versions. Since I have not found similar reports on the web, it probably is not a general bug in (rather outdated) version 2.2.1. Any idea what could be wrong with this peculiar installation? Thanks a lot! Python 2.2.1 (#3, May 3 2002, 16:42:06) [GCC 2.95.3 20010315 (SuSE)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import resource >>> print resource.getrusage(resource.RUSAGE_SELF) (0.01, 0.040000000000000001, 0, 0, 0, 0, 186, 410, 0, 0, 0, 0, 0, 0, 0, 0) >>> for i in range(1000000): pass ... >>> print resource.getrusage(resource.RUSAGE_SELF) (0.26999999999999996, 0.059999999999999998, 0, 0, 0, 0, 4116, 414, 0, 0, 0, 0, 0, 0, 0, 0) -- ____ __ _/_/ . ( / / ( / / / / ===================================================================== Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm RIC/AP (Machine Perception) Wilhelm-Runge-Str. 11, P.O. Box 2360, 89013 Ulm, Germany Phone: +49 731 505 2354 Fax: +49 731 505 4105 Email: matthias.oberlaender at VOID.daimlerchrysler.com ===================================================================== From johnroth at ameritech.net Tue Jul 1 12:44:02 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 1 Jul 2003 12:44:02 -0400 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: "Rim" wrote in message news:6f03c4a5.0306301931.3f15fbb7 at posting.google.com... > Hi, > > I have been thinking about how to overload the assign operation '='. > In many cases, I wanted to provide users of my packages a natural > interface to the extended built-in types I created for them, but the > assign operator is always forcing them to "type cast" or coerce the > result when they do a simple assign for the purpose of setting the > value of a variable. Use a property. Changing the semantics of the assignment statement (NOT assignment operator) is not going to happen. Properties are new in Python 2.2 (which is around a year old by now.) They enable you to have getter and setter methods with an interface that looks like an instance variable. John Roth From bokr at oz.net Mon Jul 21 01:55:01 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jul 2003 05:55:01 GMT Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: <3F1B664D.2AC5A585@alcyone.com> Message-ID: On Sun, 20 Jul 2003 21:04:29 -0700, Erik Max Francis wrote: >Jeff Epler wrote: > >> I'd have expected something like 'TypeError: unslicable type' >> meaning that you can't slice a dict, not that slice()s aren't >> hashable. > >Slicing is not a feature of the mapping interface; it's not entirely >clear what it should mean. All mapping interfaces need are keys that >are hashable; it doesn't make any kind of requirements about how those >keys related to each other. So slicing a mapping interface is something >that simply may not make any sense at all in some cases. > >If you really _do_ want to take a range out of a dictionary and know >that it has some meaning, you should probably do the slicing on the >_list of keys_ (D.keys()) -- because there is no concept of an ordering >of keys in a dictionary. > It might be interesting to define a dict slice as a lexicographic slice -- e.g., ====< slicedict.py >========================================= class SD(dict): from types import SliceType def __getitem__(self, i): if isinstance(i, self.SliceType): keys = self.keys() keys.sort() try: start = keys.index(i.start) except ValueError: start = 0 try: stop = keys.index(i.stop) except: stop = len(keys) step = i.step or 1 return SD([(k, dict.__getitem__(self, k)) for k in [keys[j] for j in xrange(start,stop,step)]]) return dict.__getitem__(self, i) ============================================================= >>> import slicedict >>> sd = slicedict.SD(zip([chr(c) for c in range(ord('a'),ord('z')+1)],range(26))) >>> sd['c':'g'] {'c': 2, 'e': 4, 'd': 3, 'f': 5} >>> sd['c':'g':2] {'c': 2, 'e': 4} >>> sd['c':'h':2] {'c': 2, 'e': 4, 'g': 6} >>> sd[:'c'] {'a': 0, 'b': 1} >>> sd[:'w'] {'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 1 2, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'v': 21} >>> sd['w':] {'y': 24, 'x': 23, 'z': 25, 'w': 22} >>> sd[:] {'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 1 2, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v' : 21, 'y': 24, 'x': 23, 'z': 25} >>> sd[::5] {'a': 0, 'p': 15, 'u': 20, 'f': 5, 'k': 10, 'z': 25} Regards, Bengt Richter From 2002 at weholt.org Fri Jul 4 12:36:00 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Fri, 4 Jul 2003 18:36:00 +0200 Subject: Kylix reality (was: Python is a gem, you need to keep pushing it ....) References: Message-ID: <82iNa.10874$Hb.190607@news4.e.nsc.no> My last attempt at Kylix was awful. It was version 1.0, don't know what the current version is. But the IDE felt messed up. Windows kept disappearing behind other windows and to just it running we had to patch and screw around with a bunch of things. A major dissapointment. "delphiro" wrote in message news:mailman.1057323066.3751.python-list at python.org... > > How is Kylix "nasty and not-so-friendly"? I > > generally think of it as rather polished and > > useful. > > We (the company I work for) have a lot of problems with Kylix. > On RedHat 9 debugging threads crashes Kylix, on Debian > Woody the C++ compiler crashes with any compilation and there > are more crashes, even on 'certified' linux disrtibutions. > > It just seems like Borland only supports older Linux distributions > and does not want to release patches for newer RedHat / Suse / > Mandrake releases. Apart from that I think it should work on > *any* linux distribution not just the 'major' ones. > > The IDE also is kind of sloppy (based on Wine) and feels akward > when you are used to the Delphi IDE (there seems to be a slight delay > between a keypress and the action that should happen, even on a PIII-900). > Personaly I think the Kylix IDE could improve a lot if the code was native. > > Don't get me wrong, I think it is great that Borland takes linux > seriously and compiled Kylix applications run perfectly but > the product needs a lot of polishing before becoming > as smooth as it is for the Windows platforms. > > Rob > From bokr at oz.net Fri Jul 25 14:00:03 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 18:00:03 GMT Subject: Downloading Python files References: Message-ID: On Fri, 25 Jul 2003 15:26:49 +0000 (UTC), Luke StClair wrote: >Only marginally belonging in this newsgroup... but oh well. > >I've just started writing in python, and I want to make the files >available on the web. So I did the standard href="mypath/myfile.py"> and not surprisingly, it displays like a >webpage, but just the code. If I gzip it, and then link to the new >file, it will download, but its so small I don't want it zipped. >How can I make this into a downloadable >file SIMPLY? The other thread seems a bit complicated... > >Thanks If the user has .py set up for automatic shell execution of .py files, the browser should warn of security risk and provide an option to save to disk. If the user doesn't, then it may show as text as you describe. If that's already happened, s/he should be able to do file>save as ... and save as a .py file somewhere. If the user is still looking at your page with the highlighted link, s/he should be able to right-click the link and get an option to "save link as ..." You could just tell the user about that in association with your link(s), e.g., with the following (untested!) HTML: Right-click this to save myfile.py to disk.
Left-click this to open myfile.py according to your browser settings. Note that it's really the same link, just different instructions. I guess for different browsers YMMV. Regards, Bengt Richter From englim at pc.jaring.my Thu Jul 17 10:58:41 2003 From: englim at pc.jaring.my (lec) Date: Thu, 17 Jul 2003 22:58:41 +0800 Subject: Reading from serial port & writing to X console Message-ID: <3F16B9A1.2000602@pc.jaring.my> Hi, I'm trying to write a program to read from the serial port & write whatever that is read to the X console (/dev/tty7). For X to recognize the characters sent, I believe you have to send "scancodes". Any suggestion is appreciated. This is my attempt which doesn't work: #!/usr/bin/python scancodes = [[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,0x1c,0x9c,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,0x39,0xb9,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, 0x0b, 0x8b, 0],[0, 2, 130, 0],[0, 3, 131, 0],[0, 4, 132, 0],[0, 5, 133, 0],[0, 6, 134, 0],[0, 7, 135, 0],[0, 8, 136, 0],[0, 9, 137, 0],[0, 10, 138, 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],[0x2A,0x1E,0x9E,0xAA],[0x2A,0x30,0xb0,0xAA],[0x2A,0x2e,0xae,0xAA],[0x2A,0x20,0xa0,0xAA],[0x2A,0x12,0x92,0xAA],[0x2A,0x21,0xa1,0xAA],[0x2A,0x22,0xa2,0xAA],[0x2A,0x23,0xa3,0xAA],[0x2A,0x17,0x97,0xAA],[0x2A,0x24,0xa4,0xAA],[0x2A,0x25,0xa5,0xAA],[0x2A,0x26,0xa6,0xAA],[0x2A,0x32,0xb2,0xAA],[0x2A,0x31,0xb1,0xAA],[0x2A,0x18,0x98,0xAA],[0x2A,0x19,0x99,0xAA],[0x2A,0x10,0x90,0xAA],[0x2A,0x13,0x93,0xAA],[0x2A,0x1f,0x9f,0xAA],[0x2A,0x14,0x94,0xAA],[0x2A,0x16,0x96,0xAA],[0x2A,0x2f,0xaf,0xAA],[0x2A,0x11,0x91,0xAA],[0x2A,0x2d,0xad,0xAA],[0x2A,0x15,0x95,0xAA],[0x2A,0x2c,0xac,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,0x1E,0x9E,0],[0,0x30,0xb0,0],[0,0x2e,0xae,0],[0,0x20,0xa0,0],[0,0x12,0x92,0],[0,0x21,0xa1,0],[0,0x22,0xa2,0],[0,0x23,0xa3,0],[0,0x17,0x97,0],[0,0x24,0xa4,0],[0,0x25,0xa5,0],[0,0x26,0xa6,0],[0,0x32,0xb2,0],[0,0x31,0xb1,0],[0,0x18,0x98,0],[0,0x19,0x99,0],[0,0x10,0x90,0],[0,0x13,0x93,0],[0,0x1f,0x9f,0],[0,0x14,0x94,0],[0,0x16,0x96,0],[0,0x2f,0xaf,0],[0,0x11,0x91,0],[0,0x2d,0xad,0],[0,0x15,0x95,0],[0,0x2c,0xac,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]] def readserial(dev='/dev/ttyS0'): p = open(dev) line = '' line = char = '' while char <> chr(13): char = p.read(1) if char <> '': line = line + char print line # write to /dev/tty7 which is console for X tty7 = open('/dev/tty7', 'w') #import FCNTL, fcntl #import termios, TERMIOS for ch in line: for ch1 in scancodes[ ord(ch)]: if ch1: tty7.write("%c"%chr(ch1)) tty7.close() p.close() if __name__ == '__main__': while 1: readserial() From nirina at mail.blueline.mg Sat Jul 19 04:53:17 2003 From: nirina at mail.blueline.mg (Raseliarison nirinA) Date: Sat, 19 Jul 2003 11:53:17 +0300 Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively Message-ID: <00e701c34dd4$636d0340$f7a2383e@raseliar> hi all, i found an unanswered question at http://www.faqts.com/knowledge_base/index.phtml/fid/538 with possible response below. i've tried to send it at faqt.python but can't figure out how to edit the page. so i put it here. i want to kwon if this can convert all wave file. is there other encodage than 8 or 16 bits for .wav files? any bug and comment are welcome -- nirinA #--------------stereo2mono-R.py--------------- '''stereo2mono-R.py convert stereo to mono recursively usage : python stereo2mono-R.py path-directory ''' import os, sys from stereo2mono import * directory = sys.argv[1] os.chdir(directory) for name in os.listdir('.'): if name.endswith('.wav'): w = Stereo2Mono(name) if w.isStereo() == 1: print '%s is in stereo'%name print 'Check for %s samples in the audio frame'%SAMPLING w.CompareSampling() print 'Both channels seem to be identical' print 'Check all data frames and save to mono file' w.CompareAndSave() print 'Done' else: print '%s is already in mono'%name else: pass #-----stereo2mono.py----------- '''stereo2mono.py convert a stereo wave to mono if both channels are identical http://www.faqts.com/knowledge_base/view.phtml/aid/12121/fid/538 ''' import wave, sys FORMAT = {'11':'1b','12':'1h','21':'2b','22':'2h'} # format for wave files encoded in 8 and 16 bits SAMPLING = 128 class Stereo2Mono: '''open the wave file and get its parameters compare the channels it will be done in two steps. samples are first compared, then if the samples are identical further comparison is performed and the mono wave file created ''' def __init__(self, name): self.name = name self.w = wave.open(self.name) def isStereo(self): if self.w.getnchannels() == 2: return 1 else: return 0 def format_in(self): self.fmt = ''.join((str(self.w.getnchannels()), str(self.w.getsampwidth()))) return FORMAT.get(self.fmt) def format_out(self): self.fmt = ''.join(('1', str(self.w.getsampwidth()))) return FORMAT.get(self.fmt) def Parameters(self): return self.w.getparams() def Compare(self, amplitude): if amplitude[0] == amplitude[1]: return 1 else: return 0 def CompareSampling(self): for s in range(0, self.Parameters()[3],SAMPLING): if self.Compare(wave.struct.unpack( self.format_in(),self.w.readframes(1))) == 1: pass else: print 'channels at %s are not identical,abort!'%s #sys.exit() print 'Samples pass test' def CompareAndSave(self): '''Compare all and save to mono''' self.w.rewind() self.chars = '/-\\|' self.Save = wave.open(self.name.split('.')[0]+ '-mono'+'.wav','w') self.newparams = (1, self.Parameters()[1], self.Parameters()[2], self.Parameters()[3], self.Parameters()[4], self.Parameters()[5]) self.Save.setparams(self.newparams) for i in range(1, self.Parameters()[3]+1): self.UnPack = wave.struct.unpack( self.format_in(), self.w.readframes(1)) if self.Compare(self.UnPack) == 1: self.Save.writeframes(wave.struct.pack( self.format_out(), self.UnPack[0])) sys.stdout.write(chr(13)) sys.stdout.write('%s %i/%i ' % ( self.chars[i % 4], i, self.Parameters()[3])) sys.stdout.flush() else: print 'Data at index %s are not the same, abort!'%i self.w.close() self.Save.close() def main(): try: name = sys.argv[1] w = Stereo2Mono(name) if w.isStereo() == 1: print '%s is in stereo'%name print 'Check for %s samples in the audio frame'%SAMPLING w.CompareSampling() print 'Both channels seem to be identical' print 'Check all data frames and save to mono file' w.CompareAndSave() print 'Done' else: print '%s is already in mono'%name except: print '''usage : python stereo2mono.py the-stereo-wavefile.wav\n the wave file must be encoded in 8 or 16 bits''' if __name__ == '__main__': main() # 030718 19:41:48 nirinA From webmaster at beyond-thoughts.com Sat Jul 12 17:53:06 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Sat, 12 Jul 2003 23:53:06 +0200 Subject: Python Global Constant; __builtins__ In-Reply-To: References: Message-ID: <3F108342.4020408@beyond-thoughts.com> Hello, Maybe I missunderstood the OP. So I said that __builtins__ might be useful. I know that you should not use it in most cases because it makes code less readable (where is xy defined?) and might cause unwanted side-effects. However e.g. if you're programming a big framework like Zope it is useful. cbf From drs at ecp.cc Wed Jul 2 03:36:19 2003 From: drs at ecp.cc (drs) Date: Wed, 02 Jul 2003 07:36:19 GMT Subject: My Big Dict. References: <20030702073735.40293ba2.christophe.delord@free.fr> Message-ID: "Christophe Delord" wrote in message news:20030702073735.40293ba2.christophe.delord at free.fr... > Hello, > > On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote: > > > Greetings, > > > > (do excuse the possibly comical subject text) > > > > I need advice on how I can convert a text db into a dict. Here is an > > example of what I need done. > > > > some example data lines in the text db goes as follows: > > > > CODE1!DATA1 DATA2, DATA3 > > CODE2!DATA1, DATA2 DATA3 > > > > As you can see, the lines are dynamic and the data are not alike, they > > change in permission values (but that's obvious in any similar > > situation) > > > > Any idea on how I can convert 20,000+ lines of the above into the > > following protocol for use in my code?: > > > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} > > > > If your data is in a string you can use a regular expression to parse > each line, then the findall method returns a list of tuples containing > the key and the value of each item. Finally the dict class can turn this > list into a dict. For example: and you can kill a fly with a sledgehammer. why not f = open('somefile.txt') d = {} l = f.readlines() for i in l: a,b = i.split('!') d[a] = b.strip() or am i missing something obvious? (b/t/w the above parsed 20000+ lines on a celeron 500 in less than a second.) -d From vze4rx4y at verizon.net Thu Jul 24 15:59:59 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 24 Jul 2003 19:59:59 GMT Subject: Mystery Theater New Style Classes References: Message-ID: <3VWTa.23726$0F4.18360@nwrdny02.gnilink.net> "Bob Gailer" > Predict the output: > > class A(int): > classval = 99 > def __init__(self, val = 0): > if val: > self = val > else: > self = A.classval > a=A(3) > b=A() > print a,b The output would be 3 and 0. I think the point is that the value binding occurs in the int.__new__ classmethod and that self already has its value when __init__ is called. Assigning the local variable, self, has no effect. The other tidbit is that int() with no args returns zero. Raymond Hettinger From guettler at thomas-guettler.de Mon Jul 21 07:07:47 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 21 Jul 2003 13:07:47 +0200 Subject: Directory Structure for Distutils References: Message-ID: Thomas G?ttler wrote: > Hi! > > What is the best directory structure for python modules? > > ... (Replying to myself) I downloaded the source of distutils and took it as an example. One thing is still unclear: How can I copy non python files into the destination? There is a directory called "gif" which needs to be in the directory of the my module. thomas From jjl at pobox.com Sun Jul 20 13:28:11 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Jul 2003 18:28:11 +0100 Subject: object as a reserved keyword References: <7dokhvgv12fdbha8sun6c6q658cth5uq2c@4ax.com> Message-ID: <87adb9f6qc.fsf@pobox.com> danb_83 at yahoo.com (Dan Bishop) writes: [...] > When I write in other languages and need a meaningless variable name, > I tend to use an abbreviation for the variable's type. > > public void foo(String str) {/* ... */} > public void foo(List list) {/* ... */} > > As you can see, this convention doesn't carry over very well to > Python. Which is frequently a good thing, I think. Most of the time one does this, it's (bad) laziness. Better to think of a name that describes more than the type. People do often use names ending in 's' for iterators (including sequences), which is useful for ease of reading: foos = [Foo(1), Foo(2), Foo(3)] for foo in foos: print foo (breaking the rule about naming things after their type there, of course! -- but I have the excuse that there's no meaning *there* to use when picking names in that made-up example) Also, I often use the name 'text' where you write 'str' above. John From psycho_78 at libero.libero.it Thu Jul 31 09:08:07 2003 From: psycho_78 at libero.libero.it (Simone Finotti) Date: Thu, 31 Jul 2003 15:08:07 +0200 Subject: [Newbie] FAQ? Message-ID: hi all, is there a FAQ for this NG? TIA, Simone -- questo articolo e` stato inviato via web dal servizio gratuito http://www.newsland.it/news segnala gli abusi ad abuse at newsland.it From jamie at nospam.net Mon Jul 7 00:03:29 2003 From: jamie at nospam.net (Jamie) Date: Mon, 7 Jul 2003 16:03:29 +1200 Subject: Problems with py2exe for python 2.3 beta Message-ID: Hi all, I have a wxPython application that I'm packaging with py2exe. I've encountered a couple of problems with the latest py2exe with the latest python and wxPython releases, and was wondering if any of you have had a similar experience. The version for python 2.2 works like a charm. - I've included "-p encodings" in the command line flags, but still get the "no codec search functions registered" error at runtime. - py2exe is now including tcl files as dependencies, whereas these weren't required in the python 2.2 version. Also, I was hoping to use the archived executable to do imports with the new zip import feature - is there any reason why this wouldn't work as opposed to importing it from a regular zip file? Many thanks, Jamie From bokr at oz.net Sun Jul 20 19:44:00 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Jul 2003 23:44:00 GMT Subject: List of declared variables in interactive Python session? References: <20030720143606.18124.00000262@mb-m15.aol.com> <3F1AEAFB.3C62F613@engcorp.com> Message-ID: On Sun, 20 Jul 2003 15:18:19 -0400, Peter Hansen wrote: >"Raymond Arthur St. Marie II of III" wrote: >> >> >>> vars( ) >> >> {'d': 'pywin', '__builtins__': , '__name__': >> '__main__', 'pywin': > 'C:\PYTHON22\lib\site-packages\Pythonwin\pywin\__init__.pyc'>, '__doc__': None} >> >> >>> for v in vars(): print v >> ... >> >> Traceback (most recent call last): >> File "", line 1, in ? >> RuntimeError: dictionary changed size during iteration > >for v in vars().copy(): print v > >works fine... > I sometimes find it handy to leave out underscore items: >>> [name for name in dir() if not name.startswith('_')] [] >>> x=123 >>> [name for name in dir() if not name.startswith('_')] ['name', 'x'] vs. >>> dir() ['__builtins__', '__doc__', '__name__', 'name', 'x'] Regards, Bengt Richter From martin at v.loewis.de Sun Jul 13 11:14:37 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jul 2003 17:14:37 +0200 Subject: Windows XP - Environment variable - Unicode In-Reply-To: References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: John Roth wrote: > Good point. That does make it somewhat harder; the routine > would have to precompute both versions, and store them with > both standard strings and unicode strings as keys. That doesn't work. You cannot have separate dictionary entries for unicode and byte string keys if the keys compare and hash equal, which is the case for all-ASCII keys (which environment variable names typically are). Regards, Martin From jjl at pobox.com Sat Jul 19 09:42:09 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Jul 2003 14:42:09 +0100 Subject: How to identify the method that has called another method ? References: <764b8294.0307180620.37781a4@posting.google.com> <7h34r1j23g1.fsf@pc150.maths.bris.ac.uk> Message-ID: <87oezqr5u6.fsf@pobox.com> Michael Hudson writes: > martin_a_clausen at hotmail.com (Mars) writes: > > > I am using Python 2.2.3 and new-style classes. I want to implement a > > static factory method to build objects for me. My plan is to have > > __init__ check that it has been called from said factory method and > > not directly. Is there a elegant way of achieving this ? > > No. sys.getframe(1).f_code.co_name might be a start. > > > (and is this a silly idea in general ?) > > I've always disliked trying to disallow this kind of abuse -- it's > very hard to make it impossible, and I think you're better off just > documenting the restrictions. [...] A hard-to-miss way of documenting it: class MyClass: def __init__(self, arga, argb, yes_I_know_I_should_use_the_factory_function=False): def Factory(): return MyClass(get_arga(), get_argb(), True) John From lamar_air at hotmail.com Tue Jul 15 16:23:09 2003 From: lamar_air at hotmail.com (lamar_air) Date: 15 Jul 2003 13:23:09 -0700 Subject: String Manipulation Message-ID: <2c6431ab.0307151223.4173c4ee@posting.google.com> I need a piece of code that takes a string like this string1 = "aaa/bbb/ccc/dd" and extracts a string containting the character after the last "/" So for this example the result would be "dd" like this: for i=0; string1.right(i) != '/'; i++ result = string1.mid(i, string1.length()) but in python. From ianb at colorstudy.com Sun Jul 13 22:47:30 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2003 21:47:30 -0500 Subject: anything like C++ references? In-Reply-To: References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <1058150850.28457.525.camel@lothlorien> On Sun, 2003-07-13 at 20:32, Aahz wrote: > In article , > Ian Bicking wrote: > > > >(Admittedly, some confusion may occur because these very different > >operations use the same syntax: > > > > x = 10 > > x[0] = 10 > > obj.x = 10 > > > >The second and third are entirely different from the first.) > > No, they aren't. They are precisely the same; they just have different > assignment targets. Sure they are different. The first is a primitive operation binding the variable x. The second gets x, and calls x.__setitem__(0, 10), and the third is equivalent to setattr(obj, 'x', 10). The first is primitive syntax. I suppose you could say that it could be reduced to operations on locals() and globals(), but I feel like that's a detail that is best not brought up ;) The local and global scope are not as flexible as other objects The other two are really just syntactic sugar. Ian From rshaw2 at midsouth.rr.com Thu Jul 3 11:40:24 2003 From: rshaw2 at midsouth.rr.com (Richard) Date: 3 Jul 2003 08:40:24 -0700 Subject: How to setup webserver for Python References: Message-ID: <84e0f331.0307030740.41c687fd@posting.google.com> "A" wrote in message news:... > Hello, > I have a webhosting account with one company. > I can use python from command line through Telnet(SSH) but can not run successfully > Python program from a browser.(They use Apache web server.) > What must I do? > What permission must I set on directory and the python file? > Here is a simple program I would like to run > ######## > #!/usr/bin/python > print "Content-Type: text/html" print > print"AAA" > ######## > Thanks for help > Ladislav > > I look forward to hearing from you soon. > > Best regards, > Ladislav Blazek( Mr.) I would ask if they have mod_python setup, and if not, I would request it. This keeps python loaded into memory so there is much less load put on the server than having to load python every time your page got a hit. Richard From andy at wild-flower.co.uk Thu Jul 10 19:01:44 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 11 Jul 2003 00:01:44 +0100 Subject: Executing scripts In-Reply-To: <3F0D94CA.38C71FFC@engcorp.com> References: <3F0D94CA.38C71FFC@engcorp.com> Message-ID: <200307110001.44807.andy@wild-flower.co.uk> On Thursday 10 Jul 2003 5:31 pm, Peter Hansen wrote: > Ken Fettig wrote: > > I am having a problem executing scripts from python. The script is > > located at C:\Python22\learn and is named more.py. This is an example > > from the Programming Python book by Mark Lutz published by O'Reilly. I > > have tried how the author outlines to execute the script but it doesn't > > work. I am on a Windows 2000 machine. > > The example shows to, at the command line, enter C:\Python22\learn>python > > > > more.py more.py. I get the following output: > > >>> C:\Python22\learn>python more.py more.py > > > > File "", line 1 > > C:\Python22\learn>python more.py more.py > > ^ > > I have tried many combinations all unsuccessfully. Can someone please > > help me???? > > You are not at the right command line. The >>> indicates you have already > run Python, but are trying to execute a DOS command line at the *Python* > prompt. > > See http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp > > -Peter Ken, You need: execfile("learn\more.py") if you are already at the PYTHON command line. In computer books, it is convention to usually show the PROMPT as well as the command you should enter (The prompt is the computer program's signal to the user (you!) that it's ready for you to type something). The "C:\Python22\learn>" bit is the DOS (or win 2000 CMD) PROMPT. The PYTHON PROMPT is ">>>". DOS (or WIN 2k CMD.EXE) doesn't understand PYTHON commands. PYTHON doesn't understand DOS commands. To get a win 2k CMD prompt, click Start/Run... and enter CMD into the prompt. A black box will appear with the DOS prompt in it. If you then type... c:\python22\python c:\python22\learn\more.py ...it should launch your program. Python is probably on your PATH environment variable, so you *may* be able to get away with (note the prompt!!): C:\>cd python22 C:\Python22>python learn\more.py ... try it and see, but remember, don't type the PROMPTS! hope that helps -andyj From peter at engcorp.com Mon Jul 14 23:08:44 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 23:08:44 -0400 Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> Message-ID: <3F13703C.C12392D6@engcorp.com> Conrad wrote: > > I'll give them a shot tomorrow. USPP made me a little > nervous, because frankly, it looks like it died a year > and a half ago, with outstanding Linux bugs Thanks for checking that out better than I did. I was worried about that myself, having seen nothing about it for a very long time, but the name had stuck in my head. > pyserial seemed from it's docs > to require jython - which means pulling in a whole slew > of third-party DLLs for Java. No! Try PySerial first, for sure. It does NOT require Jython, but does support it. As the home page says, "It provides backends for stadard (sic) Python running on Windows, Linux, BSD (possibly any POSIX compilant system) and Jython. The module named "serial" automaticaly (sic) selects the appropriate backed (sic)." (Chris, if you'd like, I'll happily proofread that page and correct a few spelling errors for you. ;-) -Peter From richardc at hmgcc.gov.uk Tue Jul 15 04:38:15 2003 From: richardc at hmgcc.gov.uk (richardc) Date: Tue, 15 Jul 2003 09:38:15 +0100 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> Message-ID: <3f13bd77$1@mail.hmgcc.gov.uk> Thanks for all the replies, I think I'll use optik for the argument parsing, its very close to a C++ library I wrote to do the same job. Although my 10 second scan of the docs didnt reveal exactly what the 'store' param dose ? As for 'convention' based 'enforcement', not so shure about that as a programming paradime, perhaps thats the C++ programmer in me :) but if its the way to do it ... so be it. Im guessing from the lack of responce that there arnt many python editors which run on OSX. As you all seem so helpful I'll ask a couple of other questions. 1. How do tyou do enum's in python, infact dose anybody know of a C++ -> Python crossreference doc out there ? 2. Is there a reason that the python documentation is ... dont know how to describe it really. Ive used PHP and their documentation and its great, particually the 'user comments' bit. But for some reason python's seems a little 'obscure'. I mean doing things like searching for 'for', I want a simple description and some examples showing me the use of range in a for loop, and answering how to reverse iterate through a list. Instead I get the formal syntax for the 'for' command. Not really that useful. 3. How do I reverse iterate through a loop ... is there an easier way than something like the following l = ['some', 'text', 'in', 'a', 'list' ] for i in range( 0, len( l ) ): do something to l[ i ] 4. Is there an easy way to reverse read a file ? I mean like a 'getline' that works by reading backwards through the file. Im guessing getting single characters and moving the file pointer back is going to be slow in python. Its not actally that important... just wondering Many thanks Rich From tjland at iserv.net Mon Jul 28 00:15:35 2003 From: tjland at iserv.net (tjland at iserv.net) Date: Mon, 28 Jul 2003 00:15:35 -0400 (EDT) Subject: How to reverse lookup characters in list? Message-ID: <1886.68.75.128.108.1059365735.squirrel@webmail.iserv.net> Okay so im working on a very simple encryption method using just loops. Kind of novel i think. Okay so first i set up a list of the alphabet with just every seperate letter, then user is prompted for a word, this is not user friendly just for me. Ok now as you can see below this is pretty basic, if u can follow all the loops i get to a point where I have the letter positions in the list for the final word but i dont know of a way to come back with the corresponding letter to output to the user. Ummm some help would be really appreciated. Sorry about the length! ---------------------------------------------------------------------------- from time import sleep #Alphabet list used to move letters forward for simple encryption. alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] word_list = [] number_list = [] number_list2 = [] new_word = [] #variable for how far you want to switch v = 2 word = raw_input("Word: ") a = len(word) for x in range(0, len(word)): print word[x], word_list.append(word[x]) b = alphabet.index(word[x]) number_list.append(b) for x in range(0, len(number_list)): c = number_list[x] c = c + v number_list2.append(c) for x in range(0, len(number_list2)): d = number_list2[x] new_word.append(d) for x in range(0, #Stopped here because dont know of way to switch back. ---------------------------------------------------------------------------- When you see the net take the shot When you miss your shot shoot again When you make your shot you win! Just remember Offense sells tickets But defense wins championships! From op73418 at mail.telepac.pt Sat Jul 12 18:12:24 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sat, 12 Jul 2003 23:12:24 +0100 Subject: any such thing as list interleaving? References: Message-ID: On Sat, 12 Jul 2003 14:00:49 -0700, Tom Plunket wrote: > >I find myself often doing the following sort of thing (sorry for >lack of whitespace, I don't want the line to break): > >for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)): > # ... > >This definitely seems like a roundabout way to loop through >parallel lists together. Is this map routine truly the easiest/ >best/most straight-forward way to do a for loop through parallel >lists, if I feel that the Python anti-idom of: > Check the zip builtin: >>> help(zip) Help on built-in function zip: zip(...) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. >for index in range(len(myList)): > entry = aList(index) > anotherEntry = anotherList(index) > # ... > >??? > >This also brings up a similar problem for me when iterating over >dictionaries: > >for key in myDict: > value = myDict[key] > # ... > Fire the interpreter and type: >>> help(dict) As it's a long stretch of text, I'll just post the relevant part: | iteritems(...) | D.iteritems() -> an iterator over the (key, value) items of D | >This seems a pretty sloppy way to go about it, imo. There must >be something more in the Python spirit! :) > >Thanks. > >-tom! With my best regards, G. Rodrigues From touma at eglin.af.mil Tue Jul 29 13:57:59 2003 From: touma at eglin.af.mil (JamesT) Date: 29 Jul 2003 10:57:59 -0700 Subject: Wrtiting AVI files with Python Message-ID: <3b24bbb8.0307290957.17a126b8@posting.google.com> Hi all, I looked around for information about how to write AVI files with Python but I didn't find any. PIL does not have that feature implemented. The closest thing I found what the source code for avifile which is in C++. Does any one know if there is such a tool for Python or some libraries that I could import and use in my code? Thanks, JET From pu at vo.lu Thu Jul 31 18:43:34 2003 From: pu at vo.lu (Patrick Useldinger) Date: 31 Jul 2003 15:43:34 -0700 Subject: bug in file.write() ? Message-ID: <13a4e2e3.0307311443.299bd59d@posting.google.com> Hi, I think I found a bug in the write method of file objects. It seems as if before writing each block, a check was done in order to verifiy that there is enough space left for the *whole* file, not for the *remaining* data to be written. It happens both under 2.3 and 2.2.3. Any ideas? ========================== Python 2.3 ================================== I:\My Programs\dfc>b2 start dfc.py [v.0.19.final (July 31st, 2003)] @ 2003-08-01 00:21:48 Python 2.3.final running on win32 reading configuration file dfcCfgBackupCd instantiating processor(s) . paths & includes/excludes taken from configuration file creating initial reference point i:\dfc\ref\dfcRefBackupCd.dfc .copying i:\dfc\arc\dfcArchive cheetah 20030731-234648 F.zip to f:\dfcArchive cheetah 20030731-234648 F.zip Traceback (most recent call last): File "I:\My Programs\dfc\dfc.py", line 199, in ? dfc.doProcess(cfgFile.DFCProcTags) File "I:\My Programs\dfc\dfc.py", line 144, in doProcess newStat=self.newStat.get(fileName,None)) == None: File "I:\My Programs\dfc\dfc.py", line 129, in process return self.pubSub.publishMessage(self.pubSubProcess,kwargs,checkRet=True) File "I:\My Programs\dfc\PubSub.py", line 170, in publishMessage retVal.append(subscriber(**dict(args))) File "I:\My Programs\dfc\dfcProcCopy.py", line 20, in process shutil.copyfile(fileName,toFile) File "C:\Python23\lib\shutil.py", line 39, in copyfile copyfileobj(fsrc, fdst) File "C:\Python23\lib\shutil.py", line 24, in copyfileobj fdst.write(buf) IOError: [Errno 28] No space left on device I:\My Programs\dfc>dir f: Volume in drive F is Backup 01 Volume Serial Number is E2CB-1650 Directory of F:\ 18/05/2002 15:39 . 18/05/2002 15:39 .. 01/08/2003 00:25 299.630.592 dfcArchive cheetah 20030731-234648 F.zip 1 File(s) 299.630.592 bytes 2 Dir(s) 299.636.736 bytes free ========================= Python 2.2.3 ================================= I:\My Programs\dfc>i:\py222\python.exe dfc.py dfcCfgBackupCd start dfc.py [v.0.19.final (July 31st, 2003)] @ 2003-08-01 00:29:08 Python 2.2.3.final running on win32 reading configuration file dfcCfgBackupCd instantiating processor(s) . paths & includes/excludes taken from configuration file creating initial reference point i:\dfc\ref\dfcRefBackupCd.dfc .copying i:\dfc\arc\dfcArchive cheetah 20030731-234648 F.zip to f:\dfcArchive cheetah 20030731-234648 F.zip Traceback (most recent call last): File "dfc.py", line 199, in ? dfc.doProcess(cfgFile.DFCProcTags) File "dfc.py", line 144, in doProcess newStat=self.newStat.get(fileName,None)) == None: File "dfc.py", line 129, in process return self.pubSub.publishMessage(self.pubSubProcess,kwargs,checkRet=True) File "PubSub.py", line 170, in publishMessage retVal.append(subscriber(**dict(args))) File "dfcProcCopy.py", line 20, in process shutil.copyfile(fileName,toFile) File "i:\py222\lib\shutil.py", line 30, in copyfile copyfileobj(fsrc, fdst) File "i:\py222\lib\shutil.py", line 20, in copyfileobj fdst.write(buf) IOError: [Errno 28] No space left on device ======================================================================== From peter at engcorp.com Mon Jul 14 14:47:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 14:47:00 -0400 Subject: (Suggestion) Download Options References: <221d8dbe.0307140147.6417e501@posting.google.com> Message-ID: <3F12FAA4.58026440@engcorp.com> srijit at yahoo.com wrote: > > Can we have a download option for upcoming Python 2.3 without TCL/Tk? > Though I know the extremely popular Tkinter is the default GUI of > Python, I see one immediate advantage of a download option without > TCL/Tk > 1) Download size is less and it is a boon for people like me with slow > modem connection. > 2) Tkinter with TCL/TK can be a separate add-on > > I look forward to opinions from members. Maybe this should be written up as a PEP? See http://www.python.org/peps/pep-0001.html for more information. -Peter From donn at drizzle.com Thu Jul 24 11:13:35 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 24 Jul 2003 15:13:35 -0000 Subject: How to disable output messages of the child process, in spawnv( )? References: <3f1eddc9$0$160$a1866201@newsreader.visi.com> Message-ID: <1059059614.658900@yasure> Quoth nushin2 at yahoo.com (nushin): | Is there any trick to disable the output of a child process spawned by | spawnv( ) API? No. | I believe in Python and i am sure there's a way around it. Correct me | if i am wrong. You believe in tricks, is the problem. Read what people are telling you. You can redirect output of a command, you can do it Python, but the only way to do it in spawnv is to make spawnv execute a shell command. Donn Cave, donn at drizzle.com | grante at visi.com (Grant Edwards) wrote in message news:<3f1eddc9$0$160$a1866201 at newsreader.visi.com>... |> In article , nushin wrote: |> > I'd like to disable the output of the process spawned by spawnv( ) |> > API, but the catch is that i *have to* see the output of the parent |> > process making the spawnv( ) call. Has anyone done that? I have some |> > pointers that by using dup2( ) API i might be able to do that, any |> > ideas how? Also, i have to spawn as an asynch call, using P_NOWAIT, |> > e.g.,: |> > |> > os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) |> |> Nope. |> |> The ">" and "&" are things that a shell (like bash or ksh) |> handles. The python interpreter has no idea what to do with |> them. If you want to use ">" and "&", then spawn a shell, and |> pass it a command to run the python program with output |> redirected. From max at alcyone.com Sat Jul 12 19:11:23 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 16:11:23 -0700 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> <87y8z34d3d.fsf@pobox.com> Message-ID: <3F10959B.17327C19@alcyone.com> "John J. Lee" wrote: > Perhaps Erik was wondering, as I was, where that " instance > object>" came from. Indeed. I was quite aware of what was happening, just not clear on why his particular Python session said something that mine didn't. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Now I must follow them! \__/ Beowulf, King of the Geats From jjl at pobox.com Mon Jul 7 08:24:39 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Jul 2003 13:24:39 +0100 Subject: Will Python exceptions be documented? References: <33a013af.0307070318.73013d4@posting.google.com> Message-ID: <873chi8qyg.fsf@pobox.com> vegard at mail.com (Vegard Bakke) writes: > From whet I can see, Python documentation is lacking a very important > piece of information. Very few functions have documented what > exceptions they raise, and under what cicumstances. Is this a task on > the schedule? IIRC, yes. [...] > I have seen many different examples for catching exceptions from > open(). Which is the right one? What examples, specifically? The docs say IOError can be raised. Just about everything can raise ValueError, TypeError, KeyboardInterrupt and MemoryError, so they aren't typically documented. I'm not sure exactly when WindowsError (rather than something more specific) gets raised. Not answering your question, but as a BTW: in that particular case, if you're getting uncontrolled input you might sometimes want to normalise the exceptions raised by catching everything but a few exceptions. This is useful because you might not have anticipated every way that weird input might trip up your code (ie. your code may be buggy). See this recipe and my comment http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/101853 In fact, I didn't show the try / finally needed to close the file there, so it should really be: import traceback from cStringIO import StringIO DEBUG = True def debug(msg): print msg def load(filename): f = open(filename) try: try: # Some code that might raise IOError, or another exception that you # weren't expecting, if the user is imaginitive enough... except (AssertionError, KeyboardInterrupt, IOError): # NOTE WELL the brackets around the exception classes -- an except # with two arguments means something quite different! raise except: if DEBUG: f = StringIO() traceback.print_exc(None, f) debug("uncaught exception:\n%s" % f.getvalue()) raise IOError, "invalid file '%s'" % filename finally: f.close() load("/some/nonsense/file.txt") > The error from function math.log(0) is a by unpredictable, but at > least that is documentet. What about all the others? math.asin(2), > shutil, os, sys? > > All know that asin(2) is wrong, but how do I know that ValueError is > the exception I should catch, and how do I know that is the only one? > (Sorry, try it is the wrong answere here.) For the math module, the log(0) situation applies. From the 2.3 library docs for the math module: Note: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases is loosely specified by the C standards, and Python inherits much of its math-function error-reporting behavior from the platform C implementation. As a result, the specific exceptions raised in error cases (and even whether some arguments are considered to be exceptional at all) are not defined in any useful cross-platform or cross-release way. For example, whether math.log(0) returns -Inf or raises ValueError or OverflowError isn't defined, and in cases where math.log(0) raises OverflowError, math.log(0L) may raise ValueError instead. > My other issue with is concerning the documentation of the exceptions > themselves. How can I find out that I can use 'filename', 'errno' and > 'strerror' for the exception IOError without having to use > dir(IOError())? And is it valid in all versions/platforms? That's documented under the base class, EnvironmentError. > Since I'm critisising the lack of work, I will voulunteer to help out > with the process. But I will need some guidance and pointers in the [...] Great. I'd say just submit some specific doc patches with the knowledge you already have (as long as you make it clear where you're unsure). Since that shows you're prepared to do some work on it, it's likely to get you feedback from the people who know all the details but don't have time to work on it themselves. Of course, the core people are probably particularly busy with 2.3 ATM, so don't expect a rapid response. John From me at home.net Sat Jul 5 09:42:50 2003 From: me at home.net (J-P) Date: Sat, 05 Jul 2003 09:42:50 -0400 Subject: Why so many references to global variables? In-Reply-To: References: <0S2Na.6305$bD1.721957@news20.bellglobal.com> Message-ID: Thank you both for the advice, I appreciate it! J-P From dave at pythonapocrypha.com Fri Jul 11 20:42:26 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 11 Jul 2003 18:42:26 -0600 Subject: socket problem In-Reply-To: <955.1057965717@www25.gmx.net> References: <20030711230938.GA22310@intarweb.us> <955.1057965717@www25.gmx.net> Message-ID: <200307111842.26177.dave@pythonapocrypha.com> On Friday 11 July 2003 05:21 pm, Gordon Wetzstein wrote: > > On Sat, Jul 12, 2003 at 01:05:27AM +0200, Gordon Wetzstein wrote: > > > Hello everyone, > > > I have a problem with python sockets. I broadcast a lot of pickled > > objects > > > with socket. sendto(...), that works. Ireceive them on the other site > > with > > > socket.recvfrom(16384) The pickled objects are smaller (like 10000 > > bytes) > > > than the max bytes. > > > > > > The problem appears if I send too many pickled objects very quickly one > > > after another, then I only receive a part of the sent objects. I print > > > them before I send them, they are there but they never reach the > > > destination. When I do a time.sleep(0.1) (but not lesser than 0.1) > > > after socket.send() all is good but it's too slow! > > > > > > Does anyone know what the problem is? And maybe a solution! > > > > UDP is an inherently unreliable protocol. If you require reliable data > > transmission, consider using TCP. > > > > Jp > > > > -- > > But then I can't use braodcast, can I? Nope. You have to choose between building some reliability on top of UDP or tracking your recipients and sending to each one as needed. Even without knowing what you're really trying to do, I recommend the latter. :) -Dave From rimbalaya at yahoo.com Fri Jul 4 08:33:48 2003 From: rimbalaya at yahoo.com (Rim) Date: 4 Jul 2003 05:33:48 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <6f03c4a5.0307022119.2b0a4bc1@posting.google.com> Message-ID: <6f03c4a5.0307040433.756b744e@posting.google.com> > >I think the suggestion to solve the problem by using the __setattr__ > >special method will not work because it intercepts attribute > >assignment of the form "self.attr = somthing", and not what I want, > >which is "name = something". > > Why don't you follow my suggestion about creating your own language? I think it would be too much work for one person, and I don't know how, and I don't think I have the time. Thanks but for now this is beyond my limited capabilities! Rim From g at prullenbak.todd.nu Tue Jul 29 02:58:25 2003 From: g at prullenbak.todd.nu (Giles Todd) Date: Tue, 29 Jul 2003 08:58:25 +0200 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: On Tue, 22 Jul 2003 08:29:14 GMT, Brian Inglis wrote: > That's a lousy printer operator: the ribbon should have been > flipped end around long before it got to that stage. > (That's the old equivalent of shaking a laser toner cartridge.) > You also wouldn't be able to differentiate between commas and > dots, some apostrophes and quotes, maybe bars and bangs, possibly > parens brackets and braces, if you had and used them. On Sunday last, having finally fixed my bike after two years of non-use, I wandered off to Amsterdam's Stedelijk Museum, where there was (and still is) an exhibition of items from its collection of purchases from the 1960s and early 1970s. In the last room (of 32, or thereabouts) there were many May 1968 and anti-Vietnam-war posters, some of them strikingly apt given current events, plus some others dedicated to apparently 'minor' issues. Among the latter were two posters printed on [now I have forgotten the English word for this type of paper, but it has tractor holes along both sides, and is flimsy, and has horizontal perforations every now and then] paper, with a silk-screeened slogan advocating recycling on the supposedly blank side. The posters were under glass, but I could still see the FORTRAN listings on the other side of them. Nice (from both of my points of view). Anyway, to return to the post I am commenting to, the commas on the listings I saw (viewed from the back, from the viewpoint of the person who originally instructed the computer to print them) lacked tails. I expect that this is probably cause for a law suit nowadays, where everything is perfect and, if something turns out not to be perfect then it must be the fault of someone who is LIABLE! Impact ribbons cost money, you know. Whether you replace them or not. The exhibition to which I refer is scheduled to carry on until the end of the year, should anyone else wish to view it. My favourite exhibit was the TV Buddha. Made me giggle for at least five minutes, in spite of it being nearly thirty years old and part of it being in monochrome. Giles. From donn at u.washington.edu Tue Jul 8 12:37:35 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 08 Jul 2003 09:37:35 -0700 Subject: Container behaviour (was: print attitude) References: Message-ID: In article , "Batista, Facundo" wrote: > #- Personally, I think the internal difference between str and repr hits > #- right upon a proper difference: str is for a "reasonable" > #- human-readable representation, and repr is for as faithful and > #- informative a representation as possible. These both have their uses > #- and I approve of the distinction. > > Beyond the specific utilization of str or repr, the detail that get me > confused is: > > repr (container) => repr (elements) > str (container) => repr (elements) > > Why cannot I, when I want the repr of a container, get the repr of its > elements, and when I want the str of a container, get the str of its > elements? Because that wouldn't make sense. Neither does the interpretation of str and repr you quote, so that's not going to be much help. str is a type conversion function. Data types that can sensibly be converted to strings can provide a __str__ function that does that. Conversion doesn't mean that all the information present in the original survives in the result, only the properties that make sense in a string. For example, you might design a sequence data type that is a list of integer values in the range [0..255], say for the purpose of some cryptography, and write a __str__ whose result simply puts the same values in a string type. Or a class that carries a list of strings might just concatenate them (cf. rfc822.Message) But lists themselves do not have any natural conversion to string type, so they fall back to repr. Eric did explain why simply applying str to the elements would make an ambiguous mess. You may be able to describe an ideal result for your application, but there are many other potentially ideal ways to do it and no way to say one of them makes more sense than another. I think if I were obliged to write the __str__ function that applies str to each element of a list, I would simply join the strings with no separator, so str([10, 11, 12]) == '101112', but I'm sure that would offend as many people as it pleased. Donn Cave, donn at u.washington.edu From glenfant at NOSPAM.bigfoot.com Fri Jul 25 11:29:14 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Fri, 25 Jul 2003 17:29:14 +0200 Subject: zope ZMySQLDA References: Message-ID: Hmmm an idea... Perhaps you didn't install MySQL-python-0.9.2 on the python instance that runs Zope. Did you compile the source by yourself or installed the binary installer.exe for your Python version ? "server_capabilities" is defined in a _mysql.so (or .pyd .dll in Windows), so it's quite difficult to hack a binary compiled C module. Strange : My windows Zope config works perfectly with a similar config (but running Zope 2.6.1 and DB server is on a Linux box) Don't try to write your own DA (tricky job) when your some bits away from the result. --Gilles "Don Rivard" a ?crit dans le message de news: ZtydnYXEa-NqpbyiRTvUqg at net1plus.com... > I know get: > > Error Type: AttributeError > Error Value: server_capabilities > > > Traceback (innermost last): > > a.. Module ZPublisher.Publish, line 49, in publish > b.. Module ZPublisher.mapply, line 32, in mapply > c.. Module ZPublisher.Publish, line 38, in call_object > d.. Module Products.ZMySQLDA.DA, line 102, in manage_addZMySQLConnection > e.. Module Shared.DC.ZRDB.Connection, line 58, in __init__ > f.. Module Shared.DC.ZRDB.Connection, line 86, in edit > g.. Module Products.ZMySQLDA.DA, line 120, in connect > h.. Module Products.ZMySQLDA.db, line 179, in __init__ > AttributeError: server_capabilities > > I'm not sure what server_capabilities really means. > I will write my own DA for this. Thanks > > "Thomas G?ttler" wrote in message > news:bfobe2$h17es$1 at ID-63505.news.uni-berlin.de... > > Don Rivard wrote: > > > > > zope 2.71b > > > ZMySQLDA 2.08 > > > MySQL-python-0.9.2 > > > mysql 3.23.55NT > > > > > > When I attempt to connect, by creating a Add Z MySQL Database > Connection, > > > I set the connection string > > > to database user password, and i keep getting the following error > > > Site Error > > > An error was encountered while publishing this resource. > > > > > > Error Type: AttributeError > > > Error Value: server_capabilities > > > > Hi, > > > > If you want to see the stacktrace in error messages put > > > > in the standard_error_message of Zope. This needs to be done > > trough the web and is very handy for debugging. > > > > The stacktrace shows you the file and the line where > > the error occured. Maybe this helps you to find your problem. > > > > thomas > > > > > > From mis6 at pitt.edu Sun Jul 20 10:04:25 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Jul 2003 07:04:25 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> Message-ID: <2259b0e2.0307200604.44d343f4@posting.google.com> "Raymond Hettinger" wrote in message news:.. > I prefer that this feature not be added. Convenience functions > like this one rarely pay for themselves because: > > -- The use case is not that common (afterall, endswith() isn't even > used that often). This is arguable. > -- It complicates the heck out of the C code Really? Of course, you are the expert. I would do it in analogy to "isinstance" and internally calling "ifilter" as you suggest. > -- Checking for optional arguments results in a slight slowdown > for the normal case. Perhaps slight enough to be negligible? Of course without implementation we cannot say, but I would be surprised to have a sensible slowdown. > -- It is easy to implement a readable version in only two or three > lines of pure python. Yes, but not immediately obvious. See later. > -- It is harder to read because it requires background knowledge > of how endswith() handles a tuple (quick, does it take any > iterable or just a tuple, how about a subclass of tuple; is it > like min() and max() in that it *args works just as well as > argtuple; which python version implemented it, etc). I have used "isinstance" and never wondered about these technicalities, so I guess the average user should not be more concerned with .endswith. > -- It is a pain to keep the language consistent. Change endswith() > and you should change startswith(). Change the string object and > you should also change the unicode object and UserString and > perhaps mmap. Update the docs for each and add test cases for > each (including weird cases with zero-length tuples and such). This is true for any modification of the language. One has to balance costs and benefits. The balance is still largely subjective. > -- The use case above encroaches on scanning patterns that are > already efficiently implemented by the re module. I think the general rule is to avoid regular expressions when possible. > -- Worst of all, it increases the sum total of python language to be > learned without providing much in return. That it is exactly what I am arguing *against*: there is no additional learning effort needed, since a similar feature is already present in "isinstance" and an user could be even surprised that it is not implemented in .endswith. > -- In general, the language can be kept more compact, efficient, and > maintainable by not trying to vectorize everything (the recent addition > of the __builtin__.sum() is a rare exception that is worth it). It is > better to use a general purpose vectorizing function (like map, filter, > or reduce). This particular case is best implemented in terms of the > some() predicate documented in the examples for the new itertools module > (though any() might have been a better name for it): > > some(filename.endswith, ('.jpg','.jpeg','.gif','.png')) Uhm... don't like "some", nor "any"; what about "the"? import itertools the=lambda pred,seq: list(itertools.ifilter(pred,seq)) for filename in os.listdir('.'): if the(filename.endswith, ('.jpg','.jpeg','.gif','.png')): print "This is a valid image" That's readable enough for me, still not completely obvious. The first time, I got it wrong by defining "the=itertools.ifilter". I had the idea that "ifilter" was acting just as "filter", which of course is not the case in this example. > The implementation of some() is better than the filter version because > it provides an "early-out" upon the first successful hit. No point against that. > > Raymond Hettinger Michele Simionato P.S. I am not going to pursue this further, since I like quite a lot if the(filename.endswith, ('.jpg','.jpeg','.gif','.png')): dosomething() Instead, I will suggest this example to be added to the itertools documentation ;) I could also submit it as a cookbook recipe, since I think it is a quite useful trick. Also, it is good to make people aware of itertool goodies (myself I have learned something in this thread). From alanmk at hotmail.com Thu Jul 17 18:22:58 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 23:22:58 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: <3F1721C2.9D9E95CF@hotmail.com> JanC: >>> The verb "gignooskoo" (trying to write it with Latin letters ;) Alan Kennedy wrote: >> Why limit yourself to that nasty little us-ascii alphabet? >;-) Ben Finney wrote: > Because it will display reliably on any computer. I'm not so sure. Depends on what you mean by display I suppose. I have a luddite classics professor friend who would deride the assertion that the above is an accurate representation of the original greek word. > > Here it is in a format where almost everybody will be able to see the > > original greek verb on their screen. > > [instructions to cut and paste to a file, then open in a limited range > > of programs, on computers possessing the appropriate font] > > > > So, the challenge to the ASCII proponents is: put the greek word > > "gignooskoo" on everybody's screen, originating from a usenet message, > > in the original greek, where "oo" -> greek letter omega. > > Challenge accepted: > > Open any drawing program. Draw, in order from left to right, the Greek > characters gamma, ipsilon, gamma, nu, omega, sigma, kappa, omega. > > Done. The desired word now appears on the screen. OK, now that we've solved that problem, let's move it up a level. Now we want our greek to be indexable and searchable, so that, for example, I can go to google and have it returned as a hit for the word "gignooskoo". (apologies to greek people and greek scholars for the poor rendering, if you've found this message at all). And we want our greek to be accessible to visually disabled people. Hacks like displaying bitmaps instead of glyphs work for visual rendering. But what about non-visual renderings? Aural renderings? Braille renderings? > Oh, what's that -- you say that's cheating because the user has to use > particular programs? Perform manual steps? Have some existing > knowledge about the process? That the process may fail for any of these > reasons? Not necessarily cheating. Just not scalable (to say, "The Illiad"). And not searchable. Or accessible. Yes, I could automate the process, by say generating a series of vector commands, which results in drawing the glyph on the users screen. But it still isn't searchable. As for particular programs: we all use a limited set of software that fits our personal paradigm for information modelling. But my process only involved OS and software-independent concepts, listed below under "existing knowledge". Also, I think browsers are pretty universal these days. Note also that your proposed process requires the availability of drawing software. Perform manual steps: There'll always be manual steps. I count 12 mouse presses to follow my process. How many for yours? Existing knowledge: All I need was knowledge of copy&paste, file creation and file viewing. I might need Pretty basic and universal computer knowledge, in these days of GUIs. > Those are attributes of the "simple" process of manually manipulating > XML content you gave. Fair enough, if copying and pasting is a complex and error-prone operation. But it's not. And even the copying and pasting would be eliminated if I could have the usenet transport protocol encode its data and metadata in XML. And yes, it would also be necessary if I could encode protocol metadata in UTF-8. But I can't. HTTP and MIME, restrict me to 8-bit character sets like iso-8859-1. > Not every computer is capable of automatically displaying Greek > characters. Even for those which can, there's not yet a universal way > to instruct them to do so. Hence, it is not possible to have any > computer automatically display a word with Greek characters. > But you already knew that, so why the silly challenge? To raise the stakes once somebody has "ante'd up" >;-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jdhunter at ace.bsd.uchicago.edu Tue Jul 22 10:12:14 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Jul 2003 09:12:14 -0500 Subject: How do i run an external program in an python script? In-Reply-To: (Tamer Higazi's message of "Tue, 22 Jul 2003 15:49:18 +0200") References: Message-ID: >>>>> "Tamer" == Tamer Higazi writes: Tamer> Hi! I have no idea about python. I got a c++ program which Tamer> i want to be called from an python script. How do i do Tamer> that? http://groups.google.com Search for: python run external program John Hunter From richardshea at fastmail.fm Mon Jul 14 20:06:53 2003 From: richardshea at fastmail.fm (Richard Shea) Date: 14 Jul 2003 17:06:53 -0700 Subject: NEWBIE: Books/articles on Python code to run with Apache/IIS Message-ID: <282f826a.0307141606.fdf5fd3@posting.google.com> Hi - As the subject implies I'm new to Python. I'm looking for some books/articles etc which would layout the issues involved in building an application in Python which was capable of used by web browsers connecting to either a W2K/IIS box or a *nix/Apache box. In an ideal world the Python code installed on either type of box would be identical, that's the dream ... but is it doable ? I should stress that it is a business application which would be built, not really a content management system. Any pointers would be welcome. regards Richard Shea. From jjl at pobox.com Wed Jul 30 07:23:27 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 12:23:27 +0100 Subject: how best to handle httplib timeouts ? References: Message-ID: <87fzkoi7gw.fsf@pobox.com> "Rich" writes: [...] > getting a page via httplib. the problem seems to be when IIS (or ASP) dies > httplib does not always return and sometimes I'm left with an app that > hangs. what is the best way to handle this ? [...] 2.3 has timeout support for sockets (but not for DNS, IIRC). John From yaipa at yahoo.com Mon Jul 28 18:09:23 2003 From: yaipa at yahoo.com (yaipa h.) Date: 28 Jul 2003 15:09:23 -0700 Subject: Python on a USB storage device? References: Message-ID: <6e07b825.0307281409.5022b134@posting.google.com> Kevin, If you don't mind kick starting your app by hand then everything should work just fine. They are after all just disk drives that use USB as the hardware layer rather than the devices's native ATA, ATAPI, or SCSI physical layer. Now if you want to start your app using AUTORUN or AUTOPLAY, good luck. AUTORUN has been squeezed out of XP because of it's rather large security hole. With AUTOPLAY, you can simulate AUTORUN behavior, but true to MSoft it's rather convoluted. IOMEGA has nice utility that automates AUTOPLAY a bit. Once you understand what their app does you will understand what you are up against. http://www.iomega-activedisk.com/landing.jsp Cheers, --Alan "Kevin Altis" wrote in message news:... > Does anyone have experience running Python from a USB storage device? > Whether it is the need for doing a demo of your application, doing a bit of > consulting, or just showing off Python, it would be handy to be able to run > Python on machines that don't already have Python installed. I'm thinking > about giving this a try, but wondered if anyone is already doing it and the > downsides, if any? > > CD-ROM is not very effective because the media is read-only and too big to > carry in your pocket. I think USB 2.0 is supposed to be roughly 20x faster > than USB for storage devices, but I'm guessing that if you can live with the > load times for machines that don't have USB 2.0, plain USB should still be > effective. > > HP Windows desktops, Linux, and Mac OS X already have Python installed and > Mac OS X (Panther) will have Python 2.3. But even so, you generally have to > install additional packages to get the functionality you want. Having all > you need on a USB storage device and not needing to install anything on the > host machine seems like it would be very convenient. > > ka From skip at pobox.com Sat Jul 5 09:01:00 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 5 Jul 2003 08:01:00 -0500 Subject: pipeline In-Reply-To: <5.2.1.1.0.20030703184133.024aac98@66.28.54.253> References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <5.2.1.1.0.20030703184133.024aac98@66.28.54.253> Message-ID: <16134.52236.278263.30918@montanaro.dyndns.org> Bob> When I worked at IBM I came across a great mainframe utility called Bob> Pipeline. It was driven by a specification that described data Bob> sources, various stages thru which the data was to be sent, various Bob> pipes that connected the stages, and various destinations for the Bob> data. The specification was not procedural. Each line of input was Bob> treated as a unit of data. Bob> I keep looking for something like this to arise for the PC. Have Bob> you seen anything like this? If not I'm inclined to write one, and Bob> Python seems a likely candidate for implementing such a program. Depends upon your application domain. In the scientific visualization realm you might find VTK useful. Also, check out MayaVi, a data visualizer written in Python which uses VTK. If you still live in the RPI area, the VTK folks are headquartered in Clifton Park, NY. For examples of what you can do, check out http://www.kitware.com/ http://mayavi.sf.net/ Skip From bhearsum at myrealbox.com Sun Jul 27 16:07:25 2003 From: bhearsum at myrealbox.com (Ben Hearsum) Date: Sun, 27 Jul 2003 20:07:25 GMT Subject: Cookie.py troubles. Message-ID: I'm confused about the way Cookie.load outputs cookies. Is there a way I can tell it to give me the value of a key? I set my cookie like this: mycookie = Cookie.SimpleCookie() mycookie['key'] = "foobar" print mycookie print("Content-Type: text/html\n\n") print("meow") Now, to retrieve it, the documentation says I parse the HTTP_COOKIE environment variable. Makes sense to me. But when I print it out I get "Set-Cookie: key=foobar;". I was thinking of parsing it with cgi.parse_qs, but even if i do print(mycookie.output(header="")) there's still a ; at the end of the cookie. Here's what I use to print them out: cookie = Cookie.SimpleCookie() cookie.load(os.environ['HTTP_COOKIE']) print("Content-Type: text/html\n\n") print(mycookie.output(header="")) Output: key=foobar; Can anyone provide any advice? - Ben Hearsum From kmoch at whs.edu Thu Jul 24 17:01:18 2003 From: kmoch at whs.edu (Joe Kmoch) Date: Thu, 24 Jul 2003 16:01:18 -0500 (CDT) Subject: not able to run Message-ID: I've tried to install python2.2 on our Solaris 8 system using the package available on the sunfreeware.com site. When I try to run python I get the following: # ls -al python2.2 -rwxr-xr-x 1 bin bin 4902360 Feb 17 20:44 python2.2 # python2.2 ld.so.1: python2.2: fatal: libstdc++.so.5: open failed: No such file or directory Killed # ./python2.2 ld.so.1: ./python2.2: fatal: libstdc++.so.5: open failed: No such file or directory Killed # pwd /usr/local/bin I'm not very astute in dealing with Solaris so I may have missed something somewhere. Incidentally when I tried to do a find on libstd* I did discover that this file existed: ./usr/local/lib/libstdc++.so.2.10.0 but not libstdc++.so.5 I'm not sure what I should do next. Thanks in advance for your help. Joe -- Joe Kmoch Washington High School Director, Academy of Information Technology 2525 N. Sherman Blvd kmoch at whs.edu Milwaukee, WI 53210 (414) 875-5982 (desk) (414) 875-5900 (school) (414) 875-5980 (academy) (414) 875-5915 (fax) From t_therkelsen at hotmail.com Wed Jul 16 05:09:26 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 16 Jul 2003 09:09:26 GMT Subject: hex check References: Message-ID: In article , Ruslan Spivak wrote: > Hello. > > Does anybody have a hint how to check if input hex number is in correct > hex format? > > Thanks in advance. You could try the int() built-in function: Python 2.3b2 (#1, Jun 30 2003, 13:04:39) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> int("f3", 16) 243 >>> int("0xf3", 16) 243 >>> int("f3g", 16) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): f3g >>> You'd have to wrap it in a construct like this, for example: inputhex = "f3" try: i = int(inputhex, 16) except ValueErr: print "Bad hex input: %s" % inputhex Hope this hint helps, Troels Therkelsen. From a.schmolck at gmx.net Thu Jul 3 17:57:27 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 03 Jul 2003 22:57:27 +0100 Subject: Why so many references to global variables? References: Message-ID: J-P writes: > It appears that every time the interpreter tests for > the value of 'myflag', it keeps a reference to it. What makes you think so? This seems rather unlikely to me (not that the references themselves should eat your memory anyway!). Chances are, the C extension code doesn't work correctly (C extensions to python code have to do memory management by hand; increasing and decreasing reference counts for the python objects they deal with as appropriate; so if a bit of code forgets to decrease the refcount, the object will stay alive forever; my guess would be that this it what happens here). So you'll have to debug the C code. Valgrind can be *very* useful for this purpose. If you discover anything else that really helps for tracking down such memory leaks, I'd sure like to know. 'as From andy at wild-flower.co.uk Fri Jul 18 05:45:26 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 18 Jul 2003 10:45:26 +0100 Subject: [development doc updates] In-Reply-To: <20030715221007.07C7A18F01B@grendel.zope.com> References: <20030715221007.07C7A18F01B@grendel.zope.com> Message-ID: <200307181044.36085.andy@wild-flower.co.uk> On Tuesday 15 Jul 2003 11:10 pm, Fred L. Drake wrote: > The development version of the documentation has been updated: > > http://www.python.org/dev/doc/devel/ > > Wide ranging updates accumulated over the weeks preceeding > the release of Python 2.3 release candidate 1. Does the following still hold true? I thought it had all changed - do the new resolution rules only apply to "New Style Classes" ? viz: """ 9.5.1 Multiple Inheritance ..... The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. """ -andyj From alf at fayauffre.org Fri Jul 25 11:26:58 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Fri, 25 Jul 2003 15:26:58 +0000 (UTC) Subject: How to detect typos in Python programs References: Message-ID: Manish Jethani a ?crit : > Hi all, > > Is there a way to detect typos in a Python program, before > actually having to run it. You may want to give a look at pylint (http://www.logilab.org/pylint/) -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From staschuk at telusplanet.net Wed Jul 30 13:21:49 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 30 Jul 2003 11:21:49 -0600 Subject: special case loading modules with imp In-Reply-To: ; from Erendil@aol.com on Wed, Jul 30, 2003 at 11:24:21AM -0400 References: Message-ID: <20030730112149.A361@tibia.amotlpaa.bogus> Quoth Erendil at aol.com: [...] > I need my plugin module to use imp to load that string of code as a module. [...] > So, I just want to switch from using real files to being able to use strings. > The goal is to get a module object that I can place in an array. I was going to suggest StringIO, but it turns out imp.load_module wants a real file, not merely something file-like. However, you can always do it by hand: >>> import imp >>> sourcecode = 'def foo(x): return 11*x' >>> mod = imp.new_module('foo') >>> exec sourcecode in mod.__dict__ >>> mod.foo(16) 176 -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From colinsm.spam-me-not at picsel.com Wed Jul 9 06:05:14 2003 From: colinsm.spam-me-not at picsel.com (Colin S. Miller) Date: Wed, 09 Jul 2003 11:05:14 +0100 Subject: UTF-16-LE and split() under MS-Windows XP In-Reply-To: References: Message-ID: <76pgeb.if8.ln@195.171.216.1> Sorry, attached the wrong data file, correct one is attached this time Colin S. Miller -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unicode.txt URL: From sujatay at cybage.com Tue Jul 15 07:05:04 2003 From: sujatay at cybage.com (sujata) Date: Tue, 15 Jul 2003 16:35:04 +0530 Subject: Regarding Thread pooling Message-ID: <007801c34ac0$f166faa0$31001eac@ud.cybage.com> Hi, I have a query regarding threads. Is it possible to create thread pools in python.i.e. create threads and then retrieve the memory allocated to it so that the same threads can be used over and over again rather than creating new threads each time i wish to execute functions many times. If its possible plz do let me know how to do so. Can one have control over memory this way? Thanking You. ---------------- Regards, Sujata Y -------------- next part -------------- An HTML attachment was scrubbed... URL: From mis6 at pitt.edu Tue Jul 1 09:28:47 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 1 Jul 2003 06:28:47 -0700 Subject: Good code patterns in Python References: Message-ID: <2259b0e2.0307010528.29b95fea@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > If you know that your source code is going to be used > later by others, then I feel that code with the pattern: > > if some_condition: > some_name = some_value > else: > some_name = other_value > > is often a mistake. Much better, safer, would be: > > some_name = some_value > if not some_condition: > some_name = other_value I am sorry, but I feel that the first form is MUCH more readable than the second one; the first form is crystal clear to me, whereas I must read the second form two or three times to understand what it is going on. I would never follow "guidestyles" suggesting the second one! I only miss a ternary operator ... ;) Michele From m at moshez.org Thu Jul 17 09:14:02 2003 From: m at moshez.org (Moshe Zadka) Date: 17 Jul 2003 13:14:02 -0000 Subject: Replacing rexec In-Reply-To: <87adbd73f1.fsf@pobox.com> References: <87adbd73f1.fsf@pobox.com>, Message-ID: <20030717131402.26541.qmail@green.zadka.com> [Aahz] > require forking the code. Note that it's already too easy to write a > DoS attack against Python: 100L**100**100 will do it. Conversely, if > only trusted code is going into the server, there's no need for rexec. [John J. Lee] > I don't see how it's possible to prevent that, whatever language > you're using. Limits on memory and CPU ticks used by untrusted code. This brand new, cutting edge technology is not yet available, and LambdaMOO was, of course, a product of Guido misusing the time-machine. Which doesn't exist itself, either. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From tomas at fancy.org Mon Jul 14 23:57:44 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 20:57:44 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> Message-ID: <9iu6hv4r968o9s1n5fh887u2j7an94de4e@4ax.com> Stephen Horne wrote: > >Are they really technicalities, though? I mean, a mutable object > >can be changed. It's the same object, just changed. Immutable > >objects, however, can't be changed. You can get something that > >appears like changing it, but it's actually building a new thing > >and binding the label to that new thing. > > Yes. But the thing being changed *is* an object, *not* a value. Values > are always immutable - basic fact of mathematics. Sure, but we're not modelling pure mathematics, we're modelling a level of abstraction that's appropriate for the problem that we're solving. class Chameleon: pass a = Chameleon() b = a now, a and b represent the same thing. Say it's a chameleon out in the woods. If I say: a.ClimbTree() then I expect b.GetColor() to return some brown color, since a and b are referring to the same critter. We could argue that "color" should be an immutable object within the chameleon class, and I think argue quite successfully. However, the chameleon itself doesn't become a different animal, it still is the same size and has the same scars. > Variables in mathematics are bound to values. I think Python > should be implemented in a way that respects that. I don't agree, because Python is a language that allows us to model objects in a way that is comfortable to us. If I wanted to use a more mathematically pure language, I would, but that language would likely not be suited to the problems I'm trying to solve. > To me, 'Pythonic' expresses 'doing the right thing'. In this > case, in my view, Python does the wrong thing and expects > everyone to get used to it. In my view, Python does largely what I want it to do regardless of mathematical correctness. -tom! -- There's really no reason to send a copy of your followup to my email address, so please don't. From jjl at pobox.com Tue Jul 8 11:08:46 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Jul 2003 16:08:46 +0100 Subject: path module References: <1057651068.5348.386.camel@lothlorien> Message-ID: <87smphf43l.fsf@pobox.com> holger krekel writes: [...] > Recently, i also did some experimentation with "virtual-fs" features so > that you can transparently access http/ftp/svn files/directories. I even > got that to work with "-completion" but that was quite a hack :-) [...] Note that this overlaps a bit with urllib and urllib2. Just something that would need thinking about. John From tjreedy at udel.edu Tue Jul 22 22:01:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2003 22:01:16 -0400 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: "Mars" wrote in message news:764b8294.0307221520.18017b09 at posting.google.com... > I have looked long and hard at Mr. Martelli's Borg recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 > > It is a very useful substitute for a Singleton, but I can't figure out > how it works. _shared_state is never assigned any value, only > self.__dict__ is assigend self._shared_sate's value - or rather > (self.)_shared_state must be assigned a value at some point, otherwise > the code wouldn't work(right ?). Yes and no. The 'value' of a name is the object it is assigned to. In the last line of the 4 line code and only body line of the __init__ class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state the instance name '__dict__' is rebound to the object also called __shared_state, so that the two names become aliases for the *same* object (of type dict). The original instance dict gets unbound from the name__dict__ and becomes eligible to be garbage collected. The same is true for every Borg instance. Create 100 Borg instances and there are 101 aliases for one and the same dict. Now , instance.name = value is (usually) executed behind the scence as instance.__dict__['name'] = value where __dict__ is the dict *currently* bound to instance attribute __dict__. (One of the exceptions to this is _dict__ itself.) In the Borg scheme, that name is no longer bound to the original dict but to the shared dict. So nothing is (or at least need be) ever added to that dict under its first name of __shared_state. Terry J. Reedy From candiazoo at mac.com Sun Jul 13 23:03:00 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Mon, 14 Jul 2003 03:03:00 GMT Subject: MacPython and more modules References: Message-ID: <130720032302396565%candiazoo@mac.com> I do it from the command line. Invoke the setup.py with the appropriate python binary (likely to be /usr/local/bin/python2.3) and it automagically installs to the appropriate site-packages folder under /Library/Frameworks/Python.framework/Versions/... Good luck! Mike J. In article , wrote: > I install MacPython 2.3 on a Jaguar 2.6 on my house but I don't know > how I install others modules. When I use python setup install the > module is installed on usr/lib/... and not inside frameworks. How I can > solve this?? > > Thanks about help me. > > From ad at am9atNOSPAMPLEASEspeedy.co.il Thu Jul 31 04:37:29 2003 From: ad at am9atNOSPAMPLEASEspeedy.co.il (Adam) Date: Thu, 31 Jul 2003 10:37:29 +0200 Subject: Python - Runy Tkinter conflict Message-ID: Hi I had Ruby 1.6.8-8 for Windows installed on my WinXP Pro machine prior to installing Python 2.3. After installing Python 2.3, I tried to <----- screen output of python interactive command line -----> Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import * >>> root = Tk() Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\lib-tk\Tkinter.py", line 1564, in __init__ self.tk = _tkinter.create(screenName, baseName, className) _tkinter.TclError: Can't find a usable init.tcl in the following directories: {c:\ruby\tcl\lib\tcl8.3} {c:\ruby\tcl\lib\tcl8.3} c:/ruby/tcl/lib/tcl8.4 C:/ Python23/lib/tcl8.4 C:/lib/tcl8.4 C:/library c:/ruby/tcl/lib/tcl8.3/init.tcl: version conflict for package "Tcl": have 8.4, n eed 8.3 version conflict for package "Tcl": have 8.4, need 8.3 while executing "package require -exact Tcl 8.3" (file "c:/ruby/tcl/lib/tcl8.3/init.tcl" line 19) invoked from within "source c:/ruby/tcl/lib/tcl8.3/init.tcl" ("uplevel" body line 1) invoked from within "uplevel #0 [list source $tclfile]" c:/ruby/tcl/lib/tcl8.3/init.tcl: version conflict for package "Tcl": have 8.4, n eed 8.3 version conflict for package "Tcl": have 8.4, need 8.3 while executing "package require -exact Tcl 8.3" (file "c:/ruby/tcl/lib/tcl8.3/init.tcl" line 19) invoked from within "source c:/ruby/tcl/lib/tcl8.3/init.tcl" ("uplevel" body line 1) invoked from within "uplevel #0 [list source $tclfile]" This probably means that Tcl wasn't installed properly. After uninstalling Ruby 1.6.8-8 I tried again: <----- screen output of python interactive command line -----> >>> root = Tk() Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\lib-tk\Tkinter.py", line 1564, in __init__ self.tk = _tkinter.create(screenName, baseName, className) _tkinter.TclError: Can't find a usable init.tcl in the following directories: {c:\ruby\tcl\lib\tcl8.3} {c:\ruby\tcl\lib\tcl8.3} c:/ruby/tcl/lib/tcl8.4 C:/ Python23/lib/tcl8.4 C:/lib/tcl8.4 C:/library This probably means that Tcl wasn't installed properly. Tkinter started working with Python 2.3 only after uninstalling/reinstalling Python. Is this considered a bug? Should I post this somewhere else? Adam From chris.gonnerman at newcenturycomputers.net Thu Jul 24 08:32:32 2003 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 24 Jul 2003 07:32:32 -0500 Subject: [Python] Re: [OT] On the TimBot References: Message-ID: <002c01c351df$a7dde580$2100000a@house> ----- Original Message ----- From: "TZOTZIOY remotely" > "Delaney, Timothy C (Timothy)" wrote in message news:... > > > From: Christos "TZOTZIOY" Georgiou [mailto:tzot at sil-tec.gr] > > > > > > what's the use of a Bit that's always true? > > > > Well, it compresses really well ... > > Yes, a single unchanging bit in time compresses very well (contrary to > a single bit at a specific moment in time). But compressibility is an > attribute, not a use :) Doorstop? Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jepler at unpythonic.net Wed Jul 2 11:56:28 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 2 Jul 2003 10:56:28 -0500 Subject: How to keep a Tkinter-Dialog on top of all other windows? In-Reply-To: References: Message-ID: <20030702155627.GB19446@unpythonic.net> On Wed, Jul 02, 2003 at 10:44:43AM -0500, Joe Fromm wrote: > Windows actually has two z-orders. Topmost windows and normal windows. All > topmost windows are always above normal windows. > > So setting a window into the topmost group will keep it on top of your app > with one call, but it will remain topmost even if another application is > activated. If that is acceptable to you then setting it to topmost is > indeed a simpler solution. Oh. If you just want to enforce window stacking between two toplevels in your application, you can use "wm transient" for this. t = Tkinter.Tk() u = Tkinter.Toplevel(t) u.wm_transient(t) t.mainloop() however, "wm transient" has other effects (TRANSIENT_STYLE, does not appear on task bar, etc). Jeff From gh at ghaering.de Mon Jul 21 18:08:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 22 Jul 2003 00:08:52 +0200 Subject: Problem building extension sample with Python 2.2.3 In-Reply-To: References: Message-ID: <3F1C6474.8050100@ghaering.de> Bren wrote: > Hi, > > I'm trying to build the sample extension file from > http://www.python.org/doc/current/ext/simpleExample.html. > > I get a linker error: [...] Use distutils. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 Then use "python setup.py build" to build the extension module. HTH, -- Gerhard From mwh at python.net Wed Jul 16 11:26:41 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 16 Jul 2003 15:26:41 GMT Subject: docs html-2.3.0.tar.bz2 - is there anything yet? References: <3f156610$0$300$ba620e4c@reader1.news.skynet.be> Message-ID: <7h3y8yylcs8.fsf@pc150.maths.bris.ac.uk> Helmut Jarausch writes: > Hi, > I am running Python's CVS version and I would like to install > the 2.3 version of the html documentation (as requested by Idle, e.g.) > Is there already such a file or can it be built from XML? sources > contained in the distribution? At least, I haven't found a configure > option. Hmm. You can browse it online at http://www.python.org/dev/doc/devel/ but there don't seem to be tarballs of very recent docs. You can get the 2.3b2 docs from http://www.python.org/ftp/python/doc/2.3b2/ or you can wait a few days for the 2.3c1 docs (I think). As you seem to be on Linux, it's not hard to build the docs from the (LaTeX) source: try cd-ing into Doc/ and typing make. Installing all the needed tools can be a bit annoying, but recently I've found everything comes with the base install of (eg.) RedHat systems. Cheers, M. -- Screaming 14-year-old boys attempting to prove to each other that they are more 3133t than j00. -- Reason #8 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From vze4rx4y at verizon.net Thu Jul 17 01:10:52 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 17 Jul 2003 05:10:52 GMT Subject: Documentation examples needed References: Message-ID: Hi Stuart, The simplest way to get started with Python standard LaTeX markup is to cut-and-paste from existing TeX files. Then follow-up with a script to perform basic checks: see the current CVS for Tools/scripts/texcheck.py It will check for valid TeX markup, balanced delimiters, style warnings, and common markup errors (for example, confusing forward and backward slashes). A better way to get started is to actually read the Documenting Python section. In the end, you'll save more time and learn more than the try-it and see if it works method. Raymond Hettinger "Stuart D. Gathman" wrote in message news:aUnRa.16108$o54.11296 at lakeread05... > I am still wanting to produce Python standard format documentation for > Python extensions I have written. I have looked at the docs that come > with Python itself, but I am new to Latex, and don't know how to add the > document classes and styles from texinput for a new project. > > Is there a small project with documentation in the Python standard that I > can use as an example? > > -- > Stuart D. Gathman > Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 > "Confutatis maledictis, flamis acribus addictis" - background song for > a Microsoft sponsored "Where do you want to go from here?" commercial. From schull at digitalgoods.com Mon Jul 14 15:03:49 2003 From: schull at digitalgoods.com (Jon Schull) Date: 14 Jul 2003 12:03:49 -0700 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> <3F0E136A.6222F201@engcorp.com> Message-ID: <2621b014.0307140819.491f7696@posting.google.com> Well, for what its worth, I was thinking about "sniffing, spoofing, or main-in-the-middle attacks", and I was hoping for something I could stick into a program for unsophisticated users (e.g, those to whom one might give a notepad-like application, albeit with a local webserver interface). Everyone who connects to the internet should have a firewall BUT must all who import httpserver implement or insist on a firewall for all their users? Realistically? I don't want to think so. > Uh, yeah.... but the OP wasn't asking about sniffing, spoofing, or > main-in-the-middle attacks, near as I can tell, nor about using > encryption. He was suggesting an unusual modification to one or > more applications which would otherwise be decoupled from security, > by adding into them features which are better handled by firewalls. > > "Security through Obscurity" (e.g., random ports) is not the way to > go. Instead, use SSL. This can be done through a CGI on Apache > through an SSL'd port, or it can be done with stunnel. [Or it might > even be done with raw python using pyOpenSSL or M2Crypto (which I > haven't done, so I can't tell you anything that direction).] From mwh at python.net Mon Jul 21 08:30:25 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 21 Jul 2003 12:30:25 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: <7h3znjbzscu.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3n0f8yspt.fsf@pc150.maths.bris.ac.uk> Michael Hudson writes: > "Mike C. Fletcher" writes: > > > So, does anyone have a pattern which allows setting an attribute on > > a class which doesn't go through the setattr machinery (i.e. can be > > used within a descriptor)? > > No. Fun problem to think about, though :-) Actually, that was a lie. Check this horror out: class MetaProp(object): def __init__(self, val): self.val = val def __get__(self, ob, cls=None): for k in ob.__class__.__dict__: if ob.__class__.__dict__[k] is self: delattr(ob.__class__, k) break else: raise Exception, 'not found' setattr(ob, k, self.val + 1) setattr(ob.__class__, k, self) return self.val class Meta(type): p = MetaProp(1) class C: __metaclass__ = Meta print C.__dict__.keys() print C.p print C.__dict__.keys() print C.p I'm quite proud of this one :-) Cheers, mwh -- 3. Syntactic sugar causes cancer of the semicolon. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From Olivier.POYEN at clf-dexia.com Fri Jul 18 04:31:58 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Fri, 18 Jul 2003 10:31:58 +0200 Subject: dumping command-history in python interactive mode Message-ID: <8963D6370B323E4AA3241200F0EAF7318C0FCC@FCEXVEXM002.dcl.int.dexwired.net> > -----Message d'origine----- > De : Christoph Becker-Freyseng [mailto:christoph at mmc-startup.com] > Envoy? : vendredi 18 juillet 2003 00:09 > ? : python-list > Objet : dumping command-history in python interactive mode > > > Hello, > > is there a way to dump (and save) the command-history of the python > interactive mode. > > Thanks, > Christoph Becker-Freyseng > > > -- > http://mail.python.org/mailman/listinfo/python-list > ipython does it quite well, I think. But perhaps you don't want session recording, but only state recording. Then all you have to do is ikling some globals, which may be easir. HTH ---OPQ -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 15 07:06:09 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 11:06:09 GMT Subject: [OT] Re: Single or Double quotes [was Re: PyQT, Sharp Zaurus and color in the QTextBrowser] References: <3F132103.4D18759F@engcorp.com> Message-ID: Jeremy Bowers enlightened us with: > At no point is it ever specified either way in the XHTML > specification, except by reference to the XML specification. I'm sorry to tell you, but you're wrong in that. It is clearly stated in the HTML 4.01 specification at http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.2.2 I found that by going to the index, looking up the item "attibutes" and then clicking the link at "quotation marks around value". Not that hard to find. The XML specification of attributes can be found at http://www.w3.org/TR/REC-xml#sec-common-syn and is a little harder to find, but not impossible. Since XHTML 1.0 is defined as "A Reformulation of HTML 4 in XML 1.0", this should be enough to also allow single and double quoted attribute values in XHTML. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From minceme at start.no Tue Jul 15 20:46:08 2003 From: minceme at start.no (Vlad Tepes) Date: Wed, 16 Jul 2003 00:46:08 +0000 (UTC) Subject: parsing complex web pages References: <873ci7x80p.fsf@pobox.com> <87r85qqnn9.fsf@pobox.com> Message-ID: John J. Lee wrote: > John Hunter writes: >> >>>>> "John" == John J Lee writes: >> John> If it works well for you, why not stick with it? > [...] >> It did cause me to wonder though, whether some good python html->text >> converters which render the html as text (ie, preserve visual layout), >> were lurking out their beneath my radar screen. > > If they exist, it's unlikely they'll do as good a job as lynx (in > general, not talking about Yahoo in particular), because there is so > much awful HTML out there. lynx has been around a long time. And if lynx don't do what you want there's also other text browsers available. links, elinks and w3m can also dump text-files, and all of them handle tables better than lynx (at least for viewing). Looking at the sizes for these browsers, maybe it would be best to use w3m for dumping webpages: :!ls -l `which lynx links elinks w3m` -rwxr-xr-x root 619004 Jul 18 2001 /usr/bin/links -rwxr-xr-x root 807132 Jan 14 2003 /usr/local/bin/elinks -rwxr-xr-x root 1111090 Jan 21 19:58 /usr/local/bin/lynx -rwxr-xr-x root 351008 Jan 24 01:08 /usr/local/bin/w3m -- Vlad From wilkSPAM at OUTflibuste.net Mon Jul 28 14:21:23 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 28 Jul 2003 20:21:23 +0200 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> Message-ID: <87oezebjh8.fsf@flibuste.net> faizan at jaredweb.com (Fazer) writes: > Hello, > > I am an avid user of PHP and I am just fooling around with Python for > now. I originally wanted to know which one is faster. As in, works > faster. So far, I think PHP is the fastest for dynamic web-content. > Am I wrong? yes for two reasons, one relative, one more objective : - you'll write cleaner and shorter programs with python, so more easy to optimize - when you'll really need speed, you'll write standalone web-server with python, and so a lot more eficient and fast in high trafic. I've rewrite my "high" trafic web site from php to python and gain 10x of speed. -- William Dode - http://flibuste.net From tchur at optushome.com.au Sat Jul 5 18:45:26 2003 From: tchur at optushome.com.au (Tim Churches) Date: 06 Jul 2003 08:45:26 +1000 Subject: Frustration with spurious posts. In-Reply-To: <5.2.1.1.0.20030705095656.01a4e060@66.28.54.253> References: <5.2.1.1.0.20030705095656.01a4e060@66.28.54.253> Message-ID: <1057445126.1204.4.camel@emilio> On Sun, 2003-07-06 at 01:58, Bob Gailer wrote: > Does anyone know why we keep getting these posted to the list. Is there a > way to stop it? SpamBayes works a treat to filter these out - see http://www.spambayes.org Tim C > > Undeliverable: Re: Movie > > At 03:56 PM 7/5/2003 +0100, postmaster at bthub01.bt.com wrote: > > >Your message > > > > To: N.Winton at axion.bt.co.uk > > Subject: Re: Movie > > Sent: Sat, 5 Jul 2003 15:59:01 +0100 > > > >did not reach the following recipient(s): > > > >N.Winton at axion.bt.co.uk on Sat, 5 Jul 2003 15:56:09 +0100 > > The recipient name is not recognized > > The MTS-ID of the original message is: > >c=gb;a=bt;p=bt;l=CBIBIPNT0803070514563GAHP1WW > > MSEXCH:IMS:EXCHANGE:BTHUB01:CBIBIPNT08 3550 (000B09B6) 550 5.1.1 > >... User unknown > > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 > > ______________________________________________________________________ > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From tomas at fancy.org Sat Jul 12 16:53:35 2003 From: tomas at fancy.org (Tom Plunket) Date: Sat, 12 Jul 2003 13:53:35 -0700 Subject: anything like C++ references? Message-ID: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> I want to do something along the lines of the following C++ code: void change(int& i) { i++; } Is there any way to do references like this in Python? It'd be like this, though clearly this doesn't change the thing I want it to change: def change(val): val += 1 v = 0 change(v) # v == 1 now. thanks. I can see that maybe if I passed in a list of one integer I could change that, but that seems circuitous to me. -tom! From xbawolkx at pacbell.net Mon Jul 7 01:23:09 2003 From: xbawolkx at pacbell.net (Bruce Wolk) Date: Mon, 07 Jul 2003 05:23:09 GMT Subject: Newbie question: Strange TypeError In-Reply-To: References: Message-ID: <1t7Oa.40$DX3.7244067@newssvr14.news.prodigy.com> Tim Isakson wrote: > Howdy, > > I'm a new python programmer - new to python, not so much to programming - > my background was mainly C, with some C++, but it's rusty. > > I'm learning python to try and get back into some coding, > and am running into a problem - I'm writing a calculator in python and > wxPython as an exercise to learn both, and the following problem is > leaving me baffled. > > I have an event handler, and it's getting called fine - but within the > event handler, I'm calling a class method, HandleInput. The definition > and call are shown below: > > def HandleInput(self, input): > if self.results.GetValue() == "0": > return input > elif newVal == True: > return input > else: > tmpVal = self.results.GetValue() + input > return tmpVal > > def OnButton1(self,e): > tmpVal = self.HandleInput(self, "1") > self.results.SetValue(tmpVal) > > The call to HandleInput is made, but I get the following error: > > Calling HandleInput(self, '1') > Traceback (most recent call last): > File "pycalc.py", line 115, in OnButton1 > tmpVal = self.HandleInput(self, "1") > TypeError: HandleInput() takes exactly 2 arguments (3 given) > > So far as I can tell, the offending call *IS* calling HandleInput with 2 > arguments, but the interpreter obviously thinks different, and I'm at a > loss as to why that might be. > > I'm sure I'm doing something odd and not noticing, and I'd appreciate any > help you can provide! > > Thanks in advance, > > Tim The error message gave you what you needed. Bound methods, when called, do not supply an argument for the first formal parameter ("self" by convention). Since HandleInput was defined using two formal parameters, it must called using only one. So change the offending statement to tmpVal = self.HandleInput("1") -- ______ Bruce Wolk Remove the x's in the e-mail address From vimakefile at yahoo.com Mon Jul 21 17:51:29 2003 From: vimakefile at yahoo.com (MBR) Date: 21 Jul 2003 14:51:29 -0700 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: I guess you could create a BufferedIterator wrapper/mixin that holds at most one object ahead. (Would only need to cache when IsEmpty was asked.) Of course, whether this counts as a side-effect depends on your interator and its use... mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307210626.11a1bbf1 at posting.google.com>... > After a recent thread on .endswith, I have been thinking about iterators. > I realized that I don't know a satisfactory way to check if an > iterator is empty. In other words I am looking for an > "isempty" function to use in "if" statements such as > > if isempty(iterator): > do_something() > > without side effects. Here are some unsatisfactory ways of implementing > "isempty": > > #1: converting to a list or tuple > def isempty(iterator): > return not list(iterator) > > Easy, but one has to create the entire list, thus defecting the basic > purpose of the iterator, i.e. lazy evaluation. > > #2: checking for StopIteration > def isempty(iterator): > try: > iterator.next() > except StopIteration: > return True > else: > return False > > This works, for instance > > print isempty(iter([])) > > gives True and > > it=iter([1,2,3]) > print isempty(it) > > gives False. However, there is a side effect: after the check, the > iterator has advanced of one step and now "it.next()" gives 2, not 1. > In order this to work without side effects, I should be able to restart > the iterator from the beginning, but I don't know how to do that. > Is it possible? > > #3: comparing with the empty iterator > > emptyiterator=iter([]) > > it=iter([]) > > if it == emptyiterator: print 'Ok!' > > This simply doesn't work. > > I wonder if the itertools module should contain a function to check for > empty iterators, thus simplifying my life ;) Of course, I may well be > missing something obvious, if so, please enlighten me. > > > Michele From wim_wauters at skynet.be Tue Jul 15 17:18:32 2003 From: wim_wauters at skynet.be (WIWA) Date: 15 Jul 2003 14:18:32 -0700 Subject: UDP client-server problem Message-ID: <538fc8e.0307151318.12551933@posting.google.com> Hi, I want to make a UDP client server application that is conform to RFC868 (Time protocol). Both the UDP client and UDP server are in a test phase. The question is: when I add "svrsocket.sendto(resultaat, (ip, port))" in the UDP server, my application closes while running. When I leave it away, it works fine. I really need this statement as the purpose is that a client sends sth to the server and the server sends back the time ticks. Anybody an idea how I can modifu my client/server so that it works? Regards, Wim Here is the server: # UDP server example import time import socket import string import string class Tijd: def __init__(self, hours=0,minutes=0,seconds=0): self.hours=hours self.minutes=minutes self.seconds=seconds def aantal_seconden(self): x = time.time() y=(1970, 1, 1, 1, 0, 0, 0, 0, 0) y=time.mktime(y) resultaat=x-y return resultaat if __name__=="__main__": tijd=Tijd() resultaat=tijd.aantal_seconden() print 'resultaat',resultaat port=37 svrsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) svrsocket.bind(('', port)) hostname = socket.gethostname() ip = socket.gethostbyname(hostname) print 'TOD server is at IP adress: ', ip tijd=time.ctime() tijd=string.split(time.ctime()) print 'The current time is', tijd[3] print 'Listening for TOD-requests on port %s ...' %port while 1: data, address = svrsocket.recvfrom(256) print 'Received a TOD-request from modem with IP-address %s' %address[0] print 'Sending back the time to modem with IP-address',address[0] print "time", resultaat svrsocket.sendto(resultaat, (ip, port)) And here is the client: # UDP client example import socket port=37 clisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while 1: data = raw_input("Type something: ") if data: clisocket.sendto(data, ("127.0.0.1", port)) else: break s.close() From jon+usenet at unequivocal.co.uk Wed Jul 30 13:33:48 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 30 Jul 2003 17:33:48 GMT Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> <240b1020.0307292149.2cb95a13@posting.google.com> Message-ID: In article <240b1020.0307292149.2cb95a13 at posting.google.com>, Jeffrey P Shell wrote: > I work with some very talented designers. It used to be that they > would give us (the developers) their designs and we'd rip them to > shreds and they could never touch them again. Because now they were > in little bits and pieces and stuffed full of tags-within-tags, with > silly things like 'standard_html_header' and 'standard_html_footer' > (never really fitting a technical definition of header once complex > designs enter the equation) making it very painful to apply what they > would thing were rudimentary design changes. jonpy works around this problem while also avoiding the limitations of XML. The templates contain no code at all except "magic comments" and $$name$$ replacements. Both of these survive the files being mangled by HTML editors and keeping as much as possible out of the HTML file means that if you get given brand new from-scratch design it is still a quick job to 're-templatify' the new HTML. From bgailer at alum.rpi.edu Thu Jul 24 12:05:30 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 24 Jul 2003 10:05:30 -0600 Subject: Mystery Theater New Style Classes Message-ID: <5.2.1.1.0.20030724100432.01d9d460@66.28.54.253> Predict the output: class A(int): classval = 99 def __init__(self, val = 0): if val: self = val else: self = A.classval a=A(3) b=A() print a,b Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From richie at entrian.com Tue Jul 29 11:01:26 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 29 Jul 2003 16:01:26 +0100 Subject: gzip HTTP results problem In-Reply-To: References: <003401c355c1$cb6949f0$6400a8c0@EVOD31> Message-ID: <5u2div8fp3cmsvs8ifk99ancnm1vh006hp@4ax.com> [Fredrik] > this might help: > > http://effbot.org/zone/consumer-gzip.htm > > (that piece of code is used in production code, so it should > work...) This looks wrong to me: except IndexError: self.data = data Shouldn't it be: except IndexError: self.__data = data ? -- Richie Hindle richie at entrian.com From t.leeuwenburg at removme.bom.gov.au Thu Jul 17 20:38:46 2003 From: t.leeuwenburg at removme.bom.gov.au (Tennessee James Leeuwenburg) Date: Fri, 18 Jul 2003 10:38:46 +1000 Subject: Jython classpath question References: Message-ID: Thanks All. -Tennessee From deets_noospaam at web.de Mon Jul 28 14:58:10 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2003 20:58:10 +0200 Subject: newbie needs a little help... trying to write an ftp script. References: Message-ID: > import ftplib > > ftp = ftplib.FTP('172.30.30.30') # This is wrong, somehow...? > ftp.login(user,pass) > ftp.retrlines('LIST') # I believe it might need to be > ftp.retrlines('ls -al') > ftp.sendcmd('prompt') > ftp.cwd('folder') > ftp.retrbinary(retr *tgz) > ftp.quit() Your example worked fine with me for "ftp.suse.com" - at least the first 3 lines. It didn't understand ls -al and prompt, and a folder "folder" didn't exist of course. The ftp.retrbinary(retr *tgz) is also flawed - what is retr, a variable? I think you need to look up that command again. And *tgz can't be right, too. You most probably want "*tgz" there (a string literal) ftp.quit() works. Diez From mrchameleon at hotmail.com Tue Jul 29 22:43:22 2003 From: mrchameleon at hotmail.com (Chris Reay) Date: 29 Jul 2003 19:43:22 -0700 Subject: curses and use_default_colors() References: Message-ID: <7652139e.0307291843.2ade58c6@posting.google.com> Brian Victor wrote in message news:... > I am attempting to write a curses-based program. I would like to use > the default terminal background rather than a black one (a significant > difference with transluscent terminals, regardless of one's opinion of > them). I don't know how much this'll help, but my home-brewed curses TextApp class has a white-on-blue default, and TextApp.startWin() contains these lines (inter alia) ... # ... blah, blah, blah. curses.start_color() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # ... blah, blah, blah ... self.scrn = self.stdscr.subwin(self.height, self.width, 0, 0) self.scrn.bkgd(curses.color_pair(1)) # Blah, blah, blah ... Fwiw Chris From bokr at oz.net Tue Jul 29 00:27:21 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 04:27:21 GMT Subject: pretty printing graphs References: <2259b0e2.0307281530.218400ae@posting.google.com> Message-ID: On 28 Jul 2003 16:30:03 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >"Scherer, Bill" wrote in message news:... > >Hey "dot" is great! I didn't know about it before readin your post. > >In a very short time I came out with the following recipe to draw >Python inheritance hierarchies (which I post since it is pretty >short and useful ;): > > >"How to draw inheritance hierarchies via dot" > >import os > >def label(i,n): > if n>1: return '[label="%s"]' % (i+1) > return "" > >def dotMRO(cls): > "Generates the dot code for the MRO directed graph" > yield "digraph MRO_of_%s{\n" % cls.__name__ > for c in cls.__mro__: > n=len(c.__bases__) > yield ' '.join([' %s -> %s %s;' % (b.__name__,c.__name__,label(i,n)) > for i,b in enumerate(c.__bases__)]) > yield '}' > ># Example hierarchy >O = object >class F(O): pass >class E(O): pass >class D(O): pass >class G(O): pass >class C(F,D,G): pass >class B(E,D): pass >class A(B,C): pass > ># creates the graph >dotcode='\n'.join(dotMRO(A)); print dotcode >os.system('echo "%s" | dot -Tps > prova.ps' % dotcode) >os.system('gv prova.ps&') > >Assuming you have "dot" and the standard Unix tools installed this >will generate a very nice diagram. I am open to suggestion to improve it, >since this is may first trial with "dot". I am quite impressed by the >easy of use. > >Very nice! > Decided to try the tree print I did for John Hunter in pphunter.py on your class tree: explore is just a quick-n-dirty to make the tree. ====< mrog.py >===================== # Example hierarchy O = object class F(O): pass class E(O): pass class D(O): pass class G(O): pass class C(F,D,G): pass class B(E,D): pass class A(B,C): pass import pphunter def explore(cls, tree): node = pphunter.Node(pphunter.TextBox(cls.__name__)) tree.children.append(node) for b in cls.__bases__: explore(b, node) root = pphunter.Node(pphunter.TextBox('root')) explore(A, root) print root.children[0].showInPage(20, 60) ==================================== Result: [21:26] C:\pywk\clp>python mrog.py +-+ |A| +-+ +-+ +-+ |B| |C| +-+ +-+ +-+ +-+ +-+ +-+ +-+ |E| |D| |F| |D| |G| +-+ +-+ +-+ +-+ +-+ +------+ +------+ +------+ +------+ +------+ |object| |object| |object| |object| |object| +------+ +------+ +------+ +------+ +------+ I guess I will have to do connector lines ;-) BTW, I found a bug in the showInPage method of pphunter.Node. It should be -- def showInPage(self, pageHeight=6*11, pageWidth=78): return '\n'.join(self.boxlines(pageHeight, pageWidth)) -- (I capitalized pageHeight and page Width) . Boo :-( (see 'pretty printing graphs' thread). Regards, Bengt Richter From drlinux at columbus.rr.com Wed Jul 9 10:17:49 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Wed, 9 Jul 2003 10:17:49 -0400 Subject: Application Development in Python In-Reply-To: <3089454.1057738936@dbforums.com> References: <3089454.1057738936@dbforums.com> Message-ID: <200307091017.49419.drlinux@columbus.rr.com> On Wednesday 09 July 2003 04:22, indru wrote: > Hi all, > I am new to Python programming. I am from C,C++,Perl background. I am > quite convinced by the possibilities python as a very high level > language is offering. I am seriously thinking of using python in my > project which is to create a accounting software. First thing came to my > mind was C++ but the time required could be enormous and my people are > not ready to wait that long. The project is a medium sized one but > bigger than something like gnucash and KMyMoney2. Do any body have > experience with application development using python and their > experiences ?. Also please advice me whether Python can be used for > such purposes. > Thanks in advance > Indru Of course! I wrote a 24,000 Python program that uses pygtk/gnome (interfaces were created with glade) and postgresql. It's a patient database/accounting package for my wife's optometric office. It does double entry accounting to handle all the monetary transactions and generate reports for their accountant. It also keeps track of their frame inventory, does insurance reimbursement calculations for the insurances they accept, and many, many, other things. About 1,000 of that 24,000 lines of code is strings that hold PostScript code for printing out receipts, etc. It took me about 300 hours including design time. I've got 22 years of programming experience (the last 3.5 years almost exclusively in Python) so YMMV on coding time. I use gnucash for my personal finances and IMO, the system I wrote is more complex than a basic accounting system such as gnucash (which I use for my personal finances), although using Postgresql to store all the data greatly reduces the amount of code you have to write to manipulate the data. So my guess is fairly full featured accounting system could be written in less than 24,000 lines of Python code if you use a database to store all the actual data. Also note that using the database for manipulating the data makes the speed very acceptable. I'm almost certain that manipulating the data in Python would be way too slow to make it usable (e.g., generating a balance sheet that looks through all the transactions and groups them by account in Python would be much slower than using sql commands to do that). Have fun! Dave From bignose-hates-spam at and-zip-does-too.com.au Fri Jul 18 07:23:42 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 18 Jul 2003 21:13:42 +0950 Subject: dumping command-history in python interactive mode References: Message-ID: On Thu, 17 Jul 2003 23:40:22 -0700, Matt Gerrans wrote: > "Christoph Becker-Freyseng" wrote: >> is there a way to dump (and save) the command-history of the python >> interactive mode. > > I always prefer IDLE over the console interactive mode, unless there > is some particular reason not to (like experimenting with TKinter, or > running in a non-GUI OS. What? Where you find such a thing these > days?!). Any of millions of Unix (or GNU/Linux) servers around the world. Running a GUI on a machine that won't have someone sitting in front of it most of the time it's being used, is just bloat and is yet more code to go wrong. -- \ "The face of a child can say it all, especially the mouth part | `\ of the face." -- Jack Handey | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From tjreedy at udel.edu Thu Jul 3 17:14:04 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jul 2003 17:14:04 -0400 Subject: getting a submatrix of all true References: Message-ID: "John Hunter" wrote in message news:mailman.1057250709.8853.python-list at python.org... > >>>>> "Terry" == Terry Reedy writes: > > > Terry> Statisticians have tried a variety of approaches. Googling > Terry> for ' statistics "missing data" 'will give you some leads > Terry> if you want. > > I have done some searching. I'm familiar with the common methods > (delete every row that contains any missing, replace missing via mean > or regression or something clever) but haven't seen any discussion of > dropping variables and observations together to yield data sets with > no missing values. Have you seen something like this? There are also calculation methods for at least some analyses that allow for missing data . One of the google hits is for the book Statistical Analysis with Missing Data. I have not seen it, but it is not unique. As I hinted, there are no really nice solutions to missing data. I have done both row and column deletion. Sometimes I have done multiple analyses with different deletion strategies: once with enough vars deleted so all or most cases are complete, and again with enough cases deleted so that all or most var are complete. I would start by counting (with a program) the number of missing values for each row and then construction the frequency distribution thereof. Then the same for the columns, with the addition of a correlation table or tables. One thing one can do with vars is to combine some to make a composite measure. For instance, if three variables more-or-less measure the same thing, one can combine (perhaps by the mean of those present) to make one variable that is present if any of the three are, so it is only missing for cases (rows) that are missing all three. This type of work requires that you look at the variables and consider their meaning, rather than just inputing them into a blind proceedure that consisders all vars to be the same. Terry J. Reedy From scasjos at mixmail.com Wed Jul 9 08:42:07 2003 From: scasjos at mixmail.com (jose maria) Date: 9 Jul 2003 05:42:07 -0700 Subject: Socket Win32 IO References: <99071af2.0307070647.6ab3e329@posting.google.com> <3F099791.6AA68B8F@engcorp.com> <99071af2.0307080439.2bacd2d4@posting.google.com> <3F0AC6B8.A94C0435@engcorp.com> Message-ID: <99071af2.0307090442.76c43e00@posting.google.com> Peter Hansen wrote in message news:<3F0AC6B8.A94C0435 at engcorp.com>... > jose maria wrote: > > > > Hello Peter tanks for you attenion and time > > > > Yes really I forget put in the message one parameter in the function > > I put the traceback and all code I hope that this help you. Thousands > > of pardons for my bad English > > > > Traceback: > > > > ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on > > Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on wi > > Type "help", "copyright", "credits" or "license" for more informatio > > >>> from socket import * > > >>> import win32api > > >>> import win32file > > >>> Ip=getprotobyname("ip") > > >>> SIO_RCVALL=0x98000001 > > >>> ip=('xxx.xxx.xxx.xxx',0) > > >>> Sock=socket(AF_INET,SOCK_RAW,Ip) #Raw Socket > > >>> Sock.bind(ip) # Bind Socket to ip > > >>> fh=Sock.fileno() # Get file handle > > >>> test=win32file.DeviceIoControl(fh,SIO_RCVALL,"", 0,None) # The > > function > > Traceback (most recent call last): > > File "", line 1, in ? > > pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.') > > I still get a different result (the second of the two that I posted > before) even if I add that "None" argument, not what you show above. > Are you certain you are cutting and pasting *exactly* what you typed? > I note you have 'xxx.xxx.xxx.xxx' above, so presumably you have > edited the transcript manually in at least one way... any others? > > I'm not likely to be able to solve the problem, since I have no idea > what DeviceIoControl is for, nor what you're trying to accomplish. > I just thought I'd report that I do not get the results you are > getting when I try what you show you are trying. > > -Peter Hi Peter thanks again for your time I feel it if my message is not correct I will try to explain more in detail my objective and try to explain my code in more detail My objective is write a simple sniffer for Windows 2000/XP without have to resort external code (DLL) I evaluate several options 1) Use pylibpcap: problem: Not with himself that work in my machine 2) Write a external DLL in C++ and then expose to python: problem I have little experience in C++ 3) Imagination (?why not?) : Reading several code from sniffers in win32 I finded similarities in all parts of the code the similarities are that all use constant 0x98000001 in SocketIOControl this especial mode permit to read all ip packets that arrive in network adapter I put you a simple example in C++ ############# This is the file PacketCapture.h########################## #include #include #define SIO_RCVALL 0x98000001 #define MAX_IP_SIZE 65535 class CPacketCapture { public: int GetPacket(WSABUF *wsabuf); int Initialize(int AdapterNr); SOCKET sock; WSADATA wsd; CPacketCapture(); virtual ~CPacketCapture(); }; ########################################################################### ############# NetAdapter.h########################## #include class CNetAdapter { public: int GetAdapterList(SOCKET_ADDRESS_LIST* slist); int GetAdapter(SOCKET s, SOCKADDR_IN *ifx, int num); CNetAdapter(); virtual ~CNetAdapter(); }; ############################################################################ ############### This is the file PacketCapture.cpp########################## #include "PacketCapture.h" #include "NetAdapter.h" CPacketCapture::CPacketCapture() { } CPacketCapture::~CPacketCapture() { } int CPacketCapture::Initialize(int AdapterNr) { CNetAdapter *netadapter=new CNetAdapter; SOCKADDR_IN if0; unsigned int optval; DWORD dwBytesRet; sock=WSASocket(AF_INET,SOCK_RAW,IPPROTO_IP,NULL,0,WSA_FLAG_OVERLAPPED); if(sock==INVALID_SOCKET) { MessageBox(NULL,"Creation of Socket(SOCK_RAW/IPPROTO_IP) failed","Alert!",MB_OK); return -1; } if(netadapter->GetAdapter(sock,&if0,AdapterNr)!=0) { MessageBox(NULL,"Unable to obtain selected network adapter!","Alert!",MB_OK); return -1; } if0.sin_family = AF_INET; if0.sin_port = htons(0); if(bind(sock,(SOCKADDR *)&if0,sizeof(if0))==SOCKET_ERROR) { MessageBox(NULL,"Bind call failed!","Alert!",MB_OK); return -1; } optval=1; if(WSAIoctl(sock,SIO_RCVALL,&optval,sizeof(optval),NULL,0,&dwBytesRet,NULL,NULL)==SOCKET_ERROR){ MessageBox(NULL,"WSAIoCtl(SIO_RCVALL) failed","Alert!",MB_OK); return -1; } delete netadapter; return 0; } int CPacketCapture::GetPacket(WSABUF *wbuf) { DWORD dwBytesRet=0,dwFlags=0; if(SOCKET_ERROR==WSARecv(sock,wbuf,1,&dwBytesRet,&dwFlags,NULL,NULL)){ char buf[200]; sprintf(buf,"WSARecv failed. Code %d",WSAGetLastError(),sock); MessageBox(NULL,buf,"Alert!",MB_OK); } wbuf->len=dwBytesRet; return 0; } ###################################################################################################################### I try to emulate this code in python (if its posible that that I don`t know it) reading doc for socket module I not found a method, property that permit to take control for IO in the socket (perhaps there is it but I?don't know I?m newbie) After to give him returned to the problem I founded in win32file module a function that permit control for devices this function is win32fileDeviceIoControl that have this arguments: string = DeviceIoControl(hFile, dwIoControlCode , data , readSize , ol ) Call DeviceIoControl Parameters hFile : int Handle to the file dwIoControlCode : int IOControl Code to use. data : string The data to write. readSize : int Size of the buffer to create for the read. ol=None : PyOVERLAPPED An overlapped structure My trick is (if it's posible) play with this function for to take control in the sockect. My code ## import the necessary modules from socket import * # for create socket import win32file # for manage IO of the socket( in my theory ) Ip=getprotobyname("ip") # for raw socket SIO_RCVALL=0x98000001 # constant for IO to recived all ip packtes ip=('XXX.XXX.XXX.XXX',0) # ip that I want read for after bind to the socket #pardom for to omit this detail # where XXXX.XXXX.XXX.XXX is the ip from one network # adapter I hope that this clarify # your doubts :) no be a transcript error there was # my ip sorry Sock=socket(AF_INET,SOCK_RAW,Ip) # I create the raw socket no stream socket or # other kind only raw Sock.bind(ip) # Bind socket to the IP fh=Sock.fileno() # Get the file handle test=win32file.DeviceIoControl(fh,SIO_RCVALL,"", 0,None) # The function to # manage IO End Code More details sorry for my mistake I?m using Windows 2000 professional SP4 and ActiveState Python 2.2.1 This is my traceback ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win Type "help", "copyright", "credits" or "license" for more information >>> from socket import * >>> import win32file >>> Ip=getprotobyname("ip") >>> SIO_RCVALL=0x98000001 >>> ip=('10.134.202.22',0) >>> Sock=socket(AF_INET,SOCK_RAW,Ip) >>> Sock.bind(ip) >>> fh=Sock.fileno() >>> fh 892 >>> test=win32file.DeviceIoControl(fh,SIO_RCVALL,"", 0,None) Traceback (most recent call last): File "", line 1, in ? pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.') >>> End of traceback I try to emulate yours errors but only I obtained the first error that you posted not the second and I don?t know how try to emulate your second error and I don?t know why I obtained this error pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.') Thousands Thanks Peter for your time and patience (pardon for my bad English) sincerely Jose Maria From gre7g-d-1059769811.c49085 at wolfhome.com Sun Jul 27 16:24:13 2003 From: gre7g-d-1059769811.c49085 at wolfhome.com (Gre7g Luterman) Date: Sun, 27 Jul 2003 14:24:13 -0600 Subject: Why does Python do this? In-Reply-To: <87fzksc1r7.fsf@pobox.com> References: <87fzksc1r7.fsf@pobox.com> Message-ID: On 27 Jul 2003 00:22:04 +0100, jjl at pobox.com (John J. Lee) wrote: > 2.2.1 only does this from the interactive prompt, not from a .py. No, it does do it from .py files as well, although perhaps only under special circumstances. Otherwise I would never have noticed it. I found it because a .py CGI program was adding a space into my HTML headers, which breaks them. It was easy enough to work around, but I had to ask if anyone knew more. Gre7g. From skip at pobox.com Thu Jul 31 13:25:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 12:25:09 -0500 Subject: [Newbie] FAQ? In-Reply-To: References: Message-ID: <16169.20725.527187.700126@montanaro.dyndns.org> Simone> is there a FAQ for this NG? No, but there's a FAQ for Python: http://www.python.org/cgi-bin/faqw.py?req=index Skip From tom_web at gmx.net Sat Jul 5 13:45:50 2003 From: tom_web at gmx.net (Thomas Weber) Date: Sat, 05 Jul 2003 19:45:50 +0200 Subject: execute scripts on GUI Message-ID: Hi, I want to start a script via an Icon on the Desktop, and I wonder how I can execute my GUI-scirpts (Tk on KDE) without the "Pyhton Shell" window popping up... Thankx! Tom From glenfant at NOSPAM.bigfoot.com Thu Jul 24 07:28:55 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Thu, 24 Jul 2003 13:28:55 +0200 Subject: zope ZMySQLDA References: Message-ID: "Thomas G?ttler" a ?crit dans le message de news: bfobe2$h17es$1 at ID-63505.news.uni-berlin.de... > Don Rivard wrote: > > If you want to see the stacktrace in error messages put > > in the standard_error_message of Zope. This needs to be done > trough the web and is very handy for debugging. > > The stacktrace shows you the file and the line where > the error occured. Maybe this helps you to find your problem. > > thomas > > With Zope 2.6.x (and later), the full traceback and the REQUEST object value when the exception raised are in the error_log object. --Gilles From bignose-hates-spam at and-zip-does-too.com.au Fri Jul 18 06:26:35 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 18 Jul 2003 20:16:35 +0950 Subject: gui References: Message-ID: On Fri, 18 Jul 2003 05:19:35 GMT, Linkages wrote: > a good GUI for linux ? XFree86 is a pretty good one. Did you have something more Python-specific in mind? -- \ "God forbid that any book should be banned. The practice is as | `\ indefensible as infanticide." -- Dame Rebecca West | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mis6 at pitt.edu Sat Jul 5 08:41:31 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Jul 2003 05:41:31 -0700 Subject: Overriding list.__new__ References: <2259b0e2.0307031246.6054693d@posting.google.com> Message-ID: <2259b0e2.0307050441.51396ee6@posting.google.com> "Terry Reedy" wrote in message news:... > "Michele Simionato" wrote in message > news:2259b0e2.0307031246.6054693d at posting.google.com... > > Let me show first how does it work for tuples: > > > > >>> class MyTuple(tuple): > > ... def __new__(cls,strng): # implicit conversion string of ints > => tuple > > ... return > super(MyTuple,cls).__new__(cls,map(int,strng.split())) > > >>> MyTuple('1 2') > > (1, 2) > > > > No wonder here, everything is fine. However, if I do the same for > > lists I get the following: > > Values of immutable objects must be set when created, because they > cannot be changed thereafter. Mutable objects can be initialized in > the __init__() method. I suspect this is true of lists, so that > overriding __new__ for lists has no effect. > > TJR This seems reasonable now that you point it out to me. Let me check ... >>> class MyList(list): def __init__(self,strng): self.extend(list(map(int,strng.split()))) >>> MyList('1 2') [1, 2] It works, indeed! Michele From MACALISTER at coltonhouse43.freeserve.co.uk Sat Jul 26 07:57:14 2003 From: MACALISTER at coltonhouse43.freeserve.co.uk (Iain Macalister) Date: Sat, 26 Jul 2003 12:57:14 +0100 Subject: running python References: Message-ID: RE: running pythonwindows xp "Batista, Facundo" wrote in message news:mailman.1059077438.2574.python-list at python.org... Platform? #- -----Mensaje original----- #- De: Iain Macalister [mailto:MACALISTER at coltonhouse43.freeserve.co.uk] #- Enviado el: Jueves 24 de Julio de 2003 3:53 PM #- Para: python-list at python.org #- Asunto: running python #- #- #- How do you run files written with python if you don't have #- the compiler and #- stuff on your computer? #- #- #- -- #- http://mail.python.org/mailman/listinfo/python-list #- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. From peter at engcorp.com Mon Jul 21 16:47:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 16:47:32 -0400 Subject: os.spawn[*] help References: Message-ID: <3F1C5164.79BC6D08@engcorp.com> Stephen Boulet wrote: > > Can someone who understands the os module better than I offer some insight? > > I want to open some text in xemacs (on Windows) using os.spawn[*], but I want > the text to appear in the current xemacs window, as opposed to opening a new > xemacs window. > > Is this doable? Thanks. I doubt this has anything to do with os.spawn, and everything to do with xemacs itself. Check the documentation on command line options for that program, and just pass the right stuff to it through os.spawn. -Peter From ebolonev at rol.ru Fri Jul 4 03:08:33 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 18:08:33 +1100 Subject: module and file locations References: Message-ID: Hello, Stuart! You wrote on Thu, 03 Jul 2003 12:38:53 GMT: SG> I am writing a debugging a Tkinter program. SG> While debugging I want to run it by pressing F5. SG> When in use I want to run it by double-clicking (win2000) SG> The program reads and write to various files which I want to store in SG> the same directory (or a sub directory) of the main script. SG> My question is: How can my program where it lives so I can get the base SG> directory? SG> argv[0] - will this work debugging if I just import the file? SG> There is some about finding where a module is. This seems to return SG> readable text that would require parsing rather than just a file name SG> Thanks, Try vars() With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From jeske at chat.net Sun Jul 27 15:06:50 2003 From: jeske at chat.net (David Jeske) Date: Sun, 27 Jul 2003 12:06:50 -0700 Subject: Web tool kit : pro - cons ? In-Reply-To: <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> Message-ID: <20030727120650.M22756@mozart> On Sun, Jul 27, 2003 at 12:58:26PM +0200, vincent_delft wrote: > >> - Build pages via templates (easy to split content and layout) > > > > ZPT seems to be a good option there. > > > Nice. New to me. I've already played with Zope.... but ZPT seams to > take the best from Templates without having the Zope constraints. If you are not wedded to Zope for your applications, you may want to look at Clearsilver. (http://www.clearsilver.net) It is a very mature system which was developed at eGroups.com, and today is in use on high-performance sites such as Yahoo! Groups and wunderground.com. Clearsilver includes a full CGI kit which handles form variables, cookies, etc. It also includes a PythonObject<->RDBMS mapping system (MySQL only today, no pgsql yet), and a transparent translation string extraction system. It is not a "server environment" like Zope, and in fact you can use it inside of your server of choice (Apache, Boa, IIS, Zope, etc). I find ZPT's model for replacement hard to work with, because it tries to fit into the xml document namespace. From the ZPT documentation here: http://www.zope.org/Documentation/Books/ZopeBook/current/ZPT.stx This example: Page Title Illustrates how ZPT is making it's "tag" (i.e. tal:content) fit in as an attribute defined by a new XML namespace. The problem is, this constrains where you can use template commands to construct the document. Clearsilver uses a model more like PHP where the tags exist as items outside of the XML document parsing. This has the drawback that your template document is not a valid XML document, but it has the advantage that you can put the tags anywhere. For example, in clearsilver, you can construct URLS using sequences of template commands, even looping. Here is a small example (whitespace added for readability): a_link > No. Each part of the web page will be "boxes". I would like to be very > flexible and display "dynamically" some selected boxes. > For example the same page (url) will not display the same boxes if you are > administrator, maintener or simple viewer. This should be pretty easy in most template systems worth their weight. > An another example will be to have possibility to re-use existing boxes. If > I have a boxes displaying the last 5 news from Slashdot, I don't want to > re-write it each time I need a new bacground color (for example). My Idea > is to use those "boxes" like we use classes : if you need some modification > you subclass it on the rest remains the same. Clearsilver has a macro definition facility for doing just this. You can supply arguments to macros, and even call macros recursively. Here is a simple example: The paramaters can be any expressions, including constructed strings, or data from your dynamic CGI. For example: As always, there are lots of systems out there, and YMMV. -- David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske at chat.net From max at alcyone.com Tue Jul 22 22:06:35 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jul 2003 19:06:35 -0700 Subject: 'int' object is not callable References: <3607e8e4.0307221646.7d24707@posting.google.com> Message-ID: <3F1DEDAB.AA08A28D@alcyone.com> JW wrote: > If i remove line 1, then my foo() method does print out correct value > for aTuple[0]. > > Why am I getting this error when i try using python len() built-in > function? Probably because somewhere along the line someone's replacement the `len' builtin with a variable containing an int object. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Many things are lost for want of asking. \__/ (an English proverb) From abelikov72 at hotmail.com Tue Jul 8 12:04:21 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 08 Jul 2003 16:04:21 GMT Subject: Python vs PHP References: Message-ID: On Tue, 08 Jul 2003 15:56:58 GMT, Afanasiy wrote: >On Mon, 07 Jul 2003 13:47:00 +0300, Catalin >wrote: >A couple other slight issues : > >* catch-all error handling not as flexible or non-existent >* no equivalent to php_value auto_prepend_file "_header.php" >* no equivalent to php_value auto_append_file "_footer.php" >* not as intelligent form value handling >* white space sensitivity is a unique problem when embedding I think I should add import, pythonpath and module caching to this list. These are much more annoying than PHP's inclusion mechanisms. I am even annoyed in non-web applications by them quite often, but not necessarily all at the same time. Also add to the list, the need for PyChecker. You must run PyChecker to discover errors which would occur on a section of logic being hit which contained a silly typographical error. PHP would discover these without them being hit, when you were developing the page. Python is more beautiful and more powerful, but for this purpose I consider the current implementations still lacking compared to PHP. So much so that I am unable to bring myself to write new PHP, but unable to continue using Python until I find the perfect implementation. -AB From max at alcyone.com Tue Jul 22 22:18:42 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jul 2003 19:18:42 -0700 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <3F1DF082.C182FA39@alcyone.com> Mars wrote: > It is a very useful substitute for a Singleton, but I can't figure out > how it works. _shared_state is never assigned any value, only > self.__dict__ is assigend self._shared_sate's value - or rather > (self.)_shared_state must be assigned a value at some point, otherwise > the code wouldn't work(right ?). It is assigned a value; it's bound to a new, empty dictionary. Since it's a class attribute, that means that empty dictionary is shared by all instances. _All_ instances have precisely the same __dict__ object. They all are exactly the same. That's how the pattern works. >>> class Borg: ... __sharedState = {} ... def __init__(self): ... self.__dict__ = self.__sharedState ... >>> x = Borg() >>> y = Borg() >>> x is y 0 >>> x.__dict__ is y.__dict__ 1 >>> x.a = 123 >>> y.a 123 >>> y.b = 321 >>> x.b 321 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ People say that life is the thing, but I prefer reading. \__/ Logan Pearsall Smith From ageron at HOHOHOHOvideotron.ca Thu Jul 3 11:24:44 2003 From: ageron at HOHOHOHOvideotron.ca (Aurélien Géron) Date: Thu, 3 Jul 2003 17:24:44 +0200 Subject: Python Code Snippets Message-ID: Hi, Does anyone know where I can find a lot of Python code snippets? I searched the Python wiki and Internet but could not find more than five or ten code snippets at a time. I'm looking for a kind of organized list (GUI snippets, database access snippets, I/O snippets, etc.). I find that there's no better way to learn a language than to be able to cut&paste actual working bits of code. Thanks, Aur?lien From max at alcyone.com Fri Jul 25 15:10:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 25 Jul 2003 12:10:20 -0700 Subject: file.close() References: <7xhe5b82ip.fsf@ruckus.brouhaha.com> Message-ID: <3F21809C.21720CD@alcyone.com> Bengt Richter wrote: > 1) Is f.done() really necessary? I.e., doesn't an explicit del f take > care of it > if the object has been coded with a __del__ method? I.e., the idea > was to get > the effect of CPython's immediate effective del on ref count going > to zero, right? It wouldn't if there were circular references at that point. If you're going to have some kind of `with' structure that constraints lifetimes, I'd think you'd probably want something more concrete than just object deletion; you'd want to make sure a "Stop whatever you were doing now" method were present and called. But maybe that really depends on the primary thing that the `with' construct would be used for. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Love is when you wake up in the morning and have a big smile. \__/ Anggun From bdesth.nospam at removeme.free.fr Wed Jul 2 07:37:36 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 02 Jul 2003 11:37:36 +0000 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: <3F02C400.5040209@removeme.free.fr> Tom Plunket wrote: > How can I create a functor object in Python? > > What I want (being a C++ coder ), is to be able to create an > object that I is callable. __call__ is your friend. > The following is my attempt, but it > doesn't work: > > class Countdown: > def __init__(self): > self.callback = None > > def SetCallback(self, time, callback): > self.callback = callback > self.timeRemaining = time > > def Update(self): > if self.callback is not None: > self.timeRemaining -= 1 > if self.timeRemaining <= 0: > print "Callback fired." > self.callback() > self.callback = None > > class SomeClass: > def __init__(self): > self.countdown = Countdown() > self.countdown.SetCallback(30, lambda s=self: s.Callback) This is not the same problem as making an object (ie a class instance) callable. Here you just want to use an instance object as callback function. Functions in Python are first-class objects, so you don't need this lambda stuff. This should work (I tried a simplified version...): self.countdown.SetCallback(30, self.Callback) HTH Bruno From noah at noah.org Thu Jul 10 16:44:15 2003 From: noah at noah.org (Noah) Date: 10 Jul 2003 13:44:15 -0700 Subject: Convert between Windows style paths and POSIX style paths Message-ID: Does anyone have a function to convert back and forth between NT style paths and POSIX style? It seems trivial, but I want to make sure I don't overlook some obscure detail. Is it a simple matter of translating / and \ characters? FYI, I need a Python function that does what cygpath does so that I can run a script on either NT or UNIX or Cygwin. I want my config files use one style of path. Yours, Noah From martin at v.loewis.de Sun Jul 13 18:17:19 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 00:17:19 +0200 Subject: anything like C++ references? References: Message-ID: Stephen Horne writes: > 1. Why are dictionarys called dictionaries (rather than references to > dictionarys or whatever)? Similar for lists and class instances. Because they are the values themselves, instead of being references to values. These values (like all other values) are objects, though, which means they have identity, state, and behaviour. You might be thinking of values which only have state and behaviour. Such values are not supported in Python - objects always have an identity. > 2. Why are the values of mutable objects always forced to be accessed > via a pointer (or reference or whatever)? Because all variables are references to objects. In Python, you cannot have a variable that *is* a value - variables are always *bound* to values, and accessing the variable yields the associated value. The values exist independently from the variables they are bound to, and a single value may be bound to different variables. > 3. Why is there no way to reference an immutable object via a > pointer, other than stuffing it into a mutable object designed for > some purpose other than simple pointer behaviour? But there is: If I do a = 1 b = a then b *refers* the same value that a refers to. That is, the values associated with a and b have the same identity. > This excuse is, as I already said, invalid. Which excuse? You have only listed questions in this message, not excuses. Regards, Martin From jkpangtang at yahoo.com Mon Jul 14 10:59:34 2003 From: jkpangtang at yahoo.com (J W) Date: Mon, 14 Jul 2003 07:59:34 -0700 (PDT) Subject: Passing pointer to array from C to Python..and modifying same array in python? In-Reply-To: <20030712154559.A6639@mozart> Message-ID: <20030714145934.13900.qmail@web14303.mail.yahoo.com> Hi David (and all membors of this list): Thank you so much for your advice. I have a few follow-up questions. 1) when you say to "have the C function construct a new python object (i.e. the "wrapper")", what type of python object would it be: PyLong, PyObject, PyCobject (not exactly sure what this is, but i've seen this in literature), or something else? 2) When you say " > The get method should take self and the array > index as paramaters and return the values in that slot of the array", Do I use the "PyArg_ParseTuple" funciton call in the "get()" method? If so, what parameters am I using to indicate object type? Is it correct to assume that the keyword "_self_" is actually seen in Python, and not the C extension object? In the C- extension function, what type of object is "_self_" -- PyLong, PyObject? Thanks again --- David Jeske wrote: > On Fri, Jul 11, 2003 at 02:06:10PM -0700, JW wrote: > > I have an array (presumably 'large') that is > mallocced in a C > > function and its values are initialized in that > same function. I > > would like to pass just the pointer to the > beginning of the array > > from this C function to a Pyton function. Then > the python method > > can individually access and MODIFY individual > members of the array. > > After the call to the python method, the C > function will see any > > changes to the array. > > > Can this be done? > > Of course this can be done, and there are a number > of ways to do > it. Based on your implication that there are many > more values put in > the array by the C code than will be accessed (or > changed) by the > Python code, this method might make sense: > > 1) have the C function construct a new python object > (i.e. the "wrapper") > > 2) put the real pointer to the C array into the > wrapper as instance data > > 3) register two methods for the object "get()" and > "set()", impelemented > in C as Python exported functions. > > The get method should take self and the array > index as paramaters and > return the values in that slot of the array > > The set method should take self, an index, and > the values as paramaters > and it should modify the real "C-version" of the > array. > > 4) when you execute your python function, it will be > given this > "wrapper" object as a paramater. It can then call > into the methods in > the wrapper object to access and change the > C-array "in-place" without > converting it at all. Each new value which is set > into the array > is converted on the fly. > > 5) If you like, you can convert get() and set() to > __get__() and __set__ > so you can use array access syntax to access the > array from python. > > > -- > David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske at chat.net __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From peter at engcorp.com Mon Jul 7 16:42:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 16:42:40 -0400 Subject: A story about Python... sort of References: Message-ID: <3F09DB40.4096E3B4@engcorp.com> Bob Gailer wrote: > > Physically impossible? or impractical. If it can be solved by Turing > machine computation then it is physically possible, even though it might > take more time/resources than anyone cares to expend. But remember "When > Harley Was One" and he invented the G.O.D.? Doesn't the Turing machine involve access to an infinitely long tape? If that's so, wouldn't that kind of make Turing machine computation discussions merely theoretically possible, but not necessarily practically possible? -Peter From ianb at colorstudy.com Tue Jul 8 05:15:34 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 04:15:34 -0500 Subject: path module In-Reply-To: References: Message-ID: <1057655734.3738.7.camel@lothlorien> On Tue, 2003-07-08 at 03:17, Just wrote: > I would greatly appreaciate such a module in the std library, but while > Jason's module has some very cool features, to my taste it goes a bit > too far with overloading operators. I really don't like overloading a/b > to mean os.path.join(a, b) and I don't think the default iterator should > do a listdir (although list(mypath) is indeed cute). If it were toned > down a bit in this area I think we may be able to make a good case for > including it in the std library. I've never wanted to iterate over a string, and find that an annoying feature in Python (I'd *much* rather get an exception), so covering up the previous string behavior doesn't seem a big deal to me. But I can see why iterating over a path may be a little too magic. But paths are also containers (at least if they point to a directory), so iterating over them seems only natural. I could see something like mypath.dir() being reasonable alternative (mypath.list() also, but that looks funny to me because "list" is special to my eye). I do like the /, though. mypath.joinpath(filename) is rather long-winded (since he wisely avoids reusing the join method). / has no meaning for strings, so it's not really overloading the operator, merely adding it in a specific context. Several operators are reused for different meanings, % in particular comes to mind, this doesn't seem that bad. I like the way it looks and feels. It feels better to me than using + for string concatenation ;) -- maybe because division is not all that common an operation anyway. Ian From faizan at jaredweb.com Mon Jul 28 13:58:38 2003 From: faizan at jaredweb.com (Fazer) Date: 28 Jul 2003 10:58:38 -0700 Subject: GET/POST Data Array in Python? References: <7b454334.0307271134.771de1ce@posting.google.com> Message-ID: <7b454334.0307280958.535da0cd@posting.google.com> Skip Montanaro wrote in message news:... > faizan> I am making a simple Pythong CGI script that collects data from > faizan> a form. When the Python CGI Script is called, I wish to gather > faizan> all the POST variables and display all their values. So, I was > faizan> wondering if all the POST data is collected in an array like in > faizan> PHP where I just go through all keys and display their values? > > Sure. For an example, visit: > > http://www.musi-cal.com/~skip/python/ > > and search for "CGI Environment Printer". > > Skip Thanks a lot! It really helped me out! From walter at livinglogic.de Wed Jul 9 18:01:32 2003 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 10 Jul 2003 00:01:32 +0200 Subject: Deleting specific characters from a string In-Reply-To: <3F0C8AC3.5010304@dadsetan.com> References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: <3F0C90BC.4030006@livinglogic.de> Behrang Dadsetan wrote: > Walter D?rwald wrote: > >> Behrang Dadsetan wrote: >> >>> Hi all, >>> >>> I would like deleting specific characters from a string. >>> As an example, I would like to delete all of the '@' '&' in the >>> string 'You are ben at orange?enter&your&code' so that it becomes >>> 'benorange?enteryourcode'. >>> >>> So far I have been doing it like: >>> str = 'You are ben at orange?enter&your&code' >>> str = ''.join([ c for c in str if c not in ('@', '&')]) >>> >>> but that looks so ugly.. I am hoping to see nicer examples to acheive >>> the above.. >> >> >> >> What about the following: >> >> str = 'You are ben at orange?enter&your&code' >> str = filter(lambda c: c not in "@&", str) >> >> Bye, >> Walter D?rwald > > > def isAcceptableChar(character): > return charachter in "@&" > > str = filter(isAcceptableChar, str) > > is going to finally be what I am going to use. > I not feel lambdas are so readable, unless one has serious experience in > using them and python in general. I feel it is acceptable to add a named > method that documents with its name what it is doing there. You're not the only one with this feeling. Compare "the eff-bot's favourite lambda refactoring rule": http://groups.google.de/groups?selm=3wFx6.2498%24sk3.826353%40newsb.telia.net > [...] Bye, Walter D?rwald From aahz at pythoncraft.com Mon Jul 7 09:37:06 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2003 09:37:06 -0400 Subject: anything new on the ternary operator? References: Message-ID: In article , Paul Rudin wrote: > >I don't know the details of this process; but personally I think a >ternary operator would be a very good thing - and don't care about the >syntax too much. Maybe the right think to vote on was simply a yes/no >to "Do you want a ternary operator?". Nope. Many people who were in favor of a ternary operator were entirely opposed to specific variants; that's even more true of people who were neutral on the subject. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From max at alcyone.com Tue Jul 8 03:50:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Jul 2003 00:50:07 -0700 Subject: Europython recordings? References: Message-ID: <3F0A77AF.7D375D93@alcyone.com> Claus D wrote: > Did anyone record the europython sessions? Apparently, Hunter hasn't > recieved a single reply from his effords to coordinate this... I wonder as well, I'd be interested to know if there are any recordings of Dinu Gherman's presentations, for obvious reasons :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I want to know God's thought; the rest are details. \__/ Albert Einstein From scott.daniels at acm.org Sun Jul 6 02:10:58 2003 From: scott.daniels at acm.org (Scott David Daniels) Date: 5 Jul 2003 23:10:58 -0700 Subject: getting a submatrix of all true References: Message-ID: <3f07bd72$1@nntp0.pdx.net> Folllowing Bengt and anton at vredegoor.doge.nl (Anton Vredegoor)'s leads, the following code can be fast (at times). It is quite sensitive to the probability of non-zeroness, (.01 works well, the .o5 is nowhere near so nice). I get 2.25 min to do 25 x 25 at .05 2.75 min to do 30 x 30 at .05 It gets slow _very_ fast, but gets good numbers if the probability is low .25 min to do 45 x 45 at .01 1.5 min to do 50 x 50 at .01 -Scott David Daniels Scott.Daniels at Acm.Org (not fully back up yet, though). Here's the code: ################################ # myopt.py __version__ = '0.3' try: assert list(enumerate('ab')) == [(0, 'a'), (1, 'b')] except NameError: def enumerate(iterable): # Not exact, but close enough lst = list(iterable) return zip(range(len(lst)), lst) def bitcount(row): '''Return the number of on bits in the integer argsA''' assert row >= 0 result = 0 while row: result += 1 lsbit = row & -row row ^= lsbit return result def rowencode(vector): '''convert from a buncha numbers to a bit-representation''' bit = 1L result = 0 for element in vector: if element: result |= bit bit <<= 1 return result def rowdecode(value, mask=-1): '''convert from a bit-rep to a buncha numbers (at least as long as mask)''' if mask < 0: mask = value assert value >= 0 result = [] while mask or value: result.append(value & 1) mask >>= 1 value >>= 1 return result class Answer(object): '''An answer represents a result calculation.''' __slots__ = 'rows', 'colmask', '_score' totalrequests = 0 totalcalcs = 0 def __init__(self, colmask, rows): '''The columns in colmask are the ones we keep.''' self.colmask = colmask self.rows = rows self._score = None def score(self): '''Calculate the score lazily''' self.__class__.totalrequests += 1 if self._score is None: self.__class__.totalcalcs += 1 self._score = bitcount(self.colmask) * len(self.rows) return self._score def __repr__(self): return '%s(%d:%s, %x):%s' % (self.__class__.__name__, len(self.rows), self.rows, self.colmask, self._score) totalcalls = 0 def choose(rows, keepcols, N=0, keeprows=None): '''Choose rows and columns to keep. Return an Answer for the choice''' global totalcalls totalcalls += 1 if keeprows is None: keeprows = [] try: while 0 == rows[N] & keepcols: keeprows.append(N) N += 1 except IndexError: return Answer(keepcols, keeprows) # a difference: some kept columns in this row are non-0 # must drop either those columns or this row # Calculate result if we keep this row (drop problem columns) withrow = choose(rows, keepcols & ~rows[N], N+1, keeprows + [N]) # Calculate result if we drop this row skiprow = choose(rows, keepcols, N+1, keeprows) # Choose the better answer (keep the row if everything is equal). if (withrow.colmask == skiprow.colmask or withrow.score() >= skiprow.score()): return withrow else: return skiprow # The data used from the example X = [ [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0] ] def printrep(row, symbols, mask=0): '''A row representing a single row (column-masked by mask)''' assert mask >= 0 result = [] for element in row: result.append(symbols[(1 & mask) * 2 + (element != 0)]) mask >>= 1 assert mask == 0 # mask doesn't extend beyond data. return ''.join(result) def printanswer(data, rows, keepcols): '''Print the represented row''' toohuge = len(data) rowqueue = rows + [toohuge] rowqueue.reverse() nextrow = rowqueue.pop() for rownumber, row in enumerate(data): if nextrow > rownumber: # This row was zapped print '#', printrep(row, '01OI', keepcols) else: assert rownumber == nextrow # This row was kept nextrow = rowqueue.pop() print '_', printrep(row, '01~@', keepcols) assert nextrow == toohuge and not rowqueue def getanswer(data): '''Calculate the best-cut for a particular matrix''' columns = max([len(row) for row in data]) rowdata = [rowencode(row) for row in data] return choose(rowdata, (1L << columns) - 1) def main(data=X): global totalcalls totalcalls = 0 answer = getanswer(data) print 'Requested: %s, Calculated: %s,' % ( Answer.totalrequests, Answer.totalcalcs), print 'answer: %r,' % answer, print 'Score: %s' % answer.score() print 'Total choose calls required: %s' % totalcalls printanswer(data, answer.rows, answer.colmask) def rangen(rows, columns, probability=0.05): '''create a rows by columns data table with 1s at the given probability''' import random result = [] for row in range(rows): result.append([int(random.random() < probability) for column in range(columns)]) return result if __name__ == '__main__': import sys assert getanswer([[0]]).score() == 1 assert getanswer([[0,1], [1,0]]).score() == 1 assert getanswer([[0,1,0], [1,0,0]]).score() == 2 if len(sys.argv) < 2: main(X) else: args = sys.argv[1:] if '.' in args[-1]: assert len(args) > 1 probability = float(args.pop()) else: probability = .2 rows = int(args[0]) if len(args) == 1: cols = rows else: assert len(args) == 2 cols = int(args[1]) main(rangen(rows, cols, probability)) From usenet_spam at janc.invalid Tue Jul 15 23:07:12 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 03:07:12 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: "richardc" schreef: > Has nobody written an editor/IDE in Python with wxWindows so that it > runs on all platforms ? There is an editor included with wxPython: PyCrust... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From alia_khouri at yahoo.com Fri Jul 11 02:40:23 2003 From: alia_khouri at yahoo.com (Alia Khouri) Date: 10 Jul 2003 23:40:23 -0700 Subject: Embedding Python, threading and scalability References: Message-ID: <40a939c9.0307102240.70c149d9@posting.google.com> [Simon Wittber] > To write scalable applications in Python, one must write the > 'scalabilty-required' parts n C. I wonder if python could benefit from working closely with a language like cilk, "a language for multithreaded parallel programming based on ANSI C." Has anybody has any experience with this? Alia From sfb at alysseum.com Thu Jul 10 08:55:54 2003 From: sfb at alysseum.com (Simon Bayling) Date: Thu, 10 Jul 2003 12:55:54 +0000 (UTC) Subject: Odp: Newbie - No module named stdwin References: <3f0c5faf.172627925@news.blueyonder.co.uk> Message-ID: "K" wrote in news:bejf32$3on$1 at topaz.icpnet.pl: > but in visual basic 6 i have graphical Interface - in Python only text > based is that correct ? Yes and no... Python only has a text interface, but can access "windowing toolkits" to allow you to make graphical interfaces. A lot of languages are like this, e.g. C++, but some have a built-in windowing toolkit, e.g. Java. Visual Basic also has its own built-in toolkit - so much so that it is all you can use, and it is easy to use - which is why it is so popular. So... yes strictly speaking Python only has a text interface, but that's not the whole story because you can create graphical interfaces with a toolkit that usually comes with Python, and it's a very common and standard thing to do. However, it requires a different style of programming, which is why the previous posters are suggesting you avoid it until you are comfortable with Python. http://www.pythonware.com/library/tkinter/introduction/hello- tkinter.htm#AEN50 Is a link to the most simple "Hello World" application with the toolkit "Tkinter". Cheers, Simon. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 1 16:47:25 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 01 Jul 2003 22:47:25 +0200 Subject: placing text at point on console In-Reply-To: <1057090010.408280@cache2> References: <1057090010.408280@cache2> Message-ID: <3f01f359$0$49115$e4fe514c@news.xs4all.nl> bart wrote: > I'm trying to place text at a certain point on the console. But I can't > figure out any way to do this. For instance place a '@' at point 6,8. > Any hints? > > (I'm trying to display a 'map'. Think nethack) You didn't say which system you use. This is important information because what you want to do is not system independent. For Unixes/Linux, try the curses module: http://www.python.org/doc/current/lib/module-curses.html import curses s=curses.initscr() s.addch(6,9,'#') s.refresh() For Windows, try the (non-standard) WConIO module: http://newcenturycomputers.net/projects/wconio.html import WConio WConio.gotoxy(6,8) WConio.cputs('@') --Irmen From runyaga at runyaga.com Fri Jul 18 12:11:01 2003 From: runyaga at runyaga.com (alan runyan) Date: Fri, 18 Jul 2003 11:11:01 -0500 Subject: Archetypes beta2 Announcement Message-ID: Announcement: Archetypes 1.0beta2 The Plone/CMF Collective communities have released Archetypes 1.0beta2 tarball. By leadership of Sidnei da Silva (and financial support from AGM Web consulting) the Archetypes project is rapidly moving to a 1.0 stable release. The Archetypes project was created by Benjamin Saller for use with the Plone/CMF to ease content-type creation by programmers. It now evolves and has a unique place in the Plone/CMF universe. It defines a schema like language and will dynamically generate class definitions on Zope startup. The schema language is in python and allows you specify the attribute name, accessor, mutator, constraints, transformation policy, marshalling policy, i18n policy as well as storage policy! All features are in production use but have not been extensively tested by the community. The biggest obstacle is (lack of) documentation which we are looking for financial/community support to resolve this critical issue. Please download the latest tarball, install it into your Plone site, and read the README. You will be able to create content objects with minimal amounts of code (see ArchetypesExample in the tarball). And for people who use UML look at the ArchGenXML that will take XMI input files and generate the Archetypes schema; you can actually model your content objects in UML and with a click of a button have them appear in your Plone site! Please give feedback to the archetypes-developers mailing list (archetypes-devel at lists.sourceforge.net) and reports bugs to: http://sourceforge.net/tracker/?group_id=75272&atid=543430 Tarball: http://prdownloads.sourceforge.net/archetypes/archetypes-1.0b2.tgz?download ChangeLog Notes: https://sourceforge.net/project/shownotes.php?group_id=75272&release_id=170750 The Archetypes Team From tomas at fancy.org Wed Jul 2 23:34:36 2003 From: tomas at fancy.org (Tom Plunket) Date: Wed, 02 Jul 2003 20:34:36 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> <3F0241D4.34010A5C@alcyone.com> Message-ID: <4297gv859qso3qv48p37jfi11oqkcl4omc@4ax.com> Erik Max Francis wrote: > The __call__ method is the equivalent of C++'s operator (). Thanks guys. -tom! From cmkleffner at gmx.de Wed Jul 2 04:48:46 2003 From: cmkleffner at gmx.de (cmkl) Date: 2 Jul 2003 01:48:46 -0700 Subject: Yet another threading question... References: Message-ID: <3b091a1c.0307020048.136dd5d0@posting.google.com> don't forget to add the -mthreads switch to gcc when compiling AS WELL linking your wrapper code with mingw's gcc. In case you use g++ instead of gcc for some reason your wrapper maybe depend on the mingw10.dll. Dependency walker will tell you.... Another compiler option which may help is -mms-bitfields The use of MS compatible bitfield layout is not enabled by default for some reason. The older mingw gcc has: -fnative-struct instead And another complication is the use of win32 unicode (wide character) functions: In this case you want to add -DUNICODE and -D_UNIOCDE to your compiler options. A completly different story is the use of the ctypes module instead. Hope this helps Carl "Kevin" wrote in message news:... > I've been pondering the exact same issue, but haven't gotten that far in > wrapping the 3rd-party C library I'm working with. > > I was thinking of stubbing the callback to a Python function that sets an > event flag, and have a Python thread monitoring that event to handle it. > I'm not sure if that will cure your access violation, but it may. You > should also make sure that your wrapper gets the GIL (Python Global > Intepreter Lock) before making the Python function call to set the event. > > Let me know if you try that, or if you get it to work some other way... I'll > be beating my head into the same problem pretty soon and could use the heads > up! > > Thanks, > Kevin Cazabon > > > "Jim West" wrote in message > news:mailman.1056639557.22837.python-list at python.org... > > Good day all, > > > > Ok, I'm starting to get the hang of this Python thing...really pretty > > cool actually. Again, thanx to those that have helped me thus far. > > > > I now have another stumbling block to which I would like help. > > > > Ok, here is my enviroment: > > > > Windows 2K > > Python 2.2 > > MinGW and MSys > > > > I'm writing a Python extension to a 3rd party DLL that controls an > > external hardware toy. > > > > One of the DLL methods is a callback registration interface. The 3rd > > party DLL is threaded as the callback is asynchronous. > > > > I'm able to call my extension function via Python to "register" my > > Python function as the callback function via a C function proxy in the > > extension. > > > > All is well until the DLL invokes the callback. When the callback > > attempts to invoke my "registered" Python function the Python > > interpreter bails with an access violation. > > > > I'm thinking it may have something to do with threading and thus am > > asking for your insight to this. > > > > I'm thinking I may have to put my proxy C callback function in it's > > own thread. If so, then would some kind soul point me in the right > > direction as to how to do this with just the MinGW environment since we > > do not have nor use MSVC++. > > > > Thank you. > > > > - Jim > > > > > > From cpitaar at yahoo.com.ar Sat Jul 19 12:28:13 2003 From: cpitaar at yahoo.com.ar (Carlos P.) Date: 19 Jul 2003 09:28:13 -0700 Subject: Calling tcl from python and viceversa Message-ID: <453d10b2.0307190828.3c576f15@posting.google.com> Hi! I want to call tcl from python and python from tcl. The big picture is that I?m writing an application GUI with tcl/tk and application logic with python, so at least I want to call python events from the tk GUI. I have read about _tkinter and tkapp.call although I couldn?t find any detailed documentation. And, anyway, that seems to work in one direction (python->tcl) but I don?t know how to make it work in the other (tcl->python). Thank you, Carlos From colinsm.spam-me-not at picsel.com Tue Jul 15 09:43:48 2003 From: colinsm.spam-me-not at picsel.com (Colin S. Miller) Date: Tue, 15 Jul 2003 14:43:48 +0100 Subject: [OT] sentances with two meanings In-Reply-To: <87brvw3ula.fsf@pobox.com> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: <4701fb.8co.ln@195.171.216.1> > > Matthew 25:35 I was a stranger, and you took me in. Care to enlighten us with the second meaning? I'm a native English speaker, but can only see one meaning 'I was unknown to you, yet you let me stay in your house' Although 'took me in' could also mean 'accept as a friend' Colin S. Miller From thomas.buschhardt at iac-leipzig.de Tue Jul 15 03:01:16 2003 From: thomas.buschhardt at iac-leipzig.de (Thomas Buschhardt) Date: Tue, 15 Jul 2003 09:01:16 +0200 Subject: Socket and Tkinter Problem Message-ID: <001801c34a9e$e2b6e0f0$9108000a@iacleipzig.de> Hallo, I have a problem with Tkinter and the module socket. In a console-window everything works fine, but in a Tkinter-window I can no more use the widgets. I found some other mails with this problem, but no solution (I understand really :-) Here is my code: ----------------------------------------------- import win32ui, dde, string, time, os, sys, shutil from socket import * from Tkinter import * from tkFileDialog import * from tkMessageBox import * import win32com.client def sockelserver(): while 1: HOST = 'localhost' PORT = 8578 s = socket(AF_INET, SOCK_STREAM) s.bind((HOST,PORT)) s.listen(1) log("wait...") hs,addr=s.accept() log("connected with: "+str(addr)) while 1: data=hs.recv(1024) if not data:break if data=="'exit'":break erg='hallo' # erg=datawash(data) log("reiceved: "+data) hs.send(erg) hs.close() if data=="'exit'":break def log(nachricht): anzahl_lines=string.count(logtext.get(1.0,END),'\n') if anzahl_lines>2000:logtext.delete(0.0,2.0) logtext.insert(END,time.asctime()+'\t'+nachricht+'\n') logtext.see(END) root.update() root = Tk() midframe =Frame(root, borderwidth=2, relief=GROOVE) Label(midframe,text='Logg-Fenster').pack(side=TOP) scrollbar = Scrollbar(midframe, orient=VERTICAL) scrollbar.pack(fill=Y, side=RIGHT) logtext = Text(midframe) logtext.pack() logtext.config(yscrollcommand=scrollbar.set) scrollbar.config(command=logtext.yview) midframe.pack(padx=2, pady=2) botframe = Frame(root) botframe.pack(padx=2, pady=2) Button(botframe, text='Start', command=sockelserver).pack(side=LEFT,padx=2,pady=2) Button(botframe, text='Exit', command=root.destroy).pack(side=LEFT,padx=2,pady=2) root.title('DDE-Server') root.mainloop() -------------------------------------- The function is easy. I want to start a server that waits for connection and answer with an result. The communication-protocol is printed out in a Text-window. Please help me out :-) Cheers Thomas From udo.gleich at web.de Mon Jul 28 06:20:02 2003 From: udo.gleich at web.de (Udo Gleich) Date: Mon, 28 Jul 2003 12:20:02 +0200 Subject: mixin class Message-ID: <3F24F8D2.E1ADFB08@web.de> Hi, I try to implement mixin classes. Thats why I need to make a new class at runtime. --tmp.py------------------------------------- import new class K1(object): pass class K2(object): pass mixed = new.classobj("K1_K2", (K1, K1), {}) new_instance = new.instance(mixed, {}) print new_instance --------------------------------------------- Making a new instance from the new class works only if K1 is not derived from object. If I use new style classes I get the following traceback: Traceback (most recent call last): File "tmp.py", line 10, in ? new_instance = new.instance(mixed, {}) TypeError: instance() argument 1 must be class, not type I use Python 2.2.3 and Win2000. My question: How do I implement mixin classes with new style classes? Thanks, Udo From usenet_spam at janc.invalid Tue Jul 15 22:20:30 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 02:20:30 GMT Subject: Confusing automated translators. References: Message-ID: "Alan Kennedy" schreef: > I was obviously completely off base with my interpretation of "pilote > ferme"/"experimental farm". :#) "Experimental farm" or "pilot farm" would have been "ferme pilote" or "ferme exp?rimentale" or something like that... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From mwh at python.net Tue Jul 22 09:53:53 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 13:53:53 GMT Subject: Problem building extension sample with Python 2.2.3 References: Message-ID: <7h34r1eznbq.fsf@pc150.maths.bris.ac.uk> iambren at sympatico.ca (Bren) writes: > Hi, > > I'm trying to build the sample extension file from > http://www.python.org/doc/current/ext/simpleExample.html. > > I get a linker error: > > Linking... > spam.obj : error LNK2001: unresolved external symbol > __imp__Py_InitModule4TraceRefs > > Also, I find it necessary to ignore python22_d.lib and link > python22.lib explicitly when I make a Debug build. There's your problem, I think. You seem to be trying to build a debug version of your module against a release version of Python. This won't work. Cheers, M. -- Check out the comments in this source file that start with: # Oh, lord help us. -- Mark Hammond gets to play with the Outlook object model From mertz at gnosis.cx Thu Jul 10 21:47:17 2003 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 10 Jul 2003 21:47:17 -0400 Subject: object instance data to docbook, xml, pdf, etc? References: Message-ID: Harry George wrote previously: |We are outputting the instance data, sort of like Gnosis xml_objectify, |but to docbook DTD. You *could* use XSLT to transform the gnosis.xml.pickle output into DocBook (I'm pretty sure you mean that, objectify goes in the other direction generic-XML -> python). However, I personally find XSLT extremely awkward. If someone doesn't give you the done-deal, you might find it useful to take gnosis.xml.pickle and fork it for your desired DocBook/XML output. All the issues about traversing objects is handled, you should pretty much be able to just look for the XML tags that get written, and substitute those as needed. 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 tebeka at cs.bgu.ac.il Wed Jul 9 08:43:30 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 9 Jul 2003 05:43:30 -0700 Subject: regexp and filenames References: Message-ID: <33803989.0307090443.1a77b754@posting.google.com> Hello, > > I'm familiar with regexp, but I've only used it in Python to act on > > the contents of a file, not filenames in a directory. Any pointers on > > how to approach this are welcome! http://www.python.org/doc/current/lib/module-glob.html and http://www.python.org/doc/current/lib/module-fnmatch.html HTH. Miki From merman at snafu.de Wed Jul 9 10:01:20 2003 From: merman at snafu.de (T. Kaufmann) Date: Wed, 09 Jul 2003 16:01:20 +0200 Subject: Tkinter question - proper output in Text widget Message-ID: <3F0C2030.40405@snafu.de> Hi there, I have some lines of code in a Tkinter programm - I want to list every single file of a zip-archive in a Text widget: fp = os.popen("%s %s" % ('unzip -vl ', 'anyarchiv.zip', 'r') for line in fp: textWidget.insert(END, "%s" % (line)) The result is that the columns are not really proper if the file-size of the listed files is different. An output example: Length Method Size Ratio Date Time CRC-32 Name -------- ------ ------- ----- ---- ---- ------ ---- 1175 Defl:N 513 56% 05-23-03 13:51 084e4103 charset.py 972 Defl:N 427 56% 04-05-03 18:42 b8bb850d controller.py Here it looks good but not in my application (in the Text widget). Whats wrong? How can I made a better result (proper columns). o-o Thomas From jmike at alum.mit.edu Mon Jul 28 12:03:15 2003 From: jmike at alum.mit.edu (J. Michael Hammond) Date: 28 Jul 2003 09:03:15 -0700 Subject: Any open source utilities built on top of PyUnit? Message-ID: I work in a company that has used Python since its (the company's) inception in late 1999. During his initial blaze of white-hot hacking, the chief architect wrote a unit test class and a moderately extensive set of unit and regression tests that use this unit test class. Since then, other developers have also written unit and regression tests on top of that unit test class, so we have a pretty large body of tests that use it. We are beginning to make some deep changes to the testing infrastructure that make now a good time to raise the question of switching from our home-brewed UnitTestClass to the PyUnit package. I've gone through the PyUnit documentation the decision comes down to this: are there any utilities out there, built on top of PyUnit, that are gaining traction? Say is there some kind of GUI package that allows easy "run these suites on these machines" sorts of things? Or a test results reporting package? Or any other things like that? If there any tools out there like that, that would reduce our total cost of switching (and maybe indicate the chance to use similar tools in the future as de-facto standards evolve), then I think we might well switch. If not, it's probably not worth the rip-up-and-redo effort for us to switch to PyUnit. So what's the scoop? Thanks! --JMike From gsmatthew at ozemail.com.au Fri Jul 18 21:29:44 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Sat, 19 Jul 2003 11:29:44 +1000 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: ok still a bit confused sorry .... first attempt at a thread pool Am I correct in saying that each thread runs in a continious loop each thread calls queue.get. The get method will block and not return anything until an item is placed into it. When an item is placed into it, one of the threads will get assinged a job i.e the first one that happens to be in use during the cycle ? The job is returned to the thread, it runs with the job and does all the processing then returns and calls queue.get again and waits for a job to become available ? When placing a job via Queue.put() one must acquire a lock place it and then release it Am i aslo correct in saying that queue is actually doing the blocking and controls which thread gets the job ? Lastly, sorry for all the questions, surely the CPU usage is the same when the queue is waiting for jobs and when the threads are polling as theyre all in one process anyway thanks very much for your help Graeme Am i getting this or am i way off :-) "Graeme Matthew" wrote in message news:NDZRa.273$vD1.11889 at nnrp1.ozemail.com.au... > Aahz > > Thanks, ive actually been using your OSCON slides which have helped a lot. > So it technically correct that all worker threads in a thread pool are > either doing some work or polling the queue to find out if there is a job > to process ? > > eg: (pseudocodish :-)) > > def run(self): > > while 1: > > self.lock.acquire() > > if QueueManager.HasJob: > job = QueueManager.GetFreeJob() > __processJob(job) > > self.lock.release() > > def __processJob(self): > > blah blah blah ..... > > > many thanks ...... > "Aahz" wrote in message > news:bf8ri5$cs7$1 at panix1.panix.com... > > In article <0tRRa.212$vD1.8077 at nnrp1.ozemail.com.au>, > > Graeme Matthew wrote: > > > > > >I just cannot seem to find any documentation that shows an example of > > >using the factory method Event() in threads. I have a thread pool and > > >if there are no jobs in a Queue I want them to wait for something to > > >be inserted. When a job is inserted I want to send an Event, the first > > >thread that picks it up runs with the job the rest wait for another > > >insert Event. > > > > Given that you're already using a Queue, there is no, repeat NO, reason > > for using an Event. Just have your threads block on the Queue. > > -- > > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > > > A: No. > > Q: Is top-posting okay? > > From kp at kyborg.dk Thu Jul 10 09:46:14 2003 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 10 Jul 2003 15:46:14 +0200 Subject: Memory leak ?? Argh! In-Reply-To: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> References: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> Message-ID: <3f0d6e26$0$13201$edfadb0f@dread15.news.tele.dk> Kim Petersen wrote: > i've run it up to 240000 recsets so far - and it eats about .1% of my > mem pr. 1000 (doesn't really matter how much does it?). > Correction - this will be a problem ... at 1M records its rounding the 79MB ram mark.... -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From duncan at NOSPAMrcp.co.uk Wed Jul 23 04:06:17 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 23 Jul 2003 08:06:17 +0000 (UTC) Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: bokr at oz.net (Bengt Richter) wrote in news:bfjokm$kbc$0 at 216.39.172.122: >>'all_false(...)' is simply 'not any_true(...)' >>'any_false(...)' is 'not all_true(...)' >> >>So you could get by with just two of these functions, in which case >>'any_of', and 'all_of' might be suitable names. >> > I don't think they're equivalent if they do short-circuiting. > any_true short circuits as soon as it finds one that is true. all_false short circuits as soon as it find one that is true. all_true short circuits as soon as it finds on that is false. any_false ditto. Why aren't they equivalent? -- 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 Tue Jul 8 12:02:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 11:02:02 -0500 Subject: path module In-Reply-To: References: Message-ID: <16138.60154.48719.630239@montanaro.dyndns.org> Hallvard> It's a long time since I used anything like that, but I think Hallvard> Tops-20 filename paths looked like this: Hallvard> device:file.ext;version Hallvard> where most components were optional. which is (not too surprisingly) very similar to VMS: device:[dir.dir.dir]file.ext;version Skip From jdhunter at ace.bsd.uchicago.edu Tue Jul 1 22:38:13 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 01 Jul 2003 21:38:13 -0500 Subject: whitespace and ?asc()? In-Reply-To: <3F02086D.9010300@ihug.co.nz> (Ray Tomes's message of "Wed, 02 Jul 2003 10:17:17 +1200") References: <3F02086D.9010300@ihug.co.nz> Message-ID: >>>>> "Ray" == Ray Tomes writes: Ray> Hi all I am totally new to python. On the whole I really like Ray> the design of the language and after just one day may be Ray> considered a convert. Welcome. Ray> I was trying to find out the exact definition of whitespace Ray> so I went to look at strings.whitespace to find out which Ray> chars were whitespace, and found 9, 10, 11, 12, 13, 32 which Ray> according to my ancient ascii chart are TAB, LF, VT, NP, CR, Ray> SPACE. Anyone know what NP = 12 is? NP = New Page Ray> Also, in trying to find the ASCII (or is it ANSI) values for Ray> characters I could not find the reverse function for chr() Ray> [in BASIC it is asc()]- can someone please tell me what Ray> reverses chr()? ord Ray> I had to do this yucky thing to decode whitespace ... If you have a relatively recent version of python (2.0 or later), perhaps you'll find this less yucky ... print [ord(c) for c in string.whitespace] This makes use of list comprehensions, which are often a cleaner and faster way of writing simple combinations of 'for' loops and 'if' statements: http://www.python.org/peps/pep-0202.html http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 Cheers, John Hunter From kevino at tulane.edu Tue Jul 22 20:07:35 2003 From: kevino at tulane.edu (Kevin Ollivier) Date: Tue, 22 Jul 2003 17:07:35 -0700 Subject: Zlib problem on Windows XP?? References: Message-ID: I apologize, when I installed the OpenOffice Python support, I had to add an environment variable pointing to the OOo modules. It turns out that there was a zlib.dll in that location, so taking off the environment variable fixed the problem (for the moment...). Sorry about that! Kevin On Tue, 22 Jul 2003 23:16:06 +0200, Gerhard H?ring wrote: >Kevin Ollivier wrote: >> Hi all, >> >> When using the latest Python 2.2.x releases as well as the Python 2.3 >> betas and rc1 on Win XP, I cannot import zlib. When I try, I get an >> error about the dynamic module not having an 'initzlib' symbol. The >> strange thing is that this problem seems to be XP-specific - on Windows >> 2K I do not get this error. I've installed Python 2.2.3 on two XP >> machines with the same results. I installed the latest beta on one of >> the machines, but the results were the same. (Haven't tried RC1 yet.) [...] > >I cannot confirm this. Windows XP Professional SP 1 (English): > >- Python 2.3b2 works >- Python 2.3c1 works > >-- Gerhard From aahz at pythoncraft.com Mon Jul 7 09:35:19 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2003 09:35:19 -0400 Subject: anything new on the ternary operator? References: <3F09252F.9B0F52BD@alcyone.com> Message-ID: In article <3F09252F.9B0F52BD at alcyone.com>, Erik Max Francis wrote: > >Bob's phrasing of it was obviously overly confrontational, but I do find >it at least a little unfortunate that the final decision on PEP 308 only >came indirectly (meaning not as any form of widespread public >announcement, but rather as a side point in a presentation at a local >conference) and many months after the voting processes was resolved >(which was in February, if I recall correctly). That I'll agree with enthusiastically. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From hokiegal99 at hotmail.com Sat Jul 5 13:48:31 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 05 Jul 2003 13:48:31 -0400 Subject: Calculating Year, Month and Day of Life Message-ID: Hello, I am a funeral director trying to write a small program that calculates the number of years, months and days a person has lived by entering the year, month and day of their birth. This is what I have so far: #--------------------- from time import * local = localtime() print "Enter the year of birth:"; y = input() print "Enter the month of birth:"; m = input() print "Enter the day of birth:"; d = input() age = y,m,d print age print local #---------------------- The output looks similiar to this: (1934, 2, 7) (2003, 7, 5, 13, 20, 0, 5, 186, 1) My problem is that localtime is a list of 9 integers while age is a list of 3 integers. Is it possible to make localtime() only return the first 3 integers? If so, how would I then do calculations on the two lists' individual parts? For example, how would I instruct localtime() to subtract the first integer from age's list from the first intger in its own list (2003 - 1934)? Also, I am new to python, but I like it a lot and have picked it up quickly. If my approach to this solving this problem is completely wrong, please point me in the right direction. Thanks in advance!!! From cneal92 at lycos.com Thu Jul 10 12:50:45 2003 From: cneal92 at lycos.com (O'Neal Computer Programmer) Date: 10 Jul 2003 09:50:45 -0700 Subject: python scripting game The Temple Of Elemental Evil update References: Message-ID: <82ff1d8b.0307100850.4098f8d4@posting.google.com> "Delaney, Timothy C (Timothy)" wrote in message news:... > > From: Geoff Gerrietts [mailto:geoff at gerrietts.net] > > > > I can't speak for the Temple of Elemental Evil in particular, but this > > pattern holds true in dozens of similar titles. If they're doing > > something different, they're doing something really very different. > > Troika have specifically said that it is being used in the AI > (presumably NPC and PC if the player turns on PC AI during combat). > > The dialog system is basically an upgraded version of the Arcanum dialog > system, so whether that's been augmented with Python I have no idea. > > That's as in-depth as I know. > > Tim Delaney Well, that's great. We can create new NPCs :D From gh at ghaering.de Sun Jul 6 16:45:04 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 06 Jul 2003 22:45:04 +0200 Subject: help! - cmd line interpreter gone "dumb" In-Reply-To: References: Message-ID: <3F088A50.8070603@ghaering.de> Tim wrote: > Maybe I've been working too long, but has anyon had their python interpreter > stop taking commands. > > The IDLE version works fine, but under Windoze: > > 1) execute "python" in teh command shell > 2) ...interpreter comes up fine > 3) type in anything and you get "SyntaxError: invalid syntax" > > Literally, you could type in "import sys" or anything common and you get the > same results. I've seen that when I used os.spawn* (or was it os.execv*?), apparently in a wrong way. > Any help greatly appreciated--thanks. Typical Windows answer: reboot and try again ;-) -- Gerhard From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 23 02:36:04 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 23 Jul 2003 16:26:04 +0950 Subject: python assignment References: Message-ID: On 22 Jul 2003 17:59:08 -0700, dan wrote: > What I need is an exact and unambiguous algorithm for determining when > an assignment will change the id of the variable As I understand it, this is specific to the implementation of each type. The only sensible way to code is as if the identity of an object, on assignment, were completely unpredictable. The examples you gave showed that integers share identity with other integers of the same value, while floats do not. This demonstrates why it's a poor idea to expect assignment to behave a particular way w.r.t. object identity: an alternative implementation may be more efficient, yet have a different relationship with identity. If you write your code so that it expects a particular identity behaviour w.r.t. assignment, that prevents future implementation changes without breaking your code. -- \ "Good judgement comes from experience. Experience comes from | `\ bad judgement." -- Frederick P. Brooks | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From tayss_temp at yahoo.com Sun Jul 27 09:37:09 2003 From: tayss_temp at yahoo.com (Tayss) Date: 27 Jul 2003 06:37:09 -0700 Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> Message-ID: <5627c6fa.0307270537.1afc94d3@posting.google.com> Bruno Desthuilliers wrote in message news:<3f23ae06$0$21093$626a54ce at news.free.fr>... > > FWIW, I do favor the addition of optional static typing for the two > > reasons Scott described - interface documentation and optimization. > > Interface documentation may be obtained in others ways (docstring for > exemple). Indeed! As I remember, Jython uses doc strings for typing, when it presents an API to Java. So it's in the comments, and I think that's an oddly appropriate place for hints to the compiler. > And I'm not sure static typing would optimize anything, but > not being a Python (nor anything else) guru, I would not bet my hand on > this... If you mess around with lisp, you can easily see the compiled assembly language of your functions when you experiment with optional typing. (By calling the function "disassemble".) Normally, the compiler spews a lot of general code because it doesn't know what you've passed in. But when you promise that you're passing in numbers or something, the assembly language is much tighter. Sort of like when someone asks you to move something to a different house, and you have no idea how big it is. If you were told, "It's just a pillow," you know that you don't need to order a huge truck or take any special precautions. From steve at cyber.com.au Sun Jul 20 21:56:51 2003 From: steve at cyber.com.au (Steven D'Aprano) Date: 20 Jul 2003 18:56:51 -0700 Subject: A challenge to the ASCII proponents. References: <3F1AAC0A.7A6326B@hotmail.com> Message-ID: Alan Kennedy wrote in message news:<3F1AAC0A.7A6326B at hotmail.com>... > Alan Kennedy: > > > The final point I'd like to make [explicit] is: nobody had to ask > > me how or why my xml snippet worked: there were no tricks. Nobody > > asked for debugging information, or for reasons why they couldn't > > see it: Sorry Alan, but when I follow your instructions and save your XML to disk and open it in Opera 6.01 on Win 98, I get this: XML parsing failed: not well-formed (1:0) At least it renders visibly in my browser, although I don't think its rendering the way you wished. (For the record, this is the contents of the XML file, triple-quoted for your convenience: """ γίγνωσκω""") [snip] > In summary: > > 1. I managed to make a greek word, using the original greek glyphs, > appear on everyone's "rendering surface", by posting a 7-bit clean XML > snippet. Another poster widened the software coverage even further by > posting a 7-bit clean HTML snippet. Both of our 7-bit markup snippets > travelled safely throughout the entirety of UseNet, including all the > 7-bit relays and gateways. I couldn't see either rendered correctly in either Opera's newsreader or the Google archive. > 2. The only other person who managed it, without using markup, was > Martin von Loewis, who is so good at this stuff that he confidently > makes statements like "what I did was right: it was Google that got it > wrong". Martin used the UTF-8 character set, i.e. a non-ASCII, > non-7-bit-clean character set, to achieve this. Although I'm sure > Martin could have managed it with UTF-7 as well. Martin's effort did work for me in Opera's newsreader, but not in the Google Groups archive. But we already knew that Google broke it. > 3. If anybody else was willing to give it a try, they don't seem to > have had enough confidence in their knowledge of encodings, MIME, > transports, NNTP, etc, etc, to have actually hit the "send" button, in > case it didn't work. Which doesn't bode well for the average person in > the street: if the technology specialists in this newsgroup don't feel > in command of the issue, what hope for everyone else? Exactly. Which brings us back to Ben's suggestion: when writing for a general audience using unknown systems, stick to ASCII, or at least follow your rich text with a description of what your reader should see: """And I can use Umlauts (???) -- you should see a, o and u all in lowercase with two dots on top.""" It's a mess and I despair. It would be nice if everyone used bug-free XML-aware newsreaders, browsers and mail clients, but the majority don't. That's why I always practice defensive writing whenever I use any character I can't see on my keyboard, and spell it out in ASCII. That's not very satisfactory, but its better than some random percentage of your audience seeing "?????". -- Steven D'Aprano From ee01b092 at ee.iitm.ernet.in Tue Jul 15 22:51:56 2003 From: ee01b092 at ee.iitm.ernet.in (Vinoo Vasudevan) Date: 15 Jul 2003 19:51:56 -0700 Subject: String Manipulation References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: <45f7ff62.0307151851.f59129f@posting.google.com> lamar_air at hotmail.com (lamar_air) wrote in message news:<2c6431ab.0307151223.4173c4ee at posting.google.com>... > I need a piece of code that takes a string like this string1 = > "aaa/bbb/ccc/dd" and extracts a string containting the character after > the last "/" > > So for this example the result would be "dd" > > like this: > for i=0; string1.right(i) != '/'; i++ > > result = string1.mid(i, string1.length()) > > but in python. How about this: string1 = 'aaa/bbb/ccc/dd' result = string1[string1.rfind('/')+1:] Hope it's helpful, Vinoo From tomas at fancy.org Tue Jul 15 13:42:00 2003 From: tomas at fancy.org (Tom Plunket) Date: Tue, 15 Jul 2003 10:42:00 -0700 Subject: Stop Python from exiting upon error in Windows References: Message-ID: John Roth wrote: > You don't have to put in the full path to Python if you > rig the command prompt you're using to add Python to > the path as the initialization command. That trick should > also let you set up PYTHONPATH for the project. Alternatively, you just set up a file association (which has probably already been done for you by the installer) and type in the filename at the command line: C:\MyProject> main.py > I keep a command prompt instance in each project > directory, pointing to the correct initialization for the > project. Wow, I just have a right-click context menu handler for directories to open a command prompt "right here", and don't require setup beyond what gets executed in the app. :) > ...each test module. Ugh, seperate tests that must be run by a person? Prefer one test "app" that runs all tests. > A mouse click to switch windows, three key strokes and voila! the > test runs (or not, as the case may be.) I just type "test.py" at the command prompt. :) Usually, I can abbreviate this to one or two presses of the up-arrow key. > It avoids any possible problem with PythonWin polluting itself by > not refreshing everything on a retest. PythonWin? Debuggers? Craziness. I haven't opened a debugger for Python in over a month, and the last time I used one was because I was too lazy to write proper test coverage. ;) -tom! -- There's really no reason to send a copy of your followup to my email address, so please don't. From bh at intevation.de Mon Jul 28 06:44:31 2003 From: bh at intevation.de (Bernhard Herzog) Date: 28 Jul 2003 12:44:31 +0200 Subject: emacs python-mode questions: C-c C-c and broken docstring fill References: <87ptjwre0x.fsf@pobox.com> Message-ID: <6qy8yjj5gw.fsf@salmakis.intevation.de> jjl at pobox.com (John J. Lee) writes: > 2. A while ago I 'upgraded' to a version of python-mode (from > somewhere on sourceforge, I think -- perhaps Python CVS, don't > remember) which somebody here claimed was able to fill comments > without needing blank lines before and after the comment. It does do > that, but the new version also breaks filling text in docstrings > (under particular circumstances which I haven't figured out, but which > occurs very frequently). I get something like: "The parameter start > is not the beginning of a python string". Where does the latest > python-mode live, and is this fill bug with docstrings fixed? One situation where this can happen is if point is the at the @ in the following triple quoted string: """nobody expects the "spanish" @inquision""" The following patch should fix this I think (I haven't tested this very well though): *** python-mode.el.~4.35.~ Sat Jul 19 17:28:04 2003 --- python-mode.el Mon Jul 28 12:25:04 2003 *************** *** 3714,3720 **** (py-fill-comment justify)) ;; are we inside a string? ((nth 3 pps) ! (py-fill-string (nth 2 pps))) ;; otherwise use the default (t (fill-paragraph justify))))) --- 3714,3720 ---- (py-fill-comment justify)) ;; are we inside a string? ((nth 3 pps) ! (py-fill-string (nth 8 pps))) ;; otherwise use the default (t (fill-paragraph justify))))) Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From cookedm+news at physics.mcmaster.ca Thu Jul 31 17:08:55 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 31 Jul 2003 17:08:55 -0400 Subject: Python speed vs csharp References: Message-ID: At some point, Mike wrote: > Here's the chunk of code that I'm spending most of my time executing: > > # Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. 7.1.26) > # Fifth order approximation. |error| <= 1.5e-7 for all x > # > def erfc( x ): > p = 0.3275911 > a1 = 0.254829592 > a2 = -0.284496736 > a3 = 1.421413741 > a4 = -1.453152027 > a5 = 1.061405429 > > t = 1.0 / (1.0 + p*float(x)) > erfcx = ( (a1 + (a2 + (a3 + > (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) > return erfcx With python2.2, a million iterations takes 9.93 s on my machine. With python2.3, 8.13 s. Replacing float(x) with just x (multiplying by p (a float) is enough to coerce x to a float), with python 2.3 I'm down to 6.98 s. Assigning math.exp to a global variable exp cuts this down to 6.44 s: exp = math.exp def erfc(x): [...] t = 1.0 / (1.0 + p*x) erfcx = ... * exp(-x**2) return erfcx You can go a little further and look up ways of optimising the polynomial evaluation -- Horner's method is a good, general-purpose technique, but you can get faster if you're willing to put some effort into it. I believe Ralston and Rabonwitz's numerical analysis book has a discussion on this (sorry, I don't have the complete reference; the book's at home). That's about the best you can do in pure python. Now look at how you're calling this routine. Can you call it on a bunch of numbers at once? Using Numeric arrays (http://numpy.org/), calling the above routine on an array of a million numbers takes 1.6 s. Calling it 1000 times on an array of 1000 numbers takes 0.61 s. Using erfc from scipy.special, this takes 0.65 s on a array of a million numbers. Scipy (from http://scipy.org/) is a library of scientific tools, supplementing Numeric. I believe the routine it uses for erfc comes from the Cephes library (http://netlib.org/), which has a error < 3.4e-14 for x in (-13,0). Calling it 1000 times on an array of 1000 numbers takes 0.43 s. (Ok, I don't know why 1000 times on arrays of 1000 numbers is twice as fast as once on an array of 1000*1000 numbers.) Extrapolating from your numbers, your C program is 28x faster. Using scipy.special.erfc on moderate-sized arrays is 18.9x faster. That's pretty good :) For numerical codes in Python, I *strongly* suggest that you use Numeric (or numarray, it's successor). It's _much_ better to pass 1000 numbers around as a aggregate, instead of 1 number 1000 times. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From vze4rx4y at verizon.net Sat Jul 26 20:09:00 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 27 Jul 2003 00:09:00 GMT Subject: very Very VERY dumb Question About The new Set( ) 's References: <20030723144732.13232.00000523@mb-m10.aol.com> <3f205d3c.745868662@news.blueyonder.co.uk> Message-ID: > > Since both dictionaries and Sets require unique members/keys, > > why not use the dictionary braces but without the key/value > > syntax. So: > > > > mySet = {1,2,3,4} > > > > Which is illegal for a dictionary but would be OK for a Set. > > It also just happens to be the same delimiters used in math > > for sets... > > > +1 if Python's parser could handle it (which seems dubious). FWIW, I think the easiest and most readable syntax is: mySet = set(1, 2, 3, 4) BTW, this is a bit reminiscent of the discussion about a syntax for entering fixed decimals. After much discussion, someone realized the obvious and noted that real programs mostly take in their fixed point data from external sources and would rarely appear as a constant in a program; hence, there was no need for a special syntax -- just Decimal(data) would do the trick. (Think about a program like Quicken for checkbook accounting -- none of the check/deposit amounts are known in advance so the program is unlikely to contain any fixed decimal constants except zero and $0.01). Raymond Hettinger From BartolomeSintes at ono.com Thu Jul 10 11:07:57 2003 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Thu, 10 Jul 2003 15:07:57 GMT Subject: keep original date and time of unzipped files Message-ID: Hi, In this mail, http://www.mail-archive.com/kragen-hacks at canonical.org/msg00030.html Kragen Sitaker explained how to unzip a file in Python #!/usr/local/bin/python # learn how to use zipfile module import sys, zipfile, os, os.path def unzip_file_into_dir(file, dir): os.mkdir(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join(dir, name)) else: outfile = open(os.path.join(dir, name), 'wb') outfile.write(zfobj.read(name)) outfile.close() def main(): unzip_file_into_dir(open(sys.argv[1]), sys.argv[2]) if __name__ == '__main__': main() The unzipped files date and time are not the original ones, but when the unzipping is done. Is there a way to keep the original files date and time? Thanks, Barto From gh at ghaering.de Sat Jul 12 11:55:12 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 17:55:12 +0200 Subject: The ASPN compiler In-Reply-To: <2k30hv4t88n5iu7nj5g3e55gd275rumf7i@4ax.com> References: <2k30hv4t88n5iu7nj5g3e55gd275rumf7i@4ax.com> Message-ID: <3F102F60.7050108@ghaering.de> Fuzzyman wrote: > On Sat, 12 Jul 2003 02:21:33 +0200, Gerhard H?ring > wrote: > >>Fuzzyman wrote: >> >>>What's the score on this (the ASPN python compiler) >> >>There was a proof-of-concept implementation of a Python compiler for the >>.NET platform done by ActiveState and sponsored by Microsoft. >> >>>- is it a true >>>compiler for python ? >>Read the whitepaper, available on the ActiveState site. > > Done that - its not entirely clear - any chance you could answer the > question...... The resulting output can be executed by the .NET runtime and two-way interoperability between Python and .NET is currenty possible according to that paper. >>>- what does it output - binary or C++ for .NET >>>framework............ >>Read the whitepaper, available on the ActiveState site. > > Done that - its not entirely clear - any chance you could answer the > question...... MSIL. >>>if the latter then it could be very cool as it >>>may work with the PocketPC 2003 SDK.... for producing binaries for >>>PDAs from python... cool... >> >>Forget it. Instead what you probably want is a Python implementation for >>Windows CE 3.0. There is one. > > Not for the SH3 processor... doesn't produce binaries. Then you could ask the maintainer to produce such binaries. Or download the free WinCE SDK + Emulator + whatnot yourself and build binaries yourself. You might even learn a little C that way ;-) Or install Linux or NetBSD on that handheld instead :-) -- Gerhard From ben at dadsetan.com Mon Jul 14 17:51:42 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Mon, 14 Jul 2003 22:51:42 +0100 Subject: Newbie with sort text file question References: <86d2ca4.0307121146.3deb854a@posting.google.com> <86d2ca4.0307131344.3fb3b9d3@posting.google.com> Message-ID: <3F1325EE.8030204@dadsetan.com> Hi Stuart, You can try some regexp with the re module. I wrote you an example in the newgroup. Regards, Ben. stuartc wrote: > Hi Bengt: > > Thank you. Your code worked perfectly based on the text file I > provided. > > Unfortunately for me, my real text file has one slight variation that > I did not account for. That is, the fruit name does not always have > an "_" after its name. For example, apple below does not an an "_" > attached to it. > > banana_c \\yellow > apple \\green > orange_b \\yellow > > > This variation in my text file caused a problem with the program. > Here's the error. > > Traceback (most recent call last): > File "G:/Python22/Sort_Fruit.py", line 47, in ? > for fruit, dummyvar in fruitlist: fruitfreq[fruit] = > fruitfreq.get(fruit, 0)+1 > ValueError: unpack list of wrong size > > I tried to debug and fix this variation, but I wasn't able to. I did > notice that your split, splits each line in the file into two fields, > as long as there's an "_" with a fruit name. If the fruit name does > not have an "_", then the split does not occur. I think this is > related to the problem, but I couldn't figure out how to fix it. > > Any help will be greatly appreciated. Thanks. > > - Stuart > > > > bokr at oz.net (Bengt Richter) wrote in message news:... > >>On 12 Jul 2003 12:46:51 -0700, stuart_clemons at us.ibm.com (stuartc) wrote: >> >> >>>Hi: >>> >>>I'm not a total newbie, but I'm pretty green. I need to sort a text >>>file and then get a total for the number of occurances for a part of >>>the string. Hopefully, this will explain it better: >>> >>>Here's the text file: >>> >>>banana_c \\yellow >>>apple_a \\green >>>orange_b \\yellow >>>banana_d \\green >>>orange_a \\orange >>>apple_w \\yellow >>>banana_e \\green >>>orange_x \\yellow >>>orange_y \\orange >>> >>>I would like two output files: >>> >>>1) Sorted like this, by the fruit name (the name before the dash) >>> >>>apple_a \\green >>>apple_w \\yellow >>>banana_c \\yellow >>>banana_d \\green >>>banana_e \\green >>>orange_a \\orange >>>orange_b \\yellow >>>orange_x \\yellow >>>orange_y \\orange >>> >>>2) Then summarized like this, ordered with the highest occurances >>>first: >>> >>>orange occurs 4 >>>banana occurs 3 >>>apple occurs 2 >>> >>>Total occurances is 9 >>> >>>Thanks for any help ! >> >>===< stuartc.py >======================================================== >>import StringIO >>textf = StringIO.StringIO(r""" >>banana_c \\yellow >>apple_a \\green >>orange_b \\yellow >>banana_d \\green >>orange_a \\orange >>apple_w \\yellow >>banana_e \\green >>orange_x \\yellow >>orange_y \\orange >>""") >> >># I would like two output files: >># (actually two files ?? Ok) >> >># 1) Sorted like this, by the fruit name (the name before the dash) >> >>fruitlist = [line.split('_',1) for line in textf if line.strip()] >>fruitlist.sort() >> >># apple_a \\green >># apple_w \\yellow >># banana_c \\yellow >># banana_d \\green >># banana_e \\green >># orange_a \\orange >># orange_b \\yellow >># orange_x \\yellow >># orange_y \\orange >> >>outfile_1 = StringIO.StringIO() >>outfile_1.write(''.join(['_'.join(pair) for pair in fruitlist])) >> >># 2) Then summarized like this, ordered with the highest occurances >># first: >> >># orange occurs 4 >># banana occurs 3 >># apple occurs 2 >> >>outfile_2 = StringIO.StringIO() >>fruitfreq = {} >>for fruit, dummyvar in fruitlist: fruitfreq[fruit] = fruitfreq.get(fruit, 0)+1 >>fruitfreqlist = [(occ,name) for name,occ in fruitfreq.items()] >>fruitfreqlist.sort() >>fruitfreqlist.reverse() >>outfile_2.write('\n'.join(['%s occurs %s'%(name,occ) for occ,name in fruitfreqlist]+[''])) >> >># Total occurances is 9 >>print >> outfile_2,"Total occurances [sic] is [sic] %s" % reduce(int.__add__, fruitfreq.values()) >> >>## show results >>print '\nFile 1:\n------------\n%s------------' % outfile_1.getvalue() >>print '\nFile 2:\n------------\n%s------------' % outfile_2.getvalue() >>========================================================================= >>executed: >> >>[15:52] C:\pywk\clp>stuartc.py >> >>File 1: >>------------ >>apple_a \\green >>apple_w \\yellow >>banana_c \\yellow >>banana_d \\green >>banana_e \\green >>orange_a \\orange >>orange_b \\yellow >>orange_x \\yellow >>orange_y \\orange >>------------ >> >>File 2: >>------------ >>orange occurs 4 >>banana occurs 3 >>apple occurs 2 >>Total occurances [sic] is [sic] 9 >>------------ >> >>Is that what you wanted? >> >>Regards, >>Bengt Richter > From mertz at gnosis.cx Mon Jul 7 01:56:08 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 07 Jul 2003 01:56:08 -0400 Subject: Newbie Question: Abstract Class in Python (fwd) Message-ID: <4tQC/kKkXkWX092yn@gnosis.cx> |Kevin Bass wrote: |>I am new to Python and want to know how to implement an abstract |>class? I have read through different books and I have no found this |>information. Thanks! aahz at pythoncraft.com (Aahz) wrote previously: |Simple answer: you don't. Python doesn't really have that concept. If |you tell us what you're trying to do, we can explain how to do that in |Python. While I agree with some of the warnings against using an abstract class unnecessarily, it *is* both possible and straightforward to do so in Python. Here's the right part of the warnings. Python isn't based around the idea of not trusting later programmers like some bondage-and-discipline languages are. There is no need to prohibit users from using your class how they think best. Languages like C++ and Java go overboard with their concepts of encapsulation. Here's the wrong part. An abstract parent might very well be able to provide implementations of many useful methods, but in principle not want to program some essential support method. The very reasonable idea is that there can be several different ways for children to implement the missing functionality... some implelentation is required, but the parent doesn't want to pre-judge which one children should choose. At bare minimum, here's how to implement an abstract class: class Abstract: def __init__(self): raise NotImplementedError, "Must subclass me" A non-abstract child will need to implement its own __init__() to become concrete. But a better approach is usually to have an abstract parent be specific about what it needs: >>> class SpecificAbstract: ... def __init__(self): ... if not hasattr(self,'support_meth'): ... raise NotImplementedError, "Must provide .support_meth()" ... def some_method(self): ... foo = self.support_meth() ... #...more with foo... ... >>> o = SpecificAbstract() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ NotImplementedError: Must provide .support_meth() >>> class InadequateChild(SpecificAbstract): ... def other_method(self): ... "...do something..." >>> o = InadequateChild() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ NotImplementedError: Must provide .support_meth() >>> class SpecificConcrete(SpecificAbstract): ... def support_meth(self): ... return "Something" ... >>> o = SpecificConcrete() >>> # happy At times it is also useful to only have certain non-magic methods raise NotImplementedError. The missing functionality might not be needed for every instance, but you let users know that it is as early as possible. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From deets_noospaam at web.de Thu Jul 31 13:46:55 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2003 19:46:55 +0200 Subject: What does "*list" mean? References: Message-ID: Greg Smethells wrote: > What exactly does "*values" mean in the following code? Is this a > pointer to a PyList? Why can I not find good documentation on this any > where? I must be blind: Just two days ago I had the same qustion, and I got this as answer from Raymond Hettinger: http://www.python.org/dev/doc/devel/ref/calls.html Regarding your C question: I didn't do such a thing, but *list only makes the items of list be used as distinct arguments - so its more a matter of the function signature you're calling. I'm sure you'll find something about variable list arguments somewhere - that means that you function looks like this: def foo(arg1, arg2, *args): .... Diez From lorenb2 at bezeqint.net Thu Jul 31 05:19:24 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Thu, 31 Jul 2003 11:19:24 +0200 Subject: how to gunzip a string ? References: <025001c356a5$2d9aad10$6400a8c0@EVOD31> Message-ID: <002001c35744$d570fbd0$6400a8c0@EVOD31> oh and another extremely_important question: were the library+dummy_interface tested ? thanks ~ B ----- Original Message ----- From: "Fredrik Lundh" To: Sent: Wednesday, July 30, 2003 7:47 PM Subject: Re: how to gunzip a string ? > Bill Loren wrote: > > I guess I really need some sort of library that will do a gzip decoding to a > > compressed string. > > assume that I have a gzipped_string_reply I got from an HTTP server, > > It'd be superb to have a gunzip class that takes it and return its decoded > > equivalent. > > > > I managed to do it with the gzip library only after saving the string to a > > file and then opening and reading it > > with gzip.open, but it's extremely ugly. > > > > any suggestions ? > > trying again: > > http://effbot.org/zone/consumer-gzip.htm > (GzipConsumer module) > > interface code (based on john j. lee's posting): > > from GzipConsumer import GzipConsumer > > class stupid_gzip_consumer: > def __init__(self): self.data = [] > def feed(self, data): self.data.append(data) > > def gunzip(data): > c = stupid_gzip_consumer() > gzc = GzipConsumer(c) > gzc.feed(data) > gzc.close() > return "".join(c.data) > > unzipped_data = gunzip(gzipped_data) > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From pedro.werneck at bol.com.br Sun Jul 20 10:23:37 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 20 Jul 2003 07:23:37 -0700 Subject: classes References: Message-ID: "Pablo" wrote in message > Can someone help me or point me to some documentation with strong emphasis > on classes? It would be perfect if that documentation had some comparisons > with classes in Java or C++. Guido's essay on new style classes is a good starting point... http://www.python.org/2.2.1/descrintro.html From peter at engcorp.com Sun Jul 20 09:32:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 09:32:55 -0400 Subject: Importing WMI module into Python CGI script fails References: Message-ID: <3F1A9A07.F71D274D@engcorp.com> MK wrote: > > I'm working with IIS on W2K server. I'm trying to > use module "wmi" in a CGI script but with no success. > > The following works: > > import cgitb; cgitb.enable() > cgi.test() > > ... but the following isn't working: > > import cgitb; cgitb.enable() > import wmi ## fails here, with msg "wmi undefined" > cgi.test() Does it really just say "wmi undefined"? If not, please cut and paste the precise traceback which you really get. -Peter From fmeehan at ctbr.com Wed Jul 23 17:22:12 2003 From: fmeehan at ctbr.com (Francois Meehan) Date: Wed, 23 Jul 2003 17:22:12 -0400 Subject: Getting started with win32pdh... In-Reply-To: <20030723123749.C356@ActiveState.com> References: <20030723123749.C356@ActiveState.com> Message-ID: Super, just what I was looking for. Thanks Mick, Francois Trent Mick wrote: > [Francois Meehan wrote] > >>Hi all, >> >>Can someone give me an example on how to use win32pdh module (that >>access windows performance counters)? For example, how to retreive the >>number of processes running on a win2k server, with the >>Objects-Processes counter? >> >>Any ideas? > > > There are a few examples installed with PyWin32 (or with ActivePython if > you got PyWin32 that way): > ...\Lib\site-packages\win32\Lib: > win32pdhquery.py > win32pdhutil.py > > > Trent > From tristaina at wp.pl Wed Jul 2 09:16:46 2003 From: tristaina at wp.pl (freone) Date: 2 Jul 2003 06:16:46 -0700 Subject: Problems with io. Message-ID: <8e35bad8.0307020516.55bb1ddc@posting.google.com> Hello, some time ago I started to learn python, today i wanted make a very samll and simple program. file = open("test.txt", "r+") file.readlines() file.close() And it doesn't work... Why? (sorry for such ask but it is anonyoning me why it doesn't work, if u don't reply i'll understand it) From hwlgw at hotmail.com Fri Jul 4 08:10:38 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 4 Jul 2003 05:10:38 -0700 Subject: Help with xml.parsers.expat please? Message-ID: There seems to be no XML parser that can do validation in the Python Standard Libraries. And I am stuck with Python 2.1.1. until my web master upgrades (I use Python for CGI). I know pyXML has validating parsers, but I can not compile things on the (unix) webserver. And even if I could, the compiler I have access to would be different than what was used to compile python for CGI. I need to write a CGI script that does XML validation (and then later also does other things). It does not have to be complete standards compliant validation but at least it should check if elements are declared and allowed in special places in the XML tree. I tried to understand SAX and DOM but I gave up, and effbot advises to avoid them anyway. So I am studying xml.parsers.expat now, but I am stuck. The program below *does* print information about DOCTYPE declarations but nothing about the element definitions in the DTD. I feed it an XML file with a DOCTYPE declaration like and the DTD is in the same directory. I also tried inputting the DTD itself to this program but that doesn't work either (ExpatError: syntaxerror at the first element definition). Please help if you can. # file: minimal_validate.py # import xml.parsers.expat def element_decl_handler(name, model): print 'ELEMENT definition: ', name, ' model: ', model def doctype_decl_handler(doctypeName, systemId, publicId, has_internal_subset): print 'DOCTYPE declaration: ' print ' doctypeName: ', doctypeName print ' systemId: ', systemId print ' publicId:', publicId print ' internal subset:', has_internal_subset p = xml.parsers.expat.ParserCreate() p.ElementDeclHandler = element_decl_handler p.StartDoctypeDeclHandler = doctype_decl_handler import sys input = file(sys.argv[1]).read() p.Parse(input) From zneptune321 at zexcite.zcom Mon Jul 14 22:54:20 2003 From: zneptune321 at zexcite.zcom (Conrad) Date: Tue, 15 Jul 2003 02:54:20 GMT Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> Message-ID: Years ago, Nostradamus predicted that on Mon, 14 Jul 2003 19:33:23 -0400, Peter Hansen would write, saying: > Conrad wrote: >> >> Greetings, >> >> I have a need to print from Win98SE to a little >> serial label printer provided by United Parcel, so >> based on Mark Hammond's recommendation in >> 'Programming on Win32' I decided to try the Sio >> module at http://starship.python.net/crew/roger/ >> >> My problem: > > Solution to problem (of a sort): don't use SIO module, > which relies on a third-party external DLL. Instead, > use http://pyserial.sourceforge.net/ or, if that doesn't work use > http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html > > -Peter Thanks, Peter - I'll give them a shot tomorrow. USPP made me a little nervous, because frankly, it looks like it died a year and a half ago, with outstanding Linux bugs (eventually, my project will migrate to Linux), and a very conservative 0.1 version label, and pyserial seemed from it's docs to require jython - which means pulling in a whole slew of third-party DLLs for Java. I'll give USPP a try first, because it's closest in spirit to what I want in terms of cross-compatibility and lack of dependencies - and after reflection, the fact that it hasn't changed in a while may just indicate the fact that RS-232 hardware has been much more static lately than, say, video hardware. Thanks again, Conrad From viffer750 at hotmail.com Fri Jul 18 14:38:46 2003 From: viffer750 at hotmail.com (BDM) Date: Fri, 18 Jul 2003 14:38:46 -0400 Subject: Calling python from asp Message-ID: <3f17dc2c@cpns1.saic.com> Greetings, I'm having a difficult time calling a python module from within ASP. I have narrowed the problem down the very beginning of my code, where I'm attempting to import a method. Below is a snippet of the code import sys print 'Imported Sys' from pscape.xml.handler import pscape_xml_parser print 'Imported XML Parser' The import sys statement works fine. The import of pscape_xml_parser is failing. pscape.xml.handler is within my site-packages directory. I have checked python's sys.path from within ASP, and c:\python22\lib\site-packages is in the path. This code runs fine when executed from within the python interpreter, but not when called from ASP. Any idea what I'm doing wrong here? I'm sure it must be something very simple. I'm running this under Windows2000 Server, IIS5.0, Python 2.2.2, and win32all-150. -=BDM=- From martin at v.loewis.de Fri Jul 18 20:57:29 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 19 Jul 2003 02:57:29 +0200 Subject: [OT] A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: Robin Munn writes: > Running slrn version 0.9.7.4 on Linux. My terminal is a PuTTY SSH > connection from a Windows box. slrn --version produces: For this to work, you need to a) explain slrn that your console uses UTF-8, and b) tell PuTTY to use UTF-8 in the console. Then, slrn should determine that all characters of the message are supported. I don't know how to do either a) or b) with PuTTY and slrn; for a), setting LANG to en_US.UTF-8 might be sufficient. Regards, Martin From bhards at bigpond.net.au Tue Jul 22 08:19:43 2003 From: bhards at bigpond.net.au (Brad Hards) Date: Tue, 22 Jul 2003 12:19:43 GMT Subject: pythonic malloc References: <7g1xwjqujm.fsf@pikespeak.metacarta.com> Message-ID: eichin at metacarta.com wrote: > >>>> import struct >>>> struct.pack(" '\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > > but it is, umm, "kind of perlish" - note also that the "21s" is > basically "string of up to 21 chars, pad with NUL if we run out" which > is probably what you wanted, but is saying it another way. This is nice, because it also deals with the case where the hostname would otherwise overflow. It also matches my mental model - this isn't really a string, its really a fixed length binary structure. Note that I don't really know what it is - I'm trying to figure out a proprietary network protocol. Now I just have a question about portability. Will this break on a big-endian box? That is, does: struct.pack(" <20030702073735.40293ba2.christophe.delord@free.fr> Message-ID: > "Christophe Delord" wrote in message > news:20030702073735.40293ba2.christophe.delord at free.fr... > > Hello, > > > > On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote: > > > > > Greetings, > > > > > > (do excuse the possibly comical subject text) > > > > > > I need advice on how I can convert a text db into a dict. Here is an > > > example of what I need done. > > > > > > some example data lines in the text db goes as follows: > > > > > > CODE1!DATA1 DATA2, DATA3 > > > CODE2!DATA1, DATA2 DATA3 > > > > > > As you can see, the lines are dynamic and the data are not alike, they > > > change in permission values (but that's obvious in any similar > > > situation) > > > > > > Any idea on how I can convert 20,000+ lines of the above into the > > > following protocol for use in my code?: > > > > > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} > > > > > > > If your data is in a string you can use a regular expression to parse > > each line, then the findall method returns a list of tuples containing > > the key and the value of each item. Finally the dict class can turn this > > list into a dict. For example: > > and you can kill a fly with a sledgehammer. why not > > f = open('somefile.txt') > d = {} > l = f.readlines() > for i in l: > a,b = i.split('!') > d[a] = b.strip() > > or am i missing something obvious? (b/t/w the above parsed 20000+ lines on a > celeron 500 in less than a second.) Your code looks good Christophe. Just two little things to be aware of: 1) if you use split like this, then each line must contain one and only one '!', which means (in particular) that empy lines will bomb, and also data must not contain any '!' or else you'll get an exception such as "ValueError: unpack list of wrong size". If your data may contain '!', then consider slicing up each line in a different way. 2) if your file is really huge, then you may want to fill up your dictionary as you're reading the file, instead of reading everything in a list and then building your dictionary (hence using up twice the memory). But apart from these details, I agree with Christophe that this is the way to go. Aur?lien From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 01:23:49 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 31 Jul 2003 15:13:49 +0950 Subject: keystroke check References: Message-ID: On Wed, 30 Jul 2003 19:34:58 -0700 (PDT), Wes Fraser wrote: > Is there any way to check in a loop to see if at that given moment in > the program, a key on the key board is being pressed without actually > stopping like raw_ipnut does? I don't have an answer, but what you're referring to is commonly termed "blocking I/O", that is, the call to raw_input blocks the program until it gets a result. This may help you search for solutions. -- \ "What if the Hokey Pokey IS what it's all about?" -- Anonymous | `\ | _o__) | Ben Finney From doug.hendricks at tnzi.com Sun Jul 27 18:27:48 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 27 Jul 2003 15:27:48 -0700 Subject: How to build/install DCOracle2 on tru64 5.1 Message-ID: I've have some fun getting DCOracle2 (python-to-oracle interface) going on HP/Compaq Tru64 with Oracle8i Release 3 (oracle 8.1.7). I'd like to share an answer/bug-fix with you: After un-tarring the source... 1) edit setup.py. Change the lines: CFLAGS = ["-fPIC","-DORACLE8i"] LFLAGS = ["-Wl,-rpath,%s" % string.join(LIB_DIR,",")] LIBS=['clntsh'] TO READ INSTEAD: CFLAGS = ["-DORACLE8i"] LFLAGS = None LIBS=['clntsh','ocijdbc8'] 2) Now run python setup.py build 3) Now, as root (or whatever), run python setup.py install 4) When you test, DO NOT sit in any directory that contains a "DCOracle2" sub-directory! Get away from the build area and its parent! This works for me. The usual technique produces a broken dco2.so, which cannot resolve "OCILobIsTemporary", due to some brain-damage in the Oracle8i libraries. The trick of using ocijdbc8 came from somebody else on the web whose name I now cannot recall, I apologize to whoever is was. Best of Luck Tru64 people! Doug From cliechti at gmx.net Tue Jul 15 09:35:34 2003 From: cliechti at gmx.net (Chris Liechti) Date: 15 Jul 2003 15:35:34 +0200 Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> <3F13703C.C12392D6@engcorp.com> Message-ID: Peter Hansen wrote in news:3F13703C.C12392D6 at engcorp.com: > Conrad wrote: >> pyserial seemed from it's docs >> to require jython - which means pulling in a whole slew >> of third-party DLLs for Java. > > No! Try PySerial first, for sure. It does NOT require > Jython, but does support it. As the home page says, thanks for defending pyserial :-) what you're saying is of course correct. > "It provides backends for stadard (sic) Python running > on Windows, Linux, BSD (possibly any POSIX compilant system) > and Jython. The module named "serial" automaticaly (sic) > selects the appropriate backed (sic)." > > (Chris, if you'd like, I'll happily proofread that page > and correct a few spelling errors for you. ;-) ok thanks, i fixed those and a few other details. chris -- Chris From johnroth at ameritech.net Thu Jul 3 10:20:03 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 3 Jul 2003 10:20:03 -0400 Subject: function overloading References: Message-ID: "Simon Burton" wrote in message news:pan.2003.07.02.02.46.56.650131 at webone.com.au... > > Yes, it's a good idea; and that's how i started; i just can't remember all the different names. > Lazy init is a good idea too... But it adds a level to the class > invariant. Well, the only thing I can suggest for that is what I was told for organizaing my filing system: call it what you're going to look for it under. John Roth From kevin at cazabon.com Tue Jul 22 20:41:51 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 22 Jul 2003 17:41:51 -0700 Subject: py2exe command line window problem References: <1ee79758.0307220827.78f8571@posting.google.com> Message-ID: <5a4226f0.0307221641.49c96703@posting.google.com> instead of using "python setup.py py2exe" try "pythonw setup.py py2exe" from your application. Pythonw won't spawn a DOS box (pythonw.exe should be in the same directory as python.exe with most standard python installs on Windows) Kevin. prashsingh at yahoo.com (Prashant Singh) wrote in message news:<1ee79758.0307220827.78f8571 at posting.google.com>... > I'm using py2exe to create a standalone executable from a Python > script, and I would like the script to run invisibly, i.e. without a > console window and without any interactive GUI. The script is a helper > app, which simply downloads and runs some other program. > > I've tried passing the -w flag to the script, and I've also tried > renaming it with a .pyw extension, but when the executable is run an > empty console window opens with the title "C:\WINNT\system32\cmd.exe". > I've checked, and there are no print statements, which might cause > py2exe to assume it's still a console app. > > Is there something I'm missing? > > Thanks, > prashant. From dkuhlman at rexx.com Fri Jul 18 20:22:53 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 18 Jul 2003 17:22:53 -0700 Subject: (mini-)ANN: Document for Python LaTeX setup Message-ID: I've written a document about how to set yourself up for processing documents with the Python LaTeX documentation system and also for reStructuredText-to-Python-LaTeX translation. You can find it here: http://www.rexx.com/~dkuhlman/#pythonlatexsetup http://www.rexx.com/~dkuhlman/pythonlatexsetup.html http://www.rexx.com/~dkuhlman/pythonlatexsetup.zip The Python LaTeX "Documenting Python" system is great. Thanks to Fred Drake and others who worked on it. Comments are welcome. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From alanmk at hotmail.com Fri Jul 11 11:42:42 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Jul 2003 16:42:42 +0100 Subject: Windows XP - Environment variable - Unicode References: <3f0ed1ba@epflnews.epfl.ch> Message-ID: <3F0EDAF2.E2DF7BAD@hotmail.com> "sebastien.hugues" wrote: > Actually the issue is that this variable is > set by the system itself. It is not accessible from the control panel. > In the other hand, i don't use any terminal. > > So the question is how to get the default encoding of the system ? > I was looking for a while in win32api documentation, msdn and > Google but i didn't get nothing. This page from MSDN explains about how locales are handled for different users. http://msdn.microsoft.com/msdnnews/2001/july/Spotlight/Spotlight.asp Quoting: (for the archives, since MS are guaranteed to make the above link break sometime) """ The System Default Locale The system default locale acts as an ANSI simulation layer. It determines the ANSI code page that the system uses when running a non-Unicode application. For example, if the system default locale is Japanese, then to a non-Unicode application the operating system will behave similarly to a Japanese operating system, fully able to support non-Unicode Japanese applications, but unable to support non-Japanese-compatible applications (such as a Korean non-Unicode app). The operating system uses the Japanese code page 932 when ANSI-Unicode translation is needed. So, the system default locale determines whether or not your non-Unicode application will run. The system default locale is set at installation, but can be changed in the Control Panel. To get the current system default locale, call the GetSystemDefaultLCID function. The User Locale and the Thread Locale The user locale and the thread locale determine which settings are used for formatting dates, times, currency, and large numbers as a default for each user. The user locale and the thread locale also determine the sort order for sorting text. The thread locale can be set separately for each thread. When the thread locale and the user locale are different, the thread locale overrides the user locale. For example, even though your app is English and the system default locale is English, as long as the user locale is Spanish (and you did not set the thread locale specifically), your strings will be sorted by the Spanish sorting order. If you need your app's numbers, currency, or sorting to be done in a certain locale, make sure that you set the thread locale explicitly by calling the SetThreadLocale function. When each thread starts, the thread locale defaults to the user locale. The user locale defaults to the locale that matches the language of the localized system. To get the user locale, call the GetUserDefaultLCID function. Call the GetThreadLocale function to get the calling thread locale. """ I'm not sure if the env var you're looking at is set in the system or user default locale, so probably best to try both:- systemdefaultlcid = win32api.GetSystemDefaultLCID() userdefaultlcid = win32api.GetUserDefaultLCID() http://aspn.activestate.com/ASPN/Python/Reference/Products/ActivePython/PythonWin32Extensions/win32api__GetUserDefaultLangID_meth.html Now, as for how to turn an LCID into a character set name, I don't know the answer to that one :-( Here's a q&d hack for getting the user default character set, through an internet explorer COM object. from win32com.client import Dispatch htmldoc = Dispatch("htmlfile") htmldoc.writeln("

any old stuff

") print htmldoc.defaultCharset HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From schull at digitalgoods.com Mon Jul 14 15:03:47 2003 From: schull at digitalgoods.com (Jon Schull) Date: 14 Jul 2003 12:03:47 -0700 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> <3F0E136A.6222F201@engcorp.com> Message-ID: <2621b014.0307140819.6ec99736@posting.google.com> Well, for what its worth, I was thinking about "sniffing, spoofing, or main-in-the-middle attacks", and I was hoping for something I could stick into a program for unsophisticated users (e.g, those to whom one might give a notepad-like application, albeit with a local webserver interface). Everyone who connects to the internet should have a firewall BUT must all who import httpserver implement or insist on a firewall for all their users? Realistically? I don't want to think so. > Uh, yeah.... but the OP wasn't asking about sniffing, spoofing, or > main-in-the-middle attacks, near as I can tell, nor about using > encryption. He was suggesting an unusual modification to one or > more applications which would otherwise be decoupled from security, > by adding into them features which are better handled by firewalls. > > "Security through Obscurity" (e.g., random ports) is not the way to > go. Instead, use SSL. This can be done through a CGI on Apache > through an SSL'd port, or it can be done with stunnel. [Or it might > even be done with raw python using pyOpenSSL or M2Crypto (which I > haven't done, so I can't tell you anything that direction).] From rastm2 at aol.commorespam Sun Jul 20 13:53:29 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 17:53:29 GMT Subject: Stopping a loop with user input. in curses References: Message-ID: <20030720135329.18124.00000260@mb-m15.aol.com> Hey Alex, I wrote a detailed explanation earlier today and it seams to have disappeared. That's okay, because I had really beat up your code. You know, it didn't occure to me till hours later that all you really had to do is move the second while loop into the "theClock()" definition like this. I move the second while loop into the "theClock()" function so that it handles the key press. Then consolodated the while loops into one loop. If the finished variable is 0(zero) then the loop continues else it breaks the loop and the function has no where else to go but out. The problem with your original code is that the call to "theClock()" function never sees the 'q' key press because the second while loop never gets executed while the first while loop is forever executing. I don't have curses installed so I can't test this for you, but it should work. # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() # If 'q' is pressed, exit finished = 0 while not finished: # finished = 0 until the 'q' key is pressed c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) Ray-- From clpy.NOSPAM at russellsalsbury.com Mon Jul 14 18:18:09 2003 From: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) Date: 14 Jul 2003 15:18:09 -0700 Subject: The ASPN compiler References: Message-ID: <4868482a.0307141418.a45699e@posting.google.com> noah at noah.org (Noah) wrote in message news:... > Gerhard H?ring wrote in message news:... > > Fuzzyman wrote: > > > What's the score on this (the ASPN python compiler) > > Read the whitepaper, available on the ActiveState site. > > ... > > -- Gerhard > > The short answer is that it looks like a dead project. > > Actually, you are better off going to Mark Hammond's .NET page here: > http://starship.python.net/crew/mhammond/dotnet/ Well, folks, I actually went off and read the paper. In spite of the declaration of success at the end of the paper, the project appears to have been just an academic proof of principle exercise. The compiler is too slow to be of practical use and not much of the much of the runtime and modules were implemented. You should read it; it doesn't look like it could have ever succeded. The paper suggests that a way around the mismatch between the dynamic typing of Python and the static typing of .NET would have been to introduce advisory type declarations into Python. Think Guido would buy that? It also suggested maybe type inferences could solve the problem. >From this paper it's evident that this was not a class effort like Jython. Was Active State suckered by some marketing ploy of MicroSoft? To be fair maybe they all expected a follow-on project to do a real implementation, but I bet it's all part of VB-forever. I also noted there is a dead-in-the-water Perl.NET implementation. -- Russ From pedro.werneck at bol.com.br Fri Jul 18 09:47:07 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 18 Jul 2003 06:47:07 -0700 Subject: dumping command-history in python interactive mode References: Message-ID: Take a look here http://www.python.org/doc/tut/node13.html Christoph Becker-Freyseng wrote in message news:... > Hello, > > is there a way to dump (and save) the command-history of the python > interactive mode. > > Thanks, > Christoph Becker-Freyseng From shane at zope.com Tue Jul 8 12:48:23 2003 From: shane at zope.com (Shane Hathaway) Date: Tue, 08 Jul 2003 12:48:23 -0400 Subject: __eq__ and __ne__ In-Reply-To: <1057681289.2342.34.camel@slothrop.zope.com> References: <3F0AEC76.8080304@zope.com> <1057681289.2342.34.camel@slothrop.zope.com> Message-ID: <3F0AF5D7.5030703@zope.com> Jeremy Hylton wrote: > On Tue, 2003-07-08 at 12:08, Shane Hathaway wrote: > >>Tim Peters wrote: >> >>>Since the richcmp operators aren't constrained to return scalars, an attempt >>>to define one in terms of the others seemed futile. Instead they're 6 >>>independent methods. >> >>Ok. Thanks for finding the docs. I guess I'll stick to my boilerplate >>code. I think some guidance should be added to the Python docs, though, >>explaining that whenever you define __eq__, you very likely ought to >>define __ne__ also. > > I believe C++ has the same behavior when you overload logical > operators. So at least people familiar with the same behavior in other > languages won't be surprised. Actually, C++ generates a compiler error if you try to do that. (See the attached program.) Java doesn't run into this because it has a simpler interface: the only operator you can override is equals(). So in this case, C++ is fully explicit and Java is fully implicit, while Python makes a guess. If we can't make it implicit like Java, then it seems preferable for Python to raise an exception, similar to C++, when you use the != operator with an instance that implements __eq__ but not __ne__. Shane -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.cpp URL: From ianb at colorstudy.com Wed Jul 16 16:58:39 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Jul 2003 15:58:39 -0500 Subject: Choosing the right framework In-Reply-To: References: Message-ID: <1058389119.19238.638.camel@lothlorien> On Wed, 2003-07-16 at 07:54, Carsten Gehling wrote: > Oh how often this subject may come up... > > The thing is, I've come to the decision of abandoning PHP as much as > possible (old projects still remain...), and use Python for all purposes. > Reason: One language to fit it all (instead of having one language for > webprogramming, one for batches, etc...) > > I stand now at the point where I must choose a framework for my web > application development. I've skimmed a few: mod_python, pso and Zope. > However, I cannot decide on which to choose. > > I've read descriptions and comments on > http://www.python.org/cgi-bin/moinmoin/WebProgramming to get other's > opinions. The user comments are sparse though, so I've decided to ask here. > > I like the ideas behind Zope. For instance the "long running process" > feature that improve performance and retain scripts between requests, among > other things. I do not, however, like the design of the management > interface, it would not appeal to my customers. I'm not yet knowledgable > enough about Zope, to know if this can be changed. Anyone who can elaborate? > (MaxM don't answer "Plone"... ;-) Webware and SkunkWeb both also use long running processes, and it's an option with Quixote (which can be run in a variety of environments). > pso looks like the framework that is easiest to deploy. If run under > mod_python, it also retains scripts in memory, but does it allow for the > aforementioned application variables? And does the performance match up > compared to mod_python and Zope? Anything not CGI-based is likely to be faster than Zope. > What is your preferred framework? And why? I use Webware (when I can). It's fairly light, when I was first looking around it was one of the few things outside of Zope that was fully developed. I didn't (and still don't) like Zope -- if you like Python, you will be disappointed when you realize you don't get to use it much in Zope, or when you do it's a crippled or complicated Python. [To Zope's credit, they are trying to improve this in Zope 3] Some other options I might recommend looking at would be SkunkWeb and Quixote, which are also fairly mature. Ian From aahz at pythoncraft.com Mon Jul 14 10:26:36 2003 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2003 10:26:36 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: In article , Stephen Horne wrote: >On 13 Jul 2003 21:43:41 -0400, aahz at pythoncraft.com (Aahz) wrote: >>In article , >>Stephen Horne wrote: >>> >>>In computer science, a variable is a named binding to a value. >>>Operations on that variable may rebind it to a different value, but >>>values don't change behind your back. A pointer is, in effect, a value >>>which indirectly refers to another (possibly anonymous) variable. A >>>pointer is something you specifically request, and by doing so you >>>allow that the 'variable' being indirectly referenced may be modified >>>by something else that has no direct access to your pointer value (via >>>your named variable or via copys or pointers-to your pointer held >>>elsewhere). >>> >>>Python should respect that. >> >>That's why I (and others) prefer to use "name" and "target" instead of >>"variable". Would that assuage your ire? > >Not really, for reasons defined elsewhere. The problem isn't >theoretical - it is practical, as shown by the fact that people do >trip over it time and time again. I'm just saying that the problem >arises out of peoples intuition of how variables should work - an >intuition that matches very well with theory. People trip over pointers, too, even when they're explicit. Heck, people have problem with the simple a = a + 1 no matter *what* programming language is used if they can't get past their high school algebra and understand that "=" is a *command* in this context. The question is not whether newcomers get tripped up, but the extent to which the language can be easily defined in a consistent and rigorous manner. Python passes that test quite handily, IMO. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From ianb at colorstudy.com Fri Jul 4 02:29:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 04 Jul 2003 01:29:46 -0500 Subject: File information?? In-Reply-To: References: Message-ID: <1057300186.13136.33.camel@lothlorien> On Fri, 2003-07-04 at 00:59, Stan Cook wrote: > Is there a way to get the file size and modified date of a file? os.stat(filename).st_size and os.stat(filename).st_mtime Ian From edavid at intnet.mu Wed Jul 23 10:53:59 2003 From: edavid at intnet.mu (David Hitillambeau) Date: Wed, 23 Jul 2003 18:53:59 +0400 Subject: The global statement Message-ID: Hi guys, As I am new to Python, i was wondering how to declare and use global variables. Suppose i have the following structure in the same module (same file): def foo: def bar: I want to enable some sharing between the two functions (foo and bar) using one global variable in such a way that each function can have read and write access over it. How can i manage this please? I've read about "The global statement" in python's documentation and still can't figure out it's use. Thanks. -- David.H From khalid.sheikh at silvaco.com Wed Jul 23 17:07:49 2003 From: khalid.sheikh at silvaco.com (Khalid Sheikh) Date: Wed, 23 Jul 2003 14:07:49 -0700 Subject: Trying to contact Lee Harr Message-ID: Hi Lee, Not sure why my email got bounced. If you read this please reply back so I can send you the appropriate documentation so I can get your help in finding out what's in the spider.Collection[i] name space. Thanks. -----Original Message----- From: MAILER-DAEMON at mx02.roc.ny.frontiernet.net [mailto:MAILER-DAEMON at mx02.roc.ny.frontiernet.net] Sent: Wednesday, July 23, 2003 1:57 PM To: khalid.sheikh at silvaco.com Subject: failure notice Hi. This is the qmail-send program at mx02.roc.ny.frontiernet.net. I'm afraid I wasn't able to deliver your message to the following addresses. This is a permanent error; I've given up. Sorry it didn't work out. : maildrop: This user's mailbox is full. --- Below this line is a copy of the message. Return-Path: Received: (qmail 26526 invoked from network); 23 Jul 2003 20:56:48 -0000 Received: from unknown (HELO portal.silvaco.com) ([192.73.228.4]) (envelope-sender ) by mx02.roc.ny.frontiernet.net (FrontierMTA 2.3.6) with SMTP for ; 23 Jul 2003 20:56:48 -0000 Received: from sbay.silvaco.com (sbay.Silvaco.COM [10.1.5.1]) by portal.silvaco.com (8.11.6+Sun/8.11.6) with ESMTP id h6NKulR11333 for ; Wed, 23 Jul 2003 13:56:47 -0700 (PDT) Received: from hades (hades [10.1.11.15]) by sbay.silvaco.com (8.9.3+Sun/8.9.3) with SMTP id NAA05397 for ; Wed, 23 Jul 2003 13:56:46 -0700 (PDT) From: "Khalid Sheikh" To: Subject: Re: Newbie question about strings Date: Wed, 23 Jul 2003 13:56:46 -0700 Message-ID: MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_000D_01C35122.4188D410" X-Priority: 3 (Normal) X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2911.0) Importance: Normal X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 This is a multi-part message in MIME format. ------=_NextPart_000_000D_01C35122.4188D410 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi Lee, Thank you for all your help. Sorry for the late response to your answer. I am not used to the python list and wasn't aware of such volume of posts that are generated on this emailing. List. To answer one of your question, no I am not familiar with Python, like I mentioned in my email I have been tasked to integrate verity enterprise search with our J2EE compliant app server. I am trying to pick up python but I still haven't caught up yet. I haven't been able to find a good reference book that deals with html embedded python. most books talk about generating html through python. Can you recommend a good book for that purpose. The book I picked up is titled Core Python Programming by Wesley Chow. I am not sure if any API calls are being made. I am including the html doc for your reference In article wrote: > Hi, > > I have been tasked to Integrate Inktomi Search (now Verity of course) > with our website. I am fairly new to Python. The way the search > engine is setup is that it has embedded python in a html document. > After looking at the html code for a day or so, I was able to pin > point the place where I need to make a change but I am having a hard > time. > > I am assuming > > &$self.text(dbcol[docdb].pretty_name); > > prints something in HTML but I am trying to figure out it's > equivalent > in Python. I am assuming this is a string and I need to check it's > value against another string say 'XXY' if it is equal then go ahead > and print that value otherwise skip to the next item in the > list/array. > > > This is what I had before and it worked > > , Test< &$self.text(dbcol[docdb].pretty_name); >Test > > when run this prints > > Test< XXY >Test, Test< ABCD >Test > > I want it to print only when the string is equal to XXY. otherwise > skip to the next string. This is the edited code that I have so far. > > > , Test< &$self.text(dbcol[docdb].pretty_name); >Test > > > I get the following error when I run the program. > > exceptions.SyntaxError: invalid syntax (line 86) > Line 86 > if dbcol[docdb] == wlines.append(u' '); > > Any help would be greatly appreciated. > Do you know python? It might be a good start to go through the python tutorial... http://python.org/doc/current/tut/tut.html -- http://mail.python.org/mailman/listinfo/python-list ------=_NextPart_000_000D_01C35122.4188D410 Content-Type: text/html; name="onehit1.html" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="onehit1.html"

=0A= =0A= =0A= =0A= =0A= =0A= =0A= =0A=
=0A= 3D"star" =0A= Title =
=0A= Description =
=0A= &$self.text(u'Topic');: =0A=
, Test< &$self.text(dbcol[docdb].pretty_name); >Test =0A= &$publisher;=0A= &$brkurl(url,70); -=0A= &$"%.1f"%(size/1024.0);KB=0A= , &$term;: &$max(int(scor+0.5),1);=0A= =0A= =0A= =0A= =0A= =0A=
&$key;&$val;
=0A=
=0A= =0A= =0A= =0A= =0A= =0A=
&$score;%
&$self.text(u'Find Similar');
3D""
=0A=
=0A= ------=_NextPart_000_000D_01C35122.4188D410-- From http Wed Jul 30 07:21:09 2003 From: http (Paul Rubin) Date: 30 Jul 2003 04:21:09 -0700 Subject: Bottleneck: easy obscurity "encryption" via xor References: <7xwue0pzcl.fsf@ruckus.brouhaha.com> <1d45gb.cjp.ln@217.11.196.167> Message-ID: <7xn0ew1cre.fsf@ruckus.brouhaha.com> Tino Lange writes: > And it seems that Bengt's reciepe is the fastest. For very small strings > (<255 chars) the method irmen2 should be the best choice - it doesn' have > to pre-create the translation-table and does everything on-the-fly. You should be able to use the array module to do the xor's 4 bytes at a time and get a speedup over the 1-byte version. The string.translate version is the fastest, of course, but depends on using the same translation table for every char in the string. If you want to encrypt in python, try the p2.py that I posted; it's been carefully designed with good algorithms and fairly well optimized and should give much better security than some roll-your-own method. From aahz at pythoncraft.com Mon Jul 28 22:25:17 2003 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2003 22:25:17 -0400 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: In article , Jeff Epler wrote: > >I don't see what's problematic about letting slices be hashable: they >don't appear to be mutable, for instance. >>>> s.start >0 >>>> s.start = -1 >TypeError: readonly attribute >... it may merely be an oversight. Hashing them as > hash((s.start,s.stop,s.step)) >might be a reasonable definition. Makes sense to me. Feel free to submit a patch to SF. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From gregadelliot at hotmail.com Thu Jul 17 11:11:46 2003 From: gregadelliot at hotmail.com (jeff) Date: 17 Jul 2003 08:11:46 -0700 Subject: html tags and webpages Message-ID: Hiya, I had a go at this in perl and to be fairly honest perl scared me, i didnt like the language one bit, ive used python before and find it a "clean" language to use. Basically what i want to do is create a script in python that will look at a website and pull off a certain type of html tag and anything contained within them tags, I did this in perl but would like to do it in python, in perl i had to use a module would i need to do this sort of think in python?? any help greatly appreciated, im not OS specific as i use both windows and linux but that wouldnt matter for a scripting language other than in the file handling?? cheers greg From gre7g-d-1059579503.1d83b3 at wolfhome.com Fri Jul 25 11:38:30 2003 From: gre7g-d-1059579503.1d83b3 at wolfhome.com (Gre7g Luterman) Date: Fri, 25 Jul 2003 09:38:30 -0600 Subject: Why does Python do this? Message-ID: I realize this is a rather queer example, but I would expect the following two classes to act the same basic way. Does anyone know why they do not? Python 2.2.2 (#3, Jun 16 2003, 19:11:56) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> class a: ... def __str__(self): ... sys.stdout.write("written\n") ... return "returned" ... >>> class b: ... def __str__(self): ... print "printed" ... return "returned" ... >>> x=a(); y=b() >>> print x written returned >>> print y printed returned Note the extra space printed when I executed the "print y" command. At first I thought it was just a quirk of the print command being interrupted by another, but I don't think it is quite that simple. Note that: >>> print str(x) written returned >>> print str(y) printed returned >>> print x.__str__() written returned >>> print y.__str__() printed returned work just as you might expect. Here's another variation: >>> import sys >>> def a(): ... sys.stdout.write("written\n") ... return "returned" ... >>> def b(): ... print "printed" ... return "returned" ... >>> print a() written returned >>> print b() printed returned which works as expected. So it only seems to happen when you interrupt a print statement with another print statement during an implicit string conversion. Any guesses? Gre7g. From jeremiah at facility9.com Mon Jul 21 12:29:16 2003 From: jeremiah at facility9.com (Jeremiah McElroy) Date: Mon, 21 Jul 2003 16:29:16 GMT Subject: SOAPpy/Oracle errors Message-ID: I am using a .NET Web Service which returns successfully when tested through a .NET client. However, when I access the client through Python, it successfully returns data to me in the format I expected (regardless of exceptions thrown, the web service always returns a datatable). However, the Web Service is returning a OracleException. Has anyone encountered anything like this in the past? jeremiah From wim_wauters at skynet.be Mon Jul 14 14:52:36 2003 From: wim_wauters at skynet.be (WIWA) Date: 14 Jul 2003 11:52:36 -0700 Subject: pySNMP: SNMPget example References: <538fc8e.0307100356.4bf46554@posting.google.com> Message-ID: <538fc8e.0307140736.19eb777@posting.google.com> Thanks Ilya, This has been very helpful. I'm able to get data out of my 'device under test'. I must be honnest and say that I understand the sample code, but could not write or produce it myself. How do you know e.g that req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) can be written? I've read through the documentation and could not find anything similar. Of course, I could overlook it. Isn't there a tutorial out there that summarizes pysnmpv3 and gives examples of snmpget, snmpset, snmpwalk, etc... Thanks in advance for helping me out. Regards, Wim Ilya Etingof wrote in message news:... > > 2) when using: 'from pysnmp import role' (found on > > http://pysnmp.sourceforge > > .net/examples/2.x/snmpget.html), I get the message 'ImportError: > > You seems to use pysnmp 2.x API which differs from the latest 3.x branch > (though, a compatibility layer exists in 3.x distribution). That's why > I suggest you looking at the 3.x docs and examples at: > > http://pysnmp.sourceforge.net/docs/3.x/index.html > > > 3) A general question: how can I get a list of what I can type after > > the 'from > > pysnmp import ...' > > dir() may help but in this case I'd better see an example. > > > 4) How can I use: 'from snmpget import snmpget'. It does not accept > > this. > > There is no such module as snmpget in pysnmp. > > > 5) Anyone has a simple example for the following application: I have a > > cable > > modem (which has an SNMP agent inside). I want to make a script where > > I can > > do SNMPgets (and later SNMPSet and SNMPwalk). > > Python 1.5.2 (#3, Aug 25 1999, 19:14:24) [GCC 2.8.1] on sunos5 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> from pysnmp.proto import v1 > >>> from pysnmp.proto.api import generic > >>> from pysnmp.mapping.udp import role > >>> req = v1.GetRequest() > >>> req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) > >>> tr = role.manager(('router-1.glas.net', 161)) > >>> (answer, src) = tr.send_and_receive(req.encode()) > >>> rsp = v1.GetResponse() > >>> rsp.decode(answer) > >>> vars = rsp.apiGetPdu().apiGetVarBind() > >>> print vars > [('.1.3.6.1.2.1.1.1.0', OctetString('Cisco Internetwork Operating System > Software\015\012IOS (tm) 5400 Software(C5400-JS-M), Version 12.2(11.8b), > MAINTENANCE INTERIM SOFTWARE\015\012 Copyright (c) 1986-2002 by cisco > Systems, Inc.\015\012 Compiled Tue 30-Jul-02 19:02 by pwade'))] > >>> > > > 7) What is the difference between snmpget and getrequest in pysnmp? > > The only difference is the SNMP request object (GetRequest vs GetNextRequest) > you create when building SNMP message. > > -ilya From exarkun at twistedmatrix.com Thu Jul 10 02:01:47 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Thu, 10 Jul 2003 02:01:47 -0400 Subject: Python Global Constant In-Reply-To: References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: <20030710060134.GA12739@intarweb.us> On Thu, Jul 10, 2003 at 04:06:55PM +1200, Greg Ewing (using news.cis.dfn.de) wrote: > Peter Hansen wrote: > >Just do what you did above, without the "const" modifier, which > >doesn't exist and is not really needed in Python. > > If you *really* insist on preventing anyone from changing > them, it is possible, with some hackery. Here's one way > that works: > > ####################################################### > # > # MyModule.py > # > > _constants = ['PI', 'FortyTwo'] > > PI = 3.1415 > FortyTwo = 42 > > import types > > class _ConstModule(types.ModuleType): > > __slots__ = [] > > def __setattr__(self, name, value): > if name in self.__dict__['_constants']: > raise ValueError("%s is read-only" % name) > self.__dict__[name] = value > > del types > import MyModule > MyModule.__class__ = _ConstModule > >>> import MyModule >>> del MyModule._constants[:] >>> MyModule.PI = 'Cherry, please' >>> MyModule.PI 'Cherry, please' Jp -- "The problem is, of course, that not only is economics bankrupt but it has always been nothing more than politics in disguise ... economics is a form of brain damage." -- Hazel Henderson From alanmk at hotmail.com Fri Jul 11 10:02:51 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Jul 2003 15:02:51 +0100 Subject: XML, xmlproc, MathML and validation References: Message-ID: <3F0EC38B.EBDE74E@hotmail.com> Will Stuyvesant wrote: > I am trying to validate a document with mixed XHTML and MathML. > And the w3c validator at http://validator.w3.org/ says my XML file is > valid. > So far so good. > But now I want to use xmlproc to both validate it and change something > in it. I use "from xml.parsers.xmlproc import xmlval". > This works good when the DTD is local but does not work in this case, > where the DTD is remote. I can't have the MathML DTD local That's what (SGML) "catalogs" are for: mapping public identifiers to local files, and non-retrievable URIs to local files. For example, the public identifier "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" could be mapped to a local file. So you should be able to map DTD identifiers to your local system for the times when a remote DTD is not available. More info from here http://www.garshol.priv.no/download/software/xmlproc/catalog-doco.html > The error message: > > ERROR: xml:space must have exactly the values 'default' and 'preserve' > at http:/ > /www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd:2025:1 Have you supplied a value for the "xml:space" attribute anywhere in your document? If yes: you must have supplied a wrong value: you can only use "default" or "preserve". If no: I'm not familiar enough with the MathML DTD to know if it has special requirements for whitespace processing. Looking at your error message, and the DTD, might it be that you have used a value other than "xml:space='preserve'" on a

 section?
Just a guess.

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



From donn at u.washington.edu  Fri Jul 18 19:52:55 2003
From: donn at u.washington.edu (Donn Cave)
Date: Fri, 18 Jul 2003 16:52:55 -0700
Subject: IMAP examples
References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl>   <1058561410.563105@smirk> <3F187ED4.6179CDDD@engcorp.com>
Message-ID: 

In article <3F187ED4.6179CDDD at engcorp.com>,
 Peter Hansen  wrote:

> "James T. Dennis" wrote:
> > 
> > Sean 'Shaleh' Perry  wrote:
> > 
> > >> If my english was better I would love to help improve the python
> > >> documentation, most modules in the standard libraries lack good
> > >> examples how to *use* them with just a simple description.  And a
> > >> short motivation for the design of a module if possible like "just
> > >> copied the C API" or "Because of efficiency ..." or "We use a class
> > >> framework here because ...".  A gigantic task.  The PSL book by effbot
> > >> is great but it's a book.  And it needs a new version.
> > 
> > > part of the reason why the docs are not but so great is that most of the
> > > library is Python code which means any questions can be answered by 
> > > reading
> > > the source.  I find myself doing this quite often.
> > 
> >  That's BS!
> > 
> >  As a dabbler in programming I have to say that poor documentation is not
> >  excused by the availability of sources.  
> 
> True, but poor documentation *is* excused quite nicely by the LACK
> of availability of _re_sources, specifically the human resources and time
> required to make them better.
> 
> Or was your flame an indirect offer to assist with improving the 
> documentation of Python?  If so, thank you!

Well, he did offer some suggestions, which is about all most of
us do around here.  But I don't think I'd go along with the premise
as easily as you did - I mean, ``poor documentation is not excused
by the availability of source'' is true as far as it goes, but in
some cases I think ``source is good documentation'' can be true, too.

And in this specific case.  IMAP4 support is a can of worms.  Big
feature set here, baroque might be the word.  Not trivial to parse.
The imaplib solution is minimal.  It does a reasonable job setting
up an imap service connection and conducting a client/server dialogue,
but it doesn't get into the structure or significance of the data.
If you want to use IMAP, the documentation you need to read is the
RFC, unfortunately but it is a reasonable discussion of the protocol.

imaplib.__doc__ points to imaplib.IMAP4;  imaplib.IMAP4.__doc__ is
30 or 40 lines of concise information about the API.  I don't think
this is a crisis situation.

   Donn Cave, donn at u.washington.edu



From alanmk at hotmail.com  Sat Jul  5 12:30:09 2003
From: alanmk at hotmail.com (Alan Kennedy)
Date: Sat, 05 Jul 2003 17:30:09 +0100
Subject: Frustration with spurious posts.
References: 
Message-ID: <3F06FD11.967D8D8A@hotmail.com>

Bob Gailer wrote:

> Does anyone know why we keep getting these posted to the list. Is there a
> way to stop it?

I think (?) it is because

1. There is a gateway process on python.org that emails usenet posts
from comp.lang.python to an email list, and vice versa.

2. So you can send to UseNet by sending to the email address of the
list.

3. People who receive the emails from the email list have emails with
the email list address on them.

4. Those people receive an email virus, e.g. SoBig, which sends a copy
of itself to every email address found in the persons mail folders,
which includes the address of the email list.

5. The email list receives the malware email, and forwards it to
everyone on the list.

6. Antivirus email gateways for *some* of the subscribers of the email
list spot the malware, and send back an email to the originator, i.e.
the email list address, saying "you sent me a virus!"

7. The gateway faithfully gateways these emails into Usenet posts, as
well as sending them to the list subscribers.

I might have got it wrong though. Take a look through the headers of
some of the messages in question, and see if the theory holds up.

Bringing an end to the problem would probably involve a fairly
substantial admin effort on the part of the python.org admins. Who are
volunteers, and pretty busy trying to keep up with the needs of the
ever-growing python community, and don't have much spare time.

regards,

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



From staschuk at telusplanet.net  Sun Jul 20 14:43:41 2003
From: staschuk at telusplanet.net (Steven Taschuk)
Date: Sun, 20 Jul 2003 12:43:41 -0600
Subject: object as a reserved keyword
In-Reply-To: ; from mwilson@the-wire.com on Sun, Jul 20, 2003 at 01:07:50PM -0400
References:   
Message-ID: <20030720124341.B438@tibia.amotlpaa.bogus>

Quoth Mel Wilson:
  [...]
>    Plus it's not impossible that somebody could export a
> name in the set of standard names from a module or a
> class and accomplish something useful.  I'm having trouble
> finding a convincing example, [...]

re.compile()

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1




From bokr at oz.net  Wed Jul 30 14:46:14 2003
From: bokr at oz.net (Bengt Richter)
Date: 30 Jul 2003 18:46:14 GMT
Subject: Upgrading python
References:  
Message-ID: 

On 30 Jul 2003 06:43:22 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote:

>Stephen Boulet  writes:
>
>> When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3?
>
>If you want to, you can have both 2.2 and 2.3 installed, side-by-side.
>If you want to replace 2.2, you should uninstall it first.
>
How do I know what will happen to file extension associations and the system path search
that takes unadorned python and finds some/path/to/python23.exe?

And how does the old python22 find what it needs? Do I need to go through a .cmd file that
sets up its environment before running? How do I know everything it needs?

IOW, how do you set up a clean way to run both 2.2.3 and 2.3 "side by side" but separately,
with default "python" going to 2.3?  I am being lazy in not reading the install docs yet,
but does it cover the question fully? If so, the answer to this post can just be "yes" ;-)

Regards,
Bengt Richter



From ianb at colorstudy.com  Fri Jul  4 16:50:50 2003
From: ianb at colorstudy.com (Ian Bicking)
Date: 04 Jul 2003 15:50:50 -0500
Subject: Least used builtins?
In-Reply-To:          
References: 
	 
	 
	          
Message-ID: <1057351850.32271.25.camel@lothlorien>

While I agree some of the math stuff need not be in builtins, in most
case I think the things in builtins are reasonable.  Except of course
for functions that are essentially deprecated, or have become redundant.

On Fri, 2003-07-04 at 15:00, Lulu of the Lotus-Eaters wrote:
> To the top of a module/script.  Some quick thoughts:
> 
>     Current builtin     Possible Home
>     ---------------     ---------------
>     abs                 math
>     apply               functional
>     basestring          internal
>     bool
>     buffer
>     callable            sys

callable is a little funny, and not hugely useful, but sys isn't really
appropriate.

>     chr
>     classmethod         new

Ick, no.  classmethod, as well as staticmethod and property, are *meant*
to be builtins.  They are idiomatic, there's no reason they should
appear in a module.  There's no reason something named "classmethod"
should ever show up in another module, for instance.  Every programmer
needs to know what classmethod is -- hiding it won't reduce the amount
of things a programmer needs to know.

>     cmp
>     coerce
>     compile             code
>     complex             math

It makes sense, but I also would like to have the basic constructors and
types available as builtins.

>     delattr
>     dict
>     dir
>     divmod              math
>     enumerate           itertools

Again, this is idiomatic, and it belongs in builtins.

>     eval                code
>     execfile            code
>     file
>     filter              functional

Only because it's become redundant.

>     float
>     getattr
>     globals
>     hasattr
>     hash                internal
>     hex                 math
>     id                  internal
>     input
>     int
>     intern              internal
>     isinstance          sys
>     issubclass          sys

Definitely not -- these are very important, importing them would be
obnoxious.  Especially since "isinstance(value, str)" is the preferred
technique over "type(value) is str".

>     iter
>     len
>     list
>     locals
>     long
>     map                 functional
>     max                 math
>     min                 math
>     object              internal

Eh?  That's just silly!  If you are doing OO using 2.2 features you will
always end up importing this.

>     oct                 math
>     open
>     ord
>     pow                 math
>     property            new
>     range
>     raw_input
>     reduce              functinal
>     reload
>     repr
>     round               math
>     setattr
>     slice
>     staticmethod        new
>     str
>     super               internal

Again, highly idiomatic, programmers should be discouraged from using
this name for anything else, and it needs to be available to encourage
the use of this new feature.

>     tuple
>     type
>     unichr
>     unicode
>     vars
>     xrange              itertools
>     zip                 itertools

zip, like enumerate, is idiomatic -- importing it does not imply
anything about your code, that it comes from itertools lends little
insight into what zip does.  

Of course, this is all academic, as reducing builtins would cause
backward compatibility issues, while providing no real advantages.

  Ian






From lists at gregfortune.com  Fri Jul 11 09:17:53 2003
From: lists at gregfortune.com (Greg Fortune)
Date: Fri, 11 Jul 2003 06:17:53 -0700
Subject: for in sequence problem... possible new operator to add to python
References: <3a8fc6c5.0307100816.634c83a3@posting.google.com>
Message-ID: 

See http://python.org/doc/current/ref/sequence-types.html to make your
objects happy little lists.

Greg


Adam Gent wrote:

> I was fooling around subclassing a dictionary object and noticed that
> when
> I do the standard "for in :" that I have no
> control on how python gets that sequence.
> 
> For example:
> 
> class Blah(dict):
>    pass
> 
> bl = Blah()
> 
> for b in bl:
>     #b will be a key and not a value
>     #no matter how I subclass Blah
> 
> However I want b to be the values with out doing:
> for b in bl.values()
> 
> I could be wrong on this but I believe python is missing an operator
> for looping over objects. I think there should be a __sequence__ or
> __forsequence__ operator that returns a sequence when "for x in
> object" syntax is used.
> So
> for b in bl: == for b in bl.__sequence__




From kumbaya at ftml.net  Tue Jul 15 05:59:49 2003
From: kumbaya at ftml.net (Jochen Knuth)
Date: Tue, 15 Jul 2003 11:59:49 +0200
Subject: PyUNO: Python bridge distributed with new OpenOffice.org
Message-ID: 

Hi,

with the release of the new 1.1rc of OpenOffice.org the python bridge to
the UNO development kit of OOo is included by default.

Look at 
http://www.openoffice.org/dev_docs/source/1.1rc/release_notes_1.1rc.html
for the announcement and
http://udk.openoffice.org/python/python-bridge.html (not yet updated
for 1.1rc) for details about PyUNO.

Ciao,
Jochen
(just read it on the OOo website)



From bockman at virgilio.it  Fri Jul  4 06:59:39 2003
From: bockman at virgilio.it (Francesco Bochicchio)
Date: Fri, 04 Jul 2003 10:59:39 GMT
Subject: [Dream] A meta-wrapper module to interface any C dynamic library
Message-ID: 

Hi all,

I was wondering if it would be possible to make a module which allows to
do something like that:

	import c_interface
	math_lib = c_interface.load('math.so', 'math.h' )
	sin_f = math_lib.get_function('sin')
	print "sin(3.14) = %f" % sin_f (3.14)

The idea would be to make a module that allows to use any C dynamic
library ( I used an hypothetical math.so only as example ) without 
the need of a specific wrapper module.

I've given some thought to this idea, but I was blocked by the theoric (?)
impossibility to correctly call a C function without knowing its prototype
at compile time.

Did anybody ever attempted to do something like this?

Ciao
-----
FB




From martin at v.loewis.de  Sun Jul  6 03:20:35 2003
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sun, 06 Jul 2003 09:20:35 +0200
Subject: problems with sf cvs server?
In-Reply-To: 
References: 
Message-ID: <3F07CDC3.1080200@v.loewis.de>

Ben Wolfson wrote:

> Is anyone else experiencing trouble checking the python source tree
> out of the sf cvs server?  I hang forever here:
> 
> cvs server: Updating python/nondist/src/Compiler/tests/output

pserver access on SF suffers from being severly overloaded at the
moment. If all you want is a snaphot of the HEAD revision (and only
of the dist/src subtree), you can find such snapshot at

http://www.dcl.hpi.uni-potsdam.de/home/loewis/python.tgz

Regards,
Martin





From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Mon Jul 14 16:42:19 2003
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Mon, 14 Jul 2003 22:42:19 +0200
Subject: ??????? ??? ??? ??????? ??????????) ))
In-Reply-To: 
References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> 
Message-ID: <3f1315ab$0$49100$e4fe514c@news.xs4all.nl>

Dan Bishop wrote:

> The Babelfish translation is
> 
> "People, you polskazhite plz where to reach progu to
> frizer(kazhet'sya, shorter must be into yekhe-shnik outdistanced)."

Ah thanks! That clears it all up. If we didn't have the Babelfish...

--Irmen




From peter at engcorp.com  Wed Jul  2 15:24:47 2003
From: peter at engcorp.com (Peter Hansen)
Date: Wed, 02 Jul 2003 15:24:47 -0400
Subject: When is unit-testing bad? [was: Re: does lack of type...]
References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com>  <87of0pno5s.fsf@titan.staselog.com>  
Message-ID: <3F03317F.DDA7D71F@engcorp.com>

"Aur?lien G?ron" wrote:
> 
> There are things that are hard to unit test (I'm talking about automated
> unit tests here) and which you just can't do without in some projects.  For
> instance, the database!  I worked in a couple of projects with automatic
> unit tests for the DB related components, and having lived through it, I'm
> not sure that it was worth it at all!  Manual unit tests would have made
> much more sense.  The same goes for GUIs.  I'd be interested to know about
> projects where they automate unit tests for GUIs, but I suspect it would be
> just as cumbersome. And live without threads?  A lot of projects would be
> better off not using them, I agree with that, but some projects just can't
> do without them!  Web sites are also horrible to automatically unit test.
> In all those cases, I much prefer having a human being go out and do the
> unit tests manually.

Databases are generally considered much easier to do unit tests for than
GUIs.  

GUIs are recognized as difficult, but there are already fairly well-known 
approaches for simplifying the process, depending on what you need/expect 
out of the testing.  For example, one should generally count on the GUI
framework to do what it does correctly and not try to test, for example,
that a call to a drawText() method actually puts pixels on the canvas.
Instead, one should be testing that a call to drawText() is made, and
contains the correct text and positioning.

Web sites are equivalently simple to test, if you aren't trying to test
the presentation itself.  For example, unit-testing web forms is pretty 
trivial.  In fact, in most cases for web stuff, you don't need to actually
run a server, but I believe here I'm getting into XP-specific terminology
where "unit" test refers to something quite different from "acceptance"
or "customer" test, which is where you would be running the actual server.

-Peter



From martin at v.loewis.de  Sat Jul 12 17:58:07 2003
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sat, 12 Jul 2003 23:58:07 +0200
Subject: any such thing as list interleaving?
In-Reply-To: 
References: 
Message-ID: <3F10846F.6030706@v.loewis.de>

Tom Plunket wrote:

> I find myself often doing the following sort of thing (sorry for
> lack of whitespace, I don't want the line to break):
> 
> for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)):
>    # ...

In Python 2.3, you can write

for index, entry in enumerate(L):
   # ...

For 2.2, you can define enumerate yourself:

def enumerate(L):
   i = 0
   while 1:
     try:
       yield i, L[i]
     except IndexError:
       return
     i += 1

For older versions, yet another definition would be needed;
I leave that as an exercise.

> This also brings up a similar problem for me when iterating over
> dictionaries:
> 
> for key in myDict:
>    value = myDict[key]
>    # ...
> 
> This seems a pretty sloppy way to go about it, imo.  There must
> be something more in the Python spirit!  :)

Here, you could always write

for key, value in myDict.items():
   #...

Since 2.2, there is another method available which does not create
a list of tuples:

for key, value in myDict.iteritems():
   #...

HTH,
Martin





From bokr at oz.net  Wed Jul  2 17:32:56 2003
From: bokr at oz.net (Bengt Richter)
Date: 2 Jul 2003 21:32:56 GMT
Subject: How Do You Get Redirected Input?
References:  <3f0333b6$0$49116$e4fe514c@news.xs4all.nl> 
Message-ID: 

On Wed, 02 Jul 2003 20:04:53 GMT, not your business  wrote:

>Irmen de Jong wrote:
>
>> not your business wrote:
>>> I have a shell tool that accepts arguments on the command line. I would
>>> like
>>> to check if the input is being piped in.  That is,
>>>  
>>>         $ mytool.py < cmdlst.txt
>>> 
>>> In this case sys.argv is empty. So I added
>>> 
>>>         pipein = os.read(sys.stdin.fileno(),256)
>>>         if (pipein):
>>>             input_args = pipein.split()
>>>         else:
>>>             input_args = sys.argv[1:]
>>>  
>>> Problem is that if nothing is redirected in, the script waits for a Enter
>>> pressed on the the keyboard. Anyone know a solution to this?  Thanx in
>>> advance for any help.
>> 
>> Why not turn it around? First check if sys.argv is *not* empty,
>> in which case the user provided command line arguments, and
>> proceed to parse those. Otherwise (if sys.argv *is* empty),
>> assume the input is piped in and proceed to read the standard
>> input.
>> 
>> --Irmen
>
>Okay, but there still seems to be a problem.  Lets say you typed 
>        $ mytool.py
>
>If sys.argv[1:] is empty, I want to display help.  But if I'm checking for
>redirected input by my problematic method next, the script hangs, again,
>waiting for a Enter to be pressed and the user, therefore, doesn't my usage
>help.

If you want to use empty cmd line as help trigger, I'd say don't try to read stdin
in that case. Use an explicit command line option to indicate stdin input,
e.g., just '-' (maybe where you might otherwise have a file spec).
>
>I think I need to find a way to test for redirected input without the actual
>os.read() thing.  One hack that came to mind was to fork() a seperate
>process to do this and pipe back within a time period any results. The 
>parent could just go on if no response.  But that seems a little extreme
>(and ugly) plus it's platform dependent unless, I guess, I it do it with
>threads.
>
Seems ugly. Any reason you couldn't use
     $ cat stuff | mytool.py -
or such?

BTW, on some versions of windows, that better be
     $ cat stuff | python mytool.py -
since i/o redirection with extension-associated execution has bugs for some versions (e.g. NT4).


Regards,
Bengt Richter



From ngps at netmemetic.com  Mon Jul  7 11:35:49 2003
From: ngps at netmemetic.com (Ng Pheng Siong)
Date: 7 Jul 2003 15:35:49 GMT
Subject: What does this core dump mean?
References:  
Message-ID: 

According to Terry Reedy :
> I cannot interprete the gdb trace either.  Info on the platform,
> Python version, what you changed to change the behavior, and the
> reproducibility of the dump behavior might help someone who can.

Ok, found the problem: in the new AES tests. Dumps core in direct EVP
usage, but not the BIO.CipherFilter. Hmmm...


-- 
Ng Pheng Siong  

http://firewall.rulemaker.net  -+- Manage Your Firewall Rulebase Changes
http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL



From petrk at pochtamt.ru  Mon Jul 21 09:09:02 2003
From: petrk at pochtamt.ru (Peter Klyushkin)
Date: Mon, 21 Jul 2003 17:09:02 +0400
Subject: Directory Structure for Distutils
References:  
Message-ID: 

Hello, Thomas!

>>>>> "TG" == Thomas G?ttler writes:

 TG> Thomas G?ttler wrote:
>> Hi!
>> 
>> What is the best directory structure for python modules?
>> 
>> ...

 TG> (Replying to myself)

 TG> I downloaded the source of distutils and took it as an example.

 TG> One thing is still unclear: How can I copy non python files into
 TG> the destination?  There is a directory called "gif" which needs
 TG> to be in the directory of the my module.

Take a look at ResourcePackage.  It isn't exactly what you want but it
is exactly for your purpose.

 TG>  thomas

-- 
                                                             C'ya, Peter.
		      --=[petrk at pochtamt.ru]=--
        --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=--



From afriere at yahoo.co.uk  Tue Jul 29 00:05:47 2003
From: afriere at yahoo.co.uk (Asun Friere)
Date: 28 Jul 2003 21:05:47 -0700
Subject: XML Validation with Python
References:  
Message-ID: <38ec68a6.0307282005.afec1c1@posting.google.com>

hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:...

> Anyway, I can now do XML validation, below is
> "validate.py".  But I am not solving my initial
> problem: if it validates, then validate.py prints
> nothing, if there is a mistake then it prints an error
> message.  What I really wanted; giving more confidence
> that the validation is okay; is to print 1 or 0
> depending on the result, but I have not figured out yet
> how to do that and now I am too tired of it all...

This might do the trick:

# file: validate.py
import sys, pyRXP

if len(sys.argv)<2 or sys.argv[1] in ['-h','--help','/?']: 
    print 'Usage: validate.py xmlfilename'
    sys.exit()

fn = open(sys.argv[1], 'r').read()
try :
    pyRXP.Parser().parse(fn)
    print True
except pyRXP.error :
    print False


Though personally, rather than printing False, I would simply raise in
the except clause, as the traceback provides the user with more
information as to what is wrong with their xml.



From LogiplexSoftware at earthlink.net  Thu Jul 10 18:15:53 2003
From: LogiplexSoftware at earthlink.net (Cliff Wells)
Date: 10 Jul 2003 15:15:53 -0700
Subject: Convert between Windows style paths and POSIX style paths
In-Reply-To: 
References: 
Message-ID: <1057875353.1799.1.camel@software1.logiplex.internal>

On Thu, 2003-07-10 at 13:44, Noah wrote:
> Does anyone have a function to convert back and forth between
> NT style paths and POSIX style? It seems trivial, but 
> I want to make sure I don't overlook some obscure detail. 
> Is it a simple matter of translating / and \ characters?
> 
> FYI, I need a Python function that does what cygpath does so that
> I can run a script on either NT or UNIX or Cygwin.
> I want my config files use one style of path.

Just use POSIX paths and let the Python library sort it out.  It works. 
If you really need to do the conversions yourself, take a look at the
os.path module.

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





From agentgt at yahoo.com  Fri Jul 11 13:23:27 2003
From: agentgt at yahoo.com (Adam Gent)
Date: 11 Jul 2003 10:23:27 -0700
Subject: for in sequence problem... possible new operator to add to python
References: <3a8fc6c5.0307100816.634c83a3@posting.google.com> <3F0D95E6.3BC763D3@engcorp.com>
Message-ID: <3a8fc6c5.0307110923.64d4fb0c@posting.google.com>

Peter Hansen  wrote in message news:<3F0D95E6.3BC763D3 at engcorp.com>...

> 
> When you iterate over a dict in recent versions of Python, you 
> are by definition iterating over the keys in the dict.  If you
> want the values, you use .values(), and if you want both keys
> and values, you use .items().  See the docs for more.
> 
> -Peter

I wanted my dict to imitate a list... just for fun. A listdict if you
will. The only problem is that if you pass my listdict to code that
expects a true list  "for x in b" will break.
I did not know about __iter__(). Thanks for informing me.
__iter__ is not explained in
http://www.python.org/doc/current/lib/module-operator.html
shouldn't it be there?



From mikael at isy.liu.se  Wed Jul  2 10:08:40 2003
From: mikael at isy.liu.se (Mikael Olofsson)
Date: Wed, 2 Jul 2003 16:08:40 +0200
Subject: splitting a string into 2 new strings
In-Reply-To: 
References: 
Message-ID: <20030702160840.3c045dcf.mikael@isy.liu.se>

Hi Mark!

You wrote:
> I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2
> strings 'C H O' and '6 12 6'.  I have played with string.split() and
> the re module - but can't quite get there.

What about this?

import string
t='C6 H12 O6'
theLetters=''.join([x for x in t if x in string.letters+' '])
theDigits=''.join([x for x in t if x in string.digits+' '])

HTH
/Mikael

-----------------------------------------------------------------------
E-Mail:  mikael at isy.liu.se
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by Sylpheed.
-----------------------------------------------------------------------
Link?pings kammark?r: www.kammarkoren.com

From tebeka at cs.bgu.ac.il  Tue Jul 29 04:51:08 2003
From: tebeka at cs.bgu.ac.il (Miki Tebeka)
Date: 29 Jul 2003 01:51:08 -0700
Subject: Debugging Python ?
References: 
Message-ID: <33803989.0307290051.4d05cdc9@posting.google.com>

Hello Bill,

> I'd be happy to hear your techniques to debug python programs.
> Is there any interactive debugging environment by any chance ?
IDLE comes with a debugger.

Personally I use pdb. I have the following line in my .bashrc:
alias pdb='python /lib/python2.3/pdb.py'

And then just
pdb myprog.py -n -q 10034

I like pdb since it allows me to evaluate expression during debugging.

HTH.
Miki



From ____indru_june at yahoo.com____  Fri Jul 11 00:54:02 2003
From: ____indru_june at yahoo.com____ (indru)
Date: Fri, 11 Jul 2003 04:54:02 +0000
Subject: Business model for Open Source - advice wanted
References: <246a4e07.0307100613.fc2fc50@posting.google.com>
Message-ID: <3098672.1057899242@dbforums.com>

Your question is very valid  and to make money out of your exposed code
is very difficult if you consider that the product you are writing is a
general purpose one, say a loan calculator . But your area is Accounting
the area which requires a lot of customization. So writing a common
engine from where you can build customized solutions for your clients is
one way to make money. Here the question of support doesnt rise up since
your are the person who have written the code and you will be the best
person who knows about it and you can easily enter a contarct with the
people for support.
Wishing you best of luck
Indru

--
Posted via http://dbforums.com



From postmaster at 127.0.0.1  Fri Jul 11 21:22:16 2003
From: postmaster at 127.0.0.1 (David McNab)
Date: Sat, 12 Jul 2003 13:22:16 +1200
Subject: The "intellectual property" misnomer
References:  
Message-ID: 

On Sat, 12 Jul 2003 08:10:48 +0950, Ben Finney paused, took a deep breath,
then came out with:

> But please *don't* muddy the water by saying the PSF holds "the
> intellectual property rights" for Python.  That says nothing useful


Too right.

Copyrights create a level of 'ownership' of verbatim code. Good.

Patents, as they're administered today, create a level of 'ownership' of
even the most simple concepts (the kind of thing anyone could think of),
whereby it's almost impossible these days to write more than a few dozen
lines of code without infringing n patents. Very bad.

The lumping together of these two very different legal categories is an
insidious lie that runs totally counter to the spirit of freedom which
Python represents, and threatens to turn software development into a
closed shop for only the largest corporations (which it was in the
earliest days, when only the largest organisations and companies could
afford a computer).

EB






From carol.crose at lmco.com  Thu Jul 10 19:47:07 2003
From: carol.crose at lmco.com (Crose, Carol)
Date: Thu, 10 Jul 2003 19:47:07 -0400
Subject: Problem running Flawfinder with Python
Message-ID: <9B38D82679975748AB4DE66A6523523601F71CEF@EMSS04M04.us.lmco.com>

 
I need to test some lsof source code and have loaded Flawfinder 1.22 to
test it.  Flawfinder  required Python 1.5 or better so I loaded Python
2.2.3.  This is all running on an HPUX 11.11 server.  
 
When I run:
/opt/flawfinder-1.22/flawfinder /usr/local/bin/lsof-4.67
I get the following error:
No such file or directory:  python
 
I am totally new to all these programs.  Can anyone help????
 
Thank you!
Carol
carol.crose at lmco.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tomas at fancy.org  Thu Jul 10 21:12:55 2003
From: tomas at fancy.org (Tom Plunket)
Date: Thu, 10 Jul 2003 18:12:55 -0700
Subject: wxPython - question
References: 
Message-ID: 

Artur M. Piwko wrote:

> How can I remove program entry from taskbar (not tray)?

By reading the docs and using the right flags.  :)

(I've been using wx for two weeks.)

in wxFrame:

wxFRAME_NO_TASKBAR - Creates an otherwise normal frame but it
      does not appear in the taskbar under Windows (note that it
      will minimize to the desktop window which may seem strange
      to the users and thus it might be better to use this style
      only without wxMINIMIZE_BOX style). Has no effect under
      other platforms.  

so-

from wxPython.wx import *

class MyFrame(wxFrame):
   def __init__(self):
      style = wxDEFAULT_FRAME_STYLE | wxFRAME_NO_TASKBAR

      wxFrame.__init__(self, None, -1, "Taskbar?", style=style)

if __name__ == "__main__":
   a = wxPySimpleApp()
   w = MyFrame()
   w.Show()
   a.MainLoop()

-tom!



From rreagan at attbi.com  Thu Jul  3 19:39:21 2003
From: rreagan at attbi.com (Russell Reagan)
Date: Thu, 03 Jul 2003 23:39:21 GMT
Subject: A story about Python... sort of
References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk>  <3f04727e@news.swissonline.ch>
Message-ID: 

"F. GEIGER"  wrote

> [OT] That's not a pro, that's a con on the C++ side. And actually that's
the
> reason why there's so much bad C++ software. A C programmer first has to
> forget C to be able to program in C++ - well, to be able to program OO in
> C++.

C++ is not an OO language. It is a multi-paradigm language that happens to
support OO features. No one is required to program OO in C++. It's even very
debatable if it's better to program OO in C++. OOP is just another tool, and
in a lot of cases, objects don't make sense for a particular problem (I
can't count the number of times I've tried to cram something into an OO
system). There is nothing wrong with using C++ as a "better C", taking
advantage of type safety, safer "macros" (inline functions), and it doesn't
require any OO knowledge to be able to understand the concept of
encapsulation within a class (you can do the same encapsulation in C
programs, and any good C programmer would do this anyway).

Personally, I prefer to pick some from both C and C++. I use classes and use
an object oriented structure to my programs, but I generally don't get into
inheritance, virtual anything, templates, etc. (there are exceptions of
course). Mainly I enjoy the compiler enforced restrictions on data and
functions that the class mechanism supplies.





From p-abel at t-online.de  Fri Jul  4 17:18:28 2003
From: p-abel at t-online.de (Peter Abel)
Date: 4 Jul 2003 14:18:28 -0700
Subject: strings problem
References: 
Message-ID: <13a533e8.0307041318.5025787a@posting.google.com>

"Jimmy verma"  wrote in message news:...
> Hello *.*
> 
> Can you please tell me how can i have the output in no's, instead of string 
> from this program:
> 
> #/usr/bin/python
> import re
> import string
> 
> def csNumEncode(num):
>     if(num>=-107 and num<=107):
>         return chr(num+139)
>     elif(num>=108 and num<=1131):
>         return chr(((num-108)/256)+247) + chr((num-108)%256)
>     else:
>         print 'do nothing'
> 
> re_num = re.compile("\-?[0-9]+(\.[0-9]+)?")
> 
> 
> def CompileCS(source):
>   result=''
>   for tkn in re.split('[ \n\t]+', source):
>     print "Token: %s"%tkn
>     if re_num.match(tkn):
>         result = result + csNumEncode(string.atoi(tkn))
>     else:
>         raise SyntaxError, "%s is invalid operator"%tkn
>   return result
> 
> src1 = '50  800'
> 
> t = CompileCS(src1)
> 
> print t
> 
> 
> 
> The output is
> 
> Token: 50
> Token: 800
> \275\371\264
> 
> 

I didn't check every line of your script.
Maybe in some earlier lines you can do some manipulation of data.

> Instead of this i want the output should be in no's like this:
> bdF9B4

But concerning the output the following two lines can do what you want:
>>> yourOutput='\275\371\264'
>>> print '%02x%02X%02X'%tuple(map(ord,yourOutput))
bdF9B4


> 
> Your suggestions will be welcomed.
> 
> Thanks a lot.
> 
> Regards,
> Jim
> 
> _________________________________________________________________
> Looking for love? Yearning for friendship? http://www.msn.co.in/Romance/ 
> You're in the right place.

Regards
Peter



From hans at deragon.biz  Sun Jul  6 07:06:59 2003
From: hans at deragon.biz (Hans Deragon)
Date: 6 Jul 2003 04:06:59 -0700
Subject: Red Hat 9, Python and Glade - a mixure not working?
References:  
Message-ID: 

"David M. Cook"  wrote in message news:...
> In article , Hans Deragon
> wrote:

[...deleted lines...]

> > gtk.glade.XML('project3.glade')
> 
> Should be
> 
> xml = gtk.glade.XML('project3.glade')

Ok, here I am embarrassed... forgetting to assign xml... ;)

> > xml.autoconnect({
> >   'on_button4_clicked': on_button4_clicked
> > })
> 
> Or you can just use
> 
> xml.signal_autoconnect(locals())
> 
> See glade_demo.py in the /usr/share/doc/pygtk2-1.99.14/examples/glade/.

Thanks for the tips.  But the problem still persist.  Now I run the
following:

------------------
[root at world project3]#
/usr/share/doc/pygtk2-1.99.14/examples/glade/glade-demo.py
project3.glade

(glade-demo.py:3405): GLib-GObject-CRITICAL **: file gobject.c: line
1002 (g_object_get): assertion `G_IS_OBJECT (object)' failed

(glade-demo.py:3405): GLib-GObject-CRITICAL **: file gobject.c: line
1002 (g_object_get): assertion `G_IS_OBJECT (object)' failed
Segmentation fault
------------------

So the problem is not my code.  I must assume that the glade module
for gnome is not adapted for taking in Glade 2 xml?

Then I tried with a Glade 1 xml:

-----------------
[root at world project2]#
/usr/share/doc/pygtk2-1.99.14/examples/glade/glade-demo.p
y project2.glade

(glade-demo.py:3541): libglade-WARNING **: Expected .
 Got .

(glade-demo.py:3541): libglade-WARNING **: did not finish in
PARSER_FINISH state
Traceback (most recent call last):
  File "/usr/share/doc/pygtk2-1.99.14/examples/glade/glade-demo.py",
line 12, in
 ?
    xml = gtk.glade.XML(fname)
RuntimeError: could not create GladeXML object
-----------------

Different errors, same results.  Nothing works.  However the
test.glade xml file provided as an example works fine.  I believe that
there is some widget in my glade2 xml file that is simply not
supported by python.  I will investigate further the issue later.

Thanks,
Hans Deragon



From logistix at cathoderaymission.net  Tue Jul 29 00:13:43 2003
From: logistix at cathoderaymission.net (logistix at cathoderaymission.net)
Date: 28 Jul 2003 21:13:43 -0700
Subject: Debugging Python ?
References:   
Message-ID: <3c91a864.0307282013.2acb2d1f@posting.google.com>

pedro.werneck at bol.com.br (Pedro Werneck) wrote in message news:...
> I use:
> 
> if __debug__: print "bla, bla, bla..."
> 
> And I was just wondering if it's legal to define a "print" function...
> isn't print a keyword ?

Instead of defining "print" you can assign a custom class to
sys.stdout.  Then all the print statements get automagically
redirected.:

if __debug__:
    class newStdout:
        def write(self,string):
            print string
else:
    class newStdout:
        def write(self,string):
            pass

import sys
sys.stdout = newStdout()



From jjl at pobox.com  Mon Jul 21 10:16:03 2003
From: jjl at pobox.com (John J. Lee)
Date: 21 Jul 2003 15:16:03 +0100
Subject: "Pure Python" MySQL module like Net::MySQL
References:   <7xk7advy4c.fsf@ruckus.brouhaha.com>
Message-ID: <87fzl0q82k.fsf@pobox.com>

Paul Rubin  writes:

> Skip Montanaro  writes:
[...]
> > libraries haven't been ported.  On the other hand, the MySQL wire protocol
> > is probably not part of the official external interface, so the author has
> > to track changes to the protocol.
> 
> What the heck?  If the wire protocol isn't part of the official
> external interface, then how on earth are external applications
> supposed to talk to the database?  They certainly can't expect you to
> use black-box client libraries if they're at all serious about being
> in the same league with Oracle.

Why not?

In any case, MySQL *isn't* in the same league as Oracle or PostgreSQL,
is it?


John



From duncan at NOSPAMrcp.co.uk  Tue Jul 22 04:14:00 2003
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Tue, 22 Jul 2003 08:14:00 +0000 (UTC)
Subject: Python scripting with Paint Shop Pro 8.0
References:    <87d6g4wzu7.fsf@pobox.com>   
Message-ID: 

Marc Wilson  wrote in
news:t25ohv824kde3dh6hvjs6ic9i3d5r98m8j at 4ax.com: 

>|The documentation is available as a separate download (for those
>|people who didn't get their copy on CD, such as the evaluation copy).
>|4798 files, but having looked at them I wouldn't say they were the
>|best documentation ever. 
> 
> I do have a CD, but the files aren't on it.  Perhaps it's a duff CD.

See the downloads area at 
http://www.jasc.com/products/paintshoppro/components.asp
for Scripting for Script Authors and Paint Shop Pro 8 Scripting API 
downloads.

-- 
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 not.valid at address.org  Sun Jul 13 15:28:15 2003
From: not.valid at address.org (YoTuco)
Date: Sun, 13 Jul 2003 19:28:15 GMT
Subject: Multiple Class Inheritance Question
Message-ID: 

Does (can) an inheritance scheme like this have any adverse effects
(pitt-falls) for the App class inheriting class 'A' twice? 

Thanx in advance for your input.

class A:
    A_attr = 'A'
    ...
    def A_methods(self):
    ...

class B(A):
    def __init__(self):
    ...

class C(A):
    def __init__(self):
    ...

class App(B,C):
    def __init__(self):
        B.__init__(self)
        C.__init__(self)
    ...




From skip at pobox.com  Wed Jul  9 14:43:08 2003
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 9 Jul 2003 13:43:08 -0500
Subject: LOADING DATA INTO ARRAYS
In-Reply-To: <200307100228.50214.skchim0@engr.uky.edu>
References: <200307100147.05841.skchim0@engr.uky.edu>
        <16140.22733.468173.643296@montanaro.dyndns.org>
        <200307100228.50214.skchim0@engr.uky.edu>
Message-ID: <16140.25148.892220.518129@montanaro.dyndns.org>

Don't forget to cc the list.  You get more people looking at your problem

    satish> The data of "fluidcylinder" is as folllows:

    satish> 1.00000000000000        0.00000000000000D+000   0.00000000000000D+000
    satish> 0.932113519778473       0.362166241174114        0.00000000000000D+000

    satish> I am getting the following error:

    satish>  xval,yval,zval=map(float,line.split())
    satish> ValueError: invalid literal for float(): 0.00000000000000D+000

It's been many years since I programmed any Fortran, so I'm no longer sure
what the 'D' notation stands for (double-precision?).  As a first guess, I'd
suggest you change the 'D's to 'E's:

    >>> line.replace('D', 'E').split()
    ['1.00000000000000', '0.00000000000000E+000', '0.00000000000000E+000']
    >>> map(float, line.replace('D', 'E').split())
    [1.0, 0.0, 0.0]

Skip





From tim.one at comcast.net  Sat Jul  5 14:06:53 2003
From: tim.one at comcast.net (Tim Peters)
Date: Sat, 5 Jul 2003 14:06:53 -0400
Subject: A possible bug in python threading/time module?
In-Reply-To: <3F0708E4.5A1603A2@hotmail.com>
Message-ID: 

[Alan Kennedy]
> I just wanted to post a quick message to thank Tim for his endless
> efforts to ensure the high quality of python on the widest range of
> platforms possible.
>
> I can see by the times of some of the posted messages that Tim worked
> long and late on this problem, and didn't stop until he knew the
> answer and implemented the solution.
>
> Thanks, Tim, for your dedication and excellence :-)

Rest assured that no good deed goes unpunished, Alan -- but it's nice to get
a "thanks" once a decade or so .

pain-is-its-own-reward-ly y'rs  - tim





From claird at lairds.com  Sat Jul  5 17:01:08 2003
From: claird at lairds.com (Cameron Laird)
Date: Sat, 05 Jul 2003 21:01:08 -0000
Subject: Python Code Snippets
References: 
Message-ID: 

In article ,
Aur?lien G?ron  wrote:
>Hi,
>
>Does anyone know where I can find a lot of Python code snippets?
>
>I searched the Python wiki and Internet but could not find more than five or
>ten code snippets at a time.
>
>I'm looking for a kind of organized list (GUI snippets, database access
>snippets, I/O snippets, etc.).  I find that there's no better way to learn a
>language than to be able to cut&paste actual working bits of code.
			.
			.
			.
Along with everything the others have offered, "Python-URL!"
 offers a con-
centrated dose of the week's highlights.  You might find
that useful in the regard you describe.
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html



From kp at kyborg.dk  Wed Jul  9 04:12:29 2003
From: kp at kyborg.dk (Kim Petersen)
Date: Wed, 09 Jul 2003 10:12:29 +0200
Subject: mx odbc
In-Reply-To: 
References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> 
Message-ID: <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk>

M.-A. Lemburg wrote:
> Kim Petersen wrote:
> 
>> Regarding ODBC usage in Python...
>>
>> it seems to me that there is a couple of ways to use odbc from python,
>> one of these is the MX version - now that one has a pretty steep 
>> licence cost (imho). So now comes my question (from reading this group 
>> quite a bit):
>>
>>     - what is the basic reason for using MX versus the others?
> 
> 
> Having a maintained and actively supported ODBC interface which
> works on all major platforms, not just Windows ?!

I'm not arguing that thats not important - *but* paying 70$ pr. 
customer, is the equivalent of paying you for 1hr of support for each 
customer [not installation mind you], where our own licence/supportcost 
is already getting lower and lower... I find that _extremely_ steep - i 
could and would accept such a cost for the python platform (no trouble!) 
[except in the few (from our view) cases where the user just needs a 
small tool.

IMHO your setting the value of the package so high, that there would be 
better economics in making a rewrite of our database modules every time 
a customer needs some new one (porting to a new database specific DB-SIG 
compliant module).

> 




From hokiegal99 at hotmail.com  Tue Jul  8 20:24:42 2003
From: hokiegal99 at hotmail.com (hokiegal99)
Date: Tue, 08 Jul 2003 20:24:42 -0400
Subject: regexp and filenames
Message-ID: 

I have a bit of a problem that I think Python can solve, but I need a 
bit of direction. I'm replacing 12 Macs with PCs. Macs allow characters 
in filenames that Windows does not, specifically the following:

: * ? " < > | / \

I would like to write a script that searches through a directory for 
filenames that contain any of the aboved listed characters and replaces 
them with a - (the minus sign).

I'm familiar with regexp, but I've only used it in Python to act on the 
contents of a file, not filenames in a directory. Any pointers on how to 
approach this are welcome!




From peter at engcorp.com  Tue Jul 15 12:21:27 2003
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 15 Jul 2003 12:21:27 -0400
Subject: delete file
References: <2c6431ab.0307100711.780a65ad@posting.google.com>   <3F0D962E.23DA9F59@engcorp.com> <2c6431ab.0307110529.7a336f30@posting.google.com> <3F0EBFED.BB283660@engcorp.com> <2c6431ab.0307150743.7dd52f3f@posting.google.com>
Message-ID: <3F142A07.34072E2F@engcorp.com>

lamar_air wrote:
> 
> I am using this remove method and it works well as long as the file is
> there
>    os.remove("C:\Inetpub\wwwroot\Cgi-bin\output.txt")
> If the file doesn't exist then i get an error that the file is not
> found.  I want to stay away from using
>    f2=open('C:\Inetpub\wwwroot\Cgi-bin\output.txt', 'w') so how can i
> check if the file exists first?

I'm still confused.  You "want to stay away from using open(xx)"
but you are getting an error from os.remove when the file doesn't
exist.

Why do you want to stay away from open() when it would clearly fix
the problem?  It does not raise an exception when the file doesn't
exist, and it quietly truncates (effectively removes) the file when
it already does exist.

Anyway, if you insist on using os.remove(), just put it in a 
try/except OSError block and catch the exception that is thrown
when the file does not exist.

Alternatively, and the worst of all the solutions, is to use
os.path.exists() first to check if the file already exists, and
only then to call os.remove().

The choice is yours.  Personally, I'd go with open(xxx, 'w') since
that's safer, idiomatic (i.e. standard usage), and much simpler.

-Peter



From adechert at earthlink.net  Tue Jul 22 16:40:31 2003
From: adechert at earthlink.net (Alan Dechert)
Date: Tue, 22 Jul 2003 20:40:31 GMT
Subject: Voting Project Needs Python People
References:      <7x65lv31hf.fsf@ruckus.brouhaha.com>  
Message-ID: <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net>

"Harry George"  wrote in message
news:xqxsmoyitto.fsf at cola2.ca.boeing.com...
>
> No, I said the paper and the CRT or LCD were correct.  It was just the
> electronic storage that was altered.
>
Okay, right.  My mistake.  I read #1 as one scenario and #2 as different
scenario.

Nonetheless, I maintain that such a game would be caught easily.  Checking a
very small sample before announcing the preliminary (electronic) count would
catch it.  If one percent of the electronic votes were altered (evenly
distributed), you will find one mismatch for sure after checking only a
dozen or two ballots.  If the one percent is not evenly distributed, it will
show up as very suspicious results in the areas where the alterations were
concentrated.  So, before announcing the electronic count, the result should
be given a common sense review.  For example, if Orange County in CA shows
75 % for the Democrat you know something's wrong (or San Francisco shows 75
% for the Republican).  Then samples should be checked in various locations
with any unexpected looking results getting special attention.

If you find one mismatch while sampling, you know there's a problem and the
tally would be delayed until all the paper ballots have been scanned.  Then
you do some manual checking of the results from scanning.

Then, you figure out how the rigging was carried out.  If the machines were
rigged all over, this would imply a very large conspiracy -- a very large
risk for a large number of people doing something that will be caught with
absolute certainty (thus very unlikely to happen).

Alan Dechert






From wayne at mishre.com  Wed Jul 16 20:31:59 2003
From: wayne at mishre.com (Wayne Pierce)
Date: 16 Jul 2003 17:31:59 -0700
Subject: Installing milter-0.5.4 (Python) on Mandrake 9.x with updates.
Message-ID: <2a897f11.0307161631.7f41db19@posting.google.com>

I have been working on installing the Python bindings for Milters on a
Mandrake 9.x system.

When I type:

python setup.py build

I get the following error (last 4 lines of output):

  File "/usr/lib/python2.2/distutils/command/build_ext.py", line 231,
in run
    customize_compiler(self.compiler)
  File "/usr/lib/python2.2/distutils/sysconfig.py", line 145, in
customize_compiler
    (cc, opt, ccshared, ldshared, so_ext) = \
  File "/usr/lib/python2.2/distutils/sysconfig.py", line 427, in
get_config_vars
    func()
  File "/usr/lib/python2.2/distutils/sysconfig.py", line 332, in
_init_posix
    raise DistutilsPlatformError(my_msg)
distutils.errors.DistutilsPlatformError: invalid Python installation:
unable to open /usr/lib/python2.2/config/Makefile (No such file or
directory)

The directory does not exist, although from what I can tell Distutils
is supposed to be included with all versions of Python since 1.6.  A
search on my system does not find anything named "Distutils" .

I used the Sendmail from the Mandrake CD and have not built it from
source (yet).

I can install Distutils, but do not want to cause issues with anything
already installed on my system...I may need to re-install python to
use threads anyway.

Any thoughts on where to look?  Thanks for any help,

Wayne



From aahz at pythoncraft.com  Fri Jul 18 18:47:13 2003
From: aahz at pythoncraft.com (Aahz)
Date: 18 Jul 2003 18:47:13 -0400
Subject: Threading Pool Event()
References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au>  
Message-ID: 

In article ,
Graeme Matthew  wrote:
>
>Thanks, ive actually been using your OSCON slides which have helped a
>lot.  So it technically correct that all worker threads in a thread
>pool are either doing some work or polling the queue to find out if
>there is a job to process ?

The whole point is that it *doesn't* poll.  It blocks on a lock internal
to the Queue object.  That makes it extremely efficient.

>eg: (pseudocodish :-))
>
>def run(self):
>
>    while 1:
>
>        self.lock.acquire()
>
>        if QueueManager.HasJob:
>            job = QueueManager.GetFreeJob()
>            __processJob(job)
>
>        self.lock.release()
>
> def __processJob(self):
>
>        blah blah blah .....

Nope, it's even simpler than that:

    def run(self):
        done = False
        while not done:
            job = q.get()
            if job.done:
                done = True
            else:
                __processJob(job)

The Queue handles all the locks for you.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

A: No.
Q: Is top-posting okay?



From mpeuser at web.de  Tue Jul 22 06:36:57 2003
From: mpeuser at web.de (Michael Peuser)
Date: Tue, 22 Jul 2003 12:36:57 +0200
Subject: Spinning OpenGL.Tk graphics
References: 
Message-ID: 

Maybe I found a work-around:

  o = Opengl()

  o.bind('', o.tkTranslate)
  o.bind('', o.StartRotate)
  o.bind('', o.tkRotate)
  o.bind('', o.tkRecordMouse)
  o.bind('', o.tkScale)

This was taken (but modified) from the OglSurface/Frame example - that demo
didn't run however before I changed
some glVertex3f to glVertex3fv .....

Michael
------------
"Michael Peuser"  schrieb im Newsbeitrag
news:bfitk2$ule$01$1 at news.t-online.com...
> Python's OpenGL.Tk binding makes simple 3D drawing a snap! The default
mouse
> keys for  panning and sizing is left and right, for rotation it seems to
be
> the middle key which is on just very few people's mouse nowadays.
>
> Of course I tried obvious and not so obvious shift/alt/contrl/mouse
> combinations- without any success.
> Is there a work-around? The docu for the binding is somewhat obscure and
one
> has to guess a lot ;-) I haven't figured out yet how to use AutoSpin ....
> I am using Windows2000
>
> Thanks for suggestions and may be hints to more detailed documentation.
>
> Michael
>
>





From vze4rx4y at verizon.net  Tue Jul 22 03:27:21 2003
From: vze4rx4y at verizon.net (Raymond Hettinger)
Date: Tue, 22 Jul 2003 07:27:21 GMT
Subject: Python Mystery Theatre -- Episode 3:  Extend this
Message-ID: 

Here are few more mini-mysteries for your amusement
and edification.

Again in this episode, the program output is not shown.
Your goal is to predict the output and, if anything
mysterious occurs, then explain what happened
(in blindingly obvious terms).

This time, the extra credit is for picking-out the three
that surfaced as errors in my own, real code over
the past few years (the example context below may be
different, but the type of error occurred in real code).

Try to solve these without looking at the other posts.
Let me know if you learned something new along the way.


Enjoy,


Raymond Hettinger


ACT I ---------------------
def real(z):
    return hasattr(z, 'real') and z.real or z
def imag(z):
    return hasattr(z, 'imag') and z.imag or 0
for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L:
    print real(z), imag(z)

ACT II ---------------------
uniq = {}
for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0):
    uniq(k) = 1
print len(uniq)

ACT III ---------------------
s = 'abracadabra'
for i in [3, 2, 1, 0]:
        print s[i:], s[-i:]

ACT IV ---------------------
pets = list('cat ')
pets += 'dog '
pets.extend('fish ')
print pets + 'python'

INTERMISSION (with output included, oh yeah! ------------
>>> import operator
>>> 1 - reduce(operator.add, [1e-7]* 10**7)
2.4983004554002264e-010

ACT V ---------------------
class Bin:
    numitems = 0
    contents = []

    def add(self, item):
        self.numitems += 1
        self.contents += [item]

laundry = Bin()
groceries = Bin()

laundry.add('shirt')
groceries.add('bananas')
groceries.add('nuts')
laundry.add('socks')
groceries.add('pretzels')

print laundry.numitems, laundry.contents
print groceries.numitems, groceries.contents


ACT VI -----------------------------------------
print "What is the technical name for this algorithm or transformation?"
a = range(0, 100, 10)
import random
random.shuffle(a)
print "Input:", a
swaps = 0
for i in range(len(a)):
    for j in range(i+1, len(a)):
    if a[i] > a[j]:
        i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1
print "Output:", a
print "Workload;", swaps






From h.b.furuseth at usit.uio.no  Tue Jul  8 10:52:33 2003
From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam))
Date: 08 Jul 2003 16:52:33 +0200
Subject: path module
References: 
Message-ID: 

If there is going to be a New Wonderful Path module, I suggest you give
some thought to paths on systems that don't fit the simple Unix/Windows
path model.  A path to a filename may e.g. looks different from a path
to a directory.  It's a long time since I used anything like that, but I
think Tops-20 filename paths looked like this:

    device:file.ext;version

where most components were optional.  The device: part could also be a
'logical name' (basically an alias) for a directory or device, I don't
remember if it could alias a file name too.

The Common Lisp pathname type might be worth looking into,

They have done a lot of work to try to get it right, and from what
I hear they did a good job.

-- 
Hallvard



From bokr at oz.net  Sat Jul 12 16:46:33 2003
From: bokr at oz.net (Bengt Richter)
Date: 12 Jul 2003 20:46:33 GMT
Subject: [OFF TOPIC] Re: The "intellectual property" misnomer
References:  <3f103fa7_6@corp.newsgroups.com>
Message-ID: 

On Sat, 12 Jul 2003 13:04:03 -0400, "Steve Pinard"  wrote:

>This newsgroup is for postings related to the computer language Python.
>
>Your discussion about the meaning of intellectual property may best be
>
>served in a newsgroup for topics related to the law.
>
>
>
>(In other words, you all should know better. Take it outside.)
>
Yeah, but you should know that telling others what they should know
and what they should do tends to rub them the wrong way ;-)

Regards,
Bengt Richter



From michaeljwhitmore at netscape.net  Tue Jul  8 16:09:55 2003
From: michaeljwhitmore at netscape.net (Michael J Whitmore)
Date: 8 Jul 2003 13:09:55 -0700
Subject: Newbie - Directory/File Creation
Message-ID: <68a42404.0307081209.4baafd5@posting.google.com>

If I do the following, a file is created in the current working
directory:
    TestFile = open("TestTest.out", 'w') 

My question is how to create a file that includes a pathname without
having to mkdir beforehand.
    Example:
    TestFile = open("TestDir\TestTest.out", 'w')

Shouldn't open be smart enough to create the TestDir directory before
creating TestTest.out   ?

Is there another command that will do this?



From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Thu Jul 31 13:33:15 2003
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Thu, 31 Jul 2003 19:33:15 +0200
Subject: Retrieve source filename
In-Reply-To: <3f29207d$0$24768$626a54ce@news.free.fr>
References: <3f29207d$0$24768$626a54ce@news.free.fr>
Message-ID: <3f2952da$0$49110$e4fe514c@news.xs4all.nl>

Shrom wrote:

> I know that you can retrieve main file name with sys.argv[0] and file name
> for a module with modulename.__file__ but is there a common way to retrieve
> file name for both main program and modules as the __FILE__ constant in PHP
> ?

I don't know if it's the "right" way, but this works:

import inspect
print inspect.getfile(inspect.currentframe())


--Irmen




From xiarcel at prodigy.net  Thu Jul  3 07:04:49 2003
From: xiarcel at prodigy.net (David Scott Williams)
Date: Thu, 03 Jul 2003 07:04:49 -0400
Subject: Python executables
References: <20030703090622.1420.48614.Mailman@mail.python.org>
Message-ID: <3F040DD1.1050008@prodigy.net>

It's been awhile since I've been on the python list... but I'll take a 
whack at this:



>
> ------------------------------------------------------------------------
>
> Subject:
>
> Re: Python executables?
> From:
>
> Geoff Howland 
> Date:
>
> Thu, 03 Jul 2003 06:41:18 GMT
> To:
>
> python-list at python.org
>
>
>On 27 Jun 2003 09:24:22 +0950, Ben Finney
> wrote:
>
>>>This solves the problem of giving python programs to users who don't 
>>>have python but doesn't solve the problem of the source "secrecy" 
>>>(copyright).
>>>
>>Wrong problem.  If you want to hide your source code from your users,
>>don't expect help from free software programmers.
>>
>
>I thought about this for a few days before responding (and Im sure I
>did a few other things too  ;) ), but I wanted to comment on this.
>
>
>I think everyone that uses Python wants it to gain acceptance for the
>great language that it is.  I believe that stating an attitude in this
>way is pretty counter productive in gaining any kind of wide-spread
>acceptance.
>
Unfortunately, though, I don't think you get any more tread coming to 
the Open Source developers and asking them how to hide your bits... This 
is your issue, reversed.  

>
>Most of the replies to this request didn't mention the concept of NOT
>protecting the software, but 2 did to different degrees.  As someone
>who uses and like open source software, and is slowly starting to
>release some things as open source, and ALSO someone who sells
>software and will continue in the future to sell software, I can say
>that nothing turns me off more to a community than being told what my
>goals should be.
>
I think if your goals are un-reasonable, asking a hammer salesman how 
best to use his tool to screw something into drywall is again, similary, 
counter-productive.  Scripting languages are hard to obfuscate, if not 
damned near impossible.  Even Java byte-code can be decompiled back to 
fairly decent looking source...

>
>I can understand wanting everything to be open, but thats not reality
>and it never will be.
>
I, personally, don't disagree with this.

>  Some people will always want things
>proprietary, and they will only work within systems that allow that.
>I think to be truly successful, systems will have to allow for this
>and make it easy to do.
>
>Currently Python does not make this REALLY easy to do, and in the
>privacy portion, I believe its not even possible.  This was a big
>concern for me when I released my last for-sale software, but I just
>decided I didn't care that much, and I love working in Python.
>
Often times, I think, Python caters to the developers that develop 
95-98% of the software --in house software where source code access 
isn't a problem either way...  It is good for mock-ups, for getting 
something structured and OO, and for writing software that otherwise 
doesn't yield you revenue (install, config scripts, for example)...  It 
is great for other software too... and some companies make money selling 
support for the source, many users are not hackers, even unix/linux 
users, now..

>
>Some people will care enough, and will avoid Python because the
>ability to protect their end results aren't there.
>
This loss is unfortunate, perhaps someday they will see that software 
really isn't a commodity, but a service.  

>
>So far, the only semi-workable way to do this would be something like:
>
>- Build a C program that embeds Python.
>- Encrypt all the Python script/bytecode files.
>- On runtime, decrypt the files and then execute.
>
>Optional:
>
>- Change the bytecode values in the Python source, and include your
>new Python with different bytecode values.
>
>I tried this last thing just to see if it would work, and I got some
>problems compiling initially, so just gave up, but I think in theory
>it should work.
>
>Ignoring the Optional portion, this semi-solution is not actually very
>secure.  It does however move the problem into having to decompile a C
>program, and then get it to decrypt the Python files.  Then the normal
>Python bytecode -> source.  It means any cracker will have to know
>something about both C and Python to do it, so a bit more barrier to
>entry.  It also means that in the US, the (vile and despicable, but
>present) DMCA laws will make it a much more severe crime because
>"cryptography reverse engineering" needed to be applied, and may at
>least reduce corporations from doing this for fear of
>lawsuits/criminal charges if they are exposed.
>
Perhaps you could write an open source python code obfuscator?   Or 
write it in C and make it closed source?  

>
>Anyway, this is a good bit of work and not a great solution, but is
>there anything else?  If Python is to have avenues of support in all
>walks of the software industry, will something like this be required?
>
I still think that python is often used as glue... the easy and 
straightforward style add value to the remaining (if obfuscated) bits...

>
>>From what I understand, there are also very good Java decompilers, but
>no one seems to complain about Java's lack of security.  Perhaps it is
>because it is seen as something that is really "compiled" while
>Python's loose compilation seems more whimsicle.
>
mentioned this above myself... There are obfuscators for java...but if 
someone wants it bad enough, they can get your source, or something 
reasonably close... in almost ANY language.  

>
>
>I think Python faces a lot of different public relations problems, and
>just thought I'd pipe up about one that I have looked at myself, and
>that I think most people coming into the Python world are faced with
>and have to decide whether to ignore or not.
>
>
>-Geoff Howland
>http://ludumdare.com/
>
>

-- 
~Dave 
xiarcel at prodigy.net

	                 Brainchild 
	            (and current obsession)
	        http://dustyscript.sourceforge.net/ 
	  >Dustyscript: Programming for Children<

	     ||*Other projects that I head up*||
	http://sourceforge.net/projects/cxtable 
	           >The xTable Project<<
	http://sourceforge.net/projects/moonroof  
	       >Moonroof, a Java desktop<

||**Projects that I am dedicated to (but not in charge of)*||
	http://sourceforge.net/projects/grapevine
 		>Grapevine p2p network<
		   "The Java Port"
	http://sourceforge.net/projects/symbiosis
		        >Symbiosis<

weblog: http://wildegrey.blogspot.com/

"When I think back on all the crap I learned in High School...
it's a wonder I can think at all..."
		-Paul Simon, "Kodachrome"

"...I took the road less travelled by, and that has made all the difference.."
		-Robert Frost

"Man is the only animal that blushes... or needs to"
		-Mark Twain








From aahz at pythoncraft.com  Tue Jul 29 10:14:30 2003
From: aahz at pythoncraft.com (Aahz)
Date: 29 Jul 2003 10:14:30 -0400
Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?)
References:    <3f2627c7$0$76067$edfadb0f@dread11.news.tele.dk>
Message-ID: 

In article <3f2627c7$0$76067$edfadb0f at dread11.news.tele.dk>,
Anders J. Munch  wrote:
>"Aahz"  wrote:
>> Jeff Epler   wrote:
>>>
>>>I don't see what's problematic about letting slices be hashable: 
>> [...]
>>Hashing them as
>>>    hash((s.start,s.stop,s.step))
>>>might be a reasonable definition.
>> 
>> Makes sense to me.  Feel free to submit a patch to SF.  ;-)
>
>I'd rather he didn't.  I prefer Python to be able to catch the bug of
>attempting to use a dict as were it a list.  For the rare case where
>using a slice key was intentional, converting to tuple form is easy
>enough.
>
>I can see that it's good for consistency to allow hashing of slices.
>However it's bad for consistency that where alist[slice] returns a
>subsequence, adict[slice] would return a single element.

Fair enough.  Note carefully that I said "submit a patch" -- that
doesn't guarantee that the patch will be accepted, and it's quite likely
that it won't be.  But "submit a patch" is usually a good way to get
people to shut up.  ;-)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

This is Python.  We don't care much about theory, except where it intersects 
with useful practice.  --Aahz



From gabriel.cooper at mediapulse.com  Wed Jul 23 17:02:56 2003
From: gabriel.cooper at mediapulse.com (Gabriel Cooper)
Date: Wed, 23 Jul 2003 17:02:56 -0400
Subject: Reading Keyboard Scan Codes
In-Reply-To: <23daa443.0307231129.12d7ccf5@posting.google.com>
References: <23daa443.0307231129.12d7ccf5@posting.google.com>
Message-ID: <3F1EF800.20802@mediapulse.com>

Michael Bendzick wrote:

>Is there a simple way in python to read a keyboard scan code?  I'm
>working on a shell script that interfaces with a proprietary keyboard
>device (extra buttons) and need to be able to distinguish between
>those keys.
>
>Thank you
>
(In theory) the extra buttons shouldn't be any different than reading 
any other
keyboard input. Simply find out what value is being sent by the keyboard
when you hit those keys and program around those values.





From logiplex at qwest.net  Fri Jul 18 18:28:48 2003
From: logiplex at qwest.net (Cliff Wells)
Date: 18 Jul 2003 15:28:48 -0700
Subject: Threading Pool Event()
In-Reply-To: 
References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au>
	   
Message-ID: <1058567328.2717.46.camel@software1.logiplex.internal>

On Fri, 2003-07-18 at 14:28, Graeme Matthew wrote:
> Aahz
> 
> Thanks, ive actually been using your OSCON slides which have helped a lot.
> So it technically correct that all worker threads in a thread pool are
> either doing some work  or polling the queue to find out if there is a job
> to process ?

They don't poll the queue, they block waiting on it until something is
available.

> eg: (pseudocodish :-))
> 
> def run(self):
> 
>     while 1:
> 
>         self.lock.acquire()
> 
>         if QueueManager.HasJob:
>             job = QueueManager.GetFreeJob()
>             __processJob(job)
> 
>         self.lock.release()
> 
>  def __processJob(self):
> 
>         blah blah blah .....

More like:

def run():
    while 1:
        job = queue.get() # this blocks until something is queue.put()
        _processjob(job)


Acquiring the locks isn't necessary and ill-advised.  The Queue itself
can be thought of as a type of locking mechanism, so you raise the
possibility of a deadlock condition by nesting locks (for instance if
you also put locks around the queue.put()).

Regards,

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





From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Wed Jul 16 16:06:36 2003
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Wed, 16 Jul 2003 22:06:36 +0200
Subject: Confusing automated translators.
In-Reply-To: 
References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl>  <3F12808B.E53193B8@hotmail.com> 
Message-ID: <3f15b04b$0$49114$e4fe514c@news.xs4all.nl>

Anton Vredegoor wrote:

> I don't know about automated translators, but I dare any non Dutch or
> German native speaker to interprete the following valid Dutch
> sentence:
> 
> "Als achter vliegen vliegen vliegen vliegen vliegen vliegen achterna."
> 
> Anton

You should really add a comma at the right place, otherwise even Dutch
people themselves tend to get confused rather quickly too:

"Als achter vliegen vliegen vliegen, vliegen vliegen vliegen achterna."

(btw, a tip: 'vliegen' is a verb and also a noun in Dutch.)

--Irmen




From duncan at NOSPAMrcp.co.uk  Thu Jul  3 04:14:19 2003
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Thu, 3 Jul 2003 08:14:19 +0000 (UTC)
Subject: does lack of type declarations make Python unsafe?
References: <3064b51d.0306151228.22c595e0@posting.google.com>  <1055736914.49032@yasure>  <3064b51d.0306170436.2b31f9e@posting.google.com>   <9a6d7d9d.0307020959.634ceb4e@posting.google.com>
Message-ID: 

aaron at reportlab.com (Aaron Watters) wrote in
news:9a6d7d9d.0307020959.634ceb4e at posting.google.com: 

> David Abrahams  wrote in message
> news:... 
>> Duncan Booth  writes:
>> 
>> I'm not saying that Python isn't a wonderful language -- it is.  It's
>> great to have the flexibility of fully dynamic typing available.  All
>> the same, I'm not going to pretend that static typing doesn't have
>> real advantages.  I seriously believe that it's better most of the
>> time, because it helps catch mistakes earlier, makes even simple code
>> easier to maintain, and makes complex code easier to write.  I would
>> trade some convenience for these other strengths.  Although it's very
>> popular around here to say that research has shown static typing
>> doesn't help, I've never seen that research, and my personal
>> experience contradicts the claim anyway.
> 
> I'm somewhere on the fence.  I've seen static typing catch errors,
> but I've also seen static typing (in java, say) make the use of a
> hash table into an exercise in code obfuscation.  I'd really like some
> sort of compromise where you could harden types incrementally.  Also
> static typing can make it more difficult for bad programmers to do
> stupid things...
> 

I didn't write any of the stuff you quoted from Dave Abrahams post. If you 
are going to trim all of my text as irrelevant to your reply, then please 
trim my name as well.

-- 
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 Erendil at aol.com  Wed Jul 30 11:24:21 2003
From: Erendil at aol.com (Erendil at aol.com)
Date: Wed, 30 Jul 2003 11:24:21 EDT
Subject: special case loading modules with imp
Message-ID: 

Alright, this is my first post here. =) Let's try to get this right?

I have a slight problem right now. I wrote a plugin architecture in Python, 
allowing any python app or python using app to use plugins. It's very flexible 
and open-ended, except for one thing: It has to use imp to load python source 
from files. Now, using imp is not the problem really. The plugin module works 
very well as of now, and I've used it lots of my other projects. What I need 
to do now is I've read Python code out of an SQLite database into a string, and 
I need my plugin module to use imp to load that string of code as a module. 
(I don't use import because I simply store the module object in an array. makes 
it unloadable later.)

So, I just want to switch from using real files to being able to use strings. 
The goal is to get a module object that I can place in an array.

       Thanks, Rob.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bokr at oz.net  Tue Jul 29 14:52:29 2003
From: bokr at oz.net (Bengt Richter)
Date: 29 Jul 2003 18:52:29 GMT
Subject: pretty printing graphs
References:    
Message-ID: 

On Tue, 29 Jul 2003 10:31:51 -0500, John Hunter  wrote:

>>>>>> "Bengt" == Bengt Richter  writes:
>
>    Bengt> should be -- def showInPage(self, pageHeight=6*11,
>    Bengt> pageWidth=78): return '\n'.join(self.boxlines(pageHeight,
>    Bengt> pageWidth)) -- [...]
>
>I think I may have discovered another bug.  In the longish example below,
>the children of n2 are n20 and n21
>
>   n2.children.extend([n20, n21])
>
>These children are the branch:
>
>     |------------------+        
> +-------+          +-------+    
> |3 4 5 6|          |6 4 5 6|    
> |3 4 5 6|          |-------|    
> |-------|          |1 1 1 1|    
> |1 1 1 1|          +-------+    
> +-------+                       
>
>However, if you run your pprint on this example, they appear below the
>n4 branch.
>
I suspect the default "page" width of 78 is insufficient. I modded your
data to include a node names (e.g., see first two below)
e.g.,
>Haven't had a chance to grok the code yet -- I just came across this
>bug when using your code on a test case for a projective clustering
>neural network algorithm I'm implementing.  The example is from Cao
>and Wu, Neural Networks 15(2002) 105-120.
>
>   http://www.sciencedirect.com/science?_ob=ArticleURL&_udi=B6T08-43T2MC4-1&_user=5745&_handle=W-WA-A-A-AD-MsSAYZA-UUW-AUCEZCZEBD-AZZEEDDUV-AD-U&_fmt=full&_coverDate=01%2F31%2F2002&_rdoc=10&_orig=browse&_srch=%23toc%234856%232002%23999849998%23290257!&_cdi=4856&view=c&_acct=C000001358&_version=1&_urlVersion=0&_userid=5745&md5=61f59ff40e082d56154538b436b0010e
>
>
>def test3():
    #>    n = Node(TextBox("""1 2 3 4
    n = Node(TextBox("""n
1 2 3 4
>2 3 4 5
>3 4 5 6
>4 5 6 7
>6 7 8 9
>1 2 3 4
>3 4 5 6
>2 3 4 5
>6 4 5 6
>4 2 3 1
>6 7 1 2
>4 5 6 7
>-------
>0 0 0 0
>"""))
>
    #>    n0 = Node(TextBox("""1 2 3 4
    n0 = Node(TextBox("""n0
1 2 3 4
>1 2 3 4
>4 2 3 1
>-------
>0 1 1 0
>"""))
>
[...]
>    n4.children.extend([n40, n41])
>
>    print n
To specify a page wide enough here, try

     print n.showInPage(35, 90)

With the name-modded data, I got

[11:56] C:\pywk\clp>pptree_t3.py 35  90

                                        +-------+
                                        |      n|
                                        |1 2 3 4|
                                        |2 3 4 5|
                                        |3 4 5 6|
                                        |4 5 6 7|
                                        |6 7 8 9|
                                        |1 2 3 4|
                                        |3 4 5 6|
                                        |2 3 4 5|
                                        |6 4 5 6|
                                        |4 2 3 1|
                                        |6 7 1 2|
                                        |4 5 6 7|
                                        |-------|
                                        |0 0 0 0|
                                        +-------+
           +---------------+----------------|---------------+----------------+
       +-------+       +-------+        +-------+       +-------+        +-------+
       |     n0|       |     n1|        |     n2|       |     n3|        |     n4|
       |1 2 3 4|       |2 3 4 5|        |3 4 5 6|       |4 5 6 7|        |6 7 8 9|
       |1 2 3 4|       |2 3 4 5|        |3 4 5 6|       |4 5 6 7|        |6 7 1 2|
       |4 2 3 1|       |-------|        |6 4 5 6|       |-------|        |-------|
       |-------|       |1 1 1 1|        |-------|       |1 1 1 1|        |1 1 0 0|
       |0 1 1 0|       +-------+        |0 1 1 1|       +-------+        +-------+
       +-------+                        +-------+                       +----|----+
      +----|----+                      +----|----+                  +-------+ +-------+
  +-------+ +-------+              +-------+ +-------+              |    n40| |    n41|
  |    n00| |    n01|              |    n20| |    n21|              |6 7 8 9| |6 7 1 2|
  |1 2 3 4| |4 2 3 1|              |3 4 5 6| |6 4 5 6|              |-------| |-------|
  |1 2 3 4| |-------|              |3 4 5 6| |-------|              |1 1 1 1| |1 1 1 1|
  |-------| |1 1 1 1|              |-------| |1 1 1 1|              +-------+ +-------+
  |1 1 1 1| +-------+              |1 1 1 1| +-------+
  +-------+                        +-------+

I guess it would be good to make it self-expanding if the default page is too small, or raise
an informative exception.

Regards,
Bengt Richter



From juliagoolia301 at hotmail.com  Sun Jul 13 09:42:59 2003
From: juliagoolia301 at hotmail.com (Julia Goolia)
Date: 13 Jul 2003 06:42:59 -0700
Subject: installing python library modules (general question)
Message-ID: <79ad5955.0307122013.6780fc53@posting.google.com>

Hi,

I'm sure this issue has been brought up a billion times... but I'm
having trouble installing a python module.  I have read all the
documentation for all the buzz words I know related to this problem
but to no avail.

Basically I downloaded a python module called pymad.  This module is
supposed to be simplified API to libmad (an mp3 decoder) (I want to
play mp3's from python).

I installed libmad.  The libraries appear to be in /usr/local/lib.  I
did all the distutils stuff for the module.  Now when I try to "import
mad" I get an ImportError exception:

ImportError: libmad.so.0: cannot open shared object file: No such file
or directory

I know the file /usr/local/lib/libmad.so.0 exists, but python can't
seem to find it.  I tried adding this path to LD_LIBRARY_PATH, but
that didn't help.

I guess that I just really dont' know enought about libraries and
linux (redhat 9).  I don't really know where they are supposed to go
after being compiled, and how python "loads" and uses them.

Any help is much appreciated,
Julia



From manish.j at gmx.net  Fri Jul 25 09:56:14 2003
From: manish.j at gmx.net (Manish Jethani)
Date: Fri, 25 Jul 2003 19:26:14 +0530
Subject: How to detect typos in Python programs
Message-ID: 

Hi all,

Is there a way to detect typos in a Python program, before
actually having to run it.  Let's say I have a function like this:

  def server_closed_connection():
    session.abost()

Here, abort() is actually misspelt.  The only time my program
follows this path is when the server disconnects from its
end--and that's like once in 100 sessions.  So sometimes I
release the program, people start using it, and then someone
reports this typo after 4-5 days of the release (though it's
trivial to fix manually at the user's end, or I can give a patch).

How can we detect these kinds of errors at development time?
It's not practical for me to have a test script that can make
the program go through all (most) the possible code paths.

-Manish

-- 
Manish Jethani (manish.j at gmx.net)
phone (work) +91-80-51073488





From anand_soliton at yahoo.com  Tue Jul 22 20:54:21 2003
From: anand_soliton at yahoo.com (Anand)
Date: 22 Jul 2003 17:54:21 -0700
Subject: wxPython looses function "wxPython.wx.miscc"
Message-ID: <3f5dc178.0307221405.db06016@posting.google.com>

I am calling a python script from LabVIEW. This is achieved by making
a dll call to python22.dll. It works perfectly well for most of my
code. I now want to throwup dialog boxes from python. It works just
fine if i run the code once.

but when i call the same piece of code the second time,
wxPython.wx.miscc does not exist for some reason. I dont know how this
gets deleted. I guess this happens during some kind of clean up. The
code that i use for showing a dialog box is as follows:

from wxPython.wx import *
            app = wxPySimpleApp()
            dlg = wxMessageDialog(None, Text,
                          'A Message Box', wxOK | wxICON_INFORMATION)
                          #wxYES_NO | wxNO_DEFAULT | wxCANCEL |
wxICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            app.MainLoop()

when i call it the second time i get the following error:

line 1139, in showDialog
    from wxPython.wx import *
  File "C:\PROGRA~1\Python22\lib\site-packages\wxPython\wx.py", line
4, in ?
    from misc import *
  File "C:\PROGRA~1\Python22\Lib\site-packages\wxPython\misc.py", line
2, in ?
    import miscc
ImportError: No module named miscc

     is there a solution? What is really happening? i am new to
WxPython.



From claird at lairds.com  Tue Jul 22 12:44:04 2003
From: claird at lairds.com (Cameron Laird)
Date: Tue, 22 Jul 2003 16:44:04 -0000
Subject: How do I get info on an exception ?
References:    
Message-ID: 

Raymond Hettinger  wrote:
>> >You could catch it with:
>> >
>> >            except socket.herror, inst:
>> >                  print inst.args
>> >
>> >or more broadly with:
>> >
>> >             except socket.error, (errno, string_message):
>> >                   print code, message
>> >
>> >
>> >> More importantly, where is the answer documented that I should
>> >> have looked?
>> >
>> >The list of possible socket exceptions is in the docs for sockets.
>> >It also describes the (errno, string) return tuple value of inst.args.
>> .
>> .
>> .
>> True.
>>
>> But unsatisfying--at least to me.
>
>Submit a patch.
			.
			.
			.
I deserved that.

There was more to my post, of course.  Part of what I was trying to
express is that exception interfaces are almost always relegated to
a footnote, with only a generalized description, even in the frequent
case that a method's exceptions are more complicated than its invoca-
tions.

Rather than tilt at the collection of all such windmills, I want to
first understand better why this is, and what response is appropriate.
To summarize:  I don't know what patch is the right one.  I also
thought it only fair to warn Mr. July that things are indeed more dif-
ficult than we were explaining, even though I didn't feel up to 
detailing the difficulties.

So, Raymond, do you have general guidelines for how you think excep-
tions should be documented?
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html



From ianb at colorstudy.com  Sun Jul  6 20:14:26 2003
From: ianb at colorstudy.com (Ian Bicking)
Date: 06 Jul 2003 19:14:26 -0500
Subject: Newbie Question: Abstract Class in Python
In-Reply-To: <007001c3441b$d8eb7060$2a523942@homebass1>
References: <00ec01c34050$49ab4bb0$6401a8c0@boxen>
	 <007001c3441b$d8eb7060$2a523942@homebass1>
Message-ID: <1057536865.514.278.camel@lothlorien>

On Sun, 2003-07-06 at 19:08, Kevin Bass wrote:
> I am new to Python and want to know how to implement an abstract class? I
> have read through different books and I have no found this information.
> Thanks!

There's no distinction between abstract and concrete classes in Python. 
So, say, you Figure class with a Square and a Circle subclass, you'd
simply do:

class Figure:
    ...

class Square(Figure):
    ...

class Circle(Figure):
    ...

I guess if you really wanted to be sure someone didn't try to
instantiate Figure, you could add something like:

class Figure:
    def __init__(self):
        assert self.__class__ is not Figure, \
            'Figure is an abstract class, do not instantiate it'






From rganesan at myrealbox.com  Thu Jul 10 06:42:04 2003
From: rganesan at myrealbox.com (Ganesan R)
Date: Thu, 10 Jul 2003 16:12:04 +0530
Subject: Python vs PHP
References:   <3F0D2827.4070501@mxm.dk>  <3F0D3E8A.3080204@mxm.dk>
Message-ID: 

>>>>> "Max" == Max M  writes:

> Ganesan R wrote:
>> How about the fact if you want something simpler than Zope you
>> cannot point
>> to a single framework and say use this one?

> That's right. But without a framework, you are about on par with
> PHP. Only with a better language and better libraries.

You are probably right.  I only given a casual look at PHP, so
I can't comment on the language, but I believe you :-). However, 
PHP does come with a default (and only) web framework. This
obviously makes it easy to get started than to experiment with
Spyce or CherryPy or Cheetah or WebWare or any of the twenty
different alternatives.

Looking at it from the perspective of a PHP developer who's
looking into Python as an alternative. Python doesn't provides
her an out of the box solution yet. Think about what the
bewildering list of choices mean to her. This is not only issue
for development but also for deployment.

Ganesan

-- 
Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/
1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832  6798 15E0 02BA 5D8C 12EA



From adalke at mindspring.com  Thu Jul 31 17:35:33 2003
From: adalke at mindspring.com (Andrew Dalke)
Date: Thu, 31 Jul 2003 15:35:33 -0600
Subject: Is there a standard module library function to access /etc/passwd or /etc/group
References: <16469f07.0307300416.351ba776@posting.google.com>  <16469f07.0307301458.59e73736@posting.google.com>  
Message-ID: 

Steven Taschuk:
> And don't forget the full-text searching capabilities at pydoc.org.

Can't forgot something I didn't know about ;)

Hmmm,  my search for "xmlrpc server" fails but "xml-rpc server" is
successful.

Any idea when it'll be updated for 2.3?

                    Andrew
                    dalke at dalkescientific.com





From b_mcerlean at yahoo.com  Fri Jul 18 12:03:25 2003
From: b_mcerlean at yahoo.com (Brian McErlean)
Date: 18 Jul 2003 09:03:25 -0700
Subject: A challenge to the ASCII proponents.
References:    <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com>  <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com>
Message-ID: 

Alan Kennedy  wrote in message news:<3F17C1D4.1A70703A at hotmail.com>...
> "Martin v. Loewis" wrote:
> 
> > So what do you think about this message?:
> > 
> > ????????????????
> > 
> > Look Ma, no markup. And not every character uses two bytes, either.
> > And I can use Umlauts (??????) and Arabic (????????.????????????)
> > if I want to.
> 
> Martin,
> 
> I can see from other people's messages that this has been successful
> for some people with modern software.
> 
> However, it failed for me on my old Netscape 4.x Messenger. Which is
> acceptable, I suppose, because I intentionally use ancient email and
> usenet software. It is also worth noting that although my poor old
> usenet client failed to display the sequence of characters, the
> "Navigator" component to which it belongs correctly displayed the
> greek text when fed Bengt's "gignooskoo.html" file (although it failed
> on my xml snippet).
> 
> More worrying however is the failure of modern browsers to display the
> characters when accessed through Google Groups.
> 
> >http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3F172442.2040907%40v.loewis.de
> 
> I tried to view this in IE6.0 and Netscape 6.2, and all I saw was 
> "?????s??".
> 
> Whereas that thread still shows my XML snippet intact, still
> copy&paste-able.
> 
> kind regards,

I saw the same as you with that URL, but viewing the thread in google,
or going to the link it gave for "View this article only":
http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3F172442.2040907%40v.loewis.de

displayed OK (Using Mozilla firebird 0.6)

The key difference seems to be the "oe=UTF-8" argument in the URL. 
Adding this to your URL displays it correctly.



From crewr at daydots.com  Fri Jul 18 15:42:06 2003
From: crewr at daydots.com (Crew Reynolds)
Date: 18 Jul 2003 12:42:06 -0700
Subject: Python dictionary syntax, need help
Message-ID: <56ba0aea.0307181142.7401aa02@posting.google.com>

I want to create a dictionary of note on/off timings and access it by
the name of the object. The following code works for one row.

a = "Hammer1" 
b = [5,45,45,45,45,50,55,57,59,61,60,59] 

notes = {a:b} 
print notes["Hammer1"][3] 
>>> 45 

The problem is, I want to load the data from a file to populate
variables a and b and build a dictionary for "Hammer1" thru
"Hammer10". That way, I can stick the name of the object in the array
index and receive a list of note timings that I can index with an
ordinal as in the above example.

This is straight Python syntax but I'm hoping someone has done this or
understands the syntax better than I.

Thanks! Alternative solutions to this concept would be greatly
appreciated.



From andre.lerche at update.com  Thu Jul 10 14:53:24 2003
From: andre.lerche at update.com (Andre Lerche)
Date: 10 Jul 2003 11:53:24 -0700
Subject: treeview / pygtk problem
Message-ID: 

Hi list,

I am quite new to Python and try to learn Python with a small pygtk
program. I am facing a problem which I am unable to solve for myself.
I think I have read the documentation and some samples, but however
I cannot find my mistake, so hopefully someone can help me with a
short hint. This is a small sample application which demonstrates
my problem:

import gtk as g
import gobject

window = g.Window ()
window.connect ('delete_event', g.mainquit)
scrolledwin = g.ScrolledWindow ()
renderer = g.CellRendererText ()
col1 = g.TreeViewColumn ("col 1", renderer, text=1)
col2 = g.TreeViewColumn ("col 2", renderer, text=1)
model = g.ListStore (gobject.TYPE_STRING, gobject.TYPE_STRING)
view = g.TreeView ()
view.set_model (model)
view.set_headers_visible (1)
view.append_column(col1)
view.append_column(col2)

scrolledwin.add (view)
window.add (scrolledwin)
window.show_all ()

iter = model.append ()
# -- Problem -- #
model.set (iter, 0, "foo", 1, "bar")
# ------------- #
g.mainloop ()

I thought, with the marked model.set... I can set the first row in my
treeview to col1 = foo and col2 = bar. But, if I execute the script
the 2 columns are set to bar.

Where is my mistake? I am using Python 2.2.2 on RedHat 9.

Thanks,

Andre



From max at alcyone.com  Wed Jul  2 03:14:04 2003
From: max at alcyone.com (Erik Max Francis)
Date: Wed, 02 Jul 2003 00:14:04 -0700
Subject: arbitrary long integer aritmetics
References: 
Message-ID: <3F02863C.31E931C9@alcyone.com>

Leo wrote:

> is there a python module around allow using arbitrary long integers?
> 
> i.e. the result of an integer operation is as long as necessary, so
> that a*b
> never produces an overflow error. (but rather an out of memory error
> ;-) )

Long (arbitrary precision) integers are a _builtin type_ in Python:

>>> 10
10
>>> 10L
10L
>>> type(10L)

>>> 2L**64L
18446744073709551616L
>>> 10L**100L
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ The death rate is a constant one hundred per cent.
\__/  Camden Benares



From http  Mon Jul 21 03:44:44 2003
From: http (Paul Rubin)
Date: 21 Jul 2003 00:44:44 -0700
Subject: Electronic voting with free software
References:    
Message-ID: <7x1xwknx1v.fsf@ruckus.brouhaha.com>

"Alan Dechert"  writes:
> Our project incorporates a proposal for Remote Attended Internet Voting to
> replace the various existing absentee voting methods employed today.

I wouldn't want to use the public internet that way.  It sounds like
an invitation to launch DOS attacks against the parts of the network
where one's political opponents live.  I don't see the need for any
network connection as long as the election info can be delivered to
all the polling places before the election starts.  If every election
can be enrolled in an FEC database a few weeks before election day
(that means the database has all the info that would get printed on a
ballot), then the whole database can get dumped to CD-ROM or DVD-ROM
and shipped to all the polling places in time for the election, no
internet needed.



From daniel.dittmar at sap.com  Fri Jul 18 08:14:15 2003
From: daniel.dittmar at sap.com (Daniel Dittmar)
Date: Fri, 18 Jul 2003 14:14:15 +0200
Subject: feature request: a better str.endswith
References: <2259b0e2.0307180401.5dae02f2@posting.google.com>
Message-ID: 

Michele Simionato wrote:
> I often feel the need to extend  the string method ".endswith" to
> tuple arguments, in such a way to automatically check for multiple
> endings. For instance, here is a typical use case:
>
> if filename.endswith(('.jpg','.jpeg','.gif','.png')):
>     print "This is a valid image file"

In your special case:

import os

if os.path.splitext (filename) [1] in ['.jpg','.jpeg','.gif','.png']:
    print "This is a valid image file"

perhaps even os.path.splitext (filename) [1].lower ()
for filesystems that are not case sensitive.

Daniel








From chrisperkins37 at hotmail.com  Mon Jul 21 16:20:43 2003
From: chrisperkins37 at hotmail.com (Chris Perkins)
Date: 21 Jul 2003 13:20:43 -0700
Subject: recognizing empty iterators
References: <2259b0e2.0307210626.11a1bbf1@posting.google.com>
Message-ID: <45228044.0307211220.7590d7e9@posting.google.com>

mis6 at pitt.edu (Michele Simionato) wrote in message 

> I realized that I don't know a satisfactory way to check if an
> iterator is empty. In other words I am looking for an
> "isempty" function to use in "if" statements such as
> 
> if isempty(iterator):
>    do_something()
> 
> without side effects.
> 


In general, it is impossible to test whether an iterator is exhausted.
For example, how would you test the following:

import random
def am_i_empty():
	while random.choice((True,False)):
		yield 42
	return

So you have to call "next" - there's no way around it. You just need a
wrapper to cache the value:

class checkable_iter:
	def __init__(self,it):
		self.it = iter(it)
		self.cached = []
	def isempty(self):
		if self.cached:
			return False
		try:
			self.cached.append(self.it.next())
			return False
		except StopIteration:
			return True
	def next(self):
		if self.cached:
			return self.cached.pop()
		return self.it.next()


>>> it = checkable_iter(am_i_empty())
>>> it.isempty()
False
>>> it.next()
42
>>> it.isempty()
True
>>> it.next()
Traceback (most recent call last):
  File "", line 1, in ?
StopIteration

Chris



From peter at engcorp.com  Fri Jul  4 23:32:46 2003
From: peter at engcorp.com (Peter Hansen)
Date: Fri, 04 Jul 2003 23:32:46 -0400
Subject: RTS/CTS and DTR/DTS control
References:   <3F060F8D.94E47DCD@engcorp.com>  <3F064661.33614890@engcorp.com>
Message-ID: <3F0646DE.6344484E@engcorp.com>

Peter Hansen wrote:
> 
> A quick search again with Google using TIOCMSET and TIOCM_CTS and a bunch
> of others finally led to this, which might be the best yet, and includes
> some constant definitions that might let you get something working, if
> this doesn't directly solve your problem:
> 
> http://sparc.dnsalias.net/Python_stuff/PosixSerial.py

Look at the main site... you might find something else of interest there. 

-Peter



From strombrg at dcs.nac.uci.edu  Wed Jul  9 17:42:50 2003
From: strombrg at dcs.nac.uci.edu (Dan Stromberg)
Date: Wed, 09 Jul 2003 14:42:50 -0700
Subject: syslogd?
Message-ID: 

Does anyone know of a syslogd (server side, not a client) implementation
in python?

I need something that'll help me ditch a particular kind of message
generated from the connections of a particular host (nagios), and the most
suitable thing I see on freshmeat appears to be in perl: metalog.  Sigh.
Perl again.

Anyone?



From op73418 at mail.telepac.pt  Wed Jul  9 13:06:36 2003
From: op73418 at mail.telepac.pt (Gonçalo Rodrigues)
Date: Wed, 09 Jul 2003 18:06:36 +0100
Subject: QUESTION
References: 
Message-ID: 

On Wed, 9 Jul 2003 10:09:41 EDT, Matt5883 at aol.com wrote:

>
>What is python 2.1.1?  How did it get on my computer? Is it a necessary 
>program?  Can I safely delete it/remove it?  If so how?  I do not recall 
>downloading it.  Does it come bundled with some other program? Maybe one of my kids did 
>it.  I do not see enough information on your site to make these 
>determinations.  I have a Compaq 5184 with OEM Win 98 installed...I do not ever recall 
>seeing "python" in the programs.  I have been having alot of problems with my 
>computer lately and I am removing unecessary "junk"
>Thanks,
>Matt
?
This is the funniest post I have seen in weeks. Involuntary humour
maybe, but thanks a lot anyway for giving me a good frame-shaking
laugh -- I was needing that.

With my best regards,
G. Rodrigues



From Matt5883 at aol.com  Wed Jul  9 10:09:41 2003
From: Matt5883 at aol.com (Matt5883 at aol.com)
Date: Wed, 9 Jul 2003 10:09:41 EDT
Subject: QUESTION
Message-ID: <4e.1efa9c3f.2c3d7c25@aol.com>

What is python 2.1.1?  How did it get on my computer? Is it a necessary 
program?  Can I safely delete it/remove it?  If so how?  I do not recall 
downloading it.  Does it come bundled with some other program? Maybe one of my kids did 
it.  I do not see enough information on your site to make these 
determinations.  I have a Compaq 5184 with OEM Win 98 installed...I do not ever recall 
seeing "python" in the programs.  I have been having alot of problems with my 
computer lately and I am removing unecessary "junk"
Thanks,
Matt




From simonb at webone.com.au  Fri Jul 11 02:49:27 2003
From: simonb at webone.com.au (Simon Burton)
Date: Fri, 11 Jul 2003 16:49:27 +1000
Subject: text file edit object
Message-ID: 

# Needed to edit a text file like a list:

file = TextFile( "foo.txt" )
del file[:-10] # remove last 10 lines
file.save()

# Ended up writing this:

#!/usr/bin/env python

from tempfile import mktemp
import shutil
import sys

class TextFile(list):
  def __init__(self,name):
    file = open( name )
    self[:] = file.readlines()
    self.name = name
  def save(self):
    temp = mktemp()
    file = open( temp, "w" )
    file.writelines( self )
    file.close()
    #tgt = "_"+self.name
    tgt = self.name
    #print temp, tgt
    shutil.copy( temp, tgt )


# Is there Another Way?

# Simon Burton.




From m at moshez.org  Wed Jul 16 07:05:51 2003
From: m at moshez.org (Moshe Zadka)
Date: 16 Jul 2003 11:05:51 -0000
Subject: Testers wanted - new Python DHTML framework
In-Reply-To: 
References: 
Message-ID: <20030716110551.3667.qmail@green.zadka.com>

On Wed, 16 Jul 2003, David McNab  wrote:

>  - easy to learn and use

Have you demonstrated it? Did you give the documentation to someone,
and had him writing useful software? Or is this just an assumption
based on the fact that you find it easy to use, and did not have
to learn it?

>  - lets you build your pages with a simple, intuitive and coherent
>    document object model (DOM)

Is your DOM more simple, intuitive and coherent than minidom? microdom?
DOM is usually used in reference to the W3C standard. If you deviate
from the standard, it's probably best not to call what you have "DOM".

>  - extremely extensible

Did you try to extend it, and are reporting success? With two different
extension directions? Or is this, again, an assumption?

> , lends itself well to templating

You mean each person has to implement templating on his own? Or does
it have a templating system?

>  - oersistent datastore that is stored on browser as compressed cookes.
>    secured via hmac/sha1, can store 10-25k of data on browser.

That probably depends on the browser. The standard states:
'''
      * at least 4096 bytes per cookie (as measured by the size of the
        characters that comprise the cookie non-terminal in the syntax
        description of the Set-Cookie header)
'''
which means that cookies might get cut off or not stored at all by
the client. You might be splitting the cookies off transparently, which
should let you go up to 80k, but would probably make the job of anyone
wanting to send his own cookies hard.

The standard also says, however,
'''
Applications should use as few and as small cookies as possible, and they
should cope gracefully with the loss of a cookie. 
'''
[All quotes are from http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2109.html]

>    Accessed in
>    python code by simply reading and setting attributes of an object

It also matters, probably, that you use a secure RNG generator for the
"secret" in the sha1/hmac schemes, otherwise a malicious client can still
force you to execute code. The RNG in Python, for example, is
'''
        if a is None:
            # Initialize from current time
            import time
            a = long(time.time() * 256)
'''
Since your server graciously sends the time, then if this is done via
CGI the client can try guessing several values for the time. CGI applications
usually run less than five seconds, so the client can even perform a brute
force attack.

> All feedback gratefully received.

Enjoy!
-- 
Moshe Zadka -- http://moshez.org/
Buffy: I don't like you hanging out with someone that... short.
Riley: Yeah, a lot of young people nowadays are experimenting with shortness.
Agile Programming Language -- http://www.python.org/




From intentionally at blank.co.uk  Sun Jul 13 12:01:32 2003
From: intentionally at blank.co.uk (Stephen Horne)
Date: Sun, 13 Jul 2003 17:01:32 +0100
Subject: removing spaces from front and end of filenames
References:  <3F10BABB.D548961B@alcyone.com> <93f5c5e9.0307130744.7e9d8377@posting.google.com>
Message-ID: <7mv2hvgm2k16h761tui5j7jikbd4l4etqd@4ax.com>

On 13 Jul 2003 08:44:05 -0700, hokiegal99 at hotmail.com (hokiegal99)
wrote:

>Erik Max Francis  wrote in message news:<3F10BABB.D548961B at alcyone.com>...
>> hokiegal99 wrote:
>> 
>> > This script works as I expect, except for the last section. I want the
>> > last section to actually remove all spaces from the front and/or end
>> > of
>> > filenames. For example, a file that was named "  test  " would be
>> > renamed "test" (the 2 spaces before and after the filename removed).
>> > Any
>> > suggestions on how to do this?
>> 
>> That's what the .strip method, which is what you're using, does.  If
>> it's not working for you you're doing something else wrong.
>
>for root, dirs, files in os.walk('/home/rbt/scripts'):
>     for file in files:
>         fname = (file)
>         fname = fname.strip( )
>print fname
>
>When I print fname, it prints the filenames w/o spaces (a file named "
>test " looks like "test"), but when I ls the actual files in the
>directory they still contain spaces at both ends. That's what I don't
>understand. It seems that .strip is ready to remove the spaces, but
>that it needs one more step to actually do so. Any ideas?

If you mean looking at the list, the stripped results aren't in there
because you didn't put them there. See my other reply.

If you literally mean 'in the directory' (ie looking using a file
browser) you need to do yet another step - to apply the stripped names
back to the files using the 'os.rename' function. I'm not familiar
with os.walk and can't find the documentation, so the following is
probably wrong, but I'd suggest something like...

for root, dirs, files in os.walk('/home/rbt/scripts'):
  for file in files:
    os.rename(file, file.strip ())

This does seem very unlikely, though.




From bokr at oz.net  Mon Jul 14 14:16:08 2003
From: bokr at oz.net (Bengt Richter)
Date: 14 Jul 2003 18:16:08 GMT
Subject: anything like C++ references?
References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com>          <1058154004.286325@yasure>
Message-ID: 

On Mon, 14 Jul 2003 03:40:05 -0000, "Donn Cave"  wrote:

>On Sun, 2003-07-13 at 20:32, Aahz wrote:
>> In article ,
>|> Ian Bicking   wrote:
>|>>
>|>> (Admittedly, some confusion may occur because these very different
>|>> operations use the same syntax:
>|>>
>|>>  x = 10
>|>>  x[0] = 10
>|>>  obj.x = 10
>|>>
>|>> The second and third are entirely different from the first.)
>|> 
>|> No, they aren't.  They are precisely the same; they just have different
>|> assignment targets.
>|
>| Sure they are different.  The first is a primitive operation binding the
>| variable x.  The second gets x, and calls x.__setitem__(0, 10), and the
>| third is equivalent to setattr(obj, 'x', 10).
Which might turn out to be equivalent to object.__setattr__(obj, 'x', 10)
or obj.__setattribute__('x', 10) or obj.__class__.__dict__['x'].fset(obj, 10) or ...

It depends on what you mean by 'targets'. I argued that the three left hand
expressions all *ultimately* result in some machine level pointer variable being set
in some object's internal representation to point to the representation of the object
resulting from evaluating the right hand side, and in that sense all the assignments
have the same ultimate semantics. Some pointer in some composite object is set to point
to another object.

Depending on the left hand object actually involved, we use different expressions to
retrieve the pointer (and often you have a choice, e.g., x.y or x.__dict__['y'] or getattr(x,'y')
or vars(x).get('y') etc., some of which might not be valid. Even plain x might sometimes be
retrieved by sys._getframe().f_locals.get('x').

>
>I wonder if this is a good example of a mutability thing that really
>is kind of missing to the detriment of Python.
>
>If you want to support user-implemented sequences (as Python does)
>but make Aahz's ``precisely the same'' assertion true in the sense
>you're taking it - then I think the user-implemented indexing function
>would have to return a reference to the index location.
>

I guess you could define something like your *loc below, but you'd have to be
willing to spell it loc.star when you used it.

class Loc(object): #XXX# untested !!
    def __init__(self, theArray, theItem=0): self._theArray=theArray; self._theItem=theItem
    def _get_it(self): return self._theArray[self._theItem]
    def _set_it(self,v): self._theArray[self._theItem] = v
    star = property(_get_it, _set_it)

>   class UserArray:
>       ...
>       def __item__(self, index):
            return Loc(self, index)
>           return &self.internal_array[index]
>
>   userArray[5] = 1
>   (python internal)
>       loc = UserArray.__item__(userArray, 5)
        loc.star = 1
>       *loc = 1
>
>   if userArray[6] == 
>   (python internal)
>       loc = UserArray.__item__(userArray, 6)
        return loc.star 
>       return *loc
>
>There are other places where instead we use some kludge with a
>mutable container type, but in this case I don't think there's
>a way to get around it.  So whether we like the idea or not,
>assignment to a user-implemented sequence doesn't have to involve
>any assignment at all, because Python lacks the "pointer" type
>(or "target" type, if you prefer) that would be required to
>implement that.

Or you could say the implementation is internal and you have
to use the right spellings to effect the semantics indirectly.
I.e., op[i]=newitem spells *p = newitem internally (names obviously not directly related):

int
PyList_SetItem(register PyObject *op, register int i,
               register PyObject *newitem)
{
    ...
    p = ((PyListObject *)op) -> ob_item + i;
    olditem = *p;
    *p = newitem;
    Py_XDECREF(olditem);
    return 0;
}

Regards,
Bengt Richter



From LogiplexSoftware at earthlink.net  Tue Jul 15 14:33:51 2003
From: LogiplexSoftware at earthlink.net (Cliff Wells)
Date: 15 Jul 2003 11:33:51 -0700
Subject: Regarding Thread pooling
In-Reply-To: <007801c34ac0$f166faa0$31001eac@ud.cybage.com>
References: <007801c34ac0$f166faa0$31001eac@ud.cybage.com>
Message-ID: <1058294031.1563.20.camel@software1.logiplex.internal>

On Tue, 2003-07-15 at 04:05, sujata wrote:
> Hi,
>         I have a query regarding threads.
> Is it possible to create thread pools in python.i.e. create threads
> and then retrieve the memory allocated to it so that the same threads
> can be used over and over again rather than creating new threads each
> time i wish to execute functions many times. If its possible plz do
> let me know how to do so.
> Can one have control over memory this way?

Not exactly in the terms you put it in, but yes, more or less.  Use a
Queue (see the standard library) and have your pool of threads wait on
it.  When there's work to be done, put it on the queue.

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





From tzot at sil-tec.gr  Fri Jul 18 10:24:48 2003
From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou)
Date: Fri, 18 Jul 2003 17:24:48 +0300
Subject: Unicode question
References: 
Message-ID: <6f0ghvksjno3nts08n553ufq2gq3uavi6l@4ax.com>

On Thu, 17 Jul 2003 17:47:30 +0200, rumours say that Gerhard H?ring
 might have written:

>>>> u"???"
>u'\x84\x94\x81'
>
>(Python 2.2.3/2.3b2; sys.getdefaultencoding() == "ascii")
>
>Why does this work?
>
>Does Python guess which encoding I mean? I thought Python should refuse 
>to guess :-)

Same here, it assumes iso8859-1, which has nothing to do with my
Windows, Linux and Irix systems (ie Windows has cp1253, and I tried Irix
and Linux pythons with el_GR settings).
-- 
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.



From tjreedy at udel.edu  Tue Jul  1 00:13:43 2003
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 1 Jul 2003 00:13:43 -0400
Subject: Suggesting for overloading the assign operator
References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com>
Message-ID: 

"Rim"  wrote in message
news:6f03c4a5.0306301931.3f15fbb7 at posting.google.com...
> Hi,
>
> I have been thinking about how to overload the assign operation '='.

Assignment is a statement, not an operator, and therefore not
overloadable .  This is an intentional design decision that GvR will
not change.

TJR





From pinard at iro.umontreal.ca  Wed Jul 23 18:10:25 2003
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=)
Date: 23 Jul 2003 18:10:25 -0400
Subject: Reading Keyboard Scan Codes
In-Reply-To: <23daa443.0307231129.12d7ccf5@posting.google.com>
References: <23daa443.0307231129.12d7ccf5@posting.google.com>
Message-ID: 

[Michael Bendzick]

> Is there a simple way in python to read a keyboard scan code?  I'm working
> on a shell script that interfaces with a proprietary keyboard device
> (extra buttons) and need to be able to distinguish between those keys.

Within Linux in console mode, you merely do:

    os.system('kbd_mode -k')

to read key codes, which might be what you want, or:

    os.system('kbd_mode -s')

to really read raw scan codes.  To get back on your feet, do:

    os.system('kbd_mode -a')

Beware that you can easily burn yourself if your program fails to restore
normal mode, as per last example.  Use try/finally!  You should probably use
the `curses' module for preparing to read codes one byte at a time.[1]

However, I do not know if reading scan codes or key codes is easily done
within X, nor on MS-Windows.  I would like finding or discovering recipes in
this area.  So, please share your tricks in this area, if any! :-)

--------------------
[1] I was given two different C programs written originally for QNX and its
own special `term' library, to be quickly ported to Linux, without rewriting
them if possible.  To achieve this, I wrote a compatibility module in C, and
a more bulky keyboard driver module in Python, meant for key code assembly
into curses key events, and for any special keyboard processing.  The link
between all parts was made using Pyrex, and a bit of Makefile trickery...

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




From frobozz_electric at hotmail.com  Thu Jul 17 11:14:42 2003
From: frobozz_electric at hotmail.com (Sean Ross)
Date: 17 Jul 2003 15:14:42 GMT
Subject: Co-routines
References:  <3F16A34A.5742F54F@engcorp.com>  
Message-ID: 

>     def _done(self):
>         return not [f for f in (f1,f2) if f.hasnext()]

# that should have been
def _done(self):
        return not [f for f in self.steppers if f.hasnext()]





From bostjan at bostjan-pc.mf.uni-lj.si  Wed Jul 23 04:25:59 2003
From: bostjan at bostjan-pc.mf.uni-lj.si (bostjan at bostjan-pc.mf.uni-lj.si)
Date: Wed, 23 Jul 2003 08:25:59 +0000 (UTC)
Subject: pyui on Linux
Message-ID: 


Hello !


Anybody managed to use pyui on Linux? It seems it uses WGL and AFAIK it
only runs on Win32, am I right?

B.



From fgeiger at datec.at  Tue Jul 29 12:49:12 2003
From: fgeiger at datec.at (F. GEIGER)
Date: Tue, 29 Jul 2003 18:49:12 +0200
Subject: VideoCapture and camera settings.
References: 
Message-ID: <3f26a509@news.swissonline.ch>

It's been a while since, but IIRC I used Paintshop Pro to config my web cam.

Cheers
Franz

"W F"  schrieb im Newsbeitrag
news:mailman.1059464577.7396.python-list at python.org...
> I haven't done much experimentation, so I am hoping someone will be able
to
> save me the trouble.
>
> Does anyone know how to specify quickcam settings such as exposure time
and
> gain when using snapshot in VideoCapture module?
>
> Thanks!
>
> Wes
>
> _________________________________________________________________
> MSN 8 with e-mail virus protection service: 2 months FREE*
> http://join.msn.com/?page=features/virus
>
>





From news at exultants.org  Mon Jul  7 00:50:27 2003
From: news at exultants.org (Van Gale)
Date: Mon, 07 Jul 2003 04:50:27 GMT
Subject: python blogging software
In-Reply-To: 
References: 
Message-ID: <3F08FB71.3050707@exultants.org>

As Greg mentioned there are a few Zope products that can be used for 
weblogging:

http://plone.org
http://zwiki.org

Outside of Zope here are a few choices:

http://pyds.muensterland.org/
http://www.pycs.net/
http://www.myelin.co.nz/bzero/
http://roughingit.subtlehints.net/pyblosxom
http://pyrite.org/byline/




From mindhog at enduden.spam.filter.com  Sat Jul 26 15:55:35 2003
From: mindhog at enduden.spam.filter.com (Michael Muller)
Date: Sat, 26 Jul 2003 15:55:35 -0400
Subject: Static typing
References:  <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net>
Message-ID: 

Well, it appears that I have inadvertantly trolled c.l.p.  I humbly
apologize.  I really just wanted to know what the status of the issue
was.

FWIW, I do favor the addition of optional static typing for the two
reasons Scott described - interface documentation and optimization.

-- 
Remove the spam and filter components to get my e-mail address.




From justinjohnson at fastmail.fm  Tue Jul  8 11:00:33 2003
From: justinjohnson at fastmail.fm (Justin Johnson)
Date: Tue, 08 Jul 2003 09:00:33 -0600
Subject: win32service problems
In-Reply-To: 
References:    
Message-ID: <20030708150033.628BD380B7@www.fastmail.fm>

Nope, nothing like that at all.  The servers are setup the same, the
domain account is accessible from all and has the same policy settings
and is a member of the administrators group.  This is the only python
software running on the machines.

I'm pretty sure this has to do with the win2k limitations.  I'll just
have to tweak the registry and reboot the machines, which will take a
little while since these machines are actively used by people.

Thanks.
-Justin

On Mon, 7 Jul 2003 22:38:35 +0200, "Tomas Christiansen"
 said:
> Justin Johnson wrote:
> > Windows 2000.  Aftering searching google for similar problems I'm
> > beginning to think I hit the dreaded shared section memory problem on
> > win2k.  Ugh...
> 
> You can't see any differences between the working and not-working
> servers,
> like:
>  - domain controller or not
>  - list of members of the local administrators group
>  - other services running Python
>  - ...
> 
> -------
> Tomas
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




From bignose-hates-spam at and-benfinney-does-too.id.au  Wed Jul 30 22:18:38 2003
From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney)
Date: 31 Jul 2003 12:08:38 +0950
Subject: Misuse of 
References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> 
Message-ID: 

On Wed, 30 Jul 2003 18:20:51 -0700, Sean 'Shaleh' Perry wrote:
> thou shalt always use even numbered indents.

More accurately, thou shalt always use even, factor-of-8 indents.
(Making 2 and 4 the only valid indent sizes.)

Ironically, this has its origins in the standard literal tab stop being
8 (which number thou shalt not alter).  Using factor-of-8 indent sizes
means that every literal tab stop falls on an indent column.  The irony
comes from the deprecation of using literal tabs for indent at all :-)

-- 
 \      "I put instant coffee in a microwave oven and almost went back |
  `\                                       in time."  -- Steven Wright |
_o__)                                                                  |
Ben Finney 



From news at yebu.de  Mon Jul 21 04:15:23 2003
From: news at yebu.de (Karl Scalet)
Date: Mon, 21 Jul 2003 10:15:23 +0200
Subject: Python dictionary syntax, need help
In-Reply-To: <56ba0aea.0307181142.7401aa02@posting.google.com>
References: <56ba0aea.0307181142.7401aa02@posting.google.com>
Message-ID: 

Crew Reynolds schrieb:
> I want to create a dictionary of note on/off timings and access it by
> the name of the object. The following code works for one row.
> 
> a = "Hammer1" 
> b = [5,45,45,45,45,50,55,57,59,61,60,59] 
> 
> notes = {a:b} 
> print notes["Hammer1"][3] 
> 
>>>>45 
> 
> 
> The problem is, I want to load the data from a file to populate
> variables a and b and build a dictionary for "Hammer1" thru
> "Hammer10". That way, I can stick the name of the object in the array
> index and receive a list of note timings that I can index with an
> ordinal as in the above example.
> 
> This is straight Python syntax but I'm hoping someone has done this or
> understands the syntax better than I.
> 
> Thanks! Alternative solutions to this concept would be greatly
> appreciated.

If there is no special format required for the text file, you could
invest a bit more in typing this text file, say, 'content.inp' like:

notes['hammer1'] = [1,2,3,4]
notes['hammer2'] = [2,3,4,5]
notes['hammer3'] = [3,4,5,6]
...

which on the other hand would simplify your code to:

...
notes = {}
execfile('content.inp')
# now notes is initialized with the content

I often do configurations/initialization stuff like this,
just using legal python syntax for such files.

Of course, my approach is not far from hardcoding the content
in the first place.

Karl




From rreagan at attbi.com  Wed Jul  2 04:04:26 2003
From: rreagan at attbi.com (Russell Reagan)
Date: Wed, 02 Jul 2003 08:04:26 GMT
Subject: My Big Dict.
References:  <20030702073735.40293ba2.christophe.delord@free.fr> 
Message-ID: 

"drs"  wrote

> f = open('somefile.txt')
> d = {}
> l = f.readlines()
> for i in l:
>     a,b = i.split('!')
>     d[a] = b.strip()

I have just started learning Python, and I have never used dictionaries in
Python, and despite the fact that you used mostly non-descriptive variable
names, I can still read your code perfectly and know exactly what it does. I
think I could use dictionaries now, just from looking at your code snippet.
Python rules :-)





From csad7 at yahoo.com  Sun Jul 20 18:15:53 2003
From: csad7 at yahoo.com (christof hoeke)
Date: Mon, 21 Jul 2003 00:15:53 +0200
Subject: xml processing and sys.setdefaultencoding (more info)
References: 
Message-ID: 

hi,
first thanks for the infos. i need to try the encoding declaration in the
python module.

some more details about the problem i had (regarding the posts by Alan and
Martin):

the original problem with the app was that the Pyana transformation
complained about the string "xml" when it came over as unicode. so i used
str(xml) but that gave the usual "ordinal not in range" error when the xslt
contained e.g. german umlauts. i did not tried that before...
setting the default encoding to utf-8 fixed that. the reason is not entirely
clear to me yet though.

- the used xslt stylesheets should have been in utf-8 as i did not state an
encoding explicitly
- xslt with latin-1 (iso8859-1) encoding should work too though
- xslt contains german umlauts ??? etc.
- i did extract parts of the xslt in python strings, yes

i read the other threads about unicode and also about PEP 0263. i have not
tried to set the encoding of the python file yet. but sounds promising.
i am wondering though, if i set the python file encoding to e.g. utf-8 and
then use a stylesheet with, lets say latin-1 encoding, i still have a
mismatch, havn't i?

if you are interested in the code, download it from
http://cthedot.de/pyxsldoc/
it is my first "bigger" python project, so the code is not the best i guess
and the version which does not work is still online. i need to put on the
version with the changed default encoding.

chris



christof hoeke wrote:
> hi,
> i wrote a small application which extracts a javadoc similar
> documentation for xslt stylesheets using python, xslt and pyana.
> using non-ascii characters was a problem. so i set the defaultending
> to UTF-8 and now everything works (at least it seems so, need to do
> more testing though).
>
> it may not be the most elegant solution (according to python in a
> nutshell) but it almost seems when doing xml processing it is
> mandatory to set the default encoding. xml processing should almost
> only work with unicode strings and this seems the easiest solution.
>
> any comments on this? better ways to work
>
> thanks
> chris





From mis6 at pitt.edu  Wed Jul  2 10:23:05 2003
From: mis6 at pitt.edu (Michele Simionato)
Date: 2 Jul 2003 07:23:05 -0700
Subject: Circular Inheritance
References: 
Message-ID: <2259b0e2.0307020623.a4ba8c@posting.google.com>

jinal jhaveri  wrote in message news:...
> Hi All,
> 
> I have one question regarding circular inheritance
> 
> I have 3 files
> 
> 1) A.py , having module A and some other modules
> 2) B.py having module B and some other modules
> 3) C.py having module C and some other modules
> 
> Now I want to import Module C in B.py
> 
> but C requires A.py 
> and A requires B.py
> 
> so 
> 
> B requires C
> C requires A
> A requires B
> 
> and when I try to do this using 
> 
> from ...import....
> it tells me that you cannot import this. 
> 
> So any suggestions on this?
> 
> thank you
> Jinal

In theses circumstances, I find useful the "execfile" built-in. 
With "execfile" you can split a big module with internal references
in various files. For instance you could split your module in three
files and do something like

#module M
execfile('M1.py')
execfile('M2.py')
execfile('M3.py')

   Michele



From kevin at cazabon.com  Wed Jul 30 20:31:27 2003
From: kevin at cazabon.com (Kevin Cazabon)
Date: 30 Jul 2003 17:31:27 -0700
Subject: urlretrieve a file whose name has spaces in it
References: <10caf2e2.0307291439.33d9fcc3@posting.google.com>
Message-ID: <5a4226f0.0307301631.3dd0c00f@posting.google.com>

You can easily escape spaces with "%20"

as in:


urllib.urlretrieve("http://website.com/path/string string1
foo.doc".replace(" ", "%20"), "local_file")



hp at rentec.com (HP) wrote in message news:<10caf2e2.0307291439.33d9fcc3 at posting.google.com>...
> I am using urllib.urlretrieve() to download a file from a web site.
> THe trouble is that the file name has spaces in it,
> such as "string string1 foo.doc".
> 
> The statement:
> urllib.urlretrieve("http://website.com/path/string string1 foo.doc",
> "local_file");
> 
> produces local_file which contains the following one line:
> ErrorThe parameter is
> incorrect. 
> 
> What is the correct way of specifying the this file in urlretrieve() ?
> 
> thanks
> HP



From adechert at earthlink.net  Wed Jul 23 15:08:12 2003
From: adechert at earthlink.net (Alan Dechert)
Date: Wed, 23 Jul 2003 19:08:12 GMT
Subject: Voting Project Needs Python People
References:      <7x65lv31hf.fsf@ruckus.brouhaha.com>   <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> 
Message-ID: 

"Andrew Dalke"  wrote in message
news:bfkch9$is4$1 at slb4.atl.mindspring.net...
> Alan Dechert:
> > catch it.  If one percent of the electronic votes were altered (evenly
> > distributed), you will find one mismatch for sure after checking only a
> > dozen or two ballots.
>
> Actually, around 70 ballots.
>
> The odds of finding one ballot to be wrong is 1%, so there's a 99%
> chance that it's unaltered.  There's a 0.99*0.99 chance that two are
> unaltered, and in general a 0.99**n chance that n are unaltered.
>
> To get even odds of noticing an error requires
>
>   0.99**n == 0.5
>   --> log(0.99)*n == log(0.5)
>
> >>> math.log(0.5) / math.log(0.99)
> 68.967563936528421
> >>>
>
> about 70 verifications.
>
 A likely story.  I actually took combinatorics and a class in statistics in
college.  But that was a long time ago.  Since then, many brain cells have
died, tragically.

BTW, do you know about cumulative binomial distribution?  I think we need to
include a tool like this to give us some "C.L" (confidence level) short of
verifying that every single paper ballot matches its electronic counterpart.

http://www.reliasoft.com/newsletter/2q2001/cumulative_binomial.htm

What I really want is a calculator.  Do you know of a free calculator for
this?  If not, could you make one? (for free, of course).

Alan Dechert





From newsgroups at jhrothjr.com  Sun Jul 20 07:06:42 2003
From: newsgroups at jhrothjr.com (John Roth)
Date: Sun, 20 Jul 2003 07:06:42 -0400
Subject: Tk mainloop()
References: 
Message-ID: 

"Petr Evstratov"  wrote in message
news:mailman.1058675670.11192.python-list at python.org...
> Hi, I have a question: how do you execute an arbitrary function in Tk
fooBar.mainloop()?
>
> I need to change the contents of a label every second, but I think I will
also use some other functions as well...
>
> I hope that someone will answer my question, because I have been looking
for an answer for 3 days, asking people, searching Google... and still have
not found anything useful...

I'd probably use a separate thread. Can't tell you exactly how to
do it, but that's the approach I'd take.

John Roth
>
>                                    Thanks, Pete
>





From rganesan at myrealbox.com  Thu Jul 10 05:49:20 2003
From: rganesan at myrealbox.com (Ganesan R)
Date: Thu, 10 Jul 2003 15:19:20 +0530
Subject: Python vs PHP
References:   <3F0D2827.4070501@mxm.dk>
Message-ID: 

>>>>> "Max" == Max M  writes:

> Afanasiy wrote:
>> Python web development is fragmented.

> Ahem ... How os Python web development fragmented? Most of it probably
> takes place in the Zope world.

How about the fact if you want something simpler than Zope you cannot point
to a single framework and say use this one? I must admit that I haven't
actually worked with any of the web development kits. As a casual observer
and a (mostly) lurker in this news group web development does appear to be a
bit fragmented. 

I agree this is the case in the Python GUI world too. However, at least I
get the impression that wxPython, PyQT and PyGtk all are reasonably good
choices. I don't think you can say that for web development. At least not
yet.

Ganesan

-- 
Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/
1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832  6798 15E0 02BA 5D8C 12EA



From mwilson at the-wire.com  Mon Jul 14 12:52:47 2003
From: mwilson at the-wire.com (Mel Wilson)
Date: Mon, 14 Jul 2003 12:52:47 -0400
Subject: A few beginning questions
References: <3f129a8a$1@mail.hmgcc.gov.uk> 
Message-ID: 

In article ,
Harry George  wrote:
>"richardc"  writes:
>> Im looking for an agument parsing library (from the command line), Ive come
>> across optik and argtools.  What other ones are there are any of them any
>> good, is there a 'standard' lib for doing this.

>1. args: I use getopt, which does the job.  The idiom is:
>if __name__ == '__main__':
>    opts,pargs=getopt.getopt(sys.argv[1:],'hvd',
>                 ['help','version','debug',
>                  'bb='])
>    for opt in opts:
>        if opt[0]=='-h' or opt[0]=='--help':
>            print modname+": version="+__version__
>            usage()
>            sys.exit(0)
>        elif opt[0]=='-v' or opt[0]=='--version':
>            print modname+": version="+__version__
>            sys.exit(0)
>        elif opt[0]=='-d' or opt[0]=='--debug':
>            debug_p=1
>        elif opt[0]=='--bb':
>            opt_b=opt[1]
>

Although I really would recommend one change:


     for opt, val in opts:
         if opt in ('-h', '--help'):
             print modname + ": version=" + __version__
             usage()
             sys.exit(0)
,,,
         elif opt == '--bb':
             opt_b = val



        Regards.        Mel.



From peter at engcorp.com  Sun Jul 20 00:02:20 2003
From: peter at engcorp.com (Peter Hansen)
Date: Sun, 20 Jul 2003 00:02:20 -0400
Subject: Python vs ...
References: <3f19dad1@news.syd.ip.net.au>  <3f19ee33@news.syd.ip.net.au>
Message-ID: <3F1A144C.B386C7FD@engcorp.com>

Ray Smith wrote:
> 
> "Tricky" was probably a bad word ... "difficult" might be a better word.

No, "tricky" is just fine, though you really meant "tricky problem".

You _did_ say "well written piece of code", and most of us understood
what you meant without any problem. ;-)

-Peter



From shrom at admin.zzn.com  Thu Jul 31 09:58:20 2003
From: shrom at admin.zzn.com (Shrom)
Date: Thu, 31 Jul 2003 15:58:20 +0200
Subject: Retrieve source filename
Message-ID: <3f29207d$0$24768$626a54ce@news.free.fr>

Hi,

I know that you can retrieve main file name with sys.argv[0] and file name
for a module with modulename.__file__ but is there a common way to retrieve
file name for both main program and modules as the __FILE__ constant in PHP
?





From wilkSPAM at OUTflibuste.net  Mon Jul 28 15:42:59 2003
From: wilkSPAM at OUTflibuste.net (Wilk)
Date: Mon, 28 Jul 2003 21:42:59 +0200
Subject: Python vs. Perl vs. PHP?
References: <7b454334.0307281002.41dae81b@posting.google.com> 
Message-ID: <87he56bfp8.fsf@flibuste.net>

"Diez B. Roggisch"  writes:

> Fazer wrote:
>
>> Hello,
>> 
>> I am an avid user of PHP and I am just fooling around with Python for
>> now.  I originally wanted to know which one is faster.  As in, works
>> faster.  So far, I think PHP is the fastest for dynamic web-content.
>> Am I wrong?
>
> Definitely. See here:
>
> http://www.bagley.org/~doug/shootout/craps.shtml

has somebody tried to run this bench with python2.3 ?

-- 
William Dode - http://flibuste.net



From Olivier.POYEN at clf-dexia.com  Tue Jul 29 05:28:23 2003
From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL))
Date: Tue, 29 Jul 2003 11:28:23 +0200
Subject: howto redirect stdout/stderr into a wxPython textctrl?
Message-ID: <8963D6370B323E4AA3241200F0EAF7318C100E@FCEXVEXM002.dcl.int.dexwired.net>



> -----Message d'origine-----
> De : newgene [mailto:newgene at bigfoot.com]
> Envoy? : lundi 28 juillet 2003 18:53
> ? : python-list at python.org
> Objet : howto redirect stdout/stderr into a wxPython textctrl?
> 
> 
> Hi, group,
>     I guess it is a simple question for you, but it puzzles me for a
> while.
>     I use a wxTextCtrl in my application for output result and any
> exception msg. I know I can add new msg onto wxTextCtrl by WriteText()
> method. But I have a function imported from another module and in this
> function all results are output by "print". I am wondering if I can
> redirect stdout and stderr into the wxTextCtrl object, so that all
> output from that function will be shown up on wxTextCtrl box and I
> don't need modify the current code for that function.
> 
> Thank you.
> 
> 
> Chunlei
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


class myOutForWxText:
    def __init__(self,aWxTextCtrl):
		self.out=aWxTextCtrl

    def write(self,string):
		self.out.WriteText(string)


myout=myOutForWxText(myWxTextInstance)
import sys
sys.stdout=myout

Then, when you want to recover the real stdout
sys.sdtout=sys.__stdout__

Beware: since the sys module is imported once, all the print statemens will commit to this 'myout' things.

The point is to create an object which has a write method, and assign sys.stdout to it.


HTH,

---OPQ
-------------- next part --------------
-----------------------------------------------------------------

Ce message est confidentiel ; son contenu ne represente en aucun

cas un engagement de la part de Dexia Credit Local ou de Dexia

CLF Banque. Toute publication, utilisation ou diffusion, meme

partielle, doit etre autorisee prealablement par l'emetteur. Si

vous n'etes pas destinataire de ce message, merci d'en avertir

immediatement l'expediteur.



This message is confidential ; its contents do not constitute a

commitment by Dexia Credit Local or Dexia CLF Banque. Any

unauthorised disclosure, use or dissemination, either whole or

partial, is prohibited. If you are not the intended recipient of

the message, please notify the sender immediately.

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

Consultez notre site internet www.dexia-clf.fr

La cle d'une gestion optimisee du secteur public local

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

From isaac at blueapples.org  Thu Jul 31 15:31:19 2003
From: isaac at blueapples.org (Isaac Raway)
Date: 31 Jul 2003 12:31:19 -0700
Subject: Controlling a spawned process
Message-ID: <5f98b3f0.0307311131.3b4824e1@posting.google.com>

I want to start a console application on a Windows 2000 machine and
control it's I/O. pexpect is exactly what I want, but it doesn't work
on Windows.

Does anyone know of another module similar to pexpect that does work
on windows?



From fdij at oce.nl  Thu Jul 31 12:30:55 2003
From: fdij at oce.nl (Fons Dijkstra)
Date: Thu, 31 Jul 2003 18:30:55 +0200
Subject: Problem with inserting dates using mx.ODBC.Windows driver
Message-ID: <1059669056.14359@news-ext.oce.nl>

Hello,

I'm using the mx.ODBC.Windows package in order to read/write a MSAccess
database. Everything works fine apart from the DATE format handling. I'm
using the default "datetimeformat" (i.e. DATETIME_DATETIMEFORMAT) as
suggested. The date columns in the MSAccess database have "Short Date"
format.

When I read a DATE item everything works fine, like:

>>> conn = mx.ODBC.Windows.connect(database)
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT * FROM table")
>>> data = cursor.fetchall()
>>> print data
[(..., , ...)]

But when I try to update the table I get a ProgrammingError, like:

>>> date = mx.ODBC.Windows.Date(2003, 07, 31)
>>> conn = mx.ODBC.Windows.connect(database)
>>> cursor = conn.cursor()
>>> cursor.execute("INSERT INTO table (..., DATE, ...) VALUES (..., ?,
...)", (..., date, ...))
ProgrammingError: Syntax Error in INSERT INTO statement.

Is it possible to use the mx.DateTime type for MSAccess databases? If so,
how should it be done? If not, how can I insert dates into a MSAccess
database?

Thank you in advance, Fons





From llafba at gmx.net  Thu Jul 10 13:36:16 2003
From: llafba at gmx.net (Tom)
Date: Thu, 10 Jul 2003 19:36:16 +0200
Subject: replace value of a specific position
Message-ID: 

Hi,

I want to replace a specific part of a string. I tried replace but this 
doesn't work the way I want it, because it checks and replaces all 
values and not the position (index).

t = '010010101001001110100101010111'
t = t.replace(t[5], '2')

This is just a bad example of what I tried. It produces this output:

212212121221221112122121212111

But I wanted:

010012101001001110100101010111

I couldn't find anything in the python library. I probably looked at the 
wrong place! :-) That's why I would appreciate your help.

Thank you very much, Tom




From davidcfox at post.harvard.edu  Wed Jul 30 16:57:04 2003
From: davidcfox at post.harvard.edu (David C. Fox)
Date: Wed, 30 Jul 2003 20:57:04 GMT
Subject: Dict to "flat" list of (key,value)
In-Reply-To: 
References:  
Message-ID: 

David C. Fox wrote:

Oops - a mistake and an omission

> 4.  and then reduce that to a list of tuples with
> 
>     reduce(operator.add, lol)

You need to import the operator module first.

>     def flatten(u):
>         if isinstance(u[1], type([])):
>             return (u[1], [u[2]])
>         return map(lambda x: (u[0], x), u[1])

I got my cases reversed - that should be "if not isinstance...




From klappnase at freenet.de  Sat Jul 19 20:20:05 2003
From: klappnase at freenet.de (klappnase)
Date: 19 Jul 2003 17:20:05 -0700
Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively
References: 
Message-ID: <9a410299.0307191620.7fe274ab@posting.google.com>

"Raseliarison nirinA"  wrote in message news:...
> hi all,
> i found an unanswered question at
> http://www.faqts.com/knowledge_base/index.phtml/fid/538
> with possible response below. i've tried to send it at
> faqt.python but can't figure out how to edit the page. so i put it here.
> i want to kwon if this can convert all wave file. is there other
> encodage than 8 or 16 bits for .wav files?
> any bug and comment are welcome
> 
> --
> nirinA
> 
Hi,

I think there might be at least 24 bit wav-files, if you have a
soundcard that supports 24 bit, may be even more, for professional use
or so.

Regards

Michael



From http  Sun Jul 20 23:36:09 2003
From: http (Paul Rubin)
Date: 20 Jul 2003 20:36:09 -0700
Subject: Possible use of Python for a voting machine demo project -- your feedback requested
References:   <7xllus94t8.fsf@ruckus.brouhaha.com>   <7x1xwk8z14.fsf@ruckus.brouhaha.com> 
Message-ID: <7xn0f8a6vq.fsf@ruckus.brouhaha.com>

"Alan Dechert"  writes:
> The absentee system would work very much like the poll site system.  The
> voter would see exactly the same screens with either one.  The printout
> would look exactly the same.  The ballot electronic record would wind up in
> exactly the same format as poll site ballots.  Here are some advantages
> highlighted in the proposal:
> 
> ? Voter does not need to plan
> ? Avoids mailing of absentee request as request is made and granted
> on-the-spot
> ? No need for the county to print and mail costly absentee ballot materials
> ? Tabulation of absentee votes available on Election Day
> ? Seamless integration with poll site system
> ? Secret ballot and voter anonymity preserved
> ? Greatly reduces potential for absentee vote fraud

Yes, that's much better than mail-in absentee voting.  Of course
polling stations would have to be installed at US embassies abroad,
military bases and vessels, etc.

> The most persistent type of corruption has to do with campaigns that
> overwork the absentee ballots -- helping voters make sure they vote.
> Sometimes it's a fine line.  A campaign worker might stop by an elderly
> voter to make sure s/he has mailed in the absentee ballot, and the voter
> asks for assistance -- or the campaign worker offers assistance.  How much
> assistance constitutes fraud where a voter is really not sure what to do?  I
> don't have any numbers but in 2000 a lot of older folks in Florida were
> getting assistance with obtaining and sending in their absentee ballots.

It was much worse than that, and it wasn't limited to older folks.
The Governor of Florida himself, Jeb Bush, sent letters to registered
Republicans on state letterhead encouraging them to cast illegal
absentee ballots:

  http://www.orlandosentinel.com/news/nationworld/sns-flavotes.story

Xavier Suarez, the guy who was elected mayor of Miami by absentee
ballot fraud (he was thrown out of office a few weeks later when the
fraud was established) was apparently part of that operation and 
actually filled in absentee ballots for people in Miami-Dade County.

Then there was the massive doctoring of defective absentee ballot
applications--but only for one party--in Martin and Seminole counties
(a third degree felony in Florida, http://www.campaignwatch.org/semdtl.htm).

See

  http://www.failureisimpossible.com/floridafollies/absentee.htm

for links to some more stories.  Anyway you get the general idea.



From aahz at pythoncraft.com  Sun Jul 13 21:43:41 2003
From: aahz at pythoncraft.com (Aahz)
Date: 13 Jul 2003 21:43:41 -0400
Subject: anything like C++ references?
References: <000301c348c7$3c501980$21795418@dell1700>   
Message-ID: 

In article ,
Stephen Horne   wrote:
>
>In computer science, a variable is a named binding to a value.
>Operations on that variable may rebind it to a different value, but
>values don't change behind your back. A pointer is, in effect, a value
>which indirectly refers to another (possibly anonymous) variable. A
>pointer is something you specifically request, and by doing so you
>allow that the 'variable' being indirectly referenced may be modified
>by something else that has no direct access to your pointer value (via
>your named variable or via copys or pointers-to your pointer held
>elsewhere).
>
>Python should respect that.

That's why I (and others) prefer to use "name" and "target" instead of
"variable".  Would that assuage your ire?
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Not everything in life has a clue in front of it...."  --JMS



From db3l at fitlinxx.com  Mon Jul 21 17:06:18 2003
From: db3l at fitlinxx.com (David Bolen)
Date: 21 Jul 2003 17:06:18 -0400
Subject: Python scripting with Paint Shop Pro 8.0
References:  
Message-ID: 

"Greg Brunet"  writes:

> 3) Interestingly, I can't find any sign of a JascApp.* file anywhere.  I
> would expect to see a PYC or PYD given the Import command, but being a
> relative newbie myself, don't have a good understanding of how this
> could be.  But, hey - it seems to work, so I won't complain.

This would work if they "embedded" Python rather than "extending" it.
Using Python as an embedded scripting engine, the embedding
application (probably the main PSP executable) can define whatever
modules it wants as built-in modules prior to executing Python code.
The "modules" actually exist right in the executable that is starting
the Python interpreter.

If true, then it would make it less likely you could use that
functionality from an externally initiated Python script, since that
script wouldn't have started from the right environment containing
those built-in modules.

-- David



From bbeck at NOSPAM.austin.rr.com  Tue Jul 15 18:31:10 2003
From: bbeck at NOSPAM.austin.rr.com (Brandon Beck)
Date: Tue, 15 Jul 2003 22:31:10 GMT
Subject: String Manipulation
References: <2c6431ab.0307151223.4173c4ee@posting.google.com>
Message-ID: 

I know a few people replied to this already, but here's one additional
possibility.  If the data in string1 is a file path for your platform,
then you can use the os.path module.

>>> import os.path
>>> os.path.split("aaa/bbb/ccc/dd")
('aaa/bbb/cc', 'dd')
>>> os.path.splitext("filename.ext")
('filename', '.ext')

The other suggestions will of course work, but if you data is a file
path, then using the os.path module should be a more portable solution.

Brandon



"lamar_air"  wrote in message
news:2c6431ab.0307151223.4173c4ee at posting.google.com...
> I need a piece of code that takes a string like this string1 =
> "aaa/bbb/ccc/dd" and extracts a string containting the character after
> the last "/"
>
> So for this example the result would be "dd"
>
> like this:
> for i=0; string1.right(i) != '/'; i++
>
> result = string1.mid(i, string1.length())
>
> but in python.





From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Wed Jul  2 15:46:05 2003
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Wed, 02 Jul 2003 21:46:05 +0200
Subject: Encoding questions
In-Reply-To: 
References: 
Message-ID: <3f03367a$0$49112$e4fe514c@news.xs4all.nl>

Marc wrote:

> Is there any way to see what encodings are installed on my computer,
> or a reference of the encodings distributed with Python and what each
> of them is for? I've looked at the reference for the codec module and
> imagine there's a folder full of Codec classes somewhere; is this how
> it works?

Yep, look in /Lib/encodings

I am not aware of a 'clean' way to get all available codecs from
within your python code.

> The specific problem I have is a Unicode file that contains a bullet
> character (Unicode BULLET, 2022). Ultimately, it's going to be written
> into a PDF file (via ReportLab). The default ASCII encoding doesn't
> work, which is OK; suprisingly neither does 'latin-1', yet 'cp1252'
> does work. These are just encodings I've seen somewhere. Basically,
> I'd like to know how to go about choosing the best/most appropriate
> encoding for a given application.

ASCII, latin-1 and cp1252 are just examples of *subsets* of the full
Unicode character range. An encoding that you might find useful is
UTF-8 (http://www.cl.cam.ac.uk/~mgk25/unicode.html).
It is widely supported and can contain any Unicode character.

If you're processing unicode texts inside your app, stick with
Python's built-in Unicode string type.

--Irmen




From adalke at mindspring.com  Wed Jul 30 22:19:48 2003
From: adalke at mindspring.com (Andrew Dalke)
Date: Wed, 30 Jul 2003 20:19:48 -0600
Subject: Is there a standard module library function to access /etc/passwd or /etc/group
References: <16469f07.0307300416.351ba776@posting.google.com>  <16469f07.0307301458.59e73736@posting.google.com>
Message-ID: 

Robin Cull:
> I assure you I did, in fact it baffles me that I missed "pwd" in the
> global module index when I was scanning for "passwd".  Then I went off
> on a complete tangent and started looking through "os" and "posix" for
> some reason.  A case of "can't see the wood for the trees" I think!

When you're stuck because you don't know which module something
might be in (eg, I was just looking for XMLRPC server code in
xmlrpclib - wrong place!), try the full index at
  http://python.org/doc/current/lib/genindex.html

Even then, the obvious searches for "passwd" and "password" don't
find anything.  If you know the C-level functions are 'getpw*' then it
becomes much easier.

Easier for your search is to start with
   http://python.org/doc/current/lib/lib.html

> 8.2 pwd -- The password database

                    Andrew
                    dalke at dalkescientific.com





From mpnugent at ra.rockwell.com  Wed Jul 23 14:25:42 2003
From: mpnugent at ra.rockwell.com (Michael P. Nugent)
Date: 23 Jul 2003 11:25:42 -0700
Subject: Getting sub-objects from ADSI
Message-ID: 

How do I get the underlying values from Win::OLE=Hash(0x...) type
objects? I can do it in Perl, but not in Python.

For instance, I get

CN=Fred
>
>

when running

#! python

import pythoncom
from win32com.client import GetObject

UserPath = "LDAP://CN=Fred,OU=Two,OU=One,DC=nw,DC=home,DC=here,DC=com"

ldap = GetObject(Userpath)

print ldap.Name
print ldap.Groups()
print ldap.LastLogoff

I know that Groups is of the type >, but that knowledge does not help me much.  I have
fiddled a bit with GetInfo and Dispatch, but it doesn't change the
results.



From bsass at edmc.net  Tue Jul 29 15:35:23 2003
From: bsass at edmc.net (Bruce Sass)
Date: Tue, 29 Jul 2003 13:35:23 -0600 (MDT)
Subject: PyQt Help and Advice
In-Reply-To: 
References: 
Message-ID: 

On Tue, 29 Jul 2003, Ilya Knizhnik wrote:
> I am fairly new to Python.  I have found it an easy language to
> learn and a very usefull one for many tasks. Currently I am working
> on a python project that involves a GUI and it was suggested that
> PyQt is the best way to design that GUI. However since PyQt is
> rather new, I have not found much documentation on it, or examples
> in it.  The only useful tutorial/book I have found is at
> www.opendocspublishing.com/pyqt/ but it is not always clear for
> someone with almost no GUI experience. Does anyone have any
> suggestions?

http://www.riverbankcomputing.co.uk/pyqt/index.php

Is a good starting point.  Subscribe to the mailing list.




From MK at foo.com  Sun Jul 20 14:50:09 2003
From: MK at foo.com (MK)
Date: Sun, 20 Jul 2003 20:50:09 +0200
Subject: Importing WMI module into Python CGI script fails
References:  <3F1A9A07.F71D274D@engcorp.com>
Message-ID: 

"Peter Hansen"  wrote

[...]

Hello Peter! This is what I get back in browser's window:





com_error


Python 2.2.2: C:\python\python.exe
Sun Jul 20 20:45:23 2003

A problem occurred in a Python script. Here is the sequence of function
calls leading up to the error, in the order they occurred.

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

 C:\python\testcgi\index.pycgi
    2 import cgitb; cgitb.enable()

    3 import wmi [MK comment: this line colored with a bright color!]

    4 import sys

    5

    6 cgi.test()

wmi undefined

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

 C:\python\testcgi\wmi.py
  114 # Do just enough to ensure constants are available

  115 #

  116 obj = win32com.client.GetObject ("winmgmts:")  [MK comment: colored
with a bright color!]

  117 win32com.client.gencache.EnsureDispatch (obj._oleobj_)

  118 del obj

obj undefined, win32com = , win32com.client =
,
win32com.client.GetObject = 

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

 C:\python\lib\site-packages\win32com\client\__init__.py in
GetObject(Pathname='winmgmts:', Class=None, clsctx=23)
   71     return GetActiveObject(Class, clsctx)

   72   else:

   73     return Moniker(Pathname, clsctx)     [MK comment: colored with a
bright color!]

   74

   75 def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL):

global Moniker = , Pathname = 'winmgmts:',
clsctx = 23

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

 C:\python\lib\site-packages\win32com\client\__init__.py in
Moniker(Pathname='winmgmts:', clsctx=23)
   86     Python friendly version of GetObject's moniker functionality.

   87   """

   88   moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)

   89   dispatch = moniker.BindToObject(bindCtx, None,
pythoncom.IID_IDispatch)

   90   return __WrapDispatch(dispatch, Pathname, clsctx = clsctx)

moniker undefined, i undefined, bindCtx undefined, global pythoncom =
,
pythoncom.MkParseDisplayName = ,
Pathname = 'winmgmts:'


com_error: (-2147217405, 'OLE error 0x80041003', None, None)
      __doc__ = None
      __getitem__ = >
      __init__ = >
      __module__ = 'pywintypes'
      __str__ = >
      args = (-2147217405, 'OLE error 0x80041003', None, None)






From pedro.werneck at bol.com.br  Sun Jul 20 10:35:52 2003
From: pedro.werneck at bol.com.br (Pedro Werneck)
Date: 20 Jul 2003 07:35:52 -0700
Subject: object as a reserved keyword
References:  <3F1A633B.98456C76@alcyone.com> 
Message-ID: 

Lawrence Oluyede  wrote in message 
> Yeah, thanks. Is this kind of idea that I'm not used to

I remember seeing a piece like this on a discussion about abusive code:

>>> class Sum(type):
...     def __new__(meta, name, bases, dict):
...             return sum(bases)
... 
>>> class blah(1, 2, 3, 4, 5):
...     __metaclass__ = Sum
... 
>>> blah
15
>>> type(blah)

>>>

It's weird to have the freedom to do that... isn't Python great ?



From mesteve_b at hotmail.com  Thu Jul 10 22:25:32 2003
From: mesteve_b at hotmail.com (python newbie)
Date: Fri, 11 Jul 2003 02:25:32 GMT
Subject: XML in python
References:  <3EF1BBD9.21D6712@hotmail.com>
Message-ID: 

This is a better url for someone who wants the Python end of XML, who
already knows XML itself.  http://pyxml.sourceforge.net/topics/

"Alan Kennedy"  wrote in message
news:3EF1BBD9.21D6712 at hotmail.com...
> Ragu wrote:
> >         I need to read a XML file content in Python.
> >         Can anyone send me link/sample source?
>
> This link should give you a good start in all things XML/python.
>
> http://pyxml.sourceforge.net/topics/howto/xml-howto.html
>
> Although it describes many of the features that are provided by the
optional
> PyXML package, it also describes many of the core XML features provided in
the
> python standard library, such as SAX2, DOM, etc.
>
> regards,
>
> --
> alan kennedy
> -----------------------------------------------------
> check http headers here: http://xhaus.com/headers
> email alan:              http://xhaus.com/mailto/alan
>





From richardc at hmgcc.gov.uk  Tue Jul 15 08:41:23 2003
From: richardc at hmgcc.gov.uk (richardc)
Date: Tue, 15 Jul 2003 13:41:23 +0100
Subject: A few beginning questions
References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com>   <3f13bd77$1@mail.hmgcc.gov.uk> 
Message-ID: <3f13f674$1@mail.hmgcc.gov.uk>

"Duncan Booth"  wrote in message
SNIP
> If the file isn't too large you can call the readlines() method and simply
> reverse the result as above. You may find this incovenient for very large
> files though.

It may well be

> I can't think of many cases where I would want to read a
> whole file in reverse, if all you want is the last few lines of a massive
> file then just seek near the end before reading the remainder and reverse
> the resulting list of lines.

This is exactly what Im doing, what Im actually doing is seeking to 1024
bytes from the end, then looking for the string
'startref\r\n\r\n%%EOF' where  is an integer in decimal
format

I wanted to scan the lines backwards until I found %%EOF (as its likley to
be the last line) and do it that way.  I might do that or might use a regex
and just let that find it.

Cheers

Rich





From staschuk at telusplanet.net  Wed Jul 23 14:41:27 2003
From: staschuk at telusplanet.net (Steven Taschuk)
Date: Wed, 23 Jul 2003 12:41:27 -0600
Subject: detecting containers during object introspection
In-Reply-To: ; from davidcfox@post.harvard.edu on Tue, Jul 22, 2003 at 03:03:11PM +0000
References:     
Message-ID: <20030723124127.B527@tibia.amotlpaa.bogus>

Quoth David C. Fox:
  [...]
> That's one possibility.  My original reaction to it was that requiring 
> developers to write comparison operations for every class whose 
> instances are found in the stored dictionary seemed like overkill.  [...]

It might well be; this really depends on how frequently new types
are introduced to the stored dict.

Note also that it would often be possible to reuse comparison
functions written for other types.  Simple scalar values, for
example, can all use the comparison function
    def cmpstruct_scalar(a, b):
        return type(a) == type(b)
For another example, as you noticed, many (but not all -- see
below) instances of classes can be compared by comparison of their
__dict__s.

The point is that, under the choke-on-unknown-types strategy, in
many cases all the developer has to do when introducing a new type
to the stored dict is to add a line
    new_type: some_existing_comparison_function,
to a registry of type -> comparison function.  Doesn't seem
onerous to me.

  [...]
> 1) type(x) == type(y), and
> 
> 2) one of the following is true:
>     a) type(x) == type({}), and
>        x.keys() and y.keys() match, and
>        for each key, cmp_struct(x[key], y[key]) is true
>     b) type(x) == type([]), and
>        for each pair of items in x and y, cmp_struct returns true
>     c) type(x) == types.InstanceType, and
>        cmp_struct(x.__dict__, y.__dict__) is true
>     d) type(x) is not any of the above

Good idea!  A few things:

This doesn't handle new-style classes -- (c) identifies instances
of classic classes only.  hasattr(x, '__dict__') might be a better
test.

Also (c) doesn't compare the structure of class attributes, since
those are in the class dict, not the instance dict.  (I suppose
for pickling this might not matter, since the class is pickled
just as its name, so changes will automagically be available to
the unpickled instance.)

An extension type written in C might maintain lists or whatnot,
but not expose them as attributes.  This is true of the list and
dict types themselves, for example -- which is why you need
special handling for them above.

Instances of subclasses of list and dict won't be treated as lists
and dicts by (a) and (b) as written.  This is probably desirable
-- such subclasses might have additional structure which needs to
be compared -- but the contents of such instances won't be
compared by the later steps, again because those contents are not
exposed as attributes.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)




From belred1 at yahoo.com  Mon Jul 28 23:56:56 2003
From: belred1 at yahoo.com (Bryan)
Date: Tue, 29 Jul 2003 03:56:56 GMT
Subject: Papers on Python
References: <8b36138c.0307281644.f6569ea@posting.google.com>
Message-ID: 

"Rick"  wrote in message
news:8b36138c.0307281644.f6569ea at posting.google.com...
> I have been given an assignment to collect 5 papers on Python and
> write a report on each of the papers. I went ahead and researched and
> collected 9 papers; all from the internet with most of them coming
> from the International Python Conference.
>
> But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal
> papers in the history of Python in the opinion of members of this
> newgroups?
>
> I might replace all or some of my papers from those suggested by the
> members on this newsgroup.
>
> -RH
> PS. Before someone starts on how college kids are using the internet
> (or the help available on the 'net) to do the work for them, No I am
> not cheating. The actual assignment is to select 9 papers that you
> find interesting and write a report on each of them. I already have my
> 9 papers selected. Now I want to know if I would like to replace some
> from my collection.

my two personal favorite articles are:

eric raymond's "why python"
http://www.linuxjournal.com/article.php?sid=3882

Python Streamlines Space Shuttle Mission Design
http://pythonology.org/success&story=usa

bryan





From torh at operamail.com  Sun Jul  6 16:59:25 2003
From: torh at operamail.com (Tor)
Date: Sun, 6 Jul 2003 22:59:25 +0200
Subject: anything new on the ternary operator?
Message-ID: 

What's the current status on the ternary operator that may or may not be
added to python.  Haven't heard much about that since the vote was announced
for a couple of months ago.  What's the best way to follow that dicussion?
Or are we just waiting for the developers to make their decision?





From unendliche at hanmail.net  Fri Jul  4 10:56:52 2003
From: unendliche at hanmail.net (Seo Sanghyeon)
Date: 4 Jul 2003 07:56:52 -0700
Subject: [Dream] A meta-wrapper module to interface any C dynamic library
References: 
Message-ID: <45e6545c.0307040656.4f273046@posting.google.com>

Use ctypes.

http://starship.python.net/crew/theller/ctypes/

To see is to believe. The following is an actual IDLE session on WinXP.
However, ctypes is cross-platform -- it rusn on Windows, Linux, MacOS X.

>>> import ctypes
>>> loader = ctypes.cdll
>>> dll = loader.msvcrt
>>> sin = dll.sin
>>> sin.argtypes = [ctypes.c_double]
>>> sin.restype = ctypes.c_double
>>> sin(3.14)
0.0015926529164868282
>>>



From piet at cs.uu.nl  Tue Jul  8 10:08:47 2003
From: piet at cs.uu.nl (Piet van Oostrum)
Date: 08 Jul 2003 16:08:47 +0200
Subject: Collective memory (was: Good code patterns in Python)
References:  <3F08E2E9.8014B9A9@engcorp.com> <3f094dfd$0$97234$edfadb0f@dread12.news.tele.dk>
Message-ID: 

>>>>> Max M  (MM) wrote:

MM> Peter Hansen wrote:
>> Actually, the moral is "use a revision control system".  Anyone not doing
>> so should not be programming professionally.(*)

>> *) I speak as someone who programmed professionally without using a good
>> revision control system, for a while, and made some serious mistakes
>> as a result.  Backups are *not* sufficient, but merely a slight step
>> up from doing nothing at all.


MM> Arh ... that will never happen to me ... If you start using CVS systems,
MM> whats next? Anti Virus software? Raid systems? backups? It will never end.
MM> It's all just expenses.

In fact the problem starts with using a computer. Just write (or type with
an oldfashioned typewriter) your Python programs on a sheet of paper. Then
the indentation will be unambiguous :=)
-- 
Piet van Oostrum 
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



From bhahn at spam-spam.g0-away.com  Thu Jul 31 22:16:19 2003
From: bhahn at spam-spam.g0-away.com (Brendan Hahn)
Date: Fri, 01 Aug 2003 02:16:19 GMT
Subject: Python speed vs csharp
References:  
Message-ID: 

cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote:
>(Ok, I don't know why 1000 times on arrays of 1000 numbers is twice as
>fast as once on an array of 1000*1000 numbers.)

Probably cache effects.

-- 
brendan DOT hahn AT hp DOT com



From warkid at hotbox.ru  Wed Jul 23 04:27:54 2003
From: warkid at hotbox.ru (Kerim)
Date: 23 Jul 2003 01:27:54 -0700
Subject: Python 2.3c1: Raising a string doesn't trigger PendingDeprecationWarning.
Message-ID: <7c58a0f1.0307230020.1336f4ea@posting.google.com>

"What's New in Python 2.3"
(http://www.python.org/doc/2.3c1/whatsnew/node17.html) says that
"Raising a string will now trigger PendingDeprecationWarning.". But
with Python 2.3c1 it seems that it isn't the case:

Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> raise 'error'
Traceback (most recent call last):
  File "", line 1, in ?
error
>>>



From tzot at sil-tec.gr  Thu Jul 24 03:59:12 2003
From: tzot at sil-tec.gr (TZOTZIOY remotely)
Date: 24 Jul 2003 00:59:12 -0700
Subject: [OT] On the TimBot
References: 
Message-ID: 

"Delaney, Timothy C (Timothy)"  wrote in message news:...
> > From: Christos "TZOTZIOY" Georgiou [mailto:tzot at sil-tec.gr]
> >
> > 3. To "Tron" fans: yes, you could assign the name TimBit to 
> > it, but it's
> > a broken Bit; what's the use of a Bit that's always true?
> 
> Well, it compresses really well ...

Yes, a single unchanging bit in time compresses very well (contrary to
a single bit at a specific moment in time).  But compressibility is an
attribute, not a use :)



From CousinStanley at hotmail.com  Sun Jul  6 17:33:53 2003
From: CousinStanley at hotmail.com (Cousin Stanley)
Date: Sun, 6 Jul 2003 14:33:53 -0700
Subject: Using Loops to track user input
References: 
Message-ID: 

| Write a program that reads 10 numbers from the user
| and prints out the sum of those numbers.

hokiegal ...

Here is one way ...

nLoops = 10
total  = 0

for i in range( nLoops ) :

    num_in = int( raw_input( 'Enter an Integer :  ' ) )

    total += num_in

print total

-- 
Cousin Stanley
Human Being
Phoenix, Arizona





From mhammond at skippinet.com.au  Wed Jul 23 19:47:58 2003
From: mhammond at skippinet.com.au (Mark Hammond)
Date: Thu, 24 Jul 2003 09:47:58 +1000
Subject: Trying to contact Lee Harr 
In-Reply-To: 
References: 
Message-ID: 

Khalid Sheikh wrote:

> Hi Lee,
> 
> Not sure why my email got bounced. 

Try reading the bounce!

> This is a permanent error; I've given up. Sorry it didn't work out.
> 
> :
> maildrop: This user's mailbox is full.

Just try again later!

Mark.




From combe.michel at 9online.fr  Tue Jul  1 10:01:13 2003
From: combe.michel at 9online.fr (Michel Combe)
Date: Tue, 01 Jul 2003 16:01:13 +0200
Subject: Why does it work ?
Message-ID: 

I'm trying to send a mail with an attached file. 
I use the following code and *it works* but I don't understand why and I 
hate that.

for filename in os.listdir(dir):
    path = os.path.join(dir, filename)
    if not os.path.isfile(path):
        continue
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path)
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    outer.attach(msg)

In the "dir" directory, I have 2 text files :
- "texte.txt" which is the text I want inside the body of the message and 
- "fichier.txt" which is the file I want attached.

Why is "texte.txt" the only file that I find in the body of the message. 
Both files are text, so the MIMEText instruction shoud be executed for both 
files, No ?
Also add_header should be executed for both files resulting in 2 attached 
files ?
Which instruction says what is included in the body and what is attached to 
the mail ?

I must say I'm not sure of what MIMEText and add_header exactly do. I read 
the doc but it was not too clear for me.

Thanks for your help
Michel Combe



From manuelbastioniNOSPAM at tin.it  Tue Jul 22 06:00:27 2003
From: manuelbastioniNOSPAM at tin.it (manuel)
Date: Tue, 22 Jul 2003 10:00:27 GMT
Subject: Pause in a loop
Message-ID: <%W7Ta.10360$t92.299097@news1.tin.it>

I've two modules: main.py and eval.py

Eval.py is imported in main.py, but I've a loop
in eval.py that must call a function in main.py...

I can't import main.py in eval.py too, because
that would create an import loop.

But I'm thinking a different solution:
a pause in a loop to return periodically an
output. It's possible?


thanks,

          Manuel





From martin at v.loewis.de  Mon Jul 14 01:56:40 2003
From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=)
Date: 14 Jul 2003 07:56:40 +0200
Subject: anything like C++ references?
References: <000301c348c7$3c501980$21795418@dell1700>         <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com>
Message-ID: 

Stephen Horne  writes:

> Funny thing. When I use algebra, the variables I define don't end up
> referring to different values, functions or whatever unless I
> explicitly redefine them. When I write a definition on one piece of
> paper, the things I wrote earlier on another sheet don't change.

That, typically, is because you don't have any mutating operations in
your formulae. All functions you use are side-effect-free. If you
translated the sheets of paper literally into Python, the formulae
would work the way you expect them to work.

Regards,
Martin



From bmoore at integrian.com  Tue Jul 22 15:15:24 2003
From: bmoore at integrian.com (bmoore at integrian.com)
Date: Tue, 22 Jul 2003 15:15:24 -0400
Subject: How do I get more events from a wxListCtrl in a panel?
Message-ID: 

Hello.

I am working on an application using wxPython that includes a panel
with a wxListCtrl populated with data received from a LAN attached
database.

I want the wxListCtrl panel to be loaded with a small amount of data
initially.  When the user moves the vertical scrollbar or press PageUp
or PageDown, I want to load the list view with new data from the
database.  I only want to load the wxListCtrl with a subset of the
database data at a time so the list view is responsive and will allow
for handling large databases.

The problem I am having is how to get events from the scrollbars or
the PageUp/PageDown keys, etc.  I can get events from selecting items,
etc.

Thanks,
Brian





From tim.one at comcast.net  Sat Jul 12 00:58:32 2003
From: tim.one at comcast.net (Tim Peters)
Date: Sat, 12 Jul 2003 00:58:32 -0400
Subject: The "intellectual property" misnomer
In-Reply-To: 
Message-ID: 

[Ben Finney]
>>>> If the PSF holds the copyright to Python, please say that.
>>>> If the PSF holds patents which cover Python, please say that.
>>>> If the PSF owns the trademark for Python, please say that.
>>>> If the PSF has trade secrets in Python, please say that.

[Tim]
>>> So you somehow managed to divine Guido's intent from that
>>> "ridiculous, meaningless term"

[Ben Finney]
>> No, I requested that the term be clarified, because *I don't* know
>> what is meant by "The PSF holds the intellectual property rights for
>> Python". It's a meaningless statement as it stands.

[Raymond Hettinger]
> PSF is the copyright holder and issuer of the python license to the
> code covered by that copyright.  Type license() at the command
> prompt to see the elaboration using terms that *do* have meaning
> to the legal types who helped craft and vette the wording.

The PSF is also seeking to obtain the trademarks and service marks CNRI has
obtained relating to Python, and those still in the application process.

> In layman's terms, it means exactly what Guido said.

Heh -- in lawyer's terms too.  I don't see any point to belaboring the
obvious again, though .





From fredrik at pythonware.com  Wed Jul 30 13:47:43 2003
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Wed, 30 Jul 2003 19:47:43 +0200
Subject: how to gunzip a string ?
References: <025001c356a5$2d9aad10$6400a8c0@EVOD31>
Message-ID: 

Bill Loren wrote:
> I guess I really need some sort of library that will do a gzip decoding to a
> compressed string.
> assume that I have a gzipped_string_reply I got from an HTTP server,
> It'd be superb to have a gunzip class that takes it and return its decoded
> equivalent.
>
> I managed to do it with the gzip library only after saving the string to a
> file and then opening and reading it
> with gzip.open, but it's extremely ugly.
>
> any suggestions ?

trying again:

    http://effbot.org/zone/consumer-gzip.htm
    (GzipConsumer module)

interface code (based on john j. lee's posting):

    from GzipConsumer import GzipConsumer

    class stupid_gzip_consumer:
        def __init__(self): self.data = []
        def feed(self, data): self.data.append(data)

    def gunzip(data):
        c = stupid_gzip_consumer()
        gzc = GzipConsumer(c)
        gzc.feed(data)
        gzc.close()
        return "".join(c.data)

    unzipped_data = gunzip(gzipped_data)









From usenet2003 at krap.dk  Mon Jul 28 07:25:33 2003
From: usenet2003 at krap.dk (Svenne Krap)
Date: Mon, 28 Jul 2003 13:25:33 +0200
Subject: Readling all input from stdin
Message-ID: 

Hi.

I am writing a small script, that is called from an external program 
(the qmail mailserver), I need to capture all input from stdin before 
continueing the script ..

I looked for sys.stdin.readlines() but that is not present. I found 
sys.stdin.readline(), but how do I loop through it (or rather how do I 
know, when I am finished with looping ?)

Thanks in advance

Svenne




From j.vanrooij_at_e-quest.nl  Mon Jul  7 03:14:25 2003
From: j.vanrooij_at_e-quest.nl (Joost van Rooij)
Date: Mon, 7 Jul 2003 09:14:25 +0200
Subject: Delete item from wxListCtrl
References: <3f05842f$0$49105$e4fe514c@news.xs4all.nl> <20030704214425.5bb4e81a.jude-venn@blueyonder.co.uk>
Message-ID: <3f091e83$0$49105$e4fe514c@news.xs4all.nl>

"Jude Venn"  wrote in message

> haven't checked, but i think there's a GetIndex() method on the event
object that returns the index of the selection.
>

Yep, I tested it, and it worked!
thanx a lot!





From ianb at colorstudy.com  Sun Jul 13 15:52:59 2003
From: ianb at colorstudy.com (Ian Bicking)
Date: 13 Jul 2003 14:52:59 -0500
Subject: anything like C++ references?
In-Reply-To: <5tn2hvgjqlqg1qs7omvugpvm62cuso261k@4ax.com>
References: <000301c348c7$3c501980$21795418@dell1700>
	 
	 
	 
	 <5tn2hvgjqlqg1qs7omvugpvm62cuso261k@4ax.com>
Message-ID: <1058125979.28456.415.camel@lothlorien>

On Sun, 2003-07-13 at 08:56, Stephen Horne wrote:>
> You are not directly returning multiple values - you are returning a
> tuple. You can return containers in C++ too. The only difference is
> that Python makes working with tuples *much* easier

Of course, anything you can do in Python you can do in any other
language.  The *whole point* is that Python is so much easier.  Don't
worry so much about every equivalent feature or about translating every
C++ idiom to Python.  Just write your programs -- they'll be different
from C++, but that's okay.

  Ian






From tyler at scalegen.com  Mon Jul 28 13:10:38 2003
From: tyler at scalegen.com (Tyler Eaves)
Date: Mon, 28 Jul 2003 13:10:38 -0400
Subject: Readling all input from stdin
References: 
Message-ID: 

#NB: Not tested. There are probably better ways to do this.

import sys
def emulate_readlines():
    data = sys.stdin.read()
    lines = data.split('\n')
    l2 = []
    for line in lines:
        l2.append(line+'\n') #Tack the newline back on...
    return l2

    




From fredrik at pythonware.com  Tue Jul  8 15:07:13 2003
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Tue, 8 Jul 2003 21:07:13 +0200
Subject: anything new on the ternary operator?
References: <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com>     <40a939c9.0307080622.3118cfd7@posting.google.com>  <2UVsCJApkwC$EwTg@jessikat.demon.co.uk>
Message-ID: 

Robin Becker wrote:

> the Middle East is certainly not in Europe at least according to
> classical authors, historians & geographers.

but all mediterranean countries are, according to the ITU.

> I suspect Israelis would prefer to be in America so that they
> wouldn't have to take part in the Eurovision song contest.

if we'd known that you folks would end up this bitter, we would
have given you one point ;-)









From Scott.Daniels at Acm.Org  Wed Jul 30 18:10:25 2003
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Wed, 30 Jul 2003 15:10:25 -0700
Subject: searching for matches within a word list
In-Reply-To: 
References: 
Message-ID: <3f284251$1@nntp0.pdx.net>

Rajarshi Guha wrote:
> Hi,
>   I have a large list of words (each on its own line) 
> and I would like to find words that contain a specific string.
How bad is (for 2.3)?
	result = []
	apnd = result.append
	source = file('data', 'U')
	for line in source:
	    if specific in line:
	        apnd(line)
	source.close()
	# result is the list you want

-Scott David Daniels
Scott.Daniels at Acm.Org




From jbar at lf1.cuni.cz  Thu Jul 10 08:02:34 2003
From: jbar at lf1.cuni.cz (Jiri Barton)
Date: Thu, 10 Jul 2003 14:02:34 +0200
Subject: LOADING DATA INTO ARRAYS
References: 
Message-ID: <3f0d55db@shknews01>

Solution:
---------

ifile1 = open('fluidcylinder', 'r')  #fluidcylinder contains the above
for line in ifile1:
  xval,yval,zval = filter(None, line.split())
  x.append(xval)
  y.append(yval)
  z.append(zval)


Because if the line is '123   456 789', then line.split() is
['123', '', '', '456', '789']
This means it will split every string between every space in the string. The
split() function thinks the original string is
123-space-empty-space-empty-space-456-789.

The error, unpack of wrong size means you wanted to assign 
xval,yval,zval = ('123', '', '', '456', '789')
.....3-tuple ? 5-tuple

The solution just filters out the members of the list that are false (the
None is the identity function) = effectively filtering out the empty
strings.



HTH,  Jiri



From ianb at colorstudy.com  Sat Jul 12 16:02:00 2003
From: ianb at colorstudy.com (Ian Bicking)
Date: 12 Jul 2003 15:02:00 -0500
Subject: Any pure-python relational databases?
In-Reply-To: <2a897f11.0307121143.4a37113b@posting.google.com>
References: 
	 <2a897f11.0307121143.4a37113b@posting.google.com>
Message-ID: <1058040119.28467.172.camel@lothlorien>

On Sat, 2003-07-12 at 14:43, Wayne Pierce wrote:
> David McNab  wrote in message news:...
> 
> [sniped]
> 
> > 1) Any pure-python interface to MySQL? or
> 
> If you cannot get the MySQL specific interface working, have you tried
> a generic database interface?
> 
> http://www.python.org/topics/database/DatabaseAPI-2.0.html

Eh?  The generic interface isn't code, it's just an abstract interface,
implemented by various actual drivers (MySQLdb, psycopy, etc).  If you
try to *use* DBAPI directly, you're just going to confuse yourself
horribly as you come to realize that it can't be done.

  Ian






From gsmatthew at ozemail.com.au  Sun Jul  6 08:29:22 2003
From: gsmatthew at ozemail.com.au (Graeme Matthew)
Date: Sun, 6 Jul 2003 22:29:22 +1000
Subject: Python is a gem ,another successful day ....
Message-ID: 

Hi all  I previously made a post (
Python is a gem, you need to keep pushing it ....)

about how impressed I was with python and how im suign it in a proposed
commercial app.

Got a call on Friday a company with a very succesfull product in Visual
Basic (Front End) SQL (Backend) wanted to move from Microsoft products due
to all the problems with MDAC (ADO etc), XP networking issues .... and
concerns with microsofts control ///

Well after three hours looks like Python (and linux and mysql) may have won
again, explained perl (semantic nightmare but a great language) , ruby
(great language but lack of libraries) etc, Vb's weaknesses and the need for
vendor neutrality anyway, as things move ill put some updates on here ...
and tell you ho it goes, ....

Hey, im trying very hard to promote it :-)

Cheers







From aahz at pythoncraft.com  Sun Jul 13 21:36:57 2003
From: aahz at pythoncraft.com (Aahz)
Date: 13 Jul 2003 21:36:57 -0400
Subject: anything like C++ references?
References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien>  
Message-ID: 

In article ,
Stephen Horne   wrote:
>
>In Python, Guido describes his rationale for the existence of both
>mutable lists and immutable tuples here...
>
>http://www.python.org/search/hypermail/python-1992/0292.html

I'll note that Guido himself has also admitted that his ability to
explain his design decisions is far worse than his ability to select a
correct decision.  These days, the rationale for tuples is that they're
a hyper-lightweight collection of heterogeneous values.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Not everything in life has a clue in front of it...."  --JMS



From paul.moore at atosorigin.com  Wed Jul  2 05:19:41 2003
From: paul.moore at atosorigin.com (Paul Moore)
Date: 2 Jul 2003 02:19:41 -0700
Subject: Python2.3 and win32all wmi problems.
References: <9c9ad528.0306031121.66b71309@posting.google.com> <8360efcd.0306040503.24cd4b7c@posting.google.com>
Message-ID: <182bcf76.0307020119.7627a8ec@posting.google.com>

tim.golden at viacom-outdoor.co.uk (Tim Golden) wrote in message news:<8360efcd.0306040503.24cd4b7c at posting.google.com>...
> murtaza_hakim at yahoo.com (Murtaza Hakim) wrote
> 
> MH> when I try to access the Windows Management
> MH> Instrumentation (WMI) classes I get a traceback.  
> MH> This operation works fine using Python 2.2.
> 
> [ snip traceback ]
> 
> Just to clarify, I believe it is the version of win32all 
>  which you are using, and not the version of Python, which
>  is the source of the error. I get the same error running
>  win32all-153 under Python 2.2.2.

I am also hitting this problem - it seems to be an issue with new code
in win32all build 153, in pythoncom.

As a workaround, if you go to Mark Hammond's website, and follow the
link to "Regular Snapshot Builds"
(http://starship.python.net/crew/mhammond/win32/CVSSnapshotBuilds.html)
you can download the 20021220 build. It's an installer executable, but
you can open it in WinZip (or similar) and extract pythoncom23.dll
from it. Replace the existing copy of this file (in your
C:\WINNT\SYSTEM32 directory) with this one, and things seem OK.

For what it's worth (Mark may be interested) the relevant change seems
to be in pywin32/com/win32com/src/PythonCOM.cpp where a call to
PyArg_ParseTuple was changed from ``PyArg_ParseTuple(args,
"s|O:MkParseDisplayName", &displayName, &obBindCtx)`` to
``PyArg_ParseTuple(args, "et|O:MkParseDisplayName",
Py_FileSystemDefaultEncoding, &displayName, &obBindCtx)``. I don't
know what this is doing, but it's pretty much where the traceback is
pointing...

Paul.



From richard.mertens at wolfi.org  Fri Jul 11 04:00:15 2003
From: richard.mertens at wolfi.org (Richard Mertens)
Date: 11 Jul 2003 08:00:15 GMT
Subject: libxml2  - Attribute
Message-ID: 

I'd like to read the attributes from a node in my xml - file, but i didn't 
found an example for this. Could someone help me please?
I ghet the attribute count work neither.

example - xml file


kulimuh


example python - script

ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//test/muh")
for myres in  res:
       print myres.AttributeCount
  

File "/usr/lib/python2.2/site-packages/libxml2.py", line 189, in __getattr__
    raise AttributeError,attr
AttributeError: AttributeCount




From dkuhlman at rexx.com  Tue Jul 15 16:58:57 2003
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 15 Jul 2003 13:58:57 -0700
Subject: call one python script from within another
References:  <3f0f40b9$0$49103$e4fe514c@news.xs4all.nl> <93f5c5e9.0307120814.4a84ca9a@posting.google.com>
Message-ID: 

hokiegal99 wrote:

> Irmen de Jong  wrote in
> message news:<3f0f40b9$0$49103$e4fe514c at news.xs4all.nl>...
>> Tubby Tudor wrote:

[snip]

>> def main():
>>      ....  body of your code here ....
>> 
>> 
>> main()               # run code in one
>> two.main()   # run code in two
>> three.main() # run code in three
>> ------------------
>> 
>> Will this do?
> 
> 
> Yes, this works. Thanks for the tip!

Note, however, that if the main() function in module two or three
uses command line paramters, you may have to trick it as follows:

  import sys

  main()               # run code in one
  sys.argv = ['junk', 'argval1', 'argval2']
  two.main()   # run code in two
  sys.argv = ['junk', 'argval3', 'argval4']
  three.main() # run code in three

By the way, I just tried this.  It works.

But, take a look at the main function in modules two and three.
It may be just as easy to call the function(s) it calls.

 - Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dkuhlman at rexx.com



From giles_brown at hotmail.com  Tue Jul 29 04:52:01 2003
From: giles_brown at hotmail.com (Giles Brown)
Date: 29 Jul 2003 01:52:01 -0700
Subject: Cannot register dll created using "py2exe --com-dll"
Message-ID: <57de9986.0307290052.688e54c5@posting.google.com>

I'm feeling quite dumb this morning.

I'm trying to build a COM server DLL using py2exe and it ain't working.

Here's what ain't working...

setup_dll.py based on py2exe sample:
"""from distutils.core import setup
import py2exe

setup(name="MadeUpName Object Model", 
    scripts=['madeupname.application'],
    output_base='madeupname')
"""

Command line for building dll (N.B. python 2.3 as instructed):
"""c:\python23\python madeupname/setup_dll.py py2exe --com-dll --excludes Tkinter"""

Command line for registering dll:
regsvr32 c:\pvcs\madeupname\model\dist\application.dll

Result when I try to register dll:
"""DllRegisterServer in c:\pvcs\madeupname\model\dist\application.dll failed.
Return code was: 0x80040201
"""

The winerror.h entry for this says:
"""//
// MessageId: CO_E_FAILEDTOGETSECCTX
//
// MessageText:
//
//  Unable to obtain server's security context
//
#define CO_E_FAILEDTOGETSECCTX           _HRESULT_TYPEDEF_(0x80040201L)
"""

But I'm guessing that this is simply a way of saying the I haven't told
pythoncom (via py2exe) which classes to register.  I'm looking at the
source and I am trying to work it out but failing :-(

I have tried an exe server, but this does not register either.

Any suggestions?

Also does anyone know what argument to use to get py2exe to build something
other than "application.[dll/exe]".  I thought 'output_base' as an argument
to setup() would do it, but no joy.

If you folks can make me feel even more stupid by pointing out my
obvious mistake, that would make me happy. :-)

Thanks for reading,
Giles Brown



From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Sun Jul 27 12:05:31 2003
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Sun, 27 Jul 2003 18:05:31 +0200
Subject: Tools for reading Dr Dobb's Python-URL
In-Reply-To: 
References:  <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> 
Message-ID: <3f23f845$0$49109$e4fe514c@news.xs4all.nl>

Egbert Bouwman wrote:
> My mail reader is the text-based Mutt, which:
> - doesn't react to mouse clicks
> - does show url's in a different color
> - seems not to do anything useful with them

I see. Would the DrDobbs web page I pointed at
(http://www.ddj.com/topics/pythonurl/)
not be a good alternative for you?
If you accept a slight delay until the latest
Python-URL is posted on that web site, you can
read it and click all links by using any web browser...

I cannot help you with a better alternative
to mutt if you want to use a text-based mail reader,
sorry.

--Irmen





From exarkun at intarweb.us  Mon Jul 21 02:19:55 2003
From: exarkun at intarweb.us (Jp Calderone)
Date: Mon, 21 Jul 2003 02:19:55 -0400
Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?)
In-Reply-To: 
References:   
Message-ID: <20030721061955.GA10920@intarweb.us>

On Mon, Jul 21, 2003 at 01:22:07AM -0400, Terry Reedy wrote:
> 
> I presume you are asking: Why hasn't slice been converted from a
> 'mere' function to a callable type like int, str, and float have been?
> 
> If this has not yet been done for the coming 2.3, \
> [snip]

  It has.

  Jp

-- 
Lowery's Law:
        If it jams -- force it.  If it breaks, it needed replacing anyway.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: 

From light at soton.ac.uk  Wed Jul  2 07:02:36 2003
From: light at soton.ac.uk (Mark Light)
Date: Wed, 2 Jul 2003 12:02:36 +0100
Subject: splitting a string into 2 new strings
Message-ID: 

Hi,
      I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2
strings
'C H O' and '6 12 6'.  I have played with string.split() and the re module -
but can't quite get there.

Any help would be greatly appreciated.

Thanks,

Mark.







From alanmk at hotmail.com  Tue Jul  1 11:54:55 2003
From: alanmk at hotmail.com (Alan Kennedy)
Date: Tue, 01 Jul 2003 16:54:55 +0100
Subject: remove special characters from line
References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> 
Message-ID: <3F01AECF.965FAADA@hotmail.com>

[Chris Rennert]

> If I have a line like this
> 
> ?blah blah blah blah blah
> 
> I know I could do a slice like this [1:] to pull everything but the
> special character, but what if I have several lines in a file.
> I am not sure how I would detect a special character like that.  I
> would just like to pull everything from those lines (and the special
> character always appears as the first character, but not on every line)
> except for the special characters.

How about something like this?

for line in file('myfile.stars'):
    print line.lstrip('*')

Should remove all '*' (even if there is more than one) from the beginnings (but
not the ends) of lines.

Egor Bolonev wrote:

> I didn't get what you're talkink about.

Then what was the purpose of your reply?

I find it helps keeps the signal noise to ratio of the group down if people only
post when they have something to contribute.

regards,

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



From exarkun at intarweb.us  Tue Jul 22 12:03:17 2003
From: exarkun at intarweb.us (Jp Calderone)
Date: Tue, 22 Jul 2003 12:03:17 -0400
Subject: Iterating order of dict.items()
In-Reply-To: <16469f07.0307220706.5e2fe1e4@posting.google.com>
References: <16469f07.0307220706.5e2fe1e4@posting.google.com>
Message-ID: <20030722160317.GA18762@intarweb.us>

On Tue, Jul 22, 2003 at 08:06:28AM -0700, Robin Cull wrote:
> [snip]
> 
> So, is the order of dict.items() defined?  If so, what is that order? 
> Is there any way to control the order my dict is iterated over?

   The order is implementation dependent.  It may change across different
versions of Python, and should not be depended upon.  There is no way to
control this in the built-in dictionary type, but it is possible to subclass
dict and override any of keys/values/items/iterkeys/itervalues/iteritems you
desire to acheive the appropriate ordering.

  Jp

-- 
"One World, one Web, one Program." - Microsoft(R) promotional ad
"Ein Volk, ein Reich, ein Fuhrer." - Adolf Hitler




From me at privacy.net  Mon Jul 28 10:13:26 2003
From: me at privacy.net (Heather Coppersmith)
Date: 28 Jul 2003 10:13:26 -0400
Subject: changing the List's behaviour?
References:  
Message-ID: 

On Mon, 28 Jul 2003 14:46:14 +0200,
Peter Otten <__peter__ at web.de> wrote:

> meinrad recheis wrote:
>> i want to change the List so that it returns None if the index for
>> accesssing list elements
>> is out of bound.

> If you really need it, you can write a class similar to the one below:

> class DefaultList(list):
>     def __init__(self, sequence=[], default=None):

That's asking for trouble.  That mutable default argument for
sequence is evaluated at class definition-time, and all instances
of DefaultList created without a sequence argument will end up
sharing one list.

Do this instead:

class DefaultList( list ):
    def __init__( self, sequence = None, default = None ):
        if sequence is None:
            sequence = [ ]

>         list.__init__(self, sequence)
>         self.default = default
>     def __getitem__(self, index):
>         try:
>             return list.__getitem__(self, index)
>         except IndexError:
>             return self.default

> if __name__ == "__main__":
>     theList = DefaultList("abc", "?")
>     print theList[1]
>     print theList[99]

>     theList = DefaultList(default="X")
>     print theList[1]

Regards,
Heather

-- 
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli




From garyr at fidalgo.net  Mon Jul 14 23:27:53 2003
From: garyr at fidalgo.net (Gary Richardson)
Date: Mon, 14 Jul 2003 20:27:53 -0700
Subject: Sio serial module install problem with ActiveState
References: 
Message-ID: 

[snip]

> BTW, this serial printer is apparently pretty much a 'dump
> and go' type device - the only thing the printer seems to
> be capable of returning is a 4-byte error code after a special
> error report command is sent to the printer - other than that,
> all of the data and commands seem to move downstream only,
> with no return from the printer expected. Is Sio overkill for
> this, i.e. is there some incredibly simple "open a serial port
> under Win32 for write only" command I'm missing in the basic
> Python stuff?
>
> Many thanks,
>
> Conrad
>

I've written a pretty simple serial I/O module that will do what you want.
Email me directly if you would like a copy.

Gary Richardson





From michael at foord.net  Wed Jul  9 04:37:10 2003
From: michael at foord.net (Fuzzyman)
Date: Wed, 09 Jul 2003 09:37:10 +0100
Subject: Executables under Win32
Message-ID: <5vkngvs2epq6rv0a3rodeb839k5ls8bafj@4ax.com>

IS there a tool to make Python Executables (binaries) under Win32...
or must people have a distribution of Python to use any scripts I
write ?

I don't need to hide my source code - but would liek to make it easy
for a newbie to use my scripts.

Fuzzyman
---
Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera 

http://www.voidspace.org.uk 
Where Headspace Meets Cyberspace
Cyberpunk and Science Resource Site
Exploring the worlds of Psychology, Spirituality, Science and Computing
--
http://www.fuchsiashockz.co.uk
http://groups.yahoo.com/group/void-shockz
http://www.learnlandrover.com



From oussoren at cistron.nl  Mon Jul  7 04:01:25 2003
From: oussoren at cistron.nl (Ronald Oussoren)
Date: Mon, 7 Jul 2003 10:01:25 +0200
Subject: ANN: PyObjC 1.0b1
Message-ID: <35051178-B051-11D7-991E-0003931CFE24@cistron.nl>

PyObjC 1.0b1 is now available for download at 
http://pyobjc.sourceforge.net/

PyObjC is a bridge between Python and Objective-C.  It allows full
featured Cocoa applications to be written in pure Python.  It is also
easy to use other frameworks containing Objective-C class libraries
from Python and to mix in Objective-C, C and C++ source.

Python is a highly dynamic programming language with a shallow learning
curve.  It combines remarkable power with very clear syntax.

The installer package includes a number of Project Builder templates for
easily creating new Cocoa-Python projects, as well as support for
syntax-coloring Python files in Project Builder.

PyObjC also supports full introspection of Objective-C classes and
direct invocation of Objective-C APIs from the interactive interpreter.

PyObjC requires MacOS X 10.2 or later.  PyObjC works both with the Apple
provided Python installation in MacOS X 10.2 (and later) and with
MacPython 2.3b1.  Users of MacPython 2.3b1 can install PyObjC though the
PackageManager application.

PyObjC 1.0b1 includes numerous improvements over earlier versions, 
including:

* Improved performance and stability
* Better tutorials and examples
* Initial support for MacOS X 10.1
* Support for the WebKit framework
* Write plugin bundles in Python (requires Python 2.3b1)

PyObjC is released with an open source license.





From prashsingh at yahoo.com  Tue Jul 22 12:27:28 2003
From: prashsingh at yahoo.com (Prashant Singh)
Date: 22 Jul 2003 09:27:28 -0700
Subject: py2exe command line window problem
Message-ID: <1ee79758.0307220827.78f8571@posting.google.com>

I'm using py2exe to create a standalone executable from a Python
script, and I would like the script to run invisibly, i.e. without a
console window and without any interactive GUI. The script is a helper
app, which simply downloads and runs some other program.

I've tried passing the -w flag to the script, and I've also tried
renaming it with a .pyw extension, but when the executable is run an
empty console window opens with the title "C:\WINNT\system32\cmd.exe".
I've checked, and there are no print statements, which might cause
py2exe to assume it's still a console app.

Is there something I'm missing?

Thanks,
prashant.



From staschuk at telusplanet.net  Tue Jul 15 16:06:18 2003
From: staschuk at telusplanet.net (Steven Taschuk)
Date: Tue, 15 Jul 2003 14:06:18 -0600
Subject: link collection
In-Reply-To: <3F140634.2010201@embeddedsystems.nl>; from gerrit.muller@embeddedsystems.nl on Tue, Jul 15, 2003 at 03:48:36PM +0200
References: <3F140634.2010201@embeddedsystems.nl>
Message-ID: <20030715140618.B438@tibia.amotlpaa.bogus>

Quoth Gerrit Muller:
  [...]
> This link collection is bootstrapped by proudly stealing the links 
> mentioned in Dr Dobbs Python URL by Steven Taschuk. Many thanks to Steven.

Though I appreciate the comment, I should point out that the
author of Python-URL changes from time to time -- at present it's
Irmen de Jong, not me.  The editor and general overseer of the
various authors is Cameron Laird, who surely deserves those thanks
more than I do.

-- 
Steven Taschuk     staschuk at telusplanet.net
"Please don't damage the horticulturalist."
         -- _Little Shop of Horrors_ (1960)




From rimbalaya at yahoo.com  Mon Jul 28 11:05:53 2003
From: rimbalaya at yahoo.com (Rim)
Date: 28 Jul 2003 08:05:53 -0700
Subject: Why instancemethod when I can add functions to classes outside class body?
References: <6f03c4a5.0307242027.85f195a@posting.google.com>   <3f210717$0$76049$edfadb0f@dread11.news.tele.dk> 
Message-ID: <6f03c4a5.0307280705.6a4ab103@posting.google.com>

"Terry Reedy"  wrote in message 
> > >>> class A: pass
>  ...
> > >>> a1 = A(); a2 = A()
> > >>> a1.f = new.instancemethod(lambda self: "hi", a1, A)
> > >>> a2.f()
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > AttributeError: A instance has no attribute 'f'
> > >>> a1.f()
> > 'hi'
> 
> So to answer the OP's question, the problem solved is that directly
> assigning a function as an instance attribute binds the function as a
> function, which means no *automatic* access to the instance and its
> other attributes.  If such access is needed, the instance must be

I don't understand why you say "no automatic access". If you examine
the following, I have access to the attributes defined in the class,
without doing anything special:

>>> class a:
...    def __init__(self,name):
...       self.msg = "hi"
...       self.name = name
... 
>>> def f(self):
...    print "hello"
...    print self.msg
...    print self.name
... 
>>> a.f = f
>>> b=a("Joe")
>>> b.f()
hello
hi
Joe

I obviously don't understand what you are trying to explain to me.

>So to answer the OP's question, the problem solved is that directly
>assigning a function as an instance attribute binds the function as a
>function, which means no *automatic* access to the instance and its
>other attributes.  If such access is needed, the instance must be
>passed explicitly, as in
>a1.f = lambda self: repr(self)
>a1.f(a1)
>
>Instancemethod adds the option of wrapping instance-specific functions
>as bound methods getting the instance as an automatic first (self)
>paramater, just like with class-wide methods.  In the 'hi' example


I think someone should write the official definitions for the following
so we all talk the same language:
- function
- method
- bound method/function
- unbound method/function
- class-wide method/function
- class-not-wide method/function
- etc.

> requires the wrapping to avoid having to explicitly pass the instance.

I did not pass the instance and it worked in my example. I'd like to understand
what you are trying to show me.

Thanks,
-Rim



From mertz at gnosis.cx  Wed Jul 16 17:22:51 2003
From: mertz at gnosis.cx (David Mertz, Ph.D.)
Date: Wed, 16 Jul 2003 17:22:51 -0400
Subject: [Announce] Gnosis Utils 1.1.0 (update)
Message-ID:                 

** SECOND TRY (aaghh!)
** I bit the bullet and bought more bandwidth, this notice is
** updated to reflect the permanent URL for Gnosis Utilities

[Announce] Gnosis Utils 1.1.0

This release contains enhancements to gnosis.xml.objectify.

    Added _XO_.__repr__ method to make nodes print in a nicer,
    more compact fashion.

    Added ._seq attribute to node objects to support structure
    preserving convenience functions.  Specifically, older
    versions of gnosis.xml.objectify lost information about mixed
    content and the order of children.  E.g.,

      >>> xml = 'Mixed content is good'
      >>> obj = XO(xml,EXPAT).make_instance()
      >>> obj.PCDATA, obj.i.PCDATA, obj.b.PCDATA
      (u'Mixed is', u'content', u'good')

    We had no way of knowing where inside  the  and the
     occur, nor even which child element occurs first.

    Now we can recover that information:

      >>> from gnosis.xml.objectify import content, children
      >>> content(obj)
      [u'Mixed ', , u' is ', ]
      >>> children(obj)
      [, ]

    Sequence information and convenience methods are NOT
    SUPPORTED (yet?) for the DOM parser, only for EXPAT!

    Changed default parser to EXPAT.  If you have relied on the
    special attribute ._XML that the DOM parser attaches to
    nodes, you will now need to explicitly specify DOM as the
    parser used.  However, the new sequence functions pretty well
    handle the job pyobj._XML used to do (in a different way).

    Some newer versions of PyXML report CDATA as #cdata-section
    nodes rather than as #text.  We deal with it either way now.

It may be obtained at:

    http://gnosis.cx/download/Gnosis_Utils-1.1.0.tar.gz

The current release is always available as:

    http://gnosis.cx/download/Gnosis_Utils-current.tar.gz

Try it out, have fun, send feedback!

David Mertz (mertz at gnosis.cx)
Frank McIngvale (frankm at hiwaay.net)

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

BACKGROUND:  Gnosis Utilities contains a number of Python libraries, most
(but not all) related to working with XML.  These include:

    gnosis.indexer          (Full-text indexing/searching)
    gnosis.xml.pickle       (XML pickling of Python objects)
    gnosis.xml.objectify    (Any XML to "native" Python objects)
    gnosis.xml.validity     (Enforce validity constraints)
    gnosis.xml.indexer      (XPATH indexing of XML documents)
    [...].convert.txt2html  (Convert ASCII source files to HTML)
    gnosis.util.dtd2sql     (DTD -> SQL 'CREATE TABLE' statements)
    gnosis.util.sql2dtd     (SQL query -> DTD for query results)
    gnosis.util.xml2sql     (XML -> SQL 'INSERT INTO' statements)
    gnosis.util.combinators (Combinatorial higher-order functions)
    gnosis.util.introspect  (Introspect Python objects)
    gnosis.magic            (Multimethods, metaclasses, etc)

...and so much more! :-)





From tdelaney at avaya.com  Wed Jul 30 01:03:56 2003
From: tdelaney at avaya.com (Delaney, Timothy C (Timothy))
Date: Wed, 30 Jul 2003 15:03:56 +1000
Subject: while (assignment):
Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE958C7E@au3010avexu1.global.avaya.com>

> From: Andrew Dalke [mailto:adalke at mindspring.com]
> 
> >>> a = [1, 2, 9, 0]
> >>> n = iter(a).next
> >>> while [x for x in [n()] if x]:
> ...  print "I have", x
> ...
> I have 1
> I have 2
> I have 9
> >>>
> 
> Again, don't this in real code.  Evil.  But cute.

I would say it's actually rude, rather than evil.

Tim Delaney




From MK at foo.com  Sat Jul 12 13:05:20 2003
From: MK at foo.com (MK)
Date: Sat, 12 Jul 2003 19:05:20 +0200
Subject: Parsing stdout through a pipe?
Message-ID: 

I have a Win32 console application (SNMPUTIL.EXE) which listens
to incoming SNMP messages:

C:\>snmputil trap
snmputil: listening for traps...


When a trap is generated on a remote server, it is being sent to
the PC running SNMPUTIL.EXE, and  then finally printed out to
stdout like this:

snmputil: trap generic=6 specific=11003
  from -> 10.198.163.89
Variable = system.sysName.0
Value    = String DEAUDIIP109387
Variable = .iso.org.dod.internet.private.enterprises.232.11.2.11.1.0
Value    = Integer32 0
Variable = .iso.org.dod.internet.private.enterprises.232.11.2.8.1.0
Value    = String Compaq Management Agents Test Trap sent - Samstag, 12.
Juli 2003 18:52:19


I'd like to write a Python application which would intercept/parse this
stdout
output, and invoke various pop-ups ("alarms"). Any ideas?





From bokr at oz.net  Sun Jul 13 22:34:47 2003
From: bokr at oz.net (Bengt Richter)
Date: 14 Jul 2003 02:34:47 GMT
Subject: =?ISO-8859-1?Q?=F1=EF=E5=F8=E8=E0=EB_=E4=EB=FF_=F0=EE=F1?=  =?ISO-8859-1?Q?=F1=E8=E9=F1=EA=E8=F5_=EF=E8=F2=EE=ED=F9=E8=EA=EE=E2=29?=  =?ISO-8859-1?Q?=29=29?=
References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F11D94A.7050208@removeme.free.fr>
Message-ID: 

On Sun, 13 Jul 2003 22:12:26 +0000, Bruno Desthuilliers  wrote:

>Irmen de Jong wrote:
>> Garber wrote:
>> 
>>> ?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ?
>>> exe-???? ?????????).
>> 
>> 
>> 
>> Yes!
>> I think.
>> 
>> ;-)
>> 
>> On second thought, what's he saying?
>> 
>
>He said :
>"?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? 
>exe-???? ?????????)."
>
>It does seem clear enough, doesn't it ?-)
>
narod, polskaschitye plye postatb progou fribyer(kaschyetbsya, korouye nado b exe-shink peregnatb)

or somethink like that. No idea, just applying cyrillic font and picking out greek ;-P

Roman can tell us ;-)

Regards,
Bengt Richter



From max at alcyone.com  Fri Jul 18 02:04:36 2003
From: max at alcyone.com (Erik Max Francis)
Date: Thu, 17 Jul 2003 23:04:36 -0700
Subject: null pointer exceptions
References:  <3F17806E.3B9B4F75@alcyone.com> 
Message-ID: <3F178DF4.A20EAF6A@alcyone.com>

Tennessee James Leeuwenburg wrote:

> Certainly I can catch it. However, Java does not require that it be
> caught
> itself.
> 
> I realise it's not great practise to leave these kinds of things in
> your
> Java code, but I'm extending someone else's code, and don't really
> want to
> back-correct class after class as I find these problems coming up,
> especially since it doesn't cause Java any hassles.

So the Java program itself handles the NullPointerException, but when
run from Jython it doesn't?  I thought NullPointerExceptions always
propagated all the way up like normal RuntimeExceptions?

Or is it that in Java a NullPointerException is thrown in a side thread,
which dies, but everything else keeps running fine -- and Jython makes a
bigger deal out of the NullPointerException because it chokes on any
exception from any Java subthread?

If it's the latter, then it sounds like the right solution -- mimicking
Java's not-great-but-satisfactory behavior would be to catch the
NullPointerException in Jython and then toss it (since that is, what in
effect, Java is doing).

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ You can buy any kind of love, but you can't buy love deluxe.
\__/  Sade Adu



From jdhunter at ace.bsd.uchicago.edu  Mon Jul 21 18:06:25 2003
From: jdhunter at ace.bsd.uchicago.edu (John Hunter)
Date: Mon, 21 Jul 2003 17:06:25 -0500
Subject: Search for a string in binary files
In-Reply-To:  (hokieghal99's message of "Mon,
 21 Jul 2003 17:19:59 -0400")
References: 
Message-ID: 

>>>>> "hokieghal99" == hokieghal99   writes:

    hokieghal99> Hello, How could I use python to search for a string
    hokieghal99> in binary files? From the command line, I would do
    hokieghal99> something like this on a Linux machine to find this
    hokieghal99> string:

    hokieghal99> grep -a "Microsoft Excel" *.xls

    hokieghal99> How can I do this in Python?

Linux doesn't distinguish between binary files and regular files, so
you can use the usual string find method.  On windows, you need to be
sure to open the file in binary mode


  >>> s = file('temp.xls', 'rb').read()
  >>> s.find('Excel')

The point is that there is nothing special about searching binary
files.  Search the google groups archives for python grep for more
information.

You can use regular expressions if you want to do more sophisticated
pattern matching.

JDH




From elainejackson7355 at home.com  Sat Jul 12 10:50:08 2003
From: elainejackson7355 at home.com (Elaine Jackson)
Date: Sat, 12 Jul 2003 14:50:08 GMT
Subject: new in town
Message-ID: 

Can Python be compiled? If so, how? (I have the 2.2 version of the interpreter.)
TIA for any and all helps

--

Peace,
EJ





From roo at dark-try-removing-this-boong.demon.co.uk  Thu Jul  3 12:53:36 2003
From: roo at dark-try-removing-this-boong.demon.co.uk (Rupert Pigott)
Date: Thu, 3 Jul 2003 17:53:36 +0100
Subject: Collective memory
References:   <1057243309.793889@saucer.planet.gong> 
Message-ID: <1057251216.551262@saucer.planet.gong>

"Pete Fenelon"  wrote in message
news:vg8hns2u0l4off at corp.supernews.com...
> In alt.folklore.computers Rupert Pigott
 wrote:
> >
> > OCCAM used WS to denote block structure... For
>
> ...and was generally written with folding editors that just "got it
> right" ;)

I noticed that a few of the KDE 3.1 editors support folding... :)

Took me a while to work out what those lines & + things were in
the left margin... Made me happy. :)

Cheers,
Ruppert





From bgailer at alum.rpi.edu  Mon Jul 28 10:58:00 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 28 Jul 2003 08:58:00 -0600
Subject: How to reverse lookup characters in list?
In-Reply-To: 
References: 
Message-ID: <5.2.1.1.0.20030728085709.02bc7df0@66.28.54.253>

At 06:11 AM 7/28/2003 +0000, Keith Jones wrote:

>okay, isn't the number in the list the index of the new letter? So you'd
>just use alphabet[d].. though what you're doing can be done in a much
>simpler manner..
>
>for starters... check out the string module. you can do
>
>import string
>string.lowercase
>
>that gives you a-z, lowercase.. I think you'll be fine with a string,
>rather than a list (infact, it's better since it's immutable). If you must
>ahve a list, you can do
>
>[a for a in string.lowercase]

Or just list(string.lowercase])
[snip]

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003

From tomas at fancy.org  Mon Jul 14 20:18:40 2003
From: tomas at fancy.org (Tom Plunket)
Date: Mon, 14 Jul 2003 17:18:40 -0700
Subject: anything like C++ references?
References: 
Message-ID: 

Michael Chermside wrote:

> > Assignment never copies anything, or creates anything except for 
> > changing the variable to point to a different address location.  
> > *Every* Python assignment (a=b) is like the C assignment (a=&b).  
> 
> I have nothing whatsoever to add to this... it is just so clearly and
> simply stated that I felt it was worth repeating.

Although I don't think that it's correct.  Either a and b are
both pointer types or they're not- but IMHO it's much more useful
(perhaps) to C programmers to say "everything's a pointer" and
when you say

a = 5

You're saying the almost-C equivalent to 

a = &5;

If one considers that everything is a pointer, and that you
cannot necessarily change the object that the pointer points to
(there is no equivalent of

*a = 5

), then it actually becomes (hopefully) fairly straight-forward
to the C programmer.

So- it would probably be more helpful to C programmers to say
"everything is a pointer" rather than "everything is a
reference," and then add that "there is no pointer
dereferencing."


-tom!



From vincent_delft at yahoo.com  Sun Jul 27 06:58:26 2003
From: vincent_delft at yahoo.com (vincent_delft)
Date: Sun, 27 Jul 2003 12:58:26 +0200
Subject: Web tool kit : pro - cons ?
References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> 
Message-ID: <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be>

Gerhard H?ring wrote:

> vincent_delft wrote:
>> My needs are :
>> - Build pages via templates (easy to split content and layout)
> 
> ZPT seems to be a good option there.
> 
Nice. New to me.
I've already played with Zope.... but ZPT seams to take the best from
Templates without having the Zope constraints.


>> - My pages will be defined with "boxes".  I would like to have a tool
>> that can manage easely such "object".
> 
> You mean a WYSIWYG web development IDE for Python? I don't think there's
> such a thing.
> 
No.  Each part of the web page will be "boxes".  I would like to be very
flexible and display "dynamically" some selected boxes.
For example the same page (url) will not display the same boxes if you are
administrator, maintener or simple viewer.
An another example will be to have possibility to re-use existing boxes.  If
I have a boxes displaying the last 5 news from Slashdot, I don't want to
re-write it each time I need a new bacground color (for example). My Idea
is to use those "boxes" like we use classes : if you need some modification
you subclass it on the rest remains the same.



>> - I will use PostgreSQL as backend.
> 
> I'd suggest you use pyPgSQL or psycopg for this. I'm a little biased
> towards pyPgSQL, being one of it's developers ;-)
> 
Yeah!!!!! Thanks for your work.  I'm fan of pyPgSQL it works very well
(version 2.4).

> -- Gerhard




From staschuk at telusplanet.net  Wed Jul  2 10:21:57 2003
From: staschuk at telusplanet.net (Steven Taschuk)
Date: Wed, 2 Jul 2003 08:21:57 -0600
Subject: Suggesting for overloading the assign operator
In-Reply-To: ; from bokr@oz.net on Wed, Jul 02, 2003 at 02:07:21AM +0000
References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com>  
Message-ID: <20030702082157.A595@tibia.amotlpaa.bogus>

Quoth Bengt Richter:
  [...suggests a := b equivalent to a.__update__(b)...]
> I guess it's a matter of what kind of sugar you like ;-)

Quite.

  [...syntactic support for Currency objects...]
> I'm not sure what that would mean.

I meant a language like Python but with a Currency literal syntax.
With syntax such as, say,
    123.45$  equivalent to  Currency(123.45)
(except, perhaps, for decimal vs binary exactness issues), the
users could type
    a = 7$
    # ...
    a = 6$
which is less onerous than writing Currency(7), Currency(6).

This idea is well-suited to the scenario in which the users make
pervasive use of objects of this type, and the main problem is
having to type "Currency" over and over again.

  [...]
-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)




From hokiegal99 at hotmail.com  Sun Jul 13 20:33:12 2003
From: hokiegal99 at hotmail.com (hokiegal99)
Date: Sun, 13 Jul 2003 20:33:12 -0400
Subject: removing spaces from front and end of filenames
References:  <3F10BABB.D548961B@alcyone.com> <93f5c5e9.0307130744.7e9d8377@posting.google.com> 
Message-ID: <3F11FA48.7010102@hotmail.com>

Bengt Richter wrote:
> On 13 Jul 2003 08:44:05 -0700, hokiegal99 at hotmail.com (hokiegal99) wrote:
> 
> 
>>Erik Max Francis  wrote in message news:<3F10BABB.D548961B at alcyone.com>...
>>
>>>hokiegal99 wrote:
>>>
>>>
>>>>This script works as I expect, except for the last section. I want the
>>>>last section to actually remove all spaces from the front and/or end
>>>>of
>>>>filenames. For example, a file that was named "  test  " would be
>>>>renamed "test" (the 2 spaces before and after the filename removed).
>>>>Any
>>>>suggestions on how to do this?
>>>
>>>That's what the .strip method, which is what you're using, does.  If
>>>it's not working for you you're doing something else wrong.
>>
>>for root, dirs, files in os.walk('/home/rbt/scripts'):
>>    for file in files:
>>        fname = (file)
>>        fname = fname.strip( )
>>print fname
>>
>>When I print fname, it prints the filenames w/o spaces (a file named "
>>test " looks like "test"), but when I ls the actual files in the
>>directory they still contain spaces at both ends. That's what I don't
>>understand. It seems that .strip is ready to remove the spaces, but
>>that it needs one more step to actually do so. Any ideas?
> 
> I don't see where you rename " test " to "test" ;-)
> 
> BTW, file is a builtin name for the file class, which creates open file objects,
> so it's best to use another name.
> 
> Maybe change that last loop to (untested!)
> 
> for root, dirs, files in os.walk('/home/rbt/scripts'):
>     for fname in files:
>         newfile = fname.strip( )
>         if newfile != fname:
>             newpath = os.path.join(root,newfile)
>             oldpath = os.path.join(root,fname)
>             os.rename(oldpath,newpath)
>             print `oldpath` # back ticks to print repr to make sure you can see spaces
> 	    print `newpath`
> 
> Regards,
> Bengt Richter

I've found the below code to OK, does anyone see any problems with it? 
I've ran it several times w/o damaging anything ;). The only problem 
with doing this on dirs is that the script doesn't act on dirs within 
dirs that are being renamed by the script as the path didn't exist when 
the script started running. So, I have to run it several times. It works 
but it's a bit of a kludge. Anyone know of a work around for this?


for root, dirs, files in os.walk('/home/rbt/test'):
     for dir in dirs:
         old_dname = (dir)
         new_dname = old_dname.strip( )
	newdir = new_dname
	if newdir <> old_dname:
             newpath = os.path.join(root,newdir)
             oldpath = os.path.join(root,dir)
             os.rename(oldpath,newpath)
	    print oldpath
	    print newpath




From maxm at mxm.dk  Thu Jul  3 05:17:30 2003
From: maxm at mxm.dk (Max M)
Date: Thu, 03 Jul 2003 11:17:30 +0200
Subject: A story about Python... sort of
Message-ID: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk>

There is a story today on Slashdot


Open Source Project Management Lessons
======================================
http://developers.slashdot.org/article.pl?sid=03/07/02/1817220&mode=flat&tid=185

"Paul Baranowski takes a moment to reflect on Open Source Project 
Management in his blog. His reflections are based on the first two years 
of the Peek-a-booty project." Interesting comments on media coverage, 
choice of programming language, when to release a project, and more.


In that article Paul Baranowski has a list of lessons. One being

Engineering Lessons
-------------------
    1. C/C++ is no longer a viable development language


He doesn't really say in the article what language should be used 
instead. But there is a link to another page:

Which Language Do You Recommend?
================================
http://peek-a-booty.org/Docs/WhichLanguageDoYouRecommend.htm


And guess which language it is?


regards Max M




From sybrenUSE at YOURthirdtower.imagination.com  Mon Jul 14 20:21:59 2003
From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel)
Date: 15 Jul 2003 00:21:59 GMT
Subject: PyQT, Sharp Zaurus and color in the QTextBrowser
References:   <3F132103.4D18759F@engcorp.com>  
Message-ID: 

Sybren Stuvel enlightened us with:
> Al least, that's the way I see it. I dont't know Trolltech's
> intentions. I'll check out the docs.

Ok, here's the scoop:

Using QTextEdit as a Display Widget 

QTextEdit can display a large HTML subset, including tables and images.
The text is set or replaced using setText() which deletes any existing
text and replaces it with the text passed in the setText() call. If you
call setText() with legacy HTML (with setTextFormat(RichText) in force),
and then call text(), the text that is returned may have different
markup, but will render the same.

So that's it. A large HTML subset, which could mean anything. Oh well,
just stick to double-quotes and we'll be fine ;-)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 



From jjl at pobox.com  Sun Jul 20 20:12:45 2003
From: jjl at pobox.com (John J. Lee)
Date: 21 Jul 2003 01:12:45 +0100
Subject: python tags on websites timeout problem
References: 
Message-ID: <87d6g4u48y.fsf@pobox.com>

gregadelliot at hotmail.com (jeff) writes:

> im trying to pull tags off a website using python ive got a few things
> running that have the potential to work its just i cant get them to
> becuase  of certain errors?
> file = urllib.urlretrieve("http://images.google.com/images?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=rabbit"
> , "temp1.tmp")

Google's terms of service, IIRC, don't allow automated queries.  I'm
not entirely sure what that means, but people seem to interpret it as
meaning "Don't web-scrape", so don't do that.  Use the Google API
instead (you can get a free key).  It is true some bits of Google
aren't accessible through the API, though.  Dunno about the image
search facility.

http://www.google.com/groups?as_q=SOAP%20python%20google

http://sourceforge.net/projects/pywebsvcs


John



From amk at amk.ca  Thu Jul 10 11:11:12 2003
From: amk at amk.ca (A.M. Kuchling)
Date: Thu, 10 Jul 2003 10:11:12 -0500
Subject: How does python work
References: 
Message-ID: 

On Thu, 10 Jul 2003 13:05:07 +0200, 
	Geiregat Jonas  wrote:
> I'm asking myself how Python code get's executed ...
> What happens first etc ...
> First read the file and then ..

The code is parsed and compiled into bytecode that can then be executed.
Consult a textbook on parsing or programming language implementation for
more details about how parsing is done.  

I thought someone (MWH?) wrote an explanation of Python's internals once,
but can't find anything at the moment.  The Python docs have some relevant
material (http://www.python.org/doc/current/ext/ext.html), but that document
doesn't concentrate on the implementation details, just on the bits you can
easily access from extensions.

> also could someone point me to the build in functions in the python source
> code ?

They're in Python/bltinmodule.c.

--amk
OTHELLO: Once more, well met at Cyprus!
      -- _Othello_, II, i
      



From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de  Tue Jul 15 11:04:18 2003
From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Koczian)
Date: Tue, 15 Jul 2003 17:04:18 +0200
Subject: Open MS Excel Spreadsheet with Python
In-Reply-To: <0vJQa.6944$G%5.4151@twister.nyroc.rr.com>
References:  <0vJQa.6944$G%5.4151@twister.nyroc.rr.com>
Message-ID: 

Cy Edmunds schrieb:
> "Allison Bailey"  wrote in message
> news:mailman.1058229111.12248.python-list at python.org...
> 
>>I would like to open an existing MS Excel spreadsheet and extract
>>information from specific worksheets and cells.
>>
First things first:

  Python programming on Win32 : [help for Windows programmers] / Mark 
Hammond and Andy Robinson. - 1. ed.
Beijing [u.a.] : O'Reilly, 2000. - XVII, 652 S. : Ill.
ISBN 1-56592-621-8

Lots of material about MS Excel <-> Python. Uses Python 1.5.2, but most 
of the code works with later versions.

And of course, use your Excel VBA help to get the object and method 
names right.

>>I'm not really sure how to get started with this process.
>>I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate),
>>using Microsoft Excel 10.0 Object Library, then
>>import win32com.client
>>xl = win32com.client.Dispatch("Excel.Application")
>>wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls")
>>
>>Then, I get errors when I try the following:
>>sh = wb.worksheets(1)
>>

Most probably a simple case sensitivity problem:

sh = wb.Worksheets(1)

sh = wb.ActiveSheet might be better, depending on context.

>>
>>Also, do I need to run the makepy utility every time I run my script?

No, just once. I don't know anything about deploying, though.

> 
> Your code worked on my system. However, I have found this interface to be
> pretty tricky. It often happens that while you are debugging the program you
> generate an instance of Excel which then makes later operations bomb
> mysteriously. On XP, hit Ctrl-Alt-Del tp bring up the task manager and then
> look at the Processes tab. If you have an instance of Excel running you
> should see it there. Use End Process to get rid of it.
>
Very true (but as I read the original post, the exceptions start at 
first try).

> You can avoid these problems by making sure that any COM references you make
> get released properly if an exception occurs. Your script would look like
> this:
> 
> import win32com.client
> xl = win32com.client.Dispatch("Excel.Application")
> try:
>     wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls")
>     try:
>         sh = wb.worksheets(1)
>         try:
>             print sh.Cells(2,3)
>         except:
>             sh = None
>             raise
>         sh = None
>     except:
>         wb.Close()
>         wb = None
>         raise
>     wb.Close()
>     wb = None
> except:
>     xl = None
>     raise
> xl = None
> 
> There are more elegant ways of doing this using classes. However, with this
> code I think you will never see one of those mysterious Excel instances in
> your task manager.
> 
I think try / finally would be better. Explicitly deleting all three: 
sh, wb and xl is the key to not having Excel zombies, if there is an 
exception or not.

That's a small bug in the easyExcel class of the Hammond book: it only 
deletes xl, not the variable representing the Workbook. So you still get 
your zombie.

HTH,
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 tzot at sil-tec.gr  Tue Jul  8 12:38:59 2003
From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou)
Date: Tue, 08 Jul 2003 19:38:59 +0300
Subject: [OT] On the TimBot
Message-ID: <62slgvsljos7v5snie6toc4qucv5nt1n15@4ax.com>

I am again trying to catch-up with the group (my time-sharing slices get
longer and longer as I grow old :), so after sequentially reading
several of TimBot's common slash-and-hack (or slash-and-wink for lamers,
or hack-and-wink for coders, or hack-slash-star-wink!-star-slash for C
coders) replies, I would like to address the following two warnings:

1. To "Matrix" fans: don't ever use the line "He's only human" on the
TimBot.  It's not.
2. To "2001 A space odyssey" fans: whenever it says "sorry", it's being
sarcastic 
3. To "Tron" fans: yes, you could assign the name TimBit to it, but it's
a broken Bit; what's the use of a Bit that's always true?

PS I can't count; there are 10 kinds of people, those who grok binary
and those who don't.  
Thanks Tim for your code and for your posts, and cheers everyone :)
-- 
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.



From mickel at csc.fi  Wed Jul  2 03:58:07 2003
From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=)
Date: Wed, 2 Jul 2003 10:58:07 +0300 (EEST)
Subject: How do I get the fractions of the visible part of a canvas?
Message-ID: 

Hi,

I have a Tkinter.Canvas of variable width. Is there a standard way of
asking the canvas which parts of it that is visible? I.e. on the
horizontal scale, I would like to know at what fraction from the left the
left visibility border is and from what fraction to the right the right
visibility border is.

Consider this ascii picture as an example

+-------------------------------+
|                               |<-- the full canvas
|     a------------------+      |
|     |                  |<--------- the currently visible part
|     +------------------b      |
|                               |
+-------------------------------+

I would like to be able to ask the canvas something like:

t = canvas.visiblebox()

and it would return a two-tuple of two-tuples with coordinates (of the
a and b points in the picture above), say:

t = ((10,10), (90,30))

Using these values I could calculate the fractions myself.

Any ideas?

/Mickel

--
Mickel Gr?nroos, application specialist, linguistics, Research support, CSC
PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237
CSC is the Finnish IT center for science, www.csc.fi





From support at takeitcheap.com  Sun Jul 13 01:10:29 2003
From: support at takeitcheap.com (Support Take It Cheap)
Date: Sun, 13 Jul 2003 00:10:29 -0500 (Central Daylight Time)
Subject: (no subject)
Message-ID: <3F10E9C5.000006.60229@criminal>

It's Finally Here!!!

www.takeitcheap.com

The place where you can get consumer electronics for almost FREE!!!





Check it out at

www.takeitcheap.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 6592 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 8000 bytes
Desc: not available
URL: 

From pifpafpuf at gmx.de  Fri Jul 18 12:55:54 2003
From: pifpafpuf at gmx.de (Harald Kirsch)
Date: 18 Jul 2003 09:55:54 -0700
Subject: Jython: preload PythonInterpreter with values for use in scripts
Message-ID: <16990fa4.0307180855.48705a33@posting.google.com>

How can I set variables in PythonInterpreter such that
scripts then run via import can have access to it.

My idea was to go along the lines of:

    PythonInterpreter ip = new PythonInterpreter();
    // make the object about to use the interpreter
    // available to that interpreter
    ip.set("javaCaller", this);
    ip.exec("import mystuff");

Within mystuff.py I wanted to do things like

    m = sys.modules['__main__']
    m.javaCaller.setThoseNiftyFeaturesOfTheCallingJavaObject("hello")

Alas, sys.modules does not contain '__main__'. 

Is there any way to get hold of locals() of PythonInterpreter ip within
a module imported as shown above?

I would expect that execfile allows the above communication,
but then I have to do all the searching for the module myself.
Therefore a solution where the module is simply imported as above
is preferred.

  Thanks,
  Harald.



From vze4rx4y at verizon.net  Wed Jul 16 05:02:52 2003
From: vze4rx4y at verizon.net (Raymond Hettinger)
Date: Wed, 16 Jul 2003 09:02:52 GMT
Subject: hex check
References: 
Message-ID: <0x8Ra.429$7O.326@nwrdny01.gnilink.net>

[Ruslan Spivak]
> Does anybody have a hint how to check if input hex number is in correct
> hex format?

Try converting it.
If the conversion fails, then the format was bad:

>>> int('0x2F', 16)
47
>>> int('0x2G', 16)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    int('0x2G', 16)
ValueError: invalid literal for int(): 0x2G



Raymond Hettinger





From tjreedy at udel.edu  Thu Jul 10 17:30:55 2003
From: tjreedy at udel.edu (Terry Reedy)
Date: Thu, 10 Jul 2003 17:30:55 -0400
Subject: for in sequence problem... possible new operator to add to python
References: <3a8fc6c5.0307100816.634c83a3@posting.google.com>
Message-ID: 

"Adam Gent"  wrote in message
news:3a8fc6c5.0307100816.634c83a3 at posting.google.com...
> However I want b [in 'for b in somedict']  to be the values with out
doing:
> for b in bl.values()

If you succeed in subverting the standard idiom, you succeed in making
your code misleading for anyone else who ever reads it.  You may also
succeed in hindering yourself from either learning the standard idiom
and understanding others' code or in understanding your own code if
you subvert it sometimes and sometimes not.  Seems like a bad idea to
me.

Terry J. Reedy





From vze4rx4y at verizon.net  Thu Jul 17 11:08:16 2003
From: vze4rx4y at verizon.net (Raymond Hettinger)
Date: Thu, 17 Jul 2003 15:08:16 GMT
Subject: list() coercion
References: 
Message-ID: 

"Ian Bicking"  wrote in message
news:mailman.1058400718.22076.python-list at python.org...
> I have an iterable object.  It supports many list-like methods,
> specifically __len__.  These methods are rather expensive (they result
> in database calls, COUNT(*) to be specific), but cheaper than iterating
> over the object.  Sometimes it is useful to create a list from the
> iterator, using list().  However, list() seems to call the object's
> __len__, I imagine to pre-allocate space.  This is a problem, as
> pre-allocation saves much less than is spent doing __len__.
>
> Is there a way I can keep this from happening?  Maybe something list()
> tries first that I can make fail.  (I notice list() catches any
> exceptions in __len__ and then will just skip that step)

Instead of:

    list(yourobj)

use:

    list(iter(yourobj))

If that doesn't help, create your own wrapper:

def myiter(it):
    for elem in it:
        yield it

list(myiter(yourobj))


This idea is to provide 'list' with a wrapper that only supplies
the iter methods and not the len method.


Raymond Hettinger





From bkelley at wi.mit.edu  Thu Jul 17 12:18:29 2003
From: bkelley at wi.mit.edu (Brian Kelley)
Date: Thu, 17 Jul 2003 12:18:29 -0400
Subject: Co-routines
In-Reply-To: 
References:  
Message-ID: <3f16cc00$0$3932$b45e6eb0@senator-bedfellow.mit.edu>

> There is a 'Flow' module in Twisted which uses generators to 
> accomplish this sort of thing.   Basically, Twisted has a 
> queue of functions that are called, and by yielding "cooperate"
> object, you re-schedule the given generator for execution
> on this queue (allowing other code blocks to execute).
> 

Check out this article:

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

on weightless threads, a simpler version of "Flow"

Now, my question is, could an arbitrary function's bytecode be liberally 
sprinkled with "yeilds" at run-time to achieve this effect without 
having to alter the source code?




From sholden at holdenweb.com  Tue Jul  1 23:39:04 2003
From: sholden at holdenweb.com (Steve Holden)
Date: Wed, 02 Jul 2003 03:39:04 GMT
Subject: Meerkat script suddenly fails: output format changed?
Message-ID: 

For quite a while now I've been filling part of the navigation-bar on my
home page with Python-related news extracted from O'Reilly's meerkat
service.

I've been experiencing intermittent problems for the past few days, and now
suddenly the crontab-triggered script has stopped working completely,
apparently due to a change in what Meerkat sends in response to my queries.
I've not been able to find any description af changes to Meerkat, but since
my script appears to have been unchanged for over six weeks and this error
has only just appeared, I can only assume this represent searching
ineptitude on my part.

The relevant extracts from the script are:

# Get a list of article categories from the O'Reilly Network
items = server.meerkat.getItems(
    {'search':'/[Pp]ython/','num_items':10,'descriptions':100})

and

print >> out, "
\n".join( ["""%(title)s """ % item for item in items] It's this last statement which is now failing, with a KeyError because there's no "link" key in the items returned by the call to server.meerkat.getitems(). Printing out the list of items confirms this, with what I can only describe as a somewhat-unexpected output: {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} {'description': "Senator Kennedy's new inaccessible web site. On writing for the web. The Python path module. The art", 'title': 'In brief: Superbowl Sunday'} About the only thing I find reassuring about this output is the fact that it explains the KeyError, and that http://www.oreillynet.com/meerkat/ looks equally disoriented if you search for the string "python". What gives? Can anyone tell me a) is this something I've done, or is it somebody else's fault, and b) how the hell do I get back to the happy state where I can get my Python news form my home page? regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From mwh at python.net Mon Jul 14 07:15:50 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Jul 2003 11:15:50 GMT Subject: Identity inconsistency and unification of types and classes References: <6f03c4a5.0306301943.d822a6d@posting.google.com> Message-ID: <7h3isq5nz5l.fsf@pc150.maths.bris.ac.uk> rimbalaya at yahoo.com (Rim) writes: > Hi, > > With the great unification of types and classes, what will happen to the > following identity inconsistency? > > >>> class myint(int): pass > ... > >>> a=int(1); b=int(1) > >>> a is b > 1 > >>> a=myint(1); b=myint(1) > >>> a is b > 0 Nothing, as is. You can always dick about in myint.__new__ if you really want to manage that, but as others keep saying, you shouldn't worry about it too much. Cheers, M. -- My hat is lined with tinfoil for protection in the unlikely event that the droid gets his PowerPoint presentation working. -- Alan W. Frame, alt.sysadmin.recovery From adalke at mindspring.com Tue Jul 22 18:18:32 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 22 Jul 2003 16:18:32 -0600 Subject: SAX questions... References: Message-ID: Timothy Grant: > def startElement(self, name, attr): > if name == "foo": > do_foo_stuff() > elif name == "bar": > do_bar_stuff() > elif name == "baz": > do_baz_stuff() ... > I could create a dictionary and dispatch to the correct method based on a > dictionary key. But it seems to me there must be a better way. def startElement(self, name, attr): f = getattr(self, "do_" + name + "_stuff", None) if f is not None: f() However, the dictionary interface is probably faster, and you can build it up using introspection, like class MyHandler: def __init__(self): self.start_d = {} self.end_d = {} for name in MyHandler.__dict__: if name.startswith("do_") and name.endswith("_stuff"): s = name[3:-6] self.start_d[s] = getattr(self, name) elif name.startswith("done_") and ... s = name[5:-6] self.end_d[s] = getattr(self, name) def startElement(self, name, attrs): f = self.start_d.get(name) if f: f() ... Andrew dalke at dalkescientific.com From rmachne at meta.lo-res.org Tue Jul 15 10:04:03 2003 From: rmachne at meta.lo-res.org (rmachne) Date: Tue, 15 Jul 2003 16:04:03 +0200 (CEST) Subject: newbie question: ImportError: No module named Numeric Message-ID: <20030715155428.C48367@meta.lo-res.org> Hi there, Sorry, if there is a newbie list or this question is answered in tutorials - I tried but without succes :-( - here is my question: Using linux, I need the 'Numerical Python' package, and I installed it on my local computer (not with the other packages in /usr/local/...) using ~/programs/Numeric-23.0>python setup.py install --home=/scratch/raim but now the Numeric package / module can't be found: ~/programs/Numeric-23.0/Test> python test.py Traceback (most recent call last): File "test.py", line 2, in ? import Numeric ImportError: No module named Numeric Exit 1 I couldn't find out which path variable to change or add. Can anyone help? (Test.py works fine when called from within the lib folder with Numeric.py) best rainer From peter at engcorp.com Wed Jul 23 09:05:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jul 2003 09:05:37 -0400 Subject: needs a logo References: <7fe97cc4.0307230144.9119f89@posting.google.com> Message-ID: <3F1E8821.B805306D@engcorp.com> Xah Lee wrote: > > it would be good if Bash and Python have a decent logo. Great! When will you have the improved logos ready for us to use? -Peter From mwh at python.net Tue Jul 15 10:43:58 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jul 2003 14:43:58 GMT Subject: anything like C++ references? References: Message-ID: <7h3vfu3n9fa.fsf@pc150.maths.bris.ac.uk> Stephen Horne writes: > However well you explain what Python does, that doesn't mean that it > is doing the right thing. Doesn't mean it's wrong, either. pointless-ly y'rs mwh -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From mis6 at pitt.edu Tue Jul 15 09:20:30 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Jul 2003 06:20:30 -0700 Subject: Need help: Compiling Python-Code References: Message-ID: <2259b0e2.0307150520.2487cd2@posting.google.com> "Thomas Buschhardt" wrote in message news:... > import py_compile > pycompile.compile(Python-file) > > Bye Thomas I am sure the OP has a good reason for asking his question, nevertheless for the sake of newbies who wonder if they should byte-compile their scripts, here is an extract from help(py_compile): Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc (or .pyo) file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc/.pyo file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. Just my 2 cents, Michele From abcdebl2nonspammy at verizon.net Thu Jul 17 21:44:16 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Fri, 18 Jul 2003 01:44:16 GMT Subject: Regular expression help In-Reply-To: References: Message-ID: Thank you Andrew, Fredrik and Bengt. This is exactly what I was looking. I actually have a moderate size test file (400k) so if I get to it, I'll post comparison times for the different methods suggested. David From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 14 21:44:06 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 01:44:06 GMT Subject: Open MS Excel Spreadsheet with Python References: Message-ID: Allison Bailey enlightened us with: > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. Save the files as OpenOffice.org spreadsheets. They have an open format, which basically boils down to a few XML files zipped up and named something.sxc. It's about 20 minutes to make a program that parses it. > I think I'm missing something fairly fundamental, but I've > googled all over the place and can't seem to find anything very > introductory about opening and using data from MS Excel using Python. That's probably because most sensible Open Source users make sure they don't come anywhere close to MS Office. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From skip at pobox.com Wed Jul 2 10:12:06 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 09:12:06 -0500 Subject: Possible fix for Bug 494589 - os.path.expandvars bug In-Reply-To: <3F02015F.3000903@dadsetan.com> References: <3F02015F.3000903@dadsetan.com> Message-ID: <16130.59446.147381.375070@montanaro.dyndns.org> Behrang> Sorry you will be getting no patch from me at the moment since Behrang> sourceforge's anonymous CVS access does not like me. The Python project requires non-anonymous submissions for a very good reason. When anonymous submissions were allowed it was impossible to contact the submitter for a followup. This was especially bothersome for bug reports. If a bug report was incomplete or the bug couldn't be reproduced, there was no choice but to close the bug report as incomplete. Skip From carsten at sarum.dk Wed Jul 16 08:54:16 2003 From: carsten at sarum.dk (Carsten Gehling) Date: Wed, 16 Jul 2003 14:54:16 +0200 Subject: Choosing the right framework Message-ID: Oh how often this subject may come up... The thing is, I've come to the decision of abandoning PHP as much as possible (old projects still remain...), and use Python for all purposes. Reason: One language to fit it all (instead of having one language for webprogramming, one for batches, etc...) I stand now at the point where I must choose a framework for my web application development. I've skimmed a few: mod_python, pso and Zope. However, I cannot decide on which to choose. I've read descriptions and comments on http://www.python.org/cgi-bin/moinmoin/WebProgramming to get other's opinions. The user comments are sparse though, so I've decided to ask here. I like the ideas behind Zope. For instance the "long running process" feature that improve performance and retain scripts between requests, among other things. I do not, however, like the design of the management interface, it would not appeal to my customers. I'm not yet knowledgable enough about Zope, to know if this can be changed. Anyone who can elaborate? (MaxM don't answer "Plone"... ;-) mod_python seems the choice, if I want the feature of retaining scripts in memory between requests and want to write my own managemen interface. I don't know, if it allows for application variables (variables shared globally between sessions). pso looks like the framework that is easiest to deploy. If run under mod_python, it also retains scripts in memory, but does it allow for the aforementioned application variables? And does the performance match up compared to mod_python and Zope? It'll probably be run behind an Apache httpd server, so I guess Twisted is out of the question. What is your preferred framework? And why? To those who would ask "What do you want to do with it", the answer is: General purpose web application development. Porting (enhancing) of my existing CMS (built in PHP - it's badly in need of a rewrite, so the time is right for changing to Python). I am to start on a new web project in the beginning of next week, and I would like to use this opportunity to make the switch from PHP to Python. Which is why I ask and don't just spend 2+ more weeks to dig further into the above mentioned frameworks before making the decision. - Carsten From grante at visi.com Wed Jul 23 14:25:30 2003 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2003 18:25:30 GMT Subject: How to do raw Ethernet under Win32? Message-ID: <3f1ed31a$0$181$a1866201@newsreader.visi.com> How does one do raw Ethernet under Win32? Ultimately, I want to do it in a Python program, but if somebody can point me to a clue on how to do it from C, I could probably figure out the rest. I want to: 1) Send an arbitrary Ethernet packet. [Well, not completely arbitrary, the source MAC will be "right", but the protocol number is a proprietary (not IP) one, and the packet isn't anything standard. 2) Receive any incoming packets with a specified protocl number -- same proto number as in 1) above. I've got a program that works under Linux, and I'd like to be able to port it to Win32... -- Grant Edwards grante Yow! I have seen these at EGG EXTENDERS in my visi.com Supermarket... I have read theINSTRUCTIONS... From Hobbes2176 at yahoo.com Wed Jul 9 10:19:08 2003 From: Hobbes2176 at yahoo.com (Mark) Date: Wed, 09 Jul 2003 14:19:08 GMT Subject: Memoizing Generators References: Message-ID: Hi Michael, Michael Sparks wrote: > How would you deal with the following generator? (On the assumption you > want a a general purpose memoisation mechanism :) > <*snip* a generator reading from an input source> > If your source is a network connection, or a real user this becomes > further indeterminate... Not a suggestion to not try, just worth > considering :) I think one of the standard assumptions with memoization is that you have a deterministic algorithm ... specifically, given an input, the output is fixed. So, your example of entering a file and getting different data, throws typical (in my opinion ... which is by no means sacred) memoization out the window. > def runGenerator(fn,args,timeAlloted): > tstart = time.time() > gen = fn(args).next > r = gen() > while 1: > if time.time()-tstart >=timeAlloted: > break > r = gen() > return r Now, this is a problem I like. It would be pretty damn awsome to memoize a function with 1) a time constraint and 2) a parameter that would indicate when a time constraint is no longer sufficient and thus more work needs to be done. Finally, if the generator could _restart_ at the point of work already done, you would be saving the work done to that point which is memoization's purpose: Something like: runGenerator(PIdigits, None, 10) and then later runGenerator(PIdigits, None, 20) Then our memoizer would say, well, I can get more digits in the extra 10 seconds .... so, I need to recompute this answer. But wait, hopefully, I've stored both the numerical result for 10 seconds along with the generator that got me there. So, all I need to do is look up the 10 second generator and run it for another 10 seconds. Humm, can we copy generators? I don't seem to think so. So, the memoizer class would need some more logic and storage to determine whether to return a stored result, computer a brand new result, or bootstrap off a previous generator. There would also need to be a mechanism for determining just how long is "long enough" that more time needs to be allocated (a really hard problem might not get any further in 12 seconds than it does in 9 seconds). And we'd need a copy of the generator so we could go from, say 10 second generator to 20 second, but later go from 10 to 15 seconds. Although, we could get around the problem by using the maximally accurate result computed so far (presuming we can look it up in the user specified time interval). Then we'd only need the generator at the farther point ... and we could just keep running it when the user gives us more time. Yeah, that could work nicely! > > Consider the possibility that the function is a "next move" in chess and > the time is set by the first player to "hard" - ie lots of time. The next > time a player comes along with the time set to "easy", the memoised > version won't be aware of this in this scenario and returns the hard We could paramaterize the generator (and/or the memoizer) based on the difficulty setting .... couldn't we? > result (but very quickly...), or worse hits stop iteration - which the This is another interesting problem .... the "quick result" is actually a means of making the game harder. > Regards, > Michael. Great ideas. I might code up the timing based memoizer for kicks. Regards, Mark From grante at visi.com Wed Jul 16 14:26:56 2003 From: grante at visi.com (Grant Edwards) Date: 16 Jul 2003 18:26:56 GMT Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> <3f156c23$0$166$a1866201@newsreader.visi.com> <3F1573FB.8ADBE587@engcorp.com> Message-ID: <3f1598ef$0$164$a1866201@newsreader.visi.com> In article <3F1573FB.8ADBE587 at engcorp.com>, Peter Hansen wrote: >> Though I was recently surprised that the remove() method for >> lists uses "==" and not "is" to determine what to remove. It's >> documented that it works that way. But, it wasn't what I >> excpected, and it took me a while to figure out that it was >> using my class's __cmp__ method rather than the object ID. > > Probably a very good thing, considering what would happen if > you were trying to remove strings from the list, rather than > simple things like integers... I didn't mean to imply that the way it's done isn't a good idea, or that what I expected wasn't a bad idea. It's just novel to be surprised by Python -- which wasn't the case with FORTRAN. -- Grant Edwards grante Yow! My nose feels like a at bad Ronald Reagan movie... visi.com From grante at visi.com Thu Jul 24 13:17:12 2003 From: grante at visi.com (Grant Edwards) Date: 24 Jul 2003 17:17:12 GMT Subject: Put sys.stdout into binary mode? Message-ID: <3f201498$0$177$a1866201@newsreader.visi.com> How do I make sure that sys.stdout (or sys.stdin) is in "binary" mode? This seems to work, is it the "right" way of doing it? sys.stdout = os.fdopen(sys.stdout.fileno(),'wb') -- Grant Edwards grante Yow! -- I can do at ANYTHING... I can visi.com even... SHOPLIFT!! From hamido at tmsk.itm.edu.my Wed Jul 9 02:42:45 2003 From: hamido at tmsk.itm.edu.my (hamido) Date: Wed, 09 Jul 2003 14:42:45 +0800 Subject: Comparing python and Perl - Network + administration Message-ID: <3F0BB965.898DCA5C@tmsk.itm.edu.my> Hi I am very-very new in Pyton langguage In my next project I will promote Python / Perl /Shell Programming I enjoy and intensively comparing python and Perl in term of networking and system admionistration. Is there any function or modules to make system administration ( like shell-bash, Perl) ? TQ ##################################################################################### This e-mail message has been scanned for Viruses and Content and cleared by NetIQ MailMarshal ##################################################################################### From newsgroups at jhrothjr.com Mon Jul 21 21:22:48 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 21 Jul 2003 21:22:48 -0400 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: "Bengt Richter" wrote in message news:bfhvnk$hvd$0 at 216.39.172.122... > On 21 Jul 2003 07:26:15 -0700, mis6 at pitt.edu (Michele Simionato) wrote: > > >After a recent thread on .endswith, I have been thinking about iterators. > >I realized that I don't know a satisfactory way to check if an > >iterator is empty. In other words I am looking for an > >"isempty" function to use in "if" statements such as > > > >if isempty(iterator): > > do_something() > > > >without side effects. Here are some unsatisfactory ways of implementing > >"isempty": > > > >#1: converting to a list or tuple > >def isempty(iterator): > > return not list(iterator) > > > >Easy, but one has to create the entire list, thus defecting the basic > >purpose of the iterator, i.e. lazy evaluation. > > > >#2: checking for StopIteration > >def isempty(iterator): > > try: > > iterator.next() > > except StopIteration: > > return True > > else: > > return False > > > >This works, for instance > > > >print isempty(iter([])) > > > >gives True and > > > >it=iter([1,2,3]) > >print isempty(it) > > > >gives False. However, there is a side effect: after the check, the > >iterator has advanced of one step and now "it.next()" gives 2, not 1. > >In order this to work without side effects, I should be able to restart > >the iterator from the beginning, but I don't know how to do that. > >Is it possible? > > > >#3: comparing with the empty iterator > > > >emptyiterator=iter([]) > > > >it=iter([]) > > > >if it == emptyiterator: print 'Ok!' > > > >This simply doesn't work. > > > >I wonder if the itertools module should contain a function to check for > >empty iterators, thus simplifying my life ;) Of course, I may well be > >missing something obvious, if so, please enlighten me. > > > If iterators had a .peek() method for 1-item lookahead, maybe that would > be easy to implement. If empty, it could raise StopIteration, and otherwise > return what next() would return, without disturbing the state w.r.t. next(). > > Alternatively, it could return [nextitem] vs [] if at the end > (without raising StopIteration). I think that's two separate functions. isEmpty() is not the same thing as willBeEmptyOnNextCall(). That said, there are places where a 1 item lookahead can be quite valuable, and lack of a sliding window is the last major thing I'd like to see addressed in the for loop. John Roth > > Regards, > Bengt Richter From intentionally at blank.co.uk Mon Jul 14 18:37:41 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 23:37:41 +0100 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Message-ID: On 14 Jul 2003 11:44:02 -0700, owski at hotmail.com (Adam Ruth) wrote: >Stephen Horne wrote in message news:<1br3hv4434gn7p2pdg1bgtg8dtlak3id3s at 4ax.com>... >> I've said my piece on meanings derived from computer science (and in >> turn from mathematics, as it happens - variables as placeholders for >> values predate electronic computers by quite some time. > >The mathematics I'm used to has a very different concept of assignment >than does a static language like C. Here's why. > >In math there are global unchanging objects called numbers, 1, 2, 3, >etc. If I have 2 variables, x and y and they both equal 500, then >they both are names bound to the value 500. They are not each copies >of the value 500, math has no such concept, there is only one 500. Yes. Mathematics does have assignment - it had assignment long before electronic computers existed because algorithms were a concept studied in mathematics long before computers existed. If in mathematics, if I have one variable a defined as representing the set {1, 2, 3} and a variable y also defined as representing the set {1, 2, 3} and I decide to change y to {1, 2, 4} then that redefinition process does not change the value {1, 2, 3} to {1, 2, 4}. It only changes what the variable y is currently taken to represent. Values cannot be mutable in mathematics. In Python, *objects* can be mutable. Values cannot be mutable because they are values - something defined in mathematics. 1 cannot become 2. But a variable can be reassigned to represent something else. In-place modification of part of an object is a practical way of replacing one value with another. Thus, if I write... >>> a=[1,2,3] >>> a[2]=4 >>> a [1, 2, 4] Nothing is wrong. The in-place modification of part of the object that a is bound to is basically a convenient shorthand for reassigning the whole value of a. The value now bound to a is [1, 2, 4] rather than [1, 2, 3]. No value has mutated. Nothing is wrong in mathematical terms. The fact that we are using something called an object (or a pointer to an object or whatever) to implement the binding to a value is unimportant. >>> a=[1,2,3] >>> b=a >>> b[2]=4 >>> b [1, 2, 4] >>> a [1, 2, 4] Because the variable b has been bound to an object (*NOT* a value), the mutation has a side-effect. Changing the value bound to the variable b also changes the value bound to a. This does *NOT* happen in mathematics, because there is no such thing as an object. Reassigning one variable in mathematics never implicitly redefines another. In short, this no longer implements a binding of values to variables because of the side-effect of changing the value bound to a when you change the value bound to b. The implementation detail of how the binding from variables to values is achieved (by binding to objects) has changed the results of running the algorithm. In a true functional language, variables are not mutable. It doesn't matter in the slightest if binding of variables is handled by copying pointers to objects instead of copying objects - it is irrelevant because copying pointers to objects achieves exactly the same thing as copy the objects themselves - it implements a binding of value to variable. The object bound to a variable in Python is a low-level implementation concept. From Guidos own words, we can see that he (at least at one point) recognised that binding to objects in a context where those objects can be mutable is confusing and error-prone. The value bound to a function in mathematics is a high-level concept. I thought Python was *supposed* to be an very high-level language? Even C++ is higher level that this. The C++ standard libraries I've used will optimise assignment of strings by merely copying pointers. The sequence of events you get is something like this... std::string x ("Hello"); // x bound to object containing value "Hello" std::string y (x); // y bound to same object as x, but with an indication that // sharing is happening. y [4] = '!'; // A write to y, with the purpose of changing the value that y // is bound to but not changing the value that x is changed to. // Thus a copy of the object containing "Hello" is made and // bound to y before applying the change. This is called // copy-on-write. In short, C++ can and often does use the pointer-copying optimisation in the standard library. But it does so in such a way that the low level binding of variables to objects implements the high level binding of variables to values correctly. It is clear now that many people are highly committed in the binding of variables to objects done in a way that does not implement binding of variables to values - though there seems to be fuzzy thinking used against me just as much as my own fuzzy thinking earlier. For instance... On 14 Jul 2003 07:39:57 +0200, martin at v.loewis.de (Martin v. L?wis) wrote: : And so does mine: Variables are *not* containers of values, in : traditional mathematics. They are bound to values instead. Python does not bind values to variables. It binds objects to variables. Objects are how values are implemented, but they are not the same thing. In computer science and mathematics, the whole point of variables is to bind a variable to a *value*. Terms such as 'store location' and 'object' are about *implementing* that binding from variable to value. In mathematics, it doesn't matter whether you talk of variables being placeholders for values or whether you talk of them being bound to values. The two are equivalent, because mathematics has no concept of objects as an implementation detail. Both terms are in common use. In support of this, I quote someone arguing against me... On 14 Jul 2003 11:44:02 -0700, owski at hotmail.com (Adam Ruth) wrote: """ C, and most static languages, have the concept of memory location, which doesn't exist in math. In C a variable is bound to a memory location which contains a value, not like math where the variable itself contains the value. Therefore I can have two variables, x and y, that point to their own distinct copy of 500 and when I assign a value, it copies the 500 into the memory location bound to x. """ "not like math where the variable itself CONTAINS the value" In addition, note that C++ does not copy the value. It copies a representation of the value. Thus when you say two variables contain "their own distinct copy of 500" what you are really saying is that two variables contain "their own distinct copy of a representation of the value 500". That is why you can use the operator '==' to test if two variables contain the same value - or rather in-store representations that represent the same value. """ In math there are global unchanging objects called numbers, 1, 2, 3, etc. If I have 2 variables, x and y and they both equal 500, then they both are names bound to the value 500. They are not each copies """ No - they are not objects, or store locations. They are global unchanging values. And yes, variables *are* bound to values - *not* objects. """ Python is more like the math form. There is only one instance of the number 500 and a name (variable) is bound to it or it isn't. To change the value of 500, then I must rebind the name, exactly in mathematics. However, Python differs from math in that math doesn't have mutable values (well it may when you get into real complex calculus, I don't know, never been there). """ Mutable values don't exist at all. Mutable objects do. When you mutate a part of an object, that object now represents a new value. Its a shorthand in Python for something that is perfectly valid in mathematics - but not if the binding of other variables to values is affected. BTW - "real complex" is a contradiction in terms ;-) Anyway, if you so love your variables binding to objects done in a way that does not correctly implement variables binding to values for mutable objects, fine. It simply means that Pythons users have to fuss about the implementation of Python instead of getting on with their applications logic, and that it will continue to cause confusion and errors on an ongoing basis. From ben at dadsetan.com Wed Jul 2 14:16:01 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 02 Jul 2003 19:16:01 +0100 Subject: Possible fix for Bug 494589 - os.path.expandvars bug References: <3F02015F.3000903@dadsetan.com> Message-ID: <3F032161.7000108@dadsetan.com> Anthony Baxter wrote: >>>>"Steve Holden" wrote >>> >>"Behrang Dadsetan" wrote ... >> >>>Sorry you will be getting no patch from me at the moment >>>since sourceforge's anonymous CVS access does not like me. >> >>[...] >> >>If you can figure out everything you wrote about, it can't be *that* hard to >>create a sourceforge account ;-). > > > I assume he's referring to the Sourceforge pserver access being... ahem... > well... less than good, of late, rather than being logged in to log a > bug or patch. > > Anthony > I guess my english was really bad in that sentence since you are the only who understood me :) I am trying to be respectful towards the tools that are offered to us for free... of course I can therefore no longer be as explicit about my actual thoughts. I there a way for me to get a SSH CVS access? Or will someone make/submit the patch for me? I could of course make one based on the version of the sources I have but I think I would get banned from here for ever if I am unlucky and the sources changed enough :) Thanks, Ben. From clpy.NOSPAM at russellsalsbury.com Mon Jul 21 17:18:11 2003 From: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) Date: 21 Jul 2003 14:18:11 -0700 Subject: Guido Makes the Wall Street Journal Message-ID: <4868482a.0307211318.8f2e6d0@posting.google.com> Guido, Python, Larry Wall, and Perl are profiled in Lee Gomes's Portals column in today's (21-Jul-2003) Wall Street Journal. Nothing very deep, but a pretty good profile of the languages and creators targeted towards business types. I would count it as quite favorable publicity. It says Python and Perl are the top two scripting languages. They rival C and Java in power and performance, but they have kept their ease of use. The article goes on to explain that languages have personalities. There is a funny take on the differences in language philosophies. The Python Way comes across as "my way or the highway." Larry Wall on Perl, "God doesn't enforce morality on us, but prefers to let us choose it. And if we are created in God's image, we ought to extend the same courtsey." I guess those of us cast out of the Garden of Perl have no right to complain that we are bound to the whims of a mad dictator. We chose this path. The article is good news, because it'll probably get an executive or two to ask, "What is this Python stuff?" -- Russ From anlri at wmdata.com Wed Jul 2 04:28:39 2003 From: anlri at wmdata.com (alr) Date: 2 Jul 2003 01:28:39 -0700 Subject: Idiomatic way of repeating items in a sequence. References: Message-ID: Wow, tanks for alle the replies. My favourite is John Hunters/Bob Gailers solution ([x for x in seq for i in range(repetitions)]). I had forgotten that you could have nested for statements in list literals... Aahz's point is taken. I happen to need to repeat lists of strings (which are immutable), but that's not what i asked about now is it. :-) -- Regards Andr? Risnes From mynews44 at yahoo.com Mon Jul 28 14:40:48 2003 From: mynews44 at yahoo.com (google account) Date: 28 Jul 2003 11:40:48 -0700 Subject: newbie needs a little help... trying to write an ftp script. Message-ID: hiya, I am a network admin type person who has (after a bit of research and a couple of dabblings) decided that python is the language for me. I have read through learning python, nad it has managed to give me a great basis for the things I have done previously (regex manipulation of config files, mostly. I got a great application built fairly quickly that would parse an apache config, add a VirtualHost entry, sort it alphabetically and sighup the deamon) but my present task is something that doesn't really get covered in this most excellent tome. I want to create an ftp script that will (from a windows2000 host) log into an ftp server, change down one directory, download specific files from this directory (wildcard passing...?) and then log out. Once it has completed this task, it should email someone to inform them of completion status, perhaps including the output of the ftp session. I can't imagine that it would be too hard, but I don't see anything afer a google search that will give me any pointers so I was hoping I might get some in response to this post. I have found the ftplib, and the info on the python.org docs. I am needing a pointer on the syntax, or a bit of a (non-programmer) translation with what they mean. The docs suggest that I could do something like.... import ftplib ftp = ftplib.FTP('172.30.30.30') # This is wrong, somehow...? ftp.login(user,pass) ftp.retrlines('LIST') # I believe it might need to be ftp.retrlines('ls -al') ftp.sendcmd('prompt') ftp.cwd('folder') ftp.retrbinary(retr *tgz) ftp.quit() Or that maybe I could define a new class with something like this: class HandleFTP(ftplib.FTP): (I am not sure what would follow here, but I'm thinking it might be what I want. This way I get to define a few functions within my own class, and these can capture all the server output to a text file, for later emailling.) Basically, I am getting errors with the first line somehow, and I am not sure what to replace it with. Some of these things, the docs tell me they return a string. Does that mean I should initialise a string for them? Would they not work if that isn't happening, or would the output just end up in /dev/null? Thanks for looking! Googleboy From claird at lairds.com Thu Jul 31 20:36:31 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 01 Aug 2003 00:36:31 -0000 Subject: Secure FTP in Python? References: Message-ID: In article , Kyler Laird wrote: >"d z e k y l" writes: > >>Or is there some other >>(noncomplicated) way how secure uploading can be implemented in Python? > >About anything is less needlessly complicated than FTP. >SSH is often the obvious choice, but WebDAV can also >run over SSL. > >--kyler rsync, in particular, is a good fit for what many people mean by "uploading", and rsync is ssh-savvy. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ray at rays-web.com Sun Jul 6 23:20:30 2003 From: ray at rays-web.com (Ray Smith) Date: 6 Jul 2003 20:20:30 -0700 Subject: Python is a gem ,another successful day .... References: Message-ID: <5654fff9.0307061920.1a80bbc7@posting.google.com> "Steve Holden" wrote in message news:... > I'd be interested in knowing some of the arguments you used to win over VB, > as I've been asked to put a couple of articles together suggesting why VB > users might consider switching to Python. The first obvious reason is that VB 6 (which most VB users currently use) will be unsupported by 31-Mar-2005. http://support.microsoft.com/default.aspx?scid=fh;en-us;LifeDevToolFam The change from VB 6 to VB.Net is a huge change and in some cases a complete re-write. For some features missing in .Net see: http://www.mvps.org/vb/index2.html?rants/vfred.htm Regards, Ray Smith From claird at lairds.com Sat Jul 12 22:18:29 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 13 Jul 2003 02:18:29 -0000 Subject: new in town References: Message-ID: In article , Ian Bicking wrote: . . . >Then maybe the better answer would be: Python can be compiled into a >Windows executable for distribution, but it cannot be compiled to >improve speed. If you have performance issues there are a multitude of . . . Pysco is, of course, making even the Python "cannont be compiled to improve speed" proposition a debatable one. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ebolonev at rol.ru Thu Jul 3 12:56:17 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 03:56:17 +1100 Subject: Reading an image file data......... References: <3F044C9D.CE43D5F4@engcorp.com> Message-ID: Hello, Peter! You wrote on Thu, 03 Jul 2003 11:32:45 -0400: PH> Egor Bolonev wrote: ??>> ??>> [Sorry, skipped] PH>> That's twice I've seen you use this... what does it mean? It's a skipper plugin for Outlook E. I select a redundant text and press the Skip button. Should I change a label? http://www.fidolook.com/ With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From pyth at devel.trillke.net Fri Jul 25 15:56:02 2003 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 25 Jul 2003 21:56:02 +0200 Subject: path module In-Reply-To: <1059160667.28096.10876.camel@lothlorien>; from ianb@colorstudy.com on Fri, Jul 25, 2003 at 02:17:48PM -0500 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> <20030725203322.P6906@prim.han.de> <1059160667.28096.10876.camel@lothlorien> Message-ID: <20030725215602.Q6906@prim.han.de> Ian Bicking wrote: > On Fri, 2003-07-25 at 13:33, holger krekel wrote: > > We currently only have one 'visit' method that accepts a filter for returning > > results and a filter for recursing into the tree. > > ... > > This proved to be flexible and convenient and mostly avoids > > the need for multiple walk-methods. > > Yeah... but we know that's not going to get into the standard library. > It requires a big namespace, logic functions (AND, OR, etc.), and it > confuses functions with these filter objects, which are named the same > (and even if the filter objects can be used as functions, it's still > confusing). It's a style that doesn't exist in the standard library, > and it seems unlikely that it would get in here. Maybe right. This is not my first priority, anyway, but i also thought that functional style is just not liked among the builtins. Anyway, the "filter functions" are indeed just callables which accept Path objects. You could as well take the unbound method Path.isdir but this feels ugly and isn't flexible enough. I don't exactly know what you mean by "big namespace". The filters are all contained in a 'filter' submodule because they can apply to multiple Path implementations anyway. > The multiple walk methods would only be a shortcut anyway. Again, they > might be difficult in a situation like a URL where directory and file > are intermingled (and maybe ReiserFS 4...?) -- which maybe is okay, a > urlpath object simply wouldn't implement that walker. Yep, URL pathes have no notion of directories and files. Thus a general URL path can't have a 'listdir' method and thus we can't recurse. You can easily special case it for Apache's "Indexes" view, though :-) holger From hokiegal99 at hotmail.com Sat Jul 19 09:36:41 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 19 Jul 2003 09:36:41 -0400 Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> <3F1871A5.3020702@hotmail.com> Message-ID: <3F194969.6020807@hotmail.com> My scripts aren't long and complex, so I don't really *need* to use functions. But the idea of using them is appealing to me because it seems the right thing to do from a design point of view. I can see how larger, more complex programs would get out of hand if the programmer did not use functions so they'd be absolutely necessary there. But if they allow larger programs to have a better overall design that's more compact and readable (like your examples showed) then one could argue that they would do the same for smaller, simplier programs too. Thanks for the indepth explanation. It was very helpful. I'm going to try using functions within my fix_files.py script. Andy Jewell wrote: > On Friday 18 Jul 2003 11:16 pm, hokiegal99 wrote: > >>Thanks again for the help Andy! One last question: What is the advantage >>of placing code in a function? I don't see how having this bit of code >>in a function improves it any. Could someone explain this? >> >>Thanks! > > 8<--- (old quotes) > > The 'benefit' of functions is only really reaped when you have a specific need > for them! You don't *have* to use them if you don't *need* to (but they can > still improve the readability of your code). > > Consider the following contrived example: > > ----------8<------------ > # somewhere in the dark recesses of a large project... > . . . > for filename in os.listdir(cfg.userdir): > newname = filename > for ch in cfg.badchars: > newname.replace(ch,"-") > if newname != filename: > os.rename(os.path.join(cfg.userdir,filename), > os.path.join(cfg.userdir,newname) > . . . > . . . > # in another dark corner... > > . . . > for filename in os.listdir(cfg.tempdir): > newname = filename > for ch in cfg.badchars: > newname.replace(ch,"-") > if newname != filename: > os.rename(os.path.join(cfg.userdir,filename), > os.path.join(cfg.userdir,newname) > . . . > # somewhere else... > > . . . > for filename in os.listdir(cfg.extradir): > newname = filename > for ch in cfg.badchars: > newname.replace(ch,"-") > if newname != filename: > os.rename(os.path.join(cfg.userdir,filename), > os.path.join(cfg.userdir,newname) > . . . > ----------8<------------ > > See the repetition? ;-) > > Imagine a situation where you need to do something far more complicated over, > and over again... It's not very programmer efficient, and it makes the code > longer, too - thus costing more to write (time) and more to store (disks). > > Imagine having to change the behaviour of this 'hard-coded' routine, and what > would happen if you missed one... however, if it is in a function, you only > have *one* place to change it. > > When we generalise the algorithm and put it into a function we can do: > > ----------8<------------ > > . . . > . . . > > # somewhere near the top of the project code... > def cleanup_filenames(dir): > > """ renames any files within dir that contain bad characters > (ie. ones in cfg.badchars). Does not walk the directory tree. > """ > > for filename in os.listdir(dir): > newname = filename > for ch in cfg.badchars: > newname.replace(ch,"-") > if newname != filename: > os.rename(os.path.join(cfg.userdir,filename), > os.path.join(cfg.userdir,newname) > > . . . > . . . > > # somewhere in the dark recesses of a large project... > . . . > cleanup_filenames(cfg.userdir) > . . . > . . . > # in another dark corner... > . . . > cleanup_filenames(cfg.tempdir) > . . . > # somewhere else... > . . . > cleanup_filenames(cfg.extradir) > . . . > > ----------8<------------ > > Even in this small, contrived example, we've saved about 13 lines of code (ok, > that's notwithstanding the blank lines and the """ docstring """ at the top > of the function). > > There's another twist, too. In the docstring for cleanup_filenames it says > "Does not walk the directory tree." because we didn't code it to deal with > subdirectories. But we could, without using os.walk... > > Directories form a tree structure, and the easiest way to process trees is by > using /recursion/, which means functions that call themselves. An old > programmer's joke is this: > > Recursion, defn. [if not understood] see Recursion. > > Each time you call a function, it gets a brand new environment, called the > 'local scope'. All variables inside this scope are private; they may have > the same names, but they refer to different objects. This can be really > handy... > > ----------8<------------ > > def cleanup_filenames(dir): > > """ renames any files within dir that contain bad characters > (ie. ones in cfg.badchars). Walks the directory tree to process > subdirectories. > """ > > for filename in os.listdir(dir): > newname = filename > for ch in cfg.badchars: > newname.replace(ch,"-") > if newname != filename: > os.rename(os.path.join(cfg.userdir,filename), > os.path.join(cfg.userdir,newname) > # recurse if subdirectory... > if os.path.isdir(os.path.join(cfg.userdir,newname)): > cleanup_filenames(os.path.join(cfg.userdir,newname)) > > ----------8<------------ > > This version *DOES* deal with subdirectories... with only two extra lines, > too! Trying to write this without recursion would be a nightmare (even in > Python). > > A very important thing to note, however, is that there is a HARD LIMIT on the > number of times a function can call itself, called the RecursionLimit: > > ----------8<------------ > >>>>n=1 >>>>def rec(): >>> > n=n+1 > rec() > > >>>>rec() >>> > . . . > (huge traceback list) > . . . > RuntimeError: maximum recursion limit reached. > >>>>n >>> > 991 > ----------8<------------ > > Another very important thing about recursion is that a recursive function > should *ALWAYS* have a 'get-out-clause', a condition that stops the > recursion. Guess what happens if you don't have one ... ;-) > > Finally (at least for now), functions also provide a way to break down your > code into logical sections. Many programmers will write the higher level > functions first, delegating 'complicated bits' to further sub-functions as > they go, and worry about implementing them once they've got the overall > algorithm finished. This allows one to concentrate on the right level of > detail, rather than getting bogged down in the finer points: you just make up > names for functions that you're *going* to implement later. Sometimes, you > might make a 'stub' like: > > def doofer(dooby, doo): > pass > > so that your program is /syntactically/ correct, and will run (to a certain > degree). This allows debugging to proceed before you have written > everything. You'd do this for functions which aren't *essential* to the > program, but maybe add 'special features', for example, additonal > error-checking or output formatting. > > A sort of extension of the function idea is 'modules', which make functions > and other objects available to other 'client' programs. When you say: > > import os > > you are effectively adding all the functions and objects of the os module into > your own program, without having to re-write them. This enables programmers > to share their functions and other code as convenient 'black boxes'. Modules, > however, are a slightly more advanced topic. > > > Hope that helps. > > -andyj > > > From just at xs4all.nl Tue Jul 8 06:11:52 2003 From: just at xs4all.nl (Just) Date: Tue, 08 Jul 2003 12:11:52 +0200 Subject: path module References: <1057651068.5348.386.camel@lothlorien> Message-ID: In article , holger krekel wrote: > I am pretty sure that virtual-fs-like-extensibility would be a big > "selling" point and would motivate the use of such a module and > finally the inclusion into the stdlib. Of course, the local-fs should > be the convenient case but it shouldn't be hard to use the same methods > for accessing remote "repositories". Excellent point! Just From bogal2 at comcast.net Sun Jul 13 15:48:06 2003 From: bogal2 at comcast.net (BogAl) Date: Sun, 13 Jul 2003 14:48:06 -0500 Subject: Can't install csv parser Message-ID: Hi, all.... I'm hoping someone can help me. I've downloaded the csv.pyd file from http://www.object-craft.com.au/projects/csv/download.html and put it into my C:\Python22\DLLs directory. Typing import csv into a python window results in the following error message: Traceback (most recent call last): File "", line 1, in ? import csv ImportError: DLL load failed: One of the library files needed to run this application cannot be found. Can someone help me get this running? Thanks, BogAl From newsgroups at jhrothjr.com Sun Jul 13 04:58:11 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 13 Jul 2003 04:58:11 -0400 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in message news:3F10795B.9000501 at v.loewis.de... > John Roth wrote: > > > I don't think encoding is an issue. Windows XP stores all character data as > > unicode internally, so whatever you get back from os.environ() is either > > going to be unicode, or it's going to be translated back to some single byte > > code by Python. > > Read the source, Luke. I haven't gotten into the Python source, and my name is not Luke. Also, don't respond to my e-mail address. Unfortunately, I had a problem where I had to reload my system, and it's gotten out to usenet. It used to go to an ISP I no longer have an account with. > Python uses environ, which is a C library > variable pointing to byte strings, so no Unicode here. The OP's question revolved around ***which*** code page was being used internally. Windows uses Unicode. That's not the same question as what code set Python uses to attempt to translate Unicode into a single byte character set. > > In the latter case, you may not be able to recover non-ascii > > values, so Rob Willscroft's workaround to get the unicode version may be > > your only hope. > > You are certainly able to recover non-ascii values, as long as they > only use CP_ACP. I said "may not," not "cannot in any and all circumstances." > > If you're getting a standard string though, I'd try using Latin-1, or the > > Windows equivalent first (it's got an additional 32 characters that aren't in > > Latin-1.) > > That, in general, is wrong. It is only true for the Western European and > American editions of Windows. In all other installations, CP_ACP differs > significantly from Latin-1. The OP's problem was a character that's in the Western European range. > > Note that Release 2.3 fixes the unicode problems for files under XP. > > It's currently in late beta, though. I don't know if it fixes the > > os.environ() > > It doesn't. "Fixing" something here is less urgent and more difficult, > as environment variables rarely exceed CP_ACP. Less urgent I can see, unless you're concerned about whether Python survives against systems that do it right. Now that the Windows 9x series is dying off, the vast majority of systems on the desktop are going to have Unicode support internally. Granted, Python is not targeted at "the vast majority of systems," but if you can't easily get Unicode from the environment and the registry, then it's not very useful for system administration tasks or automation tasks on Windows. Many, if not most, environment variables are file names. If file names need Unicode support, then so do environment variables. As to more difficult, as I said above, I haven't perused the source, so I can't comment on that. If I had to do it myself, I'd probably start out by always using the Unicode variant of the Windows API call, and then check the type of the arguement to environ() to determine which to pass back. I'm not sure whether or not I'd throw an exception if the actual value couldn't be translated to the current SBCS code. > If people get support for Unicode environment variables, they want > Unicode command line arguments next. Why not? I can enter a command with Unicode at the Windows command prompt, and that command is likely to contain file names. Same problem raising it's head in a different spot. John Roth On reading this over, it does sound a bit more strident than my responses usually do, but I will admit to being irritated at the assumption that you need to read the source to find out the answer to various questions. > Regards, > Martin > From http Mon Jul 21 18:53:14 2003 From: http (Paul Rubin) Date: 21 Jul 2003 15:53:14 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: <7xbrvnmqzp.fsf@ruckus.brouhaha.com> Marc Wilson writes: > FWIW, in the UK, the ballots are normally done by the lowest-tech method: > you're given a ballot, and a pencil, and you put an "X" in a box next to the > one you like. We don't have problems with chads, etc. In the US you have the inalienable right to vote for anyone you want for office, including for yourself, your girlfriend, your mother-in-law, or whatever. So for example, the optical scan ballots for the presidential election in Volusia County, Florida in 2000 looked something like this: ( ) Bush ( ) Gore ( ) Buchanan ( ) Nader ( ) Other (write in): ___________________________ If you wanted to vote for your mother-in-law for President, you'd check "Other" and write her name there. If enough other people did that everywhere in the US, hey, your mother-in-law could become president! (Don't hold your breath though). Trouble starts when you ask what happens if more than one box is checked. If you check both "Bush" and "Nader", there's no way to tell what candidate you wanted, so your ballot is declared invalid. Fine. If you check "Bush" and also check "Other" and write your mother-in-law's name in the blank, same thing. So the company that programmed the scanning machines thought this issue easy to deal with: if more than one box is checked, the ballot is labeled as an "overvote" and is invalid. But what if you check "Bush" and also check "Other", and in the blank you write "Bush"? Then there's no ambiguity, it's clear who you want, so it's a legal vote and it must be counted (and Florida law requires that it be counted, though establishing that takes some careful reading). But the machines make no attempt to read the write-in blank. They just don't count those votes despite what the law requires. And who would be dumb enough to mark their ballot like that? It turns out that 488 people in Volusia County alone (some for Bush and some for Gore), and more in other counties, did so. Whether this happened because of some confusion in the printed voting instructions, or bad instructions given verbally to voters, or some other reason, is unknown. It was not discovered until after the state totals had already been reported, because the lawyers busy fighting over the ballot counts in other parts of the state didn't realize that so many such "overvoted" legal ballots existed and didn't go looking for them. Had they figured it out and noticed, that could have forced deeper examination of a number of other results in the state, and a different guy might have ended up in the White House than the guy who's there now. There are a lot of not-so-obvious possibilities that any counting scheme has to take into account. Getting anything wrong can have potentially far-reaching consequences. > We've also started, in some areas, voting by phone or internet. > Very simple system- you get a polling card with a number and a PIN, > you go to a HTTPS website, log in and vote. Has to be done *before* > the "manual" ballot opens, so the returning officer knows who's > already voted. That doesn't sound like a great idea. Suppose you cast that vote a week before the normal election day. Then two days before election day, it comes out that the leading candidate committed a number of murders that got covered up til then. You voted with less information than the other voters had. In fact, that candidate, fearful that the news might come out at any moment, may have encouraged all his supporters to vote early. For a fair election, all voting should be done on the same day. This is another reason mail-in absentee voting should be curtailed. From akineko at pacbell.net Mon Jul 7 13:21:38 2003 From: akineko at pacbell.net (Aki Niimura) Date: 7 Jul 2003 10:21:38 -0700 Subject: upload file via web form (Re: to Trent Mick's posting) Message-ID: Hello everyone, Trent Mick wrote: > """Some httplib helper methods.""" > > def httprequest(url, postdata={}, headers={}): > """A urllib.urlopen() replacement for http://... that gets the > content-type right for multipart POST requests. > > "url" is the http URL to open. > "postdata" is a dictionary describing data to post. If the dict is > ... snip ... I have tried the above script and found not working. After comparing the contents of the packets (captured by tcpdump) between the one generated by the above script and the one generated by Netscape, I found the 'body' doesn't have CRLF ('\n\r') which some servers may consider it as a line terminator (for MIMIE headers). After I inserted the following line: body = string.replace(body, '\n', '\r\n') It is working correctly. Thank you for providing such excellent script. I would like to see such methods in the future Python standard distribution. Best regards, Aki Niimura From leo.broska at NOSPAM.isys.com.au Tue Jul 1 04:52:49 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Tue, 1 Jul 2003 18:52:49 +1000 Subject: new to python - looking for a good book References: Message-ID: i've just started, too and i like "programming python" from mark lutz. that's somthing to make you interested what's psossible with python. for syntax etc i use the doc frompython.org. cheers, leooo "jodocus" wrote in message news:bdpm5v$g3d$1 at info.service.rug.nl... > hi, > > I am new to python (but not to programming - have programmed in many > other languages like C++/lisp/perl etc.) and I would like to buy a good > book. The local bookstore has no books about Python, so I cannot look > into a book and see whether I like it. That is why I turned to this > newsgroup for advise. > > I would like a book with a very complete and correct description of the > language and the built-in features, and things like how to integrate > programs with C or C++. I am not looking for a beginner's handbook with > all kinds of simple examples (since I already know how to program), but > rather a good formal description of all the features of the language > (with a good structure and index, so I can use it as a reference). > > I already saw one book at an on-line bookstore that is probably good: > "Programming Python" by Mark Lutz from O'reilly > > Would you advise me to order this one or are there other books I should > know about? > > TIA, > > R. > From psimmo60 at hotmail.com Thu Jul 3 07:32:21 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 3 Jul 2003 04:32:21 -0700 Subject: My Big Dict. References: <20030702073735.40293ba2.christophe.delord@free.fr> <94974e1a.0307020532.1cb19956@posting.google.com> Message-ID: <94974e1a.0307030332.138a7054@posting.google.com> Christian Tismer wrote in message news:... > Paul Simmonds wrote: > ... > I'm not trying to intrude this thread, but was just > struck by the list comprehension below, so this is > about readability. > > > > d=dict([(l[:l.index('!')],l[l.index('!')+1:-1])\ > > for l in file('test.txt') if l.count('!')]) > > With every respect, this looks pretty much like another > P-language. The pure existance of list comprehensions > does not try to force you to use it everywhere :-) > Quite right. I think that mutation came from the fact that I was thinking in C all day. Still, I don't even write C like that...it should be put to sleep ASAP. > > d={} > > for l in file("test.txt"): > > try: i=l.index('!') > > except ValueError: continue > > d[l[:i]]=l[i+1:] > > About speed: I'm not sure with the current Python > version, but it might be worth trying to go without > the exception: > > d={} > for l in file("test.txt"): > i=l.find('!') > if i >= 0: > d[l[:i]]=l[i+1:] > > and then you might even consider to split on the first > "!", but I didn't do any timings: > > d={} > for l in file("test.txt"): > try: > key, value = l.split("!", 1) > except ValueError: continue > d[key] = value > Just when you think you know a language, an optional argument you've never used pops up to make your life easier. Thanks for pointing that out. I've done some timings on the functions above, here are the results: Python2.2.1, 200000 line file(all data lines) try/except with split: 3.08s if with slicing: 2.32s try/except with slicing: 2.34s So slicing seems quicker than split, and using if instead of try/except appears to speed it up a little more. I don't know how much faster the current version of the interpreter would be, but I doubt the ranking would change much. Paul From ianb at colorstudy.com Fri Jul 25 21:48:07 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 20:48:07 -0500 Subject: path module In-Reply-To: References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <1059184087.28095.11575.camel@lothlorien> On Fri, 2003-07-25 at 20:10, Van Gale wrote: > Interesting, I started a project modifying Jason's Path module to work > on subversion trees as well. I didn't get too far before putting the > project on a back-burner so I'm glad to hear someone else is thinking > the same way :) > > My extensions to Path included an additional argument to "open" that > included a version number, and a mechanism for retrieving some kind of > "metadata" associated with the file. It's interesting that different kinds of filesystems (or filesystem-like-things) have very different kinds of metadata available. Like last-modified, last-accessed, inode (identity), version, title, branch, mimetype, log message, etc. And then there's information that's not quite metadata... like data, or the volume name, the host, etc. I feel like a common interface for these different filesystems should somehow degrade well in terms of metadata, or expedite introspection in some fashion. The differences on the client side are probably easier to handle, as they can be handled by the constructor, which might look different for different filesystems. Like url('http://whatever', user='bob', password='secret', proxy='http://myproxy'), or cvs(pserver='cvs.sourceforge.net', repository='python'). Or should there be a string-based representation (i.e., URIs)? Of course for symmetry then __str__ would always return a URI, but for many circumstances we'd prefer a more concise notation, like a filesystem path (though most other cases would be acceptable squeezed into URIs). I'd have placed the version in the object itself, not as an argument to open. Then you'd want to query for alternate versions, most recent version -- maybe some version identifier that meant most recent... a similar situation might be language negotiation with an HTTP file. Ian From hokiegal99 at hotmail.com Wed Jul 16 10:04:29 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 16 Jul 2003 10:04:29 -0400 Subject: <> and != References: <3F154B63.3060503@hotmail.com> <3F154BBD.2060304@hotmail.com> <3jlahv8o1fcu2j0oij2p31c32nftnb3er8@4ax.com> Message-ID: <3F155B6D.8000205@hotmail.com> Gon?alo Rodrigues wrote: > On Wed, 16 Jul 2003 08:57:33 -0400, hokiegal99 > wrote: > > >>that sould be: >> >>if newfile <> oldfile >>if newfile != oldfile > > > No difference whatsoever. I believe != is prefered (style guide?) > though -- and that's the one I always use. > > With my best regards, > G. Rodrigues Thank you, that is what I thought. What's the reason for having two symbols mean the same thing? From mhammond at skippinet.com.au Wed Jul 23 19:46:56 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 24 Jul 2003 09:46:56 +1000 Subject: PyIStream and COM question for WinGraphViz In-Reply-To: References: Message-ID: Simon Frost wrote: > Dear Python List, > > I'd like to write a COM interface to WinGraphViz > (http://home.so-net.net.tw/oodtsen/wingraphviz/). I would like to dump > my image to a PyIStream, but I can't find any documentation on how to do > this. > > Here's the syntax for the COM interface > > ProgramID: WinGraphviz.BinaryImage > Dump(IStream stream) as Boolean > > I would like to do something like > istream=PyIStream(...) > myBinaryImage.Dump(istream) > > and then go on to display the image. > > Any help would be greatly appreciated. Presumably this is a method on the COM object. You want to create a stream object, pass it to the library, and have it "dump" to your object? If so, check our win32com\test\testStreams for examples of Python implemented IStream interfaces. Mark From aahz at pythoncraft.com Fri Jul 11 16:22:39 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 16:22:39 -0400 Subject: Embedding Python, threading and scalability References: Message-ID: In article , Jeff Epler wrote: >On Thu, Jul 10, 2003 at 07:48:57PM -0400, Aahz wrote: >> In article , >> Jeff Epler wrote: >>>On Thu, Jul 10, 2003 at 03:54:14PM -0400, Aahz wrote: >>>> >>>> Other people have mentioned Perl and Tcl in this thread. I wonder how >>>> they deal with the problem of loading DLLs with static data. >>> >>>As far as I know, tcl enforces a one interpreter to one thread >>>requirement. An extension should have only thread-local data, using a >>>Tcl-supplied API. >> >> What happens when Tcl wants to interact with some 3rd-party DLL that is >> *not* thread-safe? > >I guess you'd have to do your own locking. Tcl has standard C APIs for >Conditions, Mutexes, and thread-specific data, see the Thread(3) manpage. >You'd have to surround all non-reentrant calls with Tcl_MutexLock(m) >... Tcl_MutexUnlock(m). If two extensions wanted to use the same >non-thread-safe library, they'd have to cooperate in some way to use >the same 'm' to Tcl_Mutex*(). I don't know if there's a standard way to >do this, but I think that having the mutex defined in a shared lib they >both link might work. Yup. And that's exactly why there has been little movement to remove the GIL from Python. One of Python's core strengths is the ease with which random DLLs can be used from Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From martin at v.loewis.de Sun Jul 20 17:04:41 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Jul 2003 23:04:41 +0200 Subject: A challenge to the ASCII proponents. References: <3F1AAC0A.7A6326B@hotmail.com> Message-ID: Alan Kennedy writes: > 2. The only other person who managed it, without using markup, was > Martin von Loewis, who is so good at this stuff that he confidently > makes statements like "what I did was right: it was Google that got it > wrong". Martin used the UTF-8 character set, i.e. a non-ASCII, > non-7-bit-clean character set, to achieve this. Although I'm sure > Martin could have managed it with UTF-7 as well. It wasn't that hard to do: I only had to ask my newsreader to sent the message as UTF-8. If my newsreader had chosen a content-transfer-encoding of base64 or quoted-printable, it even would have been 7-bit clean. > 3. If anybody else was willing to give it a try, they don't seem to > have had enough confidence in their knowledge of encodings, MIME, > transports, NNTP, etc, etc, to have actually hit the "send" button, in > case it didn't work. Which doesn't bode well for the average person in > the street: if the technology specialists in this newsgroup don't feel > in command of the issue, what hope for everyone else? It's a matter of time. Web browsers are ahead of all other software, here, as they first hit the problem of displaying content in a wide variety of languages. Over time, most email agents and news readers will catch up, getting it right without bothering the user. It is not that MIME is more complicated than XML, on the contrary. It is just that authors of MIME software, for some reason, don't care that much about these issues. Regards, Martin From bignose-hates-spam at and-zip-does-too.com.au Sat Jul 12 00:22:32 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 12 Jul 2003 14:12:32 +0950 Subject: The "intellectual property" misnomer References: Message-ID: On Sat, 12 Jul 2003 04:29:04 GMT, Raymond Hettinger wrote: >> >> If the PSF holds the copyright to Python, please say that. If the >> >> PSF holds patents which cover Python, please say that. If the PSF >> >> owns the trademark for Python, please say that. If the PSF has >> >> trade secrets in Python, please say that. > > PSF is the copyright holder and issuer of the python license to the > code covered by that copyright. Excellent. So "The PSF is the copyright holder for Python". No need for gymnastics, and it actually says something meaningful. > In layman's terms, it means exactly what Guido said. The layman's understanding of "intellectual property" is confused, doesn't relate to reality, and is harmful. Please avoid use of that term. > Hope this helps, It does, thanks. -- \ "The best is the enemy of the good." -- Voltaire | `\ | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From donn at drizzle.com Wed Jul 16 23:51:24 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 17 Jul 2003 03:51:24 -0000 Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> <20030716123907246-0600@news.xmission.com> <20030716142716509-0600@news.xmission.com> <20030716161405965-0600@news.xmission.com> Message-ID: <1058413882.4140@yasure> Quoth Adam Ruth : ... | "there aren't any situations that I care about where you can't avoid | pointers." is certainly true. But I still believe that there aren't any | situations where the use of a pointer would provide a substantially | better solution to the non-pointer route. Any examples I've seen so far | have non-pointer implementations that are just as good or better (of | course, 'better' is a completely loaded word). Loaded or whatever, as I've said, it's not an interesting issue in this context. If we were actually trying to decide how user indexing should work, then it might be interesting to compare these two semantically different approaches, but then it might not - because the one I propose can't be implemented in Python. And that's the point, Python just cannot go there, because it lacks pointers. Whether you want to go there is not really interesting to anyone but you. Donn Cave, donn at drizzle.com From max at alcyone.com Fri Jul 18 02:29:40 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 23:29:40 -0700 Subject: How do I get info on an exception ? References: Message-ID: <3F1793D4.E6EEF8A1@alcyone.com> Frank wrote: > Using Python 2.2.2, > I want to catch all exceptions from "socket.gethostbyaddr(ip)" > > From IDLE, I can generate: > >>> socket.gethostbyaddr('1.2') > Traceback (most recent call last): > File "", line 1, in ? > socket.gethostbyaddr('1.2') > herror: (11004, 'host not found') <=== what I want when I catch > > When I run this code: > try: > hostname, aliases, hostip = socket.gethostbyaddr(ip) > return (hostip, hostname) > except: > print sys.exc_info() > print sys.exc_type > return Use the format: try: ... except ErrorType, e: ... do something with exception object e ... >>> import socket >>> socket.error >>> try: ... socket.gethostbyaddr('1.2') ... except socket.error, e: ... print e, dir(e), e.args ... (1, 'Unknown host') ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] (1, 'Unknown host') > How do I get the "(11004, 'host not found')" part? > More importantly, where is the answer documented that I should > have looked? Check the part on exception handling. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It is human nature to think wisely and act foolishly. \__/ Anatole France From achrist at easystreet.com Thu Jul 3 00:51:27 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 02 Jul 2003 21:51:27 -0700 Subject: zip() or what? References: <3F03AFA8.7030905@ihug.co.nz> Message-ID: <3F03B64F.4B5A7DA9@easystreet.com> Ray Tomes wrote: > > Hi all > > > This I am trying to flip an array around so that the "subscripts" happen > in the opposite order [x[-i-1] for i in range(len(x))] Al From intentionally at blank.co.uk Sun Jul 13 22:41:46 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 03:41:46 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <3F11C42F.5030406@alcyone.com> Message-ID: On 13 Jul 2003 21:40:32 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >>All you guys must be forgetting: >> >> >>> a = [1] >> >>> b = a >> >>> a += b >> >>> assert id(a) == id(b) >> >>> a = 1 >> >>> b = a >> >>> a += b >> >>> assert id(a) == id(b) >> Traceback... > >I'm not forgetting that. It's an unfortunate and tricky part of Python >semantics in some respects, but it's easily explained and understood if >you focus on the objects rather than the operation: I wish I'd thought of it, though - I could have avoided the 'boneheaded' confession a bit longer ;-) From imbosol at aerojockey.com Sun Jul 27 22:29:22 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Mon, 28 Jul 2003 02:29:22 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Message-ID: <6U%Ua.9024$AO6.6681@nwrdny02.gnilink.net> Carl Banks wrote: > 3. The last iteration might not happen because of floating point > uncertainties, even if rounding errors are minimized Just to be sure: what I have should have said was there might be more extra iteration. The Python convention, of course, it not to include the final point. However, with floating point, it could happen to slightly undershoot the stop value, which would cause an evident extra iteration. -- CARL BANKS From missive at frontiernet.net Sun Jul 13 12:21:20 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 13 Jul 2003 16:21:20 GMT Subject: installing python library modules (general question) References: <79ad5955.0307122013.6780fc53@posting.google.com> Message-ID: > ImportError: libmad.so.0: cannot open shared object file: No such file > or directory > > I know the file /usr/local/lib/libmad.so.0 exists, but python can't > seem to find it. I tried adding this path to LD_LIBRARY_PATH, but > that didn't help. > > I guess that I just really dont' know enought about libraries and > linux (redhat 9). I don't really know where they are supposed to go > after being compiled, and how python "loads" and uses them. > Where are your other python libraries? On my system, they are in: /usr/local/lib/python2.2/ and then modules that get added by distutils go in: /usr/local/lib/python2.2/site-packages/ I have a bunch of libfoo.so and libbaz.so.1 type files in there, so I think if you have a directory like that you should try dropping your libmad.so.0 in there. From skip at pobox.com Wed Jul 30 16:35:05 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jul 2003 15:35:05 -0500 Subject: Misuse of In-Reply-To: <3f27f0e3$1@news.broadpark.no> References: <3f27f0e3$1@news.broadpark.no> Message-ID: <16168.11257.129884.910524@montanaro.dyndns.org> Gisle> I'm confused, please enlighten me. Don't use TABs and break the knuckles of any of your co-workers who do. ;-) More seriously, I suspect most editors have some sort of setting which causes it to insert SPACE characters up to the next tab stop. Skip From tzot at sil-tec.gr Fri Jul 18 11:23:06 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 18 Jul 2003 18:23:06 +0300 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <7u1ghvc2pppu75ceesas51ghjp9a2aib45@4ax.com> On Sun, 13 Jul 2003 22:20:33 +0100, rumours say that Stephen Horne might have written: >On 13 Jul 2003 15:05:38 -0500, Ian Bicking >wrote: > >>On Sun, 2003-07-13 at 14:39, Stephen Horne wrote: >>> The fact is that 'assignment' has a common meaning separate from the >>> choice of programming language, >>This just isn't true. The C++ assignment operator is not at all like >>the Python assignment statement. Python variables are not like C++ >>variables, no surprise assignment is different too. If you used >>languages outside of C++ and its like (e.g., Pascal), you would find >>Python's behavior common. > >Think again. > >When I say "'assignment' has a common meaning separate from the choice >of programming language" I assumed you would get the hint. I'm not >referring to some specific other programming language, of which I have >used many - and not all of them imperative. I am referring to the >definitions in computer theory, which do not relate to any specific >programming language but actually apply to all of them, irrespective >of paradigm and everything else. [and snip of various other stuff] perhaps I am too late, and off subject at this point in time, but I believe I can offer something to the discussion; I just picked to follow up a post that looked appropriate for my digression below. The way I see it, practically, there are two ways to describe the python variables/names, and it comes down to choosing labels (nb. the following paragraphs are valid for CPython, and do not take account of other computer languages or computer science in general): - if you choose the labels 'name', 'object', 'binding' as most pythonistas do, then the python assignment operator 'binds' 'names' to 'objects'. You can't 'bind' 'names' to 'names', since they are not 'objects'. The function id() returns the identity of the 'object' 'bound' to 'name'. Argument passing is neither 'call by reference' or 'call by value'; it's something one can name 'call by object'. - if you choose the labels 'variable', 'value', 'reference', 'object', then *all* 'variables' are of the same type: 'reference' to 'object'. A 'variable' is not a python 'object', so you can't have one 'variable' 'referencing' another 'variable'. You can't store an 'object' to a 'variable', just a 'reference' to the 'object'. The function id() returns the 'value' of the 'variable'. In this case, all argument passing is "call by value"; all 'values' are 'references' to 'objects'. Please note that a python 'name' (or a python 'variable') is completely described by the following regular expression: ^[_A-Za-z][_A-Za-z0-9]*$ So you are certain that you are 'binding' a 'name' to an 'object' (or storing the 'reference' to an 'object' in a 'variable') only when you have something like the following: name = This is *always* an assignment operation. You can't control it with specially-named functions (something like __assign__, say). If you are of the 'variable', 'value' persuasion, then most of the time the 'value' of "name" changes by the assignment operation, even if the new 'object' is equal to the old 'one'. OTOH, if you have something like: another_name.name = then the LHS is not a 'name' (or a 'variable'). It's the "name" attribute (or property) of the "another_name" object. This code can call several python functions, depending on the type/class of "another_name". The execution of the above statement might invoke some methods of the 'object' presently known as "another_name" (eg __setattr__ or a special property put method). The "name" attribute can be a 'name' (or a 'variable'), but it's not necessarily so. This post is a good example of bad writing, but the ways of enlightenment are obscure... ;-) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From alanmk at hotmail.com Tue Jul 15 06:05:02 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 15 Jul 2003 10:05:02 +0000 Subject: Confusing automated translators. Message-ID: [Francois] >Just to repeat publicly the content of a private reply, the two meanings >could be: > > "The driver closes the door." > "The firm driver is carrying her." Aha! That's very clever. I like the dual use of "la porte" (the door) as a noun and "la porte" (carries her) as a verb. That makes it similar to the "time flies" one, where "like" is used as a comparative (french "comme") and as a verb (french "aime"). I was obviously completely off base with my interpretation of "pilote ferme"/"experimental farm". :#) Thanks Francois. Regards, Al. _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From alanmk at hotmail.com Sun Jul 20 10:49:46 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 20 Jul 2003 15:49:46 +0100 Subject: A challenge to the ASCII proponents. References: Message-ID: <3F1AAC0A.7A6326B@hotmail.com> Martin v. Loewis: >>>> So what do you think about this message?: >>>> >>>> ???????????????? >>>> >>>> Look Ma, no markup. And not every character uses two bytes, >>>> either. >>>> And I can use Umlauts (??????) and Arabic (????????.????????????) >>>> if I want to. Alan Kennedy: > The final point I'd like to make [explicit] is: nobody had to ask > me how or why my xml snippet worked: there were no tricks. Nobody > asked for debugging information, or for reasons why they couldn't > see it: eltronic at juno.com wrote: > Content-Type: text/plain; charset=iso-8859-1 > > Content-Transfer-Encoding: 8bit > > is how my email picked it up. > > other messages and replys were inconsistently rendered. > > isn't this the kind of thing the test groups were designed for? > > IIR, 7 bits is the standard in email & usenet. > > no one should expect more than 7 > > from any program or relay. the proper way > > would seem to be html using char entity's > > html appears to be no ones favorite format in email or usenet, > > so let the flames begin. > > I hope I haven't been hoodwinked into replying in 8bit as well. Hmm, on reading and re-reading your points, the only way I can make sense of them is if I assume that you didn't read the thread from the start, which is highly recommended http://tinyurl.com/hhhs In summary: 1. I managed to make a greek word, using the original greek glyphs, appear on everyone's "rendering surface", by posting a 7-bit clean XML snippet. Another poster widened the software coverage even further by posting a 7-bit clean HTML snippet. Both of our 7-bit markup snippets travelled safely throughout the entirety of UseNet, including all the 7-bit relays and gateways. 2. The only other person who managed it, without using markup, was Martin von Loewis, who is so good at this stuff that he confidently makes statements like "what I did was right: it was Google that got it wrong". Martin used the UTF-8 character set, i.e. a non-ASCII, non-7-bit-clean character set, to achieve this. Although I'm sure Martin could have managed it with UTF-7 as well. 3. If anybody else was willing to give it a try, they don't seem to have had enough confidence in their knowledge of encodings, MIME, transports, NNTP, etc, etc, to have actually hit the "send" button, in case it didn't work. Which doesn't bode well for the average person in the street: if the technology specialists in this newsgroup don't feel in command of the issue, what hope for everyone else? Maybe I should have a poke around the UseNet test groups to see how many people tried and failed ;-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mwh at python.net Fri Jul 18 13:03:34 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jul 2003 17:03:34 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: <7h3znjbzscu.fsf@pc150.maths.bris.ac.uk> "Mike C. Fletcher" writes: > So, does anyone have a pattern which allows setting an attribute on > a class which doesn't go through the setattr machinery (i.e. can be > used within a descriptor)? No. Fun problem to think about, though :-) Cheers, M. -- Beer doesn't really work over the internet, unless IPv6 improves things in ways I don't understand. -- Steven M. Haflich, comp.lang.lisp From harry.g.george at boeing.com Mon Jul 21 12:42:29 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 21 Jul 2003 16:42:29 GMT Subject: global variable References: Message-ID: Tom writes: > Hi, > > I have one "master" program which calls a small program. In this small > program I want to work with a value from the "master" program. But I > always get this error: NameError: global name 'T' is not defined > > How can I define a global variable? > > Thanks for your help. > Regards, Tom > master.py: my_global_var=1234 small.py: import master ... my_local_var=master.my_global_var * 3.14 -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From mwh at python.net Wed Jul 23 04:43:06 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 23 Jul 2003 08:43:06 GMT Subject: Python 2.3c1: Raising a string doesn't trigger PendingDeprecationWarning. References: <7c58a0f1.0307230020.1336f4ea@posting.google.com> Message-ID: <7h3llupy71t.fsf@pc150.maths.bris.ac.uk> warkid at hotbox.ru (Kerim) writes: > "What's New in Python 2.3" > (http://www.python.org/doc/2.3c1/whatsnew/node17.html) says that > "Raising a string will now trigger PendingDeprecationWarning.". But > with Python 2.3c1 it seems that it isn't the case: > > Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> raise 'error' > Traceback (most recent call last): > File "", line 1, in ? > error > >>> Try running 'python -Wall'. Cheers, M. -- Well, you pretty much need Microsoft stuff to get misbehaviours bad enough to actually tear the time-space continuum. Luckily for you, MS Internet Explorer is available for Solaris. -- Calle Dybedahl, alt.sysadmin.recovery From skip at pobox.com Sun Jul 27 11:54:23 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 27 Jul 2003 10:54:23 -0500 Subject: emacs python-mode questions: C-c C-c and broken docstring fill In-Reply-To: <87ptjwre0x.fsf@pobox.com> References: <87ptjwre0x.fsf@pobox.com> Message-ID: <16163.62895.594090.125698@montanaro.dyndns.org> John> Wrong type argument: sequencep, cpython Where the comment says "TBD: a horrible hack...": try replacing the beginning of the let with (let ((cmd (concat (if (eq shell (quote cpython)) "python" "jython") (if (string-equal py-which-bufname "JPython") " -" "")))) I have no idea what the "jython" string really should be. That was just a guess. Skip From steve at ferg.org Thu Jul 10 15:34:35 2003 From: steve at ferg.org (Stephen Ferg) Date: 10 Jul 2003 12:34:35 -0700 Subject: Newbie - No module named stdwin References: Message-ID: You might want to take a look at EasyGui. http://www.ferg.org/easygui/ That will allow you to do simple things quickly. After that, you might want to look at http://www.ferg.org/thinking_in_tkinter/index.html From lol at lolmcNOSPAM.com Fri Jul 4 17:00:55 2003 From: lol at lolmcNOSPAM.com (Rogue 9) Date: Fri, 04 Jul 2003 22:00:55 +0100 Subject: Importing packages and classes help required by newbie Message-ID: <3f05eaf3@shknews01> Hi All, I have a small problem in a program I'm developing and could do with some guidance as to how I resolve it. The hierachy of my program is as follows: 1)The toplevel package is called oop_lb 2)Beneath oop_lb are 3 packages - analysis,process and tests oop_lb | | ------------------------------------------------------- | | | analysis process tests I am using the very excellent unittest module to help me to create a program that is as bug free as I can make it and the tests are as you cn guess in the tests package mentioned above. I have developed several modules which reside in the process package and succesfully created tests in the tests package which ensure the code does what I intended.When I moved on to the analysis package however,things went a bit wonky as the modules in this package called classes which resided in the process package and when using the import statements to make them available I found that either I could get the oop_lb module to run with one set of import statements but the tests I wrote would not recognise the modules from process in the import statements and produced the following type of error: Traceback (most recent call last): File "CalculateMedianTest.py", line 14, in ? import oop_lb.analysis.CalculateMedian File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 14, in ? from process import GetDraw ImportError: No module named process This occurs with the following import statement in the CalculateMedian.py module from process import GetDraw If I change this to import oop_lb.process.GetDraw then the test program will work but the oop_lb.py file fails with the following error Traceback (most recent call last): File "oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 13, in ? import oop_lb.process.GetDraw File "/home/lol/disk/python/lotto/oop_lb/oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file ImportError: cannot import name CalculateMedian So.....my problem is that I can't seem to find the proper way to import the modules to satisfy both the testing modules in the oop_lb.tests package and also allow oop_lb.py to run without import errors. I apologise for the length of the post and any ambiguities I may not have managed to clear up whilst proff reading this before posting. Thanks,Lol -- Remove NOSPAM from my email address to use it,please. From tchur at optushome.com.au Wed Jul 30 07:44:29 2003 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 30 Jul 2003 21:44:29 +1000 Subject: python in parallel for pattern discovery in genome data In-Reply-To: <1059563927.5183.5.camel@E503BMatrixReloaded> Message-ID: <003a01c3568f$f284fe20$a300a8c0@emilio> BalyanM wrote: > Sent: Wednesday, 30 July 2003 9:19 PM > To: python-list at python.org > Subject: python in parallel for pattern discovery in genome data > > Hi, > > I am new to python.I am using it on redhat linux 9. > I am interested to run python on a sun > machine(SunE420R,os=solaris) with 4 cpu's for a pattern > discovery/search program on biological sequence(genomic > sequence).I want to write the python code so that it utilizes > all the 4 cpu's.Moreover do i need some other libraries. > Kindly advice. Manoj, Have a look at PyPar, which is Ole Neilsen's excellent Python wrapper for the MPI parallel library. It is very easy to use, and Ole gives some nice examples. See http://datamining.anu.edu.au/~ole/pypar/ That page also lists some other Python wrappers for MPI. We have been using PyPar with excellent results to parallelise probabilistic record linkage problems, running on a 4 CPU SMP Sun server under Solaris, just like yours. Some example code for doing this can be found in the lastest Febrl release at http://datamining.anu.edu.au/projects/linkage.html However, PyPAr and MPI (in particular the LAM/MPI distribution) also work well on clusters of Linux machines. I think that LAM/MPI is available as a pre-packages RPM for RedHat Linux, which makes installation even easier. Just out of interest, what types of pattern matching algorithms are you using? Hope this helps, Tim C From fredrik at pythonware.com Mon Jul 14 17:19:34 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Jul 2003 23:19:34 +0200 Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <3F130ED4.2030804@skynet.be> Message-ID: Helmut Jarausch wrote: > OK, I believe to know why the last line > print '3' three times, since only a reference > to 'f' is stored within the lambda expression > and this has the value 'thrice' when 'print' > is executed. > > But how can I achieve something like an > evaluation of one indirection so that > a reference to the function referenced by 'f' > is stored instead. assuming you meant "the function reference by 'f' when the lambda is created", the easiest solution is to use default argument binding: flam = [lambda x,f=f: f(x) for f in funcs] the "f=f" construct will bind the inner name "f" to the current value of the outer "f" for each lambda. the nested scopes mechanism is often introduced as the "right way" to do what was done with argument binding in earlier versions of Python. however, nested scopes bind *names*, while argument binding binds *values*. From furliz at libero.it Wed Jul 23 04:14:22 2003 From: furliz at libero.it (furliz) Date: Wed, 23 Jul 2003 10:14:22 +0200 Subject: newbies and win32 ... Message-ID: Hi all, I'm trying to understand how to use COM objects with python. The big problem is that in many tutorials there is ever the same example creating an instance of Microsoft Excel: well, I haven't Office installed, and when I try to instance another type of library... I get only errors... :((( This is what I'd like to obtain: embedding a Flash movie in a Tkinter-based program. Can someone help me? any example, link, suggestion is wellcome. Bye. From jjl at pobox.com Tue Jul 8 09:32:48 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Jul 2003 14:32:48 +0100 Subject: A story about Python... sort of References: <3F0A0655.99823E25@alcyone.com> Message-ID: <87smphp2in.fsf@pobox.com> [utterly OT, but couldn't resist replying again] Erik Max Francis writes: > John J Lee wrote: > > > A Google result (appropriately enough, given the origin of > > the name Google) ... > > But the origin of the name was generated from a misspelling of _googol_ > (the name for 10^100), which evidently was found via Web searches. So > the origin of the name of the search engine Yeah -- I just meant they're both pretty large numbers. [...] > infinite spatial extent. So, presuming we live in a universe that > follows this models, the true Universe is infinitely large, even though > we can only see a finite, small part of it. True, though infinite spatial extent doesn't necessarily mean infinite computation, of course (though it's true people have claimed both open and closed universes allow, or require, infinite computation). I suppose a lot of this is up for grabs ATM, with the recent discoveries about the cosmological constant &c. Still, questions like 'is chess physically solveable' (in a sense I hope we all grok by this point in the thread) are questions about physics, which I guess is the real point I was making to the guy I was replying to. Doubtless he'll put that insight to use in his next Python script. [...] > Since it's an interpretation, though, it's just an intuitive way of > looking at the situation. Quantum mechanical interpretations do not > modify the theory itself; that is, they neither add nor subtract > anything from the theory which is testable in any way. I disagree with all of that. Further discussion taken off-list! John From aahz at pythoncraft.com Sun Jul 20 09:41:55 2003 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2003 09:41:55 -0400 Subject: object as a reserved keyword References: Message-ID: In article , Lawrence Oluyede wrote: > >Does it worth to make "object" keyword a reserved one? Maybe. Python strives for a minimal syntax. Many identifiers that would be keywords in other languages are simply names in the builtin namespace. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From wayne at mishre.com Sat Jul 12 15:39:33 2003 From: wayne at mishre.com (Wayne Pierce) Date: 12 Jul 2003 12:39:33 -0700 Subject: new in town References: Message-ID: <2a897f11.0307121139.21470fbb@posting.google.com> "Elaine Jackson" wrote in message news:... > Can Python be compiled? If so, how? (I have the 2.2 version of the interpreter.) > TIA for any and all helps If you want to be able to distribute your Python apps without the end user needing a Python interpreter take a look at the following: http://www.mcmillan-inc.com/install1.html Wayne From intentionally at blank.co.uk Sun Jul 13 19:37:15 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 00:37:15 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien> Message-ID: On Sun, 13 Jul 2003 17:16:55 -0400, Jack Diederich wrote: >On Sun, Jul 13, 2003 at 03:05:38PM -0500, Ian Bicking wrote: >> On Sun, 2003-07-13 at 14:39, Stephen Horne wrote: >> > The fact is that 'assignment' has a common meaning separate from the >> > choice of programming language, >> >> This just isn't true. The C++ assignment operator is not at all like >> the Python assignment statement. Python variables are not like C++ >> variables, no surprise assignment is different too. If you used >> languages outside of C++ and its like (e.g., Pascal), you would find >> Python's behavior common. >> > >C++ is the only language that has the same semantics as C++. > >I was a long time C++ guy and my a-ha moment was when I realized that the >GoF's "Design Patterns" were not all universal -- some are C++ specific. >Trying to force Python semantics into a C++ world view will leave you feeling >empty every time. Drink the koolaid, python has a short learning curve. >If this is a problem - whatever you do - DONT TRY TO LEARN LISP. > >If you want a more polished C++, use Java. Python is in a different class >of languages. Java has the same problem as Python in this respect. You can either state that it implements a different assignment semantic for some data types than it does for other data types, or you can claim that some data types have implicit built in references while others don't. The Java rationale is essentially that 'pointer' is considered a dirty word, so it was considered necessary to disguise them in Java. End result - you have to use things which are not pointers as if they were. You have to abuse data types in an arbitrary, confusing and error-prone way in order to create the effect of pointers/references. In Python, Guido describes his rationale for the existence of both mutable lists and immutable tuples here... http://www.python.org/search/hypermail/python-1992/0292.html According to this, the benefit from an immutable tuple is that there is no immediate copy, yet the tuples stored in the object are protected from accidental 'mutation'. It allows a lazy copy-on-write optimisation combined with preventing unwanted mutation of those tuples. ie Guido justifies the need for an immutable tuple in terms of copying - the rationale is about assignment, even though the effect is the same as in Java in which the rationale is about disguising pointers. Note that Guidos rationale assumes a tie between the concepts of 'reference to value' and 'in place modifiability of part or all of value'. This is bogus - these are two different concepts. There is no reason why mutable objects shouldn't be assigned using copy-on-write semantics, and there is no reason why there shouldn't be a simple reference or pointer data type which has the explicit purpose of providing indirect reference to single values of any type whether mutable or immutable. The only 'trouble' is that it suggests a need to distinguish assignment to a variable (replacing the previous value even if it was a pointer) from assignment to a pointed-to location. In fact you already do this if you fake pointer functionality using mutable objects, the only difference is that a pointer dereference is specific to the real purpose and does not require abuse of data types that are designed for other jobs. People may say that pointers are bad news, but that impression resulted from languages like C and Pascal and it should be qualified in two ways. Pointers in C and C++ are dangerous in a very important way. Pointers don't always point to a valid object - they may point to something that was deleted, for instance. This is worse in the C family as pointers and arrays are almost treated as the same thing, and array subscripting has no bounds checking. Furthermore, there is the risk of memory leaks. If pointers always point to a valid object (except, perhaps, a special pointer-to-none value which throws an exception on dereferencing), if pointers are kept distinct from other abstractions such as arrays, and there is no possibility of accessing whatever memory happens to be beyond the bounds of some particular type, and if garbage collection is used then the only reliability objections that can be levelled at pointers would relate to code complexity - and that complexity can only be increased by faking pointers using mutable types designed for other tasks. All of these are perfectly plausible for a scripting language. From aahz at pythoncraft.com Wed Jul 23 00:01:50 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2003 00:01:50 -0400 Subject: sys.setcheckinterval query References: <84fc4588.0307201255.254582df@posting.google.com> Message-ID: In article <84fc4588.0307201255.254582df at posting.google.com>, Anand Pillai wrote: > >""" >setcheckinterval(interval) > Set the interpreter's ``check interval''. This integer value >determines how often the interpreter checks for periodic things such >as thread switches and signal handlers. The default is 10, meaning the >check is performed every 10 Python virtual instructions. Setting it to >a larger value may increase performance for programs using threads. >Setting it to a value <= 0 checks every virtual instruction, >maximizing responsiveness as well as overhead. >""" Note that Python 2.3 changes the default to 100, so be careful about hard-coding anything. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From frobozz_electric at hotmail.com Thu Jul 17 10:20:29 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 17 Jul 2003 14:20:29 GMT Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: "Peter Hansen" wrote in message > I think the problem is underspecified. What do you mean by the quoted > phrase "lock-step"? He wants to have f1 and f2 alternate executing instructions: # pseudo code def f1(): instruction1-1 instruction1-2 def f2(): instruction2-1 instruction2-2 So, for the code above, he would like to see something like the following execution routine: start execution of f1 execute instruction1-1 pause execution of f1 start execution of f2 execute instruction2-1 pause execution of f2 resume execution of f1 execute instruction1-2 pause execution of f1 resume execution of f2 execute instruction2-2 pause execution of f2 Do a piece of one, then do a piece of the other, then do another piece of the former, and so on... While the following code does not provide a solution to the OP's request, it does show something very much like the behaviour that's being asked for. class LockStepper: def __init__(self, id): self.id = id self.i = 1 self.partner = None def next(self): if self.i > 10: return print "instruction %s-%s"%(self.id, self.i) self.i += 1 self.partner.next() f1 = LockStepper(1) f2 = LockStepper(2) f1.partner = f2 f2.partner = f1 # begin lock-step execution f1.next() The idea here is to think of each LockStepper as though it were a function, and to think of the print statement in each of their next() methods as a line of instruction inside the body of that function. The LockStepper executes the first line of it's "function body", then pauses. It's partner executes the first line of it's function body, then pauses. The partner's partner was the original LockStepper, so it "resumes execution" (self.partner.next()) and executes it's second line of instructions. And so on... If someone better at generators than I could put together a version of this where the LockStepper's have a __call__() method that yields execution back and forth between a partner LockStepper, then we'd be closer to simulating the behaviour, but not to solving the problem, which asks for this behaviour using arbitrary functions (not necessarily LockSteppers). And, I've know idea how to do that :) Hope that clears things up a little, Sean From wilkSPAM at OUTflibuste.net Thu Jul 31 03:38:17 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 31 Jul 2003 09:38:17 +0200 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> <7b454334.0307301611.1b40ff11@posting.google.com> Message-ID: <87d6fri1sm.fsf@flibuste.net> faizan at jaredweb.com (Fazer) writes: > Graham Breed wrote in message news:... >> Diez B. Roggisch wrote: >> >> > http://www.bagley.org/~doug/shootout/craps.shtml >> > >> > Python is place 13, with a speed index of 578. PHP is second last (before >> > bash) and has a speed index of 197. >> >> Those benchmarks are doubly useless for the question at hand. Firstly, >> they only test command line applications. Secondly, PHP is compiled >> without optimizations because the rules state that only the default >> configuration can be used. See question 8 of the FAQ: >> >> http://www.bagley.org/~doug/shootout/faq.shtml >> >> >> Graham > > Yeah, I read the FAQ as well. I am basically looking for a FAST > alternative to PHP meaning the responce time is fast. Do you think > that Python with using the CGI module is a good solution? It depends what you mean by fast, and which kind of task you'll to do... If you really need fast answer, you'll need to use a webserver or mod-python to keep the data in memory. If you need fast execution, you can code a part in C. bye -- William Dode - http://flibuste.net From jocsch at phreaker.net Mon Jul 7 13:24:18 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Mon, 07 Jul 2003 19:24:18 +0200 Subject: Search for mapping solution References: Message-ID: Thanks for all the answers. Nice to have such a community. For me it's really interesting to see all the possible solutions. I learned some new things in this discussion Greetings, Markus From erwin at andreasen.com Wed Jul 2 11:47:48 2003 From: erwin at andreasen.com (Erwin S. Andreasen) Date: 02 Jul 2003 17:47:48 +0200 Subject: os.fork() different in cgi-script? References: Message-ID: <87vfulrkuz.fsf@andreasen.org> "Andreas Kuntzagk" writes: > following code: > print "Content-Type: text/plain\n\n" > print os.getpid() > > childPID = os.fork() > if childPID == 0: > sys.exit() > else: > os.wait() [...] > So it looks the main() is run 2 times. > Is it so? And if yes, why? The problem is buffering. When you run your script from the command line, the standard output is a terminal and becomes line-buffered. Thus at the time you fork, the stdout buffer has been flushed. When you run it as a CGI script, stdout is a socket and thus not a terminal -- so it becomes block buffered. At the time you fork, each copy of stdout holds all of our unflushed output. When the two processes exit they will both flush the output, resulting in it being printed twice. You can use sys.stdout.flush() to flush the pending output before forking. -- =============================================================== Herlev, Denmark <*> =============================================================== From mcfletch at rogers.com Sun Jul 20 06:47:52 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 20 Jul 2003 06:47:52 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: Message-ID: <3F1A7358.2080401@rogers.com> Aahz wrote: >In article , >Mike C. Fletcher wrote: > > >>Aahz wrote: >> >> >>>In article , >>>Mike C. Fletcher wrote: >>> >>> >>>>Nope, I'm trying to make meta-classes which have rich properties. The >>>>particular project is a plug-in system, where the classes (the >>>>metaclass-instances) want to have all sorts of rich metadata associated >>>>with them in a way which meshes with the rest of the system (i.e. using >>>>a descriptor-based introspection mechanism). >>>> >>>> >>>Keeping in mind that I'm really not following this discussion all that >>>closely (because metaclasses give me headaches), are you trying to make >>>a *metaclass* that has properties or a *metaclass instance* (i.e. a >>>class) that has properties? >>> >>> >>Just the meta-class instances (classes). Wasn't sufficiently precise in >>my description, the properties are normally declared in the meta-class, >>but they are actually properties of the meta-class instances. >> >> > >Next question: are you also trying to access the properties on class >instances? > Not really, I want them to be properties of the class, and would prefer that they *not* show up in the instances. That said, I can deal with it if they do show up in the instances. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From vivek at cs.unipune.ernet.in Wed Jul 30 04:10:02 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Wed, 30 Jul 2003 13:40:02 +0530 Subject: How to get success/failure in case of thread In-Reply-To: <84fc4588.0307290442.7c203e35@posting.google.com>; from pythonguy@Hotpop.com on Tue, Jul 29, 2003 at 05:42:26AM -0700 References: <20030728175542.A23857@cs.unipune.ernet.in> <16165.10847.483917.787182@montanaro.dyndns.org> <84fc4588.0307290442.7c203e35@posting.google.com> Message-ID: <20030730134002.A4660@cs.unipune.ernet.in> I think I have asked the wrong question :-( . I think the question should be : How can I use multiple threads in SimpleXMLRPCServer ??? I tried the following things: 1. added a queue object in the handler class 2. called the _dispatch mathod on a separate thread 3. in the _dispatch method after getting the reqult put it in queue 4. called another function that will send the response that was previously send by the dispatch method. But when I tried this it failed miserably :-( I even don't know whether I tried in the right direction or not ?? Any help/pointers. ??? TIA and Kind Regards Vivek Kumar From trentm at ActiveState.com Tue Jul 15 13:49:22 2003 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 15 Jul 2003 10:49:22 -0700 Subject: creating sparse files on win32 In-Reply-To: ; from erick_bodine@attbi.com on Tue, Jul 15, 2003 at 10:20:35AM -0700 References: Message-ID: <20030715104922.C12369@ActiveState.com> [erick_bodine at attbi.com wrote] > I need to create some sparse files on a win32 system (2000 & 2003 > Server) in order to do some testing of another application (not > python). I have been poking around the win32all extensions (win32file > specifically) that come w/ ActivePython but can't find anything that > allows me to create a file with the 'sparse file attribute' set. > > Has anyone done this in python? I haven't done this but MSDN teels me here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/sparse_file_operations.asp that one needs to use the FSCTL_SET_SPARSE control: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/fsctl_set_sparse.asp The code sample on the latter link uses the DeviceIoControl() Win32 API method: >>> import win32file >>> win32file.DeviceIoControl Also use this to determine if the file system supports sparse files: >>> win32api.GetVolumeInformation Hopefully that can give you a start. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From lol at lolmc.com Thu Jul 17 11:05:15 2003 From: lol at lolmc.com (Rogue9) Date: Thu, 17 Jul 2003 16:05:15 +0100 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> Message-ID: <3f16bb84@shknews01> After reviewing my question I realised that I should have posted the short piece of real code I'm working on and not tried to write some pseudo-code to illustrate the problem I'm having.Therefore I have printed the listing below which is quite short and hopefully won't annoy too many peopleabout the length of my post. To reiterate: The masterList holds the results for the UK lottery in the form [[1,'1994-10-19',3,14,16,23,34,43,2,3,'ARTHUR',234]...] and there are 792 results in the list. The skipFreqList holds the count of skipped draws between when a certain ball was drawn i.e if ball one was drawn in draw one and then not again till draw 10 the list would look like this [['Ball1',0,1,2,3,4,5,6,7,8,9,0......],['Ball2,1,2,0,1,2,3,4,5,0,0]....['Ball49',1,0,1,2,3,4,5,6,7,8]].Each item in the skipFreqList will be 1 item longer than the masterList length as each one starts with a string descriptor. So,what this code is supposed to do is to retrieve each draw from the masterList and pick the ball data from the result then for each ball index through to that balls skip frequency list e.g.r1 = skipFreqList[b1-1](the one is taken away from the ball value as the list starts at position 0 for indexing as I'm sure you know).Now we use the draw number to find the specific skip frequency value for that ball in that draw e.g.skip1 = r1[draw] and this is where it all goes wrong in that a value of zero is always returned rather than the value at the index position equal to the value of the draw variable. However,if I substitute an integer for draw in the same line e.g.skip1 = r1[10]then I always get the correct returned value! Can anyone please help with this please - it's driving menuts trying to figure out where I'm going wrong? Thanks for your time and effort, Lol McBride import cPickle import unittest import oop_lb.reports.AllDrawsReport import oop_lb.process.DrawLoop class AllDrawsReportTest(unittest.TestCase): def test1(self): # Initialise variables f=open('/home/lol/disk/python/lotto/dat/masterList.lb','r') masterList = cPickle.load(f) f.close() f=open('/home/lol/disk/python/lotto/dat/skipFreqList.lb','r') skipFreqList = cPickle.load(f) f.close() print skipFreqList draw = 1 while 1: if draw == 300:# limited to 300 whilst debugging break x = masterList[draw-1] print draw,x # Now we must write the skip frequency data into the table b1 = x[2] b2 = x[3] b3 = x[4] b4 = x[5] b5 = x[6] b6 = x[7] print b1,b2,b3,b4,b5,b6 r1 = skipFreqList[b1-1] r2 = skipFreqList[b2-1] r3 = skipFreqList[b3-1] r4 = skipFreqList[b4-1] r5 = skipFreqList[b5-1] r6 = skipFreqList[b6-1] print r1,r2,r3,r4,r5,r6 skip1 = r1[draw] print skip1 draw = draw+1 return if __name__ == '__main__': unittest.main() From CousinStanley at hotmail.com Sun Jul 6 16:43:28 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 6 Jul 2003 13:43:28 -0700 Subject: absolute beginners question about API documentation References: Message-ID: | Hi all, | I' new to python programming but a longtime java programmer. | Is there an API documentation like the javadoc API from java? | ... Markus ... I find the pydoc module handy for helping to find Python information ... The following command line starts pydoc with a small GUI as a Python documentation server with search and browse options ... python YourPythonPath/Lib/pydoc.py -g The browse option is useful because it also lists docs for any installed site-packages ... -- Cousin Stanley Human Being Phoenix, Arizona From kevin at cazabon.com Wed Jul 9 15:37:16 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 9 Jul 2003 12:37:16 -0700 Subject: Executables under Win32 References: <5vkngvs2epq6rv0a3rodeb839k5ls8bafj@4ax.com> <3F0BE70A.165B5274@engcorp.com> <2q7ogvksccj59kqmmed91u5ohqqvs2hhej@4ax.com> Message-ID: <5a4226f0.0307091137.48f1f71f@posting.google.com> > >There is py2exe and the Macmillan Installer, as well as some lesser > >known alternatives. py2exe runs on Windows only, the other on Windows > >and Linux (at least). A quick Google for either should get you there... > > > >-Peter > > > Many thanks :-) And let me say that py2exe is amazingly simple to use, and works flawlessly (at least for the 4-5 applications I've used it for) even for Tcl/Tk programs that some of the other .exe options have issues with. Also, if you need an independent installer program to install the resulting .exe and files, innosetup works very well (www.innosetup.com). (Thanks to everyone working on those projects!!!) Kevin. From peter at engcorp.com Fri Jul 4 14:12:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 14:12:45 -0400 Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> <840592e1.0307040900.14e3e668@posting.google.com> Message-ID: <3F05C39D.3F65B89C@engcorp.com> Hannu Kankaanp?? wrote: > > "Guyon Mor?e" wrote in message news:<3f054d9a$0$13803$4d4ebb8e at news.nl.uu.net>... > > I like the initiative for a messageboard for Python, but I think it would be > > similar to this newsgroup.... and I am quite happy with it so I don't > > really see a use for it imho > > Message boards are more user friendly, better organized (big plus) and more > interactive. At least when I post here from Google Groups, it takes > 3-6 hours for the message to arrive :P. Many questions thus are answered > 5 times by different people. But I don't know if the messages would arrive > quicker if I used a mail program for posting. Google Groups likely takes its feed directly of a Usenet site, and Usenet in general suffers from large propagation delay. It is that delay, caused by messages filtering slowly across the Usenet network, which leads to the "5 answers" problem, not Google Groups itself. The mailing list should be effectively instantaneous in comparison. -Peter From gh at ghaering.de Tue Jul 22 13:09:01 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 22 Jul 2003 19:09:01 +0200 Subject: Python scripting with Paint Shop Pro 8.0 In-Reply-To: References: Message-ID: <3F1D6FAD.1060402@ghaering.de> Marc Wilson wrote: > [...] One thing I've not found in the reference (perhaps I'm looking in the wrong > place): how do I capture command-line parameters? [...] sys.argv For fancier options, check out optparse (new in 2.3) or getopt. -- Gerhard From jerf at jerf.org Thu Jul 3 22:06:44 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 04 Jul 2003 02:06:44 GMT Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> <87k7azdber.fsf@titan.staselog.com> Message-ID: On Thu, 03 Jul 2003 15:47:56 +0300, Edvard Majakari wrote: > Which reminds me: I've seen two web unit testing frameworks, one which was > by the originial PyUT author, and the other that seemed more complete, > though not so well documented either. > > I've fancied developing one myself - so I'd like to know what kind of > things should I take into account before trying such a largish project? I > know that it is hard to test Web-based applications, for one thing - the > user doesn't usually type GET parameters to the URL, while doing so could > be the only possible way to do automated web site testing. Ideas/comments? Well, technically I'm using Perl to do this but this message will apply equally to Python unit testing on the web; it's not language specific. We're using mod_perl, and I'm using Test::Unit, which is a testing framework for Perl deliberately set up to look like JUnit, as Python's unittest is. What I'm doing is implementing an Apache Request faked-up object (which I later found existed in the form of the Perl module Apache::FakeRequest, but I think my own solution is better suited to our needs anyhow), and then going ahead and calling the Apache handlers directly with that object. It's tedious to construct the object if you can't find one pre-made, but it's easy. I've got mine set up so it records what is printed with it, so it can do things like extract necessary data from the output if necessary. I also have it set up to easily pass form parameters in according to the system we use. Once you do this, there's not a *whole* lot of difference between normal unit testing and this. In fact, you'll have an even easier time then me if you aren't grafting unit testing onto a multi-year old system with little to no functional separation (for practical purposes). In the end only the very, very last step (converting your output to HTML) is hard to test meaningfully, since it's hard to program whether it's doing what it's supposed to do in an automated fashion. But even in a web application, that's not the majority of the code, unless *all* you are doing is wrapping a shell around somebody else's library. Everything else is fairly straightforward. From dkuhlman at rexx.com Tue Jul 29 14:24:49 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 29 Jul 2003 11:24:49 -0700 Subject: Factories in Python References: <73b00f0c.0307290721.7a19e3d0@posting.google.com> Message-ID: Robert Ferrell wrote: [snip] > > However, I'm guessing that I'm not understanding other benefits of > using factories in Python. Does anybody have examples or pointers > on how use of factories in Python? Here is a link: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900 A reason for using a factory is that the client (the code that creates the instance) does not know which class or sub-class it wants to create an instance of. So, you build a factory that is smart enough to create an instance of the right class. In my case, while parsing an XML document and creating instances of nodes in the tree that represents the document, the classes (the super-class of each node class) does the parsing. However, each super-class must be smart enough to create a tree populated with instances of sub-classes, which may contain additional custom code,*if* they are available. I'd be interested in other reasons for using factories. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From jimmy at retzlaff.com Tue Jul 1 06:13:19 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 1 Jul 2003 03:13:19 -0700 Subject: ANN: pyUnRAR 0.1 Message-ID: Oleg Broytmann (phd at phd.pp.ru) wrote: >Hello! Hi Oleg! >On Mon, Jun 30, 2003 at 04:38:29AM -0700, Jimmy Retzlaff wrote: >> pyUnRAR requires Microsoft Windows, Python 2.2 or higher, and ctypes >> 0.6.2. > Can you instead (or in addition) to wrap http://www.unrarlib.org/ - it >is much more portable? I can't in the short term. I don't have the time and I actually need to extract files from RAR v3 archives in a project of mine - the library at http://www.unrarlib.org doesn't appear to support v3 archives yet. Perhaps when I do have more time that library will support v3, so I'll take a look again then. Thanks for the suggestion! Jimmy From heikowu at ceosg.de Tue Jul 29 15:51:06 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 29 Jul 2003 21:51:06 +0200 Subject: Itertools In-Reply-To: References: Message-ID: <1059508266.1668.64.camel@d168.stw.stud.uni-saarland.de> Untested code that does basically this, but beware of any traps (read and understand the code before trying to use it!!!), uses Python 2.3 functionality, but could be amended: --- START OF CODE --- import copy class IDup(object): def __init__(self,iterin): self.__iter = iterin self.__iterno = 0 self.__iteritems = [] self.__hasstopped = None def registerIter(): iterno = self.__iterno self.__iterno += 1 self.__iteritems.append([]) def getNext(self,iterno): if self.__iteritems[iterno]: iteritem = self.__iteritems[iterno].pop(0) elif self.__hasstopped is not None: raise self.__hasstopped else: try: iteritem = self.__iter.next() except StopIteration, e: self.__hasstopped = e raise for id, i in enumerate(self.__iteritems): if id <> iterno: i.append(copy.deepcopy(iteritem)) return iteritem class IDupped(object): def __init__(self,idup): self.__idup = idup self.__iterno = idup.registerIter() def next(self): return self.__idup.getNext(self.__iterno) def isplit(iterin,splitno=2): idup = IDup(iterin) iduppeds = [] for i in range(splitno): iduppeds.append(IDupped(idup)) return tuple(iduppeds) test = ["hello","how","are","you?"] x, y = isplit(iter(test)) for i in x: print i for i in y: print i --- END OF CODE --- Pitfalls: 1) You may not use the original iterator after it has been split. 2) Your iterator must return values which are copyable. If you wish for the values to be truly equal (even in ID) or they are not copyable, then just remove the copy.deepcopy from the code. HTH! Heiko. From aahz at pythoncraft.com Mon Jul 7 09:46:49 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2003 09:46:49 -0400 Subject: NNTP mirror of c.l.p? References: <2a897f11.0307070510.37a4ad41@posting.google.com> Message-ID: In article , Duncan Booth wrote: >wayne at mishre.com (Wayne Pierce) wrote in >news:2a897f11.0307070510.37a4ad41 at posting.google.com: >> >> Does anyone know if there is a public server where I can download >> c.l.p? I typically use GG, but want to test a program on my >> Palm-based system for accessing NNTP servers. > >Try news.freenet.de for public readonly access. Another popular option is http://news.cis.dfn.de/ which provides write access, too, but you have to register. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From brian094 at sympatico.ca Mon Jul 21 11:15:56 2003 From: brian094 at sympatico.ca (Brian Alexander) Date: Mon, 21 Jul 2003 11:15:56 -0400 Subject: update of curse panel in background? Message-ID: <3F1C03AC.1090502@sympatico.ca> Hello; Is it possible to update the contents of a curses panel in the background without bringing it to the top level? Or ... Does any update activity bring a panel to the foreground? Brian. From doug.hendricks at tnzi.com Fri Jul 25 01:53:56 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 24 Jul 2003 22:53:56 -0700 Subject: Python 2.3c2 Message-ID: Just grabbed and tried it on Tru64 5.1A (hp/compaq alpha ES40): Looks good: make test gives: ............ 221 tests OK. 34 tests skipped: test_aepack test_al test_audioop test_bsddb test_bsddb3 test_bz2 test_cd test_cl test_curses test_dl test_email_codecs test_gdbm test_gl test_imageop test_imgfile test_linuxaudiodev test_locale test_macfs test_macostools test_mpz test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_rgbimg test_scriptpackages test_socket_ssl test_socketserver test_sunaudiodev test_timeout test_urllibnet test_winreg test_winsound Ask someone to teach regrtest.py about which tests are expected to get skipped on osf1V5. ............ Thanks a bunch and good luck on the final 2.3! Doug From mcfletch at rogers.com Sun Jul 6 17:21:00 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 06 Jul 2003 17:21:00 -0400 Subject: Search for mapping solution In-Reply-To: References: Message-ID: <3F0892BC.2040800@rogers.com> result = {} for (name, whatever, costs) in lines: costs = float(number.replace(',','.')) dict[name] = dict.get( name, 0.0) + costs (that's untested, but you should get the idea). Note, however, floating point is generally a poor choice for accounting applications, so you may want to look into the libraries for fixed-point calculations. HTH, Mike Markus Joschko wrote: >Hi, >stated in a post befor, I'm a java programmer, fascinated about the elegant >way python solves iterations. Maybe you can show me a solution how to map >the following > >I have a List: > >Name - Number - Costs > >lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > >Now I want to have it in a dictionary(name,costs) Should look like >{'fred':'0,60' , 'sam':'1'} > >What's an elegant way to do it? I can use a lot of loops, but I assume, that >there is a better way of doing so. > >Thanks, > Markus > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From woooee at yahoo.com Tue Jul 1 19:56:16 2003 From: woooee at yahoo.com (Curly Joe) Date: Tue, 1 Jul 2003 16:56:16 -0700 (PDT) Subject: Good code patterns in Python Message-ID: <20030701235616.97308.qmail@web20503.mail.yahoo.com> In your original example, if some_condition: some_name = some_value else: some_name = other_value the default value is with the else statement. It is always some_name = other_value as a default whenever some_condition isn't met, so in the second part, your code should read: some_name = other_value if some_condition: some_name = some_value not vice versa as you had it - if I am interpreting it correctly. some_name = some_value if not some_condition: some_name = other_value Either way, you or I are making a mistake with your code, while using an if/else doesn't produce this type of misunderstanding IMHO. Obviously, clarity is in the eye of the beholder though, and so there is, are, and will always be differences, and this is a good thing. __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From akineko at pacbell.net Thu Jul 10 12:45:38 2003 From: akineko at pacbell.net (Aki Niimura) Date: 10 Jul 2003 09:45:38 -0700 Subject: Python and freeze (something odd) References: <3F0D5078.1CF6F138@hotmail.com> Message-ID: Alan Kennedy wrote in message > I think this might be related to a problem that existed in many > embedding situations. Check this bug on sourceforge > > [663074]: codec registry and Python embedding problem > https://sourceforge.net/tracker/?func=detail&aid=663074&group_id=5470&atid=105470 > > I had a similar problem with mod_python and python 2.2.2. I upgraded > to python 2.2.3, and the problem just went away. > > So it's probably worth upgrading to 2.2.3, and see if that fixes the > problem? Alan, thank you very much for your kind posting. I'm very surprised to hear a similar problem has existed. Unfortunately, I have already python 2.2.3. No stable version to upgrade. However, the bug info gave me many places to start. I definitely look into this further. Thanks! Aki Niimura From peter at engcorp.com Fri Jul 25 11:15:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Jul 2003 11:15:03 -0400 Subject: How to detect typos in Python programs References: Message-ID: <3F214977.AEB088C8@engcorp.com> Manish Jethani wrote: > > Is there a way to detect typos in a Python program, before > actually having to run it. Let's say I have a function like this: > > def server_closed_connection(): > session.abost() > > Here, abort() is actually misspelt. The only time my program > follows this path is when the server disconnects from its > end--and that's like once in 100 sessions. So sometimes I > release the program, people start using it, and then someone > reports this typo after 4-5 days of the release (though it's > trivial to fix manually at the user's end, or I can give a patch). > > How can we detect these kinds of errors at development time? > It's not practical for me to have a test script that can make > the program go through all (most) the possible code paths. You have no good alternative. Why do you say it's impractical to actually test your software before it's shipped? Isn't it more impractical to rely on your users to test the software, thinking it should work? Unit testing in Python is *really* easy. I can't think of any reason not to do it as the best way of catching problems like you show above. If you resist :-), however, you might find PyChecker will help. I'm not sure if it can do anything in the above case yet, however. -Peter From abelikov72 at hotmail.com Tue Jul 8 19:32:29 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 08 Jul 2003 23:32:29 GMT Subject: Python vs PHP References: Message-ID: <45lmgv4nqd0fjtt18ra70519cr5mf3d7mu@4ax.com> On 8 Jul 2003 17:59:12 GMT, Jon Ribbens wrote: >I don't understand why you keep saying "CGI is not an option" when >nobody has suggested that you use it. Ok From jjl at pobox.com Fri Jul 11 11:00:52 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Jul 2003 16:00:52 +0100 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> Message-ID: <87k7apyuor.fsf@pobox.com> Ian Bicking writes: [...] > Security isn't a big deal -- or rather, securing cookies isn't a big > deal. I don't understand. The problem is that pickles can be constructed that can damage systems when unpickled, is that right? If that's true, then surely unpickling cookie data is unsafe, because stuff coming in from the network has to be regarded as malevolent. Are you saying that web server environments are sufficiently-well bolted down that no pickle attack will work? But belt-and-braces is the best policy, isn't it? > and IE has a > bug where you can't redirect and set a cookie at the same time, which > can really drive you crazy if you don't know about it. [...] Hah. There's a slight irony there, given that they fought against restrictions on setting cookies from 'unverified' third parties when the (more-or-less stillborn) cookie RFCs were being written. So they argue against that, then end up partially implementing it by accident... John From omega at silvreus.eu.org Mon Jul 14 04:44:24 2003 From: omega at silvreus.eu.org (OM) Date: Mon, 14 Jul 2003 10:44:24 +0200 Subject: training for newbies Message-ID: hi there do you know any sites with free programs for newbies, which will help me in progress? i know that only way to develop is writing programs, but in my book i don't have programs to write, only questions.. From mis6 at pitt.edu Mon Jul 28 19:30:03 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 28 Jul 2003 16:30:03 -0700 Subject: pretty printing graphs References: Message-ID: <2259b0e2.0307281530.218400ae@posting.google.com> "Scherer, Bill" wrote in message news:... Hey "dot" is great! I didn't know about it before readin your post. In a very short time I came out with the following recipe to draw Python inheritance hierarchies (which I post since it is pretty short and useful ;): "How to draw inheritance hierarchies via dot" import os def label(i,n): if n>1: return '[label="%s"]' % (i+1) return "" def dotMRO(cls): "Generates the dot code for the MRO directed graph" yield "digraph MRO_of_%s{\n" % cls.__name__ for c in cls.__mro__: n=len(c.__bases__) yield ' '.join([' %s -> %s %s;' % (b.__name__,c.__name__,label(i,n)) for i,b in enumerate(c.__bases__)]) yield '}' # Example hierarchy O = object class F(O): pass class E(O): pass class D(O): pass class G(O): pass class C(F,D,G): pass class B(E,D): pass class A(B,C): pass # creates the graph dotcode='\n'.join(dotMRO(A)); print dotcode os.system('echo "%s" | dot -Tps > prova.ps' % dotcode) os.system('gv prova.ps&') Assuming you have "dot" and the standard Unix tools installed this will generate a very nice diagram. I am open to suggestion to improve it, since this is may first trial with "dot". I am quite impressed by the easy of use. Very nice! Michele From rtomes at ihug.co.nz Thu Jul 3 00:23:04 2003 From: rtomes at ihug.co.nz (Ray Tomes) Date: Thu, 03 Jul 2003 16:23:04 +1200 Subject: zip() or what? Message-ID: <3F03AFA8.7030905@ihug.co.nz> Hi all Many thanks to those that answered my questions about whitespace and ord() being reverse of chr(). As well as the 2 things I asked about I learned about 5 other useful things. This I am trying to flip an array around so that the "subscripts" happen in the opposite order and reading the docs I thought that zip() did this. So I tried it like this: x=[[0.1,0.2],[1.1,1.2],[2.1,2.2]] print zip(x) and what I got was (removing the .0000000001s): [([0.1, 0.2],), ([1.1, 1.2],), ([2.1, 2.2],)] which is just my original array with an extra useless level in it. What I really wanted was this: [[0.1,1.1,2.1],[0.2,1.2,2.2]] So my question is how do I do that easily? And what on earth is zip() doing? Alternatively, is there a construct to get x[*][i] if you know what I mean? Have fun Ray From newsgroups at jhrothjr.com Thu Jul 31 18:02:19 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 18:02:19 -0400 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> <1sScnW0Sv7DzrrSiRTvUpQ@speakeasy.net> Message-ID: "A.M. Kuchling" wrote in message news:1sScnW0Sv7DzrrSiRTvUpQ at speakeasy.net... > On Thu, 31 Jul 2003 08:06:29 -0500, > Skip Montanaro quoted: > > Ben> doing... I'm just a newbie who's found date and time handling in > > Ben> Python to be confusing, and thought I'd mention it. (And I am the > > Ben> original poster, btw.) If nobody else agrees, maybe it's not > > Ben> really a problem. > > It's also not very hard to write a PEP; start with an existing PEP for the > headings, and skim PEP 1 for the PEP life cycle. > > Parsing of date/time formats is the big omission from 2.3's date support and > the big advantage that mxDateTime still has. With 2.3 you still have to > roll your own parser for ISO-8601 format or whatever. Fixing the rfc822 > module is probably the largest problem; we can't just change getdate() to > return a datetime instead of a 9-tuple, so it'll have to be supported as a > new method. The standard library should probably use datetime as much as > possible, but backwards-compatible 9-tuple-based interfaces will still need > to be supported. The datetime module is a great piece of work, but I wonder why it wasn't made more compatible with the time module? It would seem to be simple enough to provide a sequence interface so the object supports the 9-tuple directly (for either naive or tz-aware, pick one,) and also supports the same attributes as the objects in the time package. I also wonder why anyone made the choice to set the year origin at 1AD? That decision, by itself, makes it almost unusable for my hobby (astrological software, which is basically astronomical software with a different focus.) Astronomical dates are always measured in days since 4700 and something BC. History did not begin, after all, six years after JC was born. (And astronomical years, btw, do include a year zero, which historical years do not.) Other than that, and a couple of other bobbles (depending on the C library for strftime(), and the lack of an input parser both come to mind) it's a great piece of work. John Roth > > --amk (www.amk.ca) > Hello! I'm the Doctor. I believe you want to kill me. > -- The Doctor, in "Silver Nemesis" From km-news1 at onlinehome.de Wed Jul 23 17:28:43 2003 From: km-news1 at onlinehome.de (Klaus Meyer) Date: Wed, 23 Jul 2003 23:28:43 +0200 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3f15b04b$0$49114$e4fe514c@news.xs4all.nl> Message-ID: > > "Als achter vliegen vliegen vliegen, vliegen vliegen vliegen achterna." > > (btw, a tip: 'vliegen' is a verb and also a noun in Dutch.) And in German you can see the nouns :-) print "Wenn hinter Fliegen Fliegen fliegen fliegen Fliegen Fliegen nach." (print because this is comp.lang.python ;-) -- Gru? - regards Klaus :-) From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 14 15:21:24 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 14 Jul 2003 19:21:24 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser Message-ID: Hi there! I'm a beginning Python programmer, and I like it a lot already. Since my Sharp Zaurus has a fairly complete Python environment including PyQT, I thought it would be the perfect language for programming some nice things on my Zaurus. The thing I really missed on the Z was a good Jabber client. That's why I'm building my own. Things are going good, and in a few nights I've been able to get a fairly decent though under-featured client. There is a small thing annoying me, though I'm trying to show the name of the person saying something in color: red = someone else, blue = me. This is an example of the text I'm adding to the QTextBrowser: <me>: hello world It works like a charm on my PC, but on the Zaurus the text is all black. Does anyone know how I can fix this? ~~~ brainwave flash ~~~ I just thought of something: what if the Z doesn't allow single quotes around the "color" attribute? I gave it a try, and replaced the text with: <me>: hello world And it works! Anyways, perhaps this will be picked up by others having the same problem. I'll stick around in this group and try to soak up as many good knowledge from people as I can ;-) A bit about myself: I'm a 24 year old, studying Computer Sciences at the University of Amsterdam, I'm Dutch (like Guido ;-)) and I currently live in Amsterdam too. I've been a programmer for half my life now :) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From b.neijt at ai.rug.nl Thu Jul 31 10:54:11 2003 From: b.neijt at ai.rug.nl (Bram) Date: Thu, 31 Jul 2003 16:54:11 +0200 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling Message-ID: Hi, Summ: "What is the best way to handle int8,16 and 32 data in python?" Im currently working on a class to implement the gui protocol of mldonkey. (http://mldonkey.lemmster.de/wiki/index.php/GuiProtocol) However this requires to send int32 and int16 and even int8 integers. To create data I'm using the work-around of converting everything to hex values, and then converting the hex values to a data string wich I put on the socket (e.g. "\x00\xF0"). I could do the same on the recieving end: chop it up in bytes and convert them to numbers (combining the hi and lo bytes of the int16 with some calculations) However, there must be a better way of doing this. Can anyone help me on this problem? Bram From bgailer at alum.rpi.edu Fri Jul 25 14:42:53 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 25 Jul 2003 12:42:53 -0600 Subject: data conversion question (binary string to 'real string') In-Reply-To: References: Message-ID: <5.2.1.1.0.20030725124016.03b462f0@66.28.54.253> FWIW here's an interesting way to get at the bit: if 13 is the number you want to represent in binary and you want 6 bits: >>> [13>>x & 1 for x in range(6,-1,-1)] [0, 0, 0, 1, 1, 0, 1] Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From candiazoo at mac.com Fri Jul 11 23:17:52 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Sat, 12 Jul 2003 03:17:52 GMT Subject: Problem with MySQLdb on Mac OS X... Message-ID: <110720032317344670%candiazoo@mac.com> I made modifications to setup.py to set safe threading to NO and also to point to the "real" location of the mysql libraries and stuff like that. To test it I wrote a simple script that just tries to connect to the database. It fails. It also fails interactively. Here is what I am getting... [h000a9578d1ca:~] mike% /usr/local/bin/python2.3 foo.py Traceback (most recent call last): File "foo.py", line 7, in ? cnn = MySQLdb.connect(db=DB, user=USER, passwd=PASSWD) File "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-pa ckages/MySQLdb/__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-pa ckages/MySQLdb/connections.py", line 116, in __init__ self.converter[types.StringType] = self.string_literal TypeError: object does not support item assignment Segmentation fault The download, build and install went fine. This same code works (well, different database name, user and password) on a different machine. The database, username and password are all correct. Any thoughts? Thanks! Mike From bill7525 at shaw.ca Sat Jul 26 00:13:26 2003 From: bill7525 at shaw.ca (Survival Bill) Date: Sat, 26 Jul 2003 04:13:26 GMT Subject: how do I add a subscribe by email in my web page Message-ID: I have things setup so far that users are able to subscribe via the web page that the program creates for users to subscribe that's ok, but what I want is to be able for users to subscribe via an e-mail statement in my web page can this even be done using the href=mailto:Survivalbillnewsletter at survivalbill.com?subject=subscribe I have tried but can not get it to subscribe users to the list I have left out the " and < > statements out of the mailto: I did cuz I don't know how it will show in the newsgroup... I just set this up the other day and have searched for the info at python couldn't find what I was looking for so I am trying to pick your brains, I know easy stuff right well ya if you know how! problem I do not know the how part :( -- _____________________________________ Survival Bill Outdoor Retreat Website: http://www.survivalbill.com Message Forum: http://www.survivalbill.com/cgi-bin/forum.pl Photos: http://www.survivalbill.com/photosa.htm From inyeol.lee at siimage.com Thu Jul 24 19:15:17 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Thu, 24 Jul 2003 16:15:17 -0700 Subject: very Very VERY dumb Question About The new Set( ) 's In-Reply-To: <3f205d3c.745868662@news.blueyonder.co.uk> References: <20030723144732.13232.00000523@mb-m10.aol.com> <3f205d3c.745868662@news.blueyonder.co.uk> Message-ID: <20030724231517.GA15764@siliconimage.com> On Thu, Jul 24, 2003 at 10:31:11PM +0000, Alan Gauld wrote: [...] > Since both dictionaries and Sets require unique members/keys, > why not use the dictionary braces but without the key/value > syntax. So: > > mySet = {1,2,3,4} > > Which is illegal for a dictionary but would be OK for a Set. > It also just happens to be the same delimiters used in math > for sets... See PEP 218. It describes a long term plan to make set builtin type, including syntax for constant set {1,2,3,4} and empty set {-}. Inyeol From peter at engcorp.com Sat Jul 5 17:24:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Jul 2003 17:24:30 -0400 Subject: Calculating Year, Month and Day of Life References: Message-ID: <3F07420E.BC640F@engcorp.com> hokiegal99 wrote: > > Once again, I'm making progress on my own. Here's where I stand now: > > ---------------------- > from time import * > local = localtime() > > y = input("Enter the year of birth: ") > m = input("Enter the month of birth: ") > d = input("Enter the day of birth: ") > > age = y,m,d > print "You are", local[0] - age[0], "years", local[1] - age[1], "months" > ----------------------- Unfortunately, you won't get the right result from this in some cases, such as when the current month is earlier in the year than the month in which the person was born.. Using mxDateTime's support for this instead will probably be easier. From giles_brown at hotmail.com Wed Jul 30 04:42:31 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 30 Jul 2003 01:42:31 -0700 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> Message-ID: <57de9986.0307300042.3d3fa846@posting.google.com> giles_brown at hotmail.com (Giles Brown) wrote in message news:<57de9986.0307290052.688e54c5 at posting.google.com>... > I'm feeling quite dumb this morning. Next morning not quite so dumb. Finally got the dll to register so I thought I'd post my findings for the record. Mark was spot on (of course!) about the lost python exception. I added "import win32traceutil" into boot_com_server and low the traceback showed in pythonwin. I had omitted to mention that I am using win32com client inside the dll, so I added the necessary '--progids' (only "ADODB.Connection.2.1" as it happens). Then I found that my dll when run (for registration) was trying to generate an '__init__.py' in the equivalent of the gen_py folder. This was failing because it was looking for win32com.__gen_path__ which is not set for frozen code. To overcome this I added (something like) the following code to my module that was included the EnsureModule call. if getattr(pythoncom, 'frozen', False): import os import win32com import tempfile # Assign (temporary) directory for gencache # (tempfile.tempdir is always 'None' so use TemporaryFile()) :-( win32com.__gen_path__ = os.path.join(os.path.dirname( tempfile.TemporaryFile().name), 'gencache') Finally I was getting the "codec" problem. I tried '--packages encodings' but for some reason this did not seem to build encodings.__init__.pyc into the dll. This exhibited itself in the "no codec search functions registered" LookupError. Adding '--include encodings" fixed this. This lead (not unreasonably) to a "unknown encoding: utf-8" LookupError which was fixed by added ",encodings.utf_8" to the command line. The final working command line looked like this: c:\python23\python madeupname/setup_dll.py py2exe --com-dll --include encodings,encodings.utf_8 --excludes Tkinter --progids ADODB.Connection.2.1 Now I need to test the DLL :-) Cheers and thanks, Giles From intentionally at blank.co.uk Mon Jul 14 22:28:26 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:28:26 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <3f12a45b.6171268@news.freeserve.com> Message-ID: On Mon, 14 Jul 2003 12:56:06 GMT, ivlenin at gmx.co.uk (I V) wrote: >On Sun, 13 Jul 2003 20:39:56 +0100, Stephen Horne > wrote: > >>The fact is that 'assignment' has a common meaning separate from the >>choice of programming language, and that the way Python handles name > >Yes. > >>binding means that meaning is not respected by Python for mutable >>objects. > >No. > >Assignment takes a name and binds it to a different value, whatever >programming language you use. No. We are in severely pedantic mode in this thread, because of the nature of the argument. 'value' is a term which has meaning in mathematics and computer science. Values are *always* immutable, whatever language you use. In Python, assignment takes a name and binds it to an object (or a pointer to that object). In C/C++, assignment takes a name and binds it to a symbolic representation of a value. Objects can be mutable. Representations can be mutable. However, using that mutability should respect the idea from mathematics of variables binding to values. The fact that the binding is implemented using objects or symbolic representations is irrelevant - they are low level implementation details. You shouldn't have to worry about them in a 'very high level' language. Of course if you explicitly ask to deal with the object (rather than the value) that is a different thing. But that isn't the case in Python. It fails to respect the mathematical concept of variables binding to values BY DEFAULT. This regularly causes confusion and errors. From donn at drizzle.com Sun Jul 13 13:22:44 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 13 Jul 2003 17:22:44 -0000 Subject: timeout on os.popen3? References: Message-ID: <1058116964.113730@yasure> Quoth selwyn : | I would like some advice on how I can include a timeout for a scanning | operation using unzip on linux and os.popen3. | | I am scanning through about 30g of rescued zip files, looking for xml | extensions within those files. What I have put together 'works', but | only for what appears to be properly reconstructed files. | Unfortunately, some aren't AND for some reason no standard error | messages are being triggered. This causes my script to hang indefinitely. | | What I would like is for the script to move on to the next file, after | say a 10sec period of inactivity, but am unsure how this could be | included. I have googled around and think the select module may be | helpful, but after reading the docs I am still confused :-( You might be able to manage it with select. When you start up a program on two or more pipes, you have kind of a juggling act. Select is the juggler, it can tell which pipe has data to read and which is ready for more data to be written to it. However, it's still a juggling act and you need some skill, too. If you decide to try it, also read about os.read, and don't try to use the file object for reading. On the other hand, if you don't mind writing to disk files instead, that will completely eliminate this aspect of your problem. Like file = '%s%s' % (sys.argv[1], i) ev = os.system('unzip -l "%s" > /tmp/zout 2> /tmp/zerr' % (file,) if os.WEXITSTATUS(ev) != 0 or nonEmptyFile('/tmp/zerr'): dealWithError(ev, open('/tmp/zerr', 'r')) elif searchFile('/tmp/zout', 'xml'): dealWithFile(file) Donn Cave, donn at drizzle.com From martin at v.loewis.de Fri Jul 25 17:57:02 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 25 Jul 2003 23:57:02 +0200 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> <3f210717$0$76049$edfadb0f@dread11.news.tele.dk> Message-ID: "Terry Reedy" writes: > So to answer the OP's question, the problem solved is that directly > assigning a function as an instance attribute binds the function as a > function, which means no *automatic* access to the instance and its > other attributes. To *really* answer the OP's question: API, in general, has no purpose - it has a function. Whether that function is useful for something depends on the application. So APIs don't try to solve problems themselves - it is the developers who solve the problems using the API. So one may ask "what is the problem that could be solved using new.instancemethod". These questions often don't have good answers, and I believe yours isn't much better than that the problem being solved is "Create an object of type instancemethod, given the function, the instance, and the class." Whether it is useful to create such objects depends on the application. Regards, Martin From JensRie at gmx.de Thu Jul 10 04:29:57 2003 From: JensRie at gmx.de (Jens Riedel) Date: Thu, 10 Jul 2003 10:29:57 +0200 Subject: Zope problem: objectValues('Folder') References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> Message-ID: <3F0D2405.1070606@gmx.de> Max M schrieb: >>
    >> >>

  • >>
    >>
> If you have written it exactly like that, it should work. You have no > folders inside the folder you are running it in then. That's my problem. I followed the instructions of the Zope Book example exactly and created 3 folders in the folder I use the objectValues()-method on. In another example I have the folder "photos" with 3 jpg-files in it. When I call "photos.objectValues()" I get a list with the 3 files, if I use "photos.objectValues('File')" I get nothing... The objectValues-method seems not working when I specify it on a type. > I assume you have not written your code that way, but rather: > > objectValues(['Folder','File']) Correct, I did write either objectValues('Folder') or objectValues('File') in my code. Greetings, Jens From paul at boddie.net Wed Jul 9 05:59:29 2003 From: paul at boddie.net (Paul Boddie) Date: 9 Jul 2003 02:59:29 -0700 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> Message-ID: <23891c90.0307090159.108be38@posting.google.com> "trewornan" wrote in message news:... > On Tue, 08 Jul 2003 18:04:11 +0200, M.-A. Lemburg wrote: > > > Having a maintained and actively supported ODBC interface which > > works on all major platforms, not just Windows ?! > > Agreed that this must be a lot of work but most of us use open source > software for a reason. Yes, mostly for access to the sources, the possibility of redistribution and the various other freedoms associated with Open Source/Free Software. Paul P.S. Of course it doesn't hurt to get stuff for free, but if that was the most important thing, you'd surely be content to download proprietary "free stuff", demos and evaluations (and be at the mercy of the binary-only distributor in question). From pinard at iro.umontreal.ca Tue Jul 15 10:24:17 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 15 Jul 2003 10:24:17 -0400 Subject: Confusing automated translators. In-Reply-To: <87brvw3ula.fsf@pobox.com> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: [John J. Lee] > Alan Kennedy writes: > > I'd love to hear of other similar phrases. And somehow I intuit > > there's people in this ng who know lots of them :-) > There are so many... Automated translators which ignore punctuation are pretty fragile, too. Here is a case where the exact same words are used, besides punctuation. I read in one of Audouard's books ("De la connerie et des cons", if I remember correctly), about Montcalm, a French Canadian military of old times. The history reports that he said: "Messieurs les Anglais, tirez les premiers!" but Audouard wrote that he fears the correct writing should have been something like: "Messieurs! Les Anglais... Tirez les premiers!" P.S. - I confess I would have more difficulty relating this one to Python. The word categorisation disambiguation program that I intend to rewrite in Python, one of these days, would (correctly) yield the same results for both sentences, so Python-wise for me, this is a non-issue! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jepler at unpythonic.net Sun Jul 27 21:59:33 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 27 Jul 2003 20:59:33 -0500 Subject: multiple file objects for some file? In-Reply-To: References: Message-ID: <20030728015933.GA7068@unpythonic.net> On Sun, Jul 27, 2003 at 01:17:50PM -0400, Tim Peters wrote: > You can get in deep trouble if the file mutates, though. Python's file > objects are wrappers around C's streams, and each C stream has its own > buffers. So, for example, a mutation (a file write) made via one file > object won't necessarily update the buffers held by the other file objects > (it depends on how your platform C works, but I don't know of any that > automagically try to update buffers across multiple streams open on the same > file), and then reading via some other file object may continue to see stale > data (left over in its buffer). ... I believe you're "safe" if you always: 1) flush() after a write that may be followed by a read: f.write("abcd"); f.flush() 2) perform a no-op seek() before a read that may follow a write SEEK_CUR=1 f1.seek(0, SEEK_CUR); f.read(4) Furthermore, using a "0" buffering argument to open() [in the reader and the writer] should save you from needing to do this, *but* it may negatively impact performance. Finally, you could use os.open/os.read/os.write, which should not have these buffering problems, but will also not have the performance gain of stdio buffering. This performance diference may or may not be significant in your application. Jeff From nospamjynyl at yahoo.co.nz Mon Jul 28 02:29:41 2003 From: nospamjynyl at yahoo.co.nz (Peter) Date: Mon, 28 Jul 2003 18:29:41 +1200 Subject: default import path Message-ID: <3f24c37e@news.maxnet.co.nz> How can I edit the default import path for Python under Windows? I want to use the piddle module. So far, I've copied the unzipped contents of the zip file to c:\prog~1\python\lib\site-packages, but how do I set it so this is automatically on the python path? (I don't want to have to manually add that directory every time.) TIA Peter From rmunn at pobox.com Fri Jul 18 10:44:17 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 18 Jul 2003 14:44:17 GMT Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> <20030716132455272-0600@news.xmission.com> Message-ID: Mel Wilson wrote: > In article <20030716132455272-0600 at news.xmission.com>, > Adam Ruth wrote: >>As a side note, I wouldn't have thought that the augmented assign would >>work the way you tried to use it. I would have thought that it would be >>analagous to the + operator and sequences: >> >>> x = [1,2,3] >>> y = [1,2,3] >>> x + y >>[1,2,3,1,2,3] >> >>So that the agumented form would be: >> >>> x = [1,2,3] >>> x += [1,2,3] >>[1,2,3,1,2,3] >> >>But I've never tried it before and didn't know that it didn't work with >>sequences. You learn something new every day. > > It does: > >>>> def multi(): > ... return 4, 5, 6 > ... >>>> a = (1,2,3) >>>> a += multi() >>>> a > (1, 2, 3, 4, 5, 6) > > It seems to be just that += refuses to work with tuple unpacking. There's a subtle but very important difference between those two. Lists: >>> l = [1,2,3] >>> id(l) 135706404 >>> l += [4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> id(l) 135706404 Tuples: >>> t = (1,2,3) >>> id(t) 135480164 >>> t += (4,5,6) >>> t (1, 2, 3, 4, 5, 6) >>> id(t) 135423036 Notice how the id remained the same in list augmented assignment, while it changed in tuple augmented assignment. That's because in the first example, l is not rebound; instead, the list object that l points to gets extended. In the second example, t gets rebound to a *new* tuple object. Another demonstration: Lists: >>> l = [1,2,3] >>> id(l) 135704132 >>> l2 = l >>> l += [4,5,6] >>> id(l) 135704132 >>> l [1, 2, 3, 4, 5, 6] >>> l2 [1, 2, 3, 4, 5, 6] Tuples: >>> t = (1,2,3) >>> id(t) 135480164 >>> t2 = t >>> t += (4,5,6) >>> id(t) 135423036 >>> t (1, 2, 3, 4, 5, 6) >>> t2 (1, 2, 3) When you do augmented assignment on a tuple, a new object is created and the name is rebound. In the example above, t2 still points to the old object, which was not affected (since tuples are immutable). One more example, with lists: >>> l = [1,2,3] >>> id(l) 135714564 >>> l2 = l >>> l = l + [4,5,6] >>> id(l) 135704372 >>> l [1, 2, 3, 4, 5, 6] >>> l2 [1, 2, 3] This time we wrote "l = l + [4,5,6]" instead of "l += [4,5,6]". See the difference? This subtlety is why you should never, IMHO, try to apply augmented assignment to a function parameter that's supposed to be a sequence. You might intend for a tuple to be passed to your function, but what if someone passes in a list instead? Be explicit: if you mean "l.append(l2)", then write that. If you mean "l = l + l2", then write that. The only time I use augmented assignment is when I'm incrementing integers, e.g. "count += 1". -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From stauffer at swarthmore.edu Thu Jul 24 15:22:42 2003 From: stauffer at swarthmore.edu (Glenn Stauffer) Date: Thu, 24 Jul 2003 15:22:42 -0400 Subject: running python In-Reply-To: References: Message-ID: <3F203202.3030000@swarthmore.edu> Iain Macalister wrote: >How do you run files written with python if you don't have the compiler and >stuff on your computer? > > Find a machine that does... Or, are you asking 'how can you distribute a python program so that someone who does not have python installed can run it'? There is a python freeze utility that converts scripts to executables (not the same as a python compiler) and there are some other programs that can do this: http://starship.python.net/crew/theller/py2exe/ http://www.mcmillan-inc.com/install1.html http://www.computronix.com/utilities.shtml --Glenn From ianb at colorstudy.com Wed Jul 9 21:53:17 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 09 Jul 2003 20:53:17 -0500 Subject: Sample Web application (Re: Python vs PHP) In-Reply-To: References: Message-ID: <1057801996.3737.1223.camel@lothlorien> On Wed, 2003-07-09 at 15:17, A.M. Kuchling wrote: > On 09 Jul 2003 12:34:46 -0500, > Ian Bicking wrote: > > One of the big problems I also had was installation. Many of the > > frameworks require non-trivial Apache configuration, which hinders > > experimentation. Actually solving this is significant work, though -- > > but also something which very much deserves solving. > > Why? The purpose is to let users compare the structure of applications, not > benchmarking. I envision users browsing the code for each framework, never > running anything until they've selected a framework and begun implementing > an application. Solving web server configuration problems is out of scope. Evaluation of course only starts with reading, of course you are also going to want to experiment directly with the system. But more generally, I can't stand writing about how to work around problems, when (as a programmer) it is within my power to fix those problems. It seems far better to spend time fixing problems than merely documenting them. The thing is, for many of the developers of these frameworks, the payoff for improving installation isn't that big, because they wrote this for themselves and they only have a handful of installations to do. But installation becomes a much bigger deal when considering larger adoption, and I think installation is a major hindrance to Python's adoption as a web programming language -- a combination off difficult installation, and a lack of robustness and generality in installation methods. Ian From stuart at bmsi.com Thu Jul 3 16:20:32 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Thu, 03 Jul 2003 16:20:32 -0400 Subject: Auto free Buffer objects in C API? Message-ID: I have a Python C module (dspam.c - http://bmsi.com/python/milter.html). It needs to return some large buffers allocated by the library I am wrapping. The buffers must be freed by the caller when finished. At present, I do the following to copy, then free the buffer: PyObject * toBuffer(char *buf;int len) { PyObject *sig = PyBuffer_New(len); if (sig) { void *data; int dlen; if (!PyObject_AsWriteBuffer(sig,&data,&dlen)) memcpy(data,buf,dlen); else { Py_DECREF(sig); sig = 0; } } free(buf); return sig; } Now, I would like to use PyBuffer_FromMemory(buf,len), but then I have no way of knowing when to free(buf). Or do I? Am I missing something? Is there a way for me to know when the Buffer object is being deleted so that I can free the underlying C data? From scasjos at mixmail.com Mon Jul 7 10:47:42 2003 From: scasjos at mixmail.com (jose maria) Date: 7 Jul 2003 07:47:42 -0700 Subject: Socket Win32 IO Message-ID: <99071af2.0307070647.6ab3e329@posting.google.com> Hi all I?m a newbie in python Im try to modify in win32 IOTCL of file handle socket to set parameter 0x98000001 but i have error (api_error:(1, 'DeviceIoControl', 'Incorrect function.')) and I dont know how continue. the porpuse of this code its to make a simple sniffer This is my code from socket import * import win32api import win32file Ip=getprotobyname("ip") SIO_RCVALL=0x98000001 Sock=socket(AF_INET,SOCK_RAW,Ip) ip=('xxx.xxx.xxx.xxx',0) Sock.bind(ip)# bind scoket to port fh=Sock.fileno() # Get file handle test=win32file.DeviceIoControl(fh,SIO_RCVALL,'',0) # Failed .... .... Thanks in advance From tim.one at comcast.net Sun Jul 13 16:57:18 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jul 2003 16:57:18 -0400 Subject: anything like C++ references? In-Reply-To: Message-ID: [Stephen Horne] > ... > The fact is that 'assignment' has a common meaning separate from the > choice of programming language, Well, that's not a fact, although there may be much commonality among the (necessarily few, if you believe this) programming languages you've used. Python's assignment semantics are in fact common among languages higher-level than those of the Fortran/COBOL/Algol/C ilk. For examples, Lisp, SNOBOL4, Scheme, Smalltalk and Icon are (very) much like Python in this respect. So is Java in the end, although the underlying machinery is more complicated there. > and that the way Python handles name binding means that meaning is not > respected by Python for mutable objects. Python's assignment semantics don't vary according to object type. > ... > Python, however, does not respect this meaning. This doesn't say more than that Python works differently than the languages you've used. It really isn't a question of respect . > It uses an arbitrary distinction based on whether or not the object > has internals that can be usefully in-place modified, and uses that > distinction to vary the effect of assignment in an arbitrary, > inconsistent and error-prone way. It's deliberate and thoroughly consistent. Any assignment semantics are error-prone in some contexts, though (Python's included -- side effects are like that). The simplicity and absolute consistency of Python-style assignment semantics are probably easiest for first-time programmers to pick up, and certainly dead easy for people coming from Lisp (etc) to pick up -- people coming from C (etc) often struggle with inappropriate expectations at first. > The need for a distinct tuple type is a symptom of the arbitrary > nature of this. Python's assignment semantics have nothing to do with mutability versus immutability. The latter is a type-dependent distinction; assignment semantics in Python don't depend on object type in any way. > ... > I've already posted too much on this, so this is going to be the end > to it. But Pythons semantics with regard to mutable and immutable > objects are simply bizarre. Hmm. Mutable objects can be mutated, and immutable objects cannot be mutated. That doesn't seem bizarre. > A historic justification may be plausible and backward compatibility > is then an important issue, but I really cannot accept claims that > Python is doing the right thing here. Well, I can assure you Guido wouldn't change anything about Python's assignment semantics if were able to do it all over from scratch. That's a puzzle for you to work out, then: is Guido unique, or are all Dutch people that stupid ? From bvelkur at yahoo.com Thu Jul 10 17:47:53 2003 From: bvelkur at yahoo.com (0wl) Date: 10 Jul 2003 14:47:53 -0700 Subject: Using xml.xpath question. Message-ID: Hi, I am trying to get the value of child from xmlstr = """Hellpppp""" using doc=parseString(xmlstr) nodeList = xml.xpath.Evaluate("/p:root/p:child/text()", doc) and am getting the following exception: xml.xpath.RuntimeException: Undefined namespace prefix: "p". I am using python 2.2.2 with PyXML 0.8 I think my usage of the Evaluate is wrong or incomplete. I have tried to google for information but to no avail. Can anyone please shed light on this. Thanks Bipin From claird at lairds.com Fri Jul 4 05:58:48 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 04 Jul 2003 09:58:48 -0000 Subject: Kylix reality (was: Python is a gem, you need to keep pushing it ....) References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: In article , delphiro wrote: >Same story here, > >My company primarily uses Delphi (Object Pascal) which is actualy a nice >development language / IDE but with linux as a rising star and Kylix as >a nasty and not-so-friendly-and-platform-indepandent Delphi-clone we >have decided to use Python for a number of small projects. As a python . . . How is Kylix "nasty and not-so-friendly"? I generally think of it as rather polished and useful. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From alf at fayauffre.org Thu Jul 31 05:22:41 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Thu, 31 Jul 2003 09:22:41 +0000 (UTC) Subject: Python speed vs csharp References: Message-ID: Dans l'article , Mike a ?crit : > This is an error function approximation, which gets called around 1.5 > billion times during the simulation, and takes around 3500 seconds (just > under an hour) to complete. While trying to speed things up, I created a > simple test case with the code above and a main function to call it 10 > million times. The code takes roughly 210 seconds to run. Hi there. This is pure numerical computation, it is therefore a job for psyco (http://psyco.sf.net/) I've made a quick test, cut'n'pasted your code in a small python module, added the following lines: --------------------------8<---------------------- def run(): results = [] for i in xrange(10000000): x = i/100. # apply erfc to a float y = erfc(x) if __name__ == '__main__': run() -------------------------8<----------------------- at the end. So I'm basically calling erfc 1 million times, and not doing much with the result. On my older machine (1.1GHz Celeron), this takes 13 seconds. By adding the following 2 lines at the top of the script: ---8<------- import psyco psyco.full() ----8<------ I get down to under 4 seconds. This is obviously not as good as you'd get with c#, but it's still a great gain with not too much work, I think. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From jdhunter at ace.bsd.uchicago.edu Mon Jul 28 13:13:10 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 28 Jul 2003 12:13:10 -0500 Subject: pretty printing graphs Message-ID: I have a tree structure (directed acyclic graph), where each node can represent itself as a multi-line string that is not very wide (eg, 10 chars per line). I would like to print the graph like C C1 C2 C1a C1b C2a C2b Where C, C1, etc.. are the multiline string blocks referred to above. Does anybody know of a tool that can do this. Here is an example, somewhat long because I have to create the multiline strings. from __future__ import division, generators def enumerate(seq): "Waiting for python 2.3" for i in range(len(seq)): yield i, seq[i] class O: def __init__(self, text): self.text = text def __str__(self): return self.text class Node: def __init__(self, o): self.node = o self.children = [] def __str__(self): s = '' #s += str(self.node) + '\n\n' if len(self.children)==0: return s childStrs = [str(child.node) for child in self.children] lines = [[] for tmp in childStrs] for lineNum, t in enumerate(childStrs): lines[lineNum].extend(t.split('\n')) maxLines = max([len(l) for l in lines]) sep = ' ' for lineNum in range(maxLines): row = '' for childNum in range(len(childStrs)): row += lines[childNum][lineNum] + sep s += row + '\n' s += '\n\n' for l in self.children: s += str(l) return s n0 = Node(O("""1 2 3 0 1 2 3 4 1 2 1 5 1 2 1 1 4 3 2 2 4 3 2 7 2 3 2 3 2 3 2 9""")) n1 = Node(O("""1 2 3 0 1 2 3 4 1 2 1 5 1 2 1 1 ---------- 1 1 0 0""")) n2 = Node(O("""4 3 2 2 4 3 2 7 2 3 2 3 2 3 2 9 ---------- 0 1 1 0""")) n1a = Node(O("""1 2 1 5 1 2 1 1 ---------- 1 1 1 0""")) n1b = Node(O("""1 2 3 0 1 2 3 4 ---------- 1 1 1 0""")) n2a = Node(O("""2 3 2 3 2 3 2 9 ---------- 1 1 1 0""")) n2b = Node(O("""4 3 2 2 4 3 2 7 ---------- 1 1 1 0""")) n0.children.extend([n1, n2]) n1.children.extend([n1a, n1b]) n2.children.extend([n2a, n2b]) print n0 Which prints: 1 2 3 0 4 3 2 2 1 2 3 4 4 3 2 7 1 2 1 5 2 3 2 3 1 2 1 1 2 3 2 9 ---------- ---------- 1 1 0 0 0 1 1 0 1 2 1 5 1 2 3 0 1 2 1 1 1 2 3 4 ---------- ---------- 1 1 1 0 1 1 1 0 2 3 2 3 4 3 2 2 2 3 2 9 4 3 2 7 ---------- ---------- 1 1 1 0 1 1 1 0 This does part of the work, printing the child nodes on the same rows, but doesn't the hierarchical part very well. What I would like is something like this: 1 2 3 0 1 2 3 4 1 2 1 5 1 2 1 1 4 3 2 2 4 3 2 7 2 3 2 3 2 3 2 9 1 2 3 0 4 3 2 2 1 2 3 4 4 3 2 7 1 2 1 5 2 3 2 3 1 2 1 1 2 3 2 9 ---------- ---------- 1 1 0 0 0 1 1 0 1 2 1 5 1 2 3 0 2 3 2 3 4 3 2 2 1 2 1 1 1 2 3 4 2 3 2 9 4 3 2 7 ---------- ---------- ---------- ---------- 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 Thanks, John Hunter From buzzard at urubu.freeserve.co.uk Mon Jul 28 20:28:09 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 29 Jul 2003 01:28:09 +0100 Subject: urn scheme References: Message-ID: "Terry Reedy" wrote in message news:rsycnR1hv40gyriiU-KYvg at comcast.com... > > "Duncan Smith" wrote in message > news:bg38sa$e6r$1 at news7.svr.pol.co.uk... [snip] > > cum_bins[j] += (j - adj) * others + adj * drawn > > I have no idea what this is about. > 'others' defines the adjustment to be made to the bins not sampled from (so zero for most purposes). The following gives me about a 30% speed up. Should save me a day or two. Cheers. Duncan def gen_samples(colours, draws, iterations): ncolours = len(colours) contents = [] for i in range(ncolours): contents.extend(colours[i]*[i]) if len(contents) / 2 > draws: draws = len(contents) - draws for i in range(iterations): random.shuffle(contents) drawn = contents[:draws] res = colours[:] for index in drawn: res[index] -= 1 yield res else: for i in range(iterations): random.shuffle(contents) drawn = contents[:draws] res = ncolours * [0] for index in drawn: res[index] += 1 yield res From ta-meyer at ihug.co.nz Fri Jul 18 19:45:57 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 19 Jul 2003 11:45:57 +1200 Subject: IMAP examples In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F855B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F280F@its-xchg4.massey.ac.nz> > It would be nice if it also explained some of the magic numbers > and strings in comments or in some text around the example: > > Why data[0] > Why M.search(None, 'ALL') > and why '(RFC822)' as the 2nd arg in the M.fetch() You're not asking for documentation about imaplib here, you're asking for documentation about the imap protocol; of course it's not there, you're looking in the wrong place. If you don't understand imap, why should you understand how to use imaplib? Using imaplib is very similar to simply passing the commands to an imap server - much more so, for example, than twisted's imap support (which hides details of IMAP, and so should provide more documentation than imaplib). > If we expect people to read the RFCs in order to use the > bloody module than we ought to at least provide the link to > the RFC! What documentation are you looking at? The 2.2.3 and 2.3b2 doc for imaplib (i.e. "11.10 imaplib -- IMAP4 protocol client") have links to both RFC2060 and RFC1730; I use them all the time. Look in the first and second sentences in the bit just below the heading. > The documentation of the .search() method also neglects to > make any mention of 'ALL' though we might expect that to be > the MOST COMMON CRITERIUM! (at least for someone who's just > trying to learn the module!) There is no reason that 'ALL' would be any more use than any other fetch parameter. In fact, if you're learning imap, then ALL is a terrible place to start because you'll be overwhelmed with the response, and because ALL is a macro, not a standard parameter. You're much better off starting with something simple, like UID, FLAGS, INTERNALDATE or RFC822. =Tony Meyer From pablo at bogus.domain.org Sat Jul 19 16:37:10 2003 From: pablo at bogus.domain.org (Pablo) Date: Sat, 19 Jul 2003 22:37:10 +0200 Subject: classes Message-ID: Hello everyone I'm rather new to Python and have a problem I hope someone can help me solve. I'm used to Java syntax and would like to make a class which holds a connection object to PostgreSQL database. I want to make this class as a singleton, and allow creation only of one instance of the class. code in Java would like more or less like this: class Connection{ private static Connection instance = null; private DBConnection = null; // in python's case it would be pgobject returned be connect() private Connection(){ DBConnection = pg.DB(); } public static Connection getInstance(){ if(instance == null) instance = new Connection(); return instance; }; How can I do the same thing in Python? How can I declare a static field (and private) of a class and allow access to it only by a static method? Can I forbid to instantiate more than one object? I'd be grateful if someone can explain it to me or send me to the good resource with description about classes which would have some comparisons of syntax regardig Java or C++. Best regards Pablo From imbosol at aerojockey.com Wed Jul 30 19:16:36 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Wed, 30 Jul 2003 23:16:36 GMT Subject: Exceptions as New Style Classes References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: Steven Taschuk wrote: > At the moment the dominant idea for solving these problems is to > make inheritance from Exception mandatory for exception types; see > Guido's 11 June post > > for details. (I have another idea involving a new special method > '__raise__', but haven't worked out the details yet.) Why not give exceptions their own metaclass? So if type(x) is ExceptionMetaclass, it's a class. If type(type(x)) is ExceptionMetaclass, it's an instance. Otherwise, it's illegal to raise it. -- CARL BANKS From harry.g.george at boeing.com Fri Jul 11 09:35:34 2003 From: harry.g.george at boeing.com (Harry George) Date: Fri, 11 Jul 2003 13:35:34 GMT Subject: object instance data to docbook, xml, pdf, etc? References: Message-ID: mertz at gnosis.cx (David Mertz, Ph.D.) writes: > Harry George wrote previously: > |We are outputting the instance data, sort of like Gnosis xml_objectify, > |but to docbook DTD. > > You *could* use XSLT to transform the gnosis.xml.pickle output into > DocBook (I'm pretty sure you mean that, objectify goes in the other > direction generic-XML -> python). > Yes, that's what I meant. BTW, thank you for those tools. > However, I personally find XSLT extremely awkward. Interesting. I've been pushing back against XSLT ever since it was invented as a "no parentheses" rendition of DSSSL. I've run into other people who used XSLT until they run into a complex task, and then realize it is a mess. What's been missing so far is a Python rendition of the common tasks, and a design pattern for growing others. > If someone doesn't > give you the done-deal, you might find it useful to take > gnosis.xml.pickle and fork it for your desired DocBook/XML output. All > the issues about traversing objects is handled, you should pretty much > be able to just look for the XML tags that get written, and substitute > those as needed. > Yep, that's what I had in mind. > 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. > -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From jwbaxter at spamcop.net Thu Jul 31 20:33:15 2003 From: jwbaxter at spamcop.net (John Baxter) Date: Thu, 31 Jul 2003 17:33:15 -0700 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > Nope. Kudos is a mass noun, but it's a discrete mass noun. So you need > to say "many kudos". This bit of pedantry is brought to you by "much > kudo about nothing". Sometimes, the indiscrete mass nouns are more fun. ;-) (Perhaps not for major college football coaches, for whom anything indiscrete can be harmful.) All this aside, heaps of praise and copious congratulations to all involved in the release (you know who you are). And thank you! --John From clpy.NOSPAM at russellsalsbury.com Mon Jul 21 17:36:15 2003 From: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) Date: 21 Jul 2003 14:36:15 -0700 Subject: [OT] SCO is Going After End Users Message-ID: <4868482a.0307211336.4ca9493a@posting.google.com> ComputerWorld says that SCO is going to charge Linux end users a license fee for "the opportunity to run Linux legally." Lots of companies will pony up. I realize that this is OT, but SCO's action strikes at the heart of Open Source. Somebody with the right patents can try to tax or shut down the rest of us, regardless of the validity of their claims. If IBM, Red Hat, and the decide that the the cost of settling is less than the cost of litigation, we all loose. Fortunally, the claim against IBM is so big, $3B that they may fight it instead of settling. -- Russ From LogiplexSoftware at earthlink.net Wed Jul 2 19:17:08 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 02 Jul 2003 16:17:08 -0700 Subject: How Do You Get Redirected Input? In-Reply-To: References: Message-ID: <1057187827.1457.59.camel@software1.logiplex.internal> On Wed, 2003-07-02 at 12:10, not your business wrote: > I have a shell tool that accepts arguments on the command line. I would like > to check if the input is being piped in. That is, import sys if sys.stdin.isatty(): print "not piped in" else: print "piped in" -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From fredrik at pythonware.com Tue Jul 15 04:19:18 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2003 10:19:18 +0200 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <3F132103.4D18759F@engcorp.com> Message-ID: Jeremy Bowers wrote: > At no point is it ever specified either way in the XHTML specification, > except by reference to the XML specification. which is the whole point, of course. (we've been through this in the XML-RPC and RSS universes lately; for some reason, some people have a really hard time understanding that when you base a format on XML, you get more than just tags in angle brackets ;-) From alanmk at hotmail.com Sun Jul 6 15:54:45 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 20:54:45 +0100 Subject: Search for mapping solution References: Message-ID: <3F087E85.9D8018E9@hotmail.com> Markus Joschko wrote: > I have a List: Name - Number - Costs > > lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > > Now I want to have it in a dictionary(name,costs) Should look like > {'fred':'0,60' , 'sam':'1'} > > What's an elegant way to do it? Must ..... resist ..... temptation ..... to ..... write .... oneliners D'oh! I'm so weak willed.... Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] >>> d = dict([(x[0], x[2]) for x in lines]) >>> d {'sam': '1', 'fred': '0,50'} >>> OK, I'll write and maintain a 1000-line perl program as penance ... sometimes-concise-is-elegant-too-ly yrs. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From andreas.kuntzagk at mdc-berlin.de Mon Jul 21 05:02:52 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Mon, 21 Jul 2003 11:02:52 +0200 Subject: UserDict -> dict, reasons for migrating existing code Message-ID: Hi, what would be the reasons to migrate existing code from the use of UserDict() to dict()? (UserString ...) What would be reasons against? Reasons I can think of: pro: - Speed Improvement because of a level of indirection less - UserDict can become deprecated con: - Code not working whith older python - cost of migrating large codebase Do you know other reasons? Andreas From member32992 at dbforums.com Thu Jul 10 16:25:49 2003 From: member32992 at dbforums.com (pygeek) Date: Thu, 10 Jul 2003 20:25:49 +0000 Subject: python mode problem in emacs Message-ID: <3097083.1057868749@dbforums.com> Hi everyone. I've just installed emacs 21.3.1 on my WinXP machine. I wanted to switch to Python mode then realized that my emacs lacked the 'python-mode.el' file. After downloading from python.org and byte-compiling the file, I went on to look for the file '.emacs' or 'emacs.el' to include a few lines of command so that emacs would load python-mode. I looked through and searched my hard drive, and there wasn't such a file by the name '.emacs' or 'emacs.el'. What's going on here? Where are the files? Can somebody help me? Thanks in advance. --Daniel D.-- -- Posted via http://dbforums.com From alanmk at hotmail.com Fri Jul 11 12:16:33 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Jul 2003 17:16:33 +0100 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <7xk7ap3j6z.fsf@ruckus.brouhaha.com> Message-ID: <3F0EE2E1.1C30CEA4@hotmail.com> Paul Rubin wrote: > My suggestion is to > authenticate the cookies with a cryptographic checksum and verify the > authentication before deserializing the cookies. That's probably the > simplest approach. Keeping session info on a multi-process server (or > worse, a multi-server network) needs some kind of concurrent storage > mechanism. Paul, Do you mean transmit the checksum to the client with the cookie? And check that they match when the cookie and checksum come back? Or is the checksum stored on the server, in some form of lookup dictionary keyed by some user session identifier? regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From dortmann at lsil.com Wed Jul 2 11:01:44 2003 From: dortmann at lsil.com (Daniel Ortmann) Date: 02 Jul 2003 10:01:44 -0500 Subject: Python-2.3b1 bugs on Windows2000 with: the new csv module,string replace, and the re module In-Reply-To: <16130.58729.717919.803534@montanaro.dyndns.org> References: <16130.58729.717919.803534@montanaro.dyndns.org> Message-ID: Skip Montanaro writes: Daniel> While using the csv module's DictWriter on MSDOS Daniel> (a.k.a. Windows2000), the output files get newlines like Daniel> \x0d\x0d\x0a instead of \x0d\x0a. Daniel> csvwriter = csv.DictWriter( file( out1filename, 'w' ), infieldnames, extrasaction='ignore' ) Daniel> csvwriter.writerow( dict( zip( infieldnames, infieldnames ) ) ) Skip> CSV files are not really plain text files. The line terminator Skip> string is an explicit property of the file. For example, you Skip> might want to write a CSV file on a Windows 2000 machine which you Skip> intend to read on a Mac OS9 system (where the line terminator is Skip> just \r). You need to open CSV files with the 'b' flag. This Skip> should work for you: Skip> csvwriter = csv.DictWriter( file( out1filename, 'wb' ), infieldnames, extrasaction='ignore' ) Skip> csvwriter.writerow( dict( zip( infieldnames, infieldnames ) ) ) Ok, that is the same work around that I used. Perhaps the documentation should say something about using binary mode? Or perhaps the DictWriter constructure should open the file in binary mode if given a string rather than a file object? How do we avoid people stumbling as I did? -- Daniel Ortmann, LSI Logic, 3425 40th Av NW, Suite 200, Rochester MN 55901 work: Daniel.Ortmann at lsil.com / 507.535.3861 / 63861 int / 8012.3861 gdds home: ortmann at isl.net / 507.288.7732, 2414 30Av NW #D, Rochester MN 55901 From loiosh13 at yahoo.com Mon Jul 7 09:40:49 2003 From: loiosh13 at yahoo.com (Tim Isakson) Date: Mon, 07 Jul 2003 13:40:49 GMT Subject: Newbie question: Strange TypeError References: <1t7Oa.40$DX3.7244067@newssvr14.news.prodigy.com> Message-ID: Thanks for your help, guys! I figured it was something that would be obvious once it was explained ;). Tim From tdelaney at avaya.com Fri Jul 25 00:55:27 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 25 Jul 2003 14:55:27 +1000 Subject: recognizing empty iterators Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE958723@au3010avexu1.global.avaya.com> > From: Raymond Hettinger [mailto:vze4rx4y at verizon.net] > > Yes, it was. So, Guido decreed that once a iterator has returned > StopIteration, it will continue to do so on subsequent calls to > it.next(). Promptly, all of Python's iterators were modified to > comply. IOW, iterators can and do stay "permanently exhausted". Yes - these are the rules, and all the standard iterators conform to them. This is a Good Thing(TM). A non-standard iterator *may* break the rules (as with just about anything in Python). That would, however, be a Bad Thing(TM). BTW I was there during those discussions (which is why the thought popped into my mind ...). I can't remember off the top of my head though if iter() is guaranteed to return an iterator that once exhausted will be permanently exhausted (which would probably require a proxy). I'm pretty certain though the the resolution was "the standard iterators will do the Right Thing(TM) and it's up to people to play nice with their own iterators". > However, Tim is essentially correct in focusing on the "just-in-time" > nature of iterators. Part of the core concept for iterators > is to *not* know what lies ahead. Why, thank you sir ;) Tim Delaney From gh at ghaering.de Sun Jul 27 10:11:10 2003 From: gh at ghaering.de (=?windows-1255?Q?Gerhard_Ha=22ring?=) Date: Sun, 27 Jul 2003 16:11:10 +0200 Subject: datetime 2 win variant datetime In-Reply-To: <91BFE89EFFA2904E9A4C3ACB4E5F2DF5027AFB@exchange.adrembi.com> References: <91BFE89EFFA2904E9A4C3ACB4E5F2DF5027AFB@exchange.adrembi.com> Message-ID: <3F23DD7E.50407@ghaering.de> Roman Yakovenko wrote: > Hi. It seems I need a little help with this subject. > I am trying to convert python datetime ( 2.3 ) to windows variant > that keeps date and time but I failed. > > Can smbd give me a hint? I'd rather try ntpd than smbd ;-) SCNR, -- Gerhard From skip at pobox.com Tue Jul 22 23:09:00 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 22 Jul 2003 22:09:00 -0500 Subject: [OT] RE: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130212AB7C@its-xchg4.massey.ac.nz> References: <1ED4ECF91CDED24C8D012BCF2B034F13026F8E3D@its-xchg4.massey.ac.nz> <1ED4ECF91CDED24C8D012BCF2B034F130212AB7C@its-xchg4.massey.ac.nz> Message-ID: <16157.64588.289006.311743@montanaro.dyndns.org> Tony> (Assuming that William Wright wins, is the the first guy by that Tony> name who stands up that becomes president?) Stranger things have happened here... Skip From dale at riverhall.NOSPAM.co.uk Wed Jul 23 17:58:33 2003 From: dale at riverhall.NOSPAM.co.uk (Dale Strickland-Clak) Date: 23 Jul 2003 21:58:33 GMT Subject: Newbie question about Python & W2K Admin References: <86d2ca4.0307231125.70ee3f57@posting.google.com> Message-ID: > I need to change a few Local Security Settings on a number of W2K > machines. An example of a Security Setting I need to change is the > "Minimum password length" setting, which is under Account Policies, > Password Policy. > > Instead of doing this manually on each machine, I would like to have > an automated way to do this. Can Python be used for this ? > > Any direction on how to automate this using Python or some other tool > will be greatly appreciated. You can do this at domain level if these machines are all part of the same domain. -- Dale Strickland-Clark Riverhall Systems Ltd, www.riverhall.co.uk From roy at panix.com Mon Jul 14 19:17:59 2003 From: roy at panix.com (Roy Smith) Date: Mon, 14 Jul 2003 19:17:59 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> Message-ID: Stephen Horne wrote: > Ah - but this is also Pythons fault. It has arbitrarily redefined the > meaning of a mathematics operator - presumably simply because C, C++, > Java, Basic and others have done this in the past. > [...] > Personally, though, I'd go with Pascal on this one. Most languages have two "equals" operators, one means assignment, the other means test for equality. Depending on the language, these are spelled "=" and "==" or ":=" and "=" (or a few other variations). The wierd thing is that I don't think either one really matches what a mathematician means when he writes "=". In math, "=" is neither an assignment or a test: it's an assertion. From peter at engcorp.com Sat Jul 5 14:08:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Jul 2003 14:08:36 -0400 Subject: A possible bug in python threading/time module? References: Message-ID: <3F071424.520DC852@engcorp.com> vm_usenet wrote: > > Right after I read Tim's recent post, I went to the python CVS and > noted that Tim refered to me as an 'anonymous coward'. Well Tim, I > just wanted to say that I appreciate you being part of the community, > too. See http://www.computerhope.com/jargon/a/ac.htm, definition #2. This is a fairly well-known term for someone who, like you, for some strange reason does not want to use their name in discourse with others (such as those who are helping them, hint, hint) online. > I hope to see more mature people working on the Python project than > Tim. If you mean you want a greater number of mature people than just Tim alone working on the Python project, then we can all agree and, fortunately, that is the current situation. If you meant something else, I suggest you learn more about Python history and about those who have really made Python what it is before you make comments of that nature. -Peter From bignose-hates-spam at and-zip-does-too.com.au Sun Jul 20 00:25:49 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 20 Jul 2003 14:15:49 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> Message-ID: On Sat, 19 Jul 2003 15:59:16 +0100, Alan Kennedy wrote: > One person, Bengt, said that he couldn't see it This is identical to the justification of "$BIGNUM percent of our target users use browser $BROWSER, so we can ignore the rest and use methods only viewable by browser $BROWSER." Which quickly leads to "You must use $BROWSER to view this site". No thanks. Provide a method that degrades gracefully to ASCII, the current standard; then I'll be interested. -- \ "I'd like to see a nude opera, because when they hit those high | `\ notes, I bet you can really see it in those genitals." -- Jack | _o__) Handey | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From faizan at jaredweb.com Wed Jul 30 20:11:07 2003 From: faizan at jaredweb.com (Fazer) Date: 30 Jul 2003 17:11:07 -0700 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> Message-ID: <7b454334.0307301611.1b40ff11@posting.google.com> Graham Breed wrote in message news:... > Diez B. Roggisch wrote: > > > http://www.bagley.org/~doug/shootout/craps.shtml > > > > Python is place 13, with a speed index of 578. PHP is second last (before > > bash) and has a speed index of 197. > > Those benchmarks are doubly useless for the question at hand. Firstly, > they only test command line applications. Secondly, PHP is compiled > without optimizations because the rules state that only the default > configuration can be used. See question 8 of the FAQ: > > http://www.bagley.org/~doug/shootout/faq.shtml > > > Graham Yeah, I read the FAQ as well. I am basically looking for a FAST alternative to PHP meaning the responce time is fast. Do you think that Python with using the CGI module is a good solution? From kamikaze at kuoi.asui.uidaho.edu Mon Jul 14 19:31:56 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 14 Jul 2003 23:31:56 GMT Subject: anything like C++ references? References: Message-ID: Mon, 14 Jul 2003 04:51:10 +0100, Stephen Horne : > On Sun, 13 Jul 2003 22:42:21 GMT, "Bryan" wrote: >>i just referenced an immutable object via a "pointer" and i __did_not__ >>stuff it into a mutable object as you say. >>a and b "point" to the same object. > Technically, but what is the point? You can't do pointer-style things > with it. You can't change the object in any way without changing the > id, and you can't use the mechanism to, for instance, allow 'var' > parameters. > In short, you are showing evidence of the use of pointers internally > within Python, but that is not the same as providing pointer-like > semantics. It looks like you've almost reached understanding, though you've been given a bad start with a very idiosyncratic and monolingual understanding of what "computer science" teaches--that was certainly not in the classes I took, but apparently yours were different. Python variables are directly equivalent to pointers in C, with some crippling limitations by C standards. They only ever point to valid objects that are dynamically allocated on the heap, never to anything else. Even None is an object. Those objects include what Python calls "integers", which are really object wrappers around a C int variable. Assignment only allows you to change a variable to point to some other valid object. At no point in Python do you ever have direct access to a C value variable, or to a reference to a variable. They just don't exist. So there are some things you can do in C that you can't do the same way in Python. And that's *by intention*. It isn't a bad thing, it was done for good design reasons, reasons well-tested by previous languages like Lisp. If you really must do a "pointer-style thing" in Python, you can do this, which is semantically equivalent to the C version: >>> def incr(pointerToVar): ... pointerToVar[0] += 1 ... >>> a = [0] >>> b = a >>> incr(a) >>> a[0] 1 >>> b[0] 1 >>> incr(a) >>> a[0] 2 >>> b[0] 2 I hope no Pythonista would actually *do* that, but it's working code, and the foo[0] is similar to explicit referencing and dereferencing of pointers. Since every operation in Python operates on pointers, there's no use in having a special syntax for it. You don't need all the * and & and -> line noise. Stop trying to make Python into C/C++, and you'll be happier with it. Or stop using Python, if you really don't like the design philosophy. There are plenty of Algol-derived languages out there. PHP and especially Perl are more C-like in their internal logic, and you might find them more pleasant. -- Mark Hughes "The computer is incredibly fast, accurate, and stupid. Man is unbelievably slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation." -Leo Cherne From davecook at nowhere.net Thu Jul 17 05:37:42 2003 From: davecook at nowhere.net (David M. Cook) Date: Thu, 17 Jul 2003 09:37:42 GMT Subject: Linux - python vs sh References: Message-ID: In article , Krisztian Kepes wrote: > Hi ! > > I want to list my rpm database to file with this: > > #!/bin/sh > > file="./allrpm.txt" > nr=1 > for rpmname in `rpm -qa` > do > echo '>>>>>>>>>>>>>>>' >>$file > echo "$nr." >>$file > echo "Name: $rpmname" >>$file > echo "" >>$file > info=`rpm -qi $rpmname` > echo "$info" >>$file > echo "" >>$file > nr=`expr $nr + 1` > done You can get the same type of output using rpm format strings: rpm -qa --queryformat ">>>>>>>>>>>>\nName: %{NAME}\n%{SUMMARY}\n" For a listing of query tags, use rpm --querytags > But it have two error: > 1. the $nr is not incremented I usually use nr=$((nr+1)) > 2. the rpm detailed info is not writed to the file Don't see why that's happening. > I want to change it to py code. I see an perl code: > > @rpmlist= rpm -qa > It is get the rpm's output. > > But how I get the rpm's output in my py program ? > list= rpm -qa > ???? You can use the commands module: from commands import getstatusoutput status, output = getstatusoutput("rpm -qa") if status==0: #do stuff with output else: print "There was an error:", output Also take a look at the popen2 module. There is also an rpm module that Red Hat uses for up2date. There's not much in the way of documentation, though. There is a new book on RPM out that has a chapter on rpm-python, but at $50 for a paperback I haven't bitten. Dave Cook From noah at noah.org Sun Jul 13 09:25:15 2003 From: noah at noah.org (Noah) Date: 13 Jul 2003 06:25:15 -0700 Subject: Parsing stdout through a pipe? References: Message-ID: "MK" wrote in message news:... > I have a Win32 console application (SNMPUTIL.EXE) which listens > to incoming SNMP messages: > > C:\>snmputil trap > snmputil: listening for traps... > ... > I'd like to write a Python application which would intercept/parse this > stdout > output, and invoke various pop-ups ("alarms"). Any ideas? You can use popen and friends to create a pipe to listen to the output of an external application, but there are many pitfalls to using a simple pipe to control an external application. Do you need to respond to the output by writing message back through stdin? If yes, then pipes are a bad way to go. Does snmptrap print events continuously (versus printing just a single trap even and then exiting)? If it runs continuously then a pipe is a bad way to go. The reason these scenarios are bad has to do with way the stdio buffers pipes. Stdio will not necessarily flush the output buffer after snmptrap prints some data. Stdio will flush the buffer when full, not after data is printed. So your snmptrap may print some data, but it will just sit in the buffer until snmptrap prints more data to fill it the buffer. There is no way for you to force the buffer to flush. The way around this is to use UNIX where you can use a pseudo TTY :-) You can also use Cygwin... I am not sure if there is an ideal solution under Windows. Cygwin manages to implement a pseduo TTY system on Windows, so there must be some sort of solution using the win32 API. I have a pseudo TTY wrapper library called pexpect here: http://pexpect.sourceforge.net/ It works pretty well under Cygwin Python, but not under regular Windows python. On the other hand if your snmptrap program just prints one event and then exits then you can use pipes because the buffer will be flushed when snmptrap exits. Or, if you can modify the source to snmptrap then you can have it force a flush on stdout after each print. Yours, Noah From steve.horsley1 at virgin.NO_SPAM.net Thu Jul 31 16:54:03 2003 From: steve.horsley1 at virgin.NO_SPAM.net (Steve Horsley) Date: Thu, 31 Jul 2003 21:54:03 +0100 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling References: <3759308d.0307311008.2d931ca@posting.google.com> Message-ID: On Thu, 31 Jul 2003 11:08:35 -0700, Rob Renaud wrote: > > This should make it a lot easier for you. > > http://www.python.org/doc/current/lib/module-struct.html > Wow! How incredibly useful! I just had to say that. Steve From pyth at devel.trillke.net Sat Jul 26 04:10:14 2003 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 26 Jul 2003 10:10:14 +0200 Subject: path module In-Reply-To: <1059184087.28095.11575.camel@lothlorien>; from ianb@colorstudy.com on Fri, Jul 25, 2003 at 08:48:07PM -0500 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <1059184087.28095.11575.camel@lothlorien> Message-ID: <20030726101014.U6906@prim.han.de> Hello Ian, Ian Bicking wrote: > ... > I feel like a common interface for these different filesystems should > somehow degrade well in terms of metadata, or expedite introspection in > some fashion. I wouldn't try to play too many tricks with meta-data. > The differences on the client side are probably easier to handle, as > they can be handled by the constructor, which might look different for > different filesystems. Like url('http://whatever', user='bob', > password='secret', proxy='http://myproxy'), or > cvs(pserver='cvs.sourceforge.net', repository='python'). Or should > there be a string-based representation (i.e., URIs)? String-based representations are often not specified. e.g. subversion/webdav/deltax don't define a URL format to get to a certain revision. The other approach (keyword-args) is a more generic and better way IMO. cheers, holger From psimmo60 at hotmail.com Tue Jul 15 13:37:44 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 15 Jul 2003 10:37:44 -0700 Subject: PyErr_SetString() != raise ? References: Message-ID: <94974e1a.0307150937.5999593f@posting.google.com> David Eger wrote in message news:... > When I use PyErr_SetString() in an extension, python just keeps on > chugging instead of acting as though a Python exception had been > 'raise'd. Why is this, and do I really have to write the Python code > to raise an exception manually after I've used PyErr_SetString()? > > if (nextEl == NULL) { > PyErr_SetString(PyExc_StopIteration, "Array index out of bounds"); > return NULL; > } > > in my iterator extension, but when I use my extension, I get an infinite loop: > (and so on, and so on...) The thing is, even though I *set* the > exception with PyErr_SetString, to the interpreter, it doesn't get > raised. Am I just misinterpretting how PyErr_SetString is supposed > to work? > > -David Hi, This part should work fine. Try looking back through the function calls, layer by layer, making sure each function in turn tests for a NULL return, and propagates it back to the interpreter. Without a little more code it's tough to say exactly what's wrong. The NULL return tells the interpreter that an exception has occurred. PyErr_SetString just sets the traceback message. HTH, Paul From borcis at users.ch Tue Jul 15 19:02:51 2003 From: borcis at users.ch (Borcis) Date: Wed, 16 Jul 2003 01:02:51 +0200 Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> <87smp7biet.fsf@pobox.com> Message-ID: <3F14881B.5040403@users.ch> John J. Lee wrote: >>>To "take someone in" means to trick or deceive them. >> >>"take in" can also mean to observe. > > But "take someone in" never means that. Except of course that in the course of deceiving someone, it is usual to observe that person. From gradha at titanium.sabren.com Sun Jul 13 06:19:23 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sun, 13 Jul 2003 12:19:23 +0200 Subject: ANN: mailbox_date_trimmer 1.0.0 -- Correct emails' date headers in a mailbox archive. Message-ID: <20030713101923.GA19555@pedos.es> Scenario description You are a mailing list administrator, or you are somebody who keeps mailing list archives for a user group, or you just have a fetish for email archives. Now, don't you always wonder why after running Hypermail or MHonArc on your archives you always have some emails which date back to 1980 or far away in the future like 2011, even though you started collecting emails in the year 2000 and it's still this very same year? While there are many answers to this question, there is a very easy way to fix many, if not all, of these messages, which results in a much more consistent email archive without broken discussion threads. Software requisites This software requires Python (http://www.python.org). It is known to work with versions 1.5.2 or 2.2.3. You also need my mailbox_reader module, which you should be able to get from: http://gradha.sdf-eu.org/program/mailbox_reader.en.html Download http://gradha.sdf-eu.org/program/mailbox_date_trimmer.en.html License GPL -- Please don't send me private copies of your public answers. Thanks. From mday at apple.com Tue Jul 22 20:33:22 2003 From: mday at apple.com (Mark Day) Date: Tue, 22 Jul 2003 17:33:22 -0700 Subject: lists and files question References: <3F1DCF52.7040607@hotmail.com> Message-ID: <220720031733228802%mday@apple.com> In article <3F1DCF52.7040607 at hotmail.com>, hokiegal99 wrote: > This code: > > import os, re, string > setpath = raw_input("Enter the path: ") > for root, dirs, files in os.walk(setpath): > id = re.compile('Microsoft Excel Worksheet') > fname = files > # print fname > content = open(fname[1],'rb') > > Produces this error: > > IOError: Error[2] No such file or directory 'Name of File' > > The strange thing is that it correctly identifies the file that it says > doesn't exist. Could someone explain why this is? The problem is that file doesn't exist in the current working directory; it's in another directory (stored in "root" in your code). Try this: content = open(os.path.join(root,fname[1]), 'rb') > Also, is "files" a nested list? It looks like one, but I'm not entirely > sure as I'm still relatively new to Python. Thanks! It is a list of strings. Each string is the name of one of the files in the directory (whose path is in "root" above). -Mark From tjland at iserv.net Sun Jul 27 11:38:09 2003 From: tjland at iserv.net (tjland at iserv.net) Date: Sun, 27 Jul 2003 11:38:09 -0400 (EDT) Subject: Beginners help with password program! In-Reply-To: References: Message-ID: <1057.68.73.66.240.1059320289.squirrel@webmail.iserv.net> > For starters, I suggest you install pychecker and use it on any programs > you create. > > Second, every error in python should give you some information as to what > line it occurred on. For example: > > : a = b > :Traceback (most recent call last): > : File "", line 1, in ? > : a = b > :NameError: name 'b' is not defined > > Here it says line 1, because this occurred in Idle. Start by going to that > line... 90% of the time, your error will be right there. > > As for your file... well the line if "login == no:" looks wrong, unless > you have a variable named 'no'.. you probably want the string 'no' there. > As was mentioned, you probably won't get much help if you ask people to > debug for you. Debugging is a major part of programming, and you can't > avoid it. So get used to it and get good at it. :D (and learn to test your > code thoroughly). Finally, I recommend you use raw_input(...), rather > than input(...), and then convert the return value from a string to > whatever you need it to be. > -- > http://mail.python.org/mailman/listinfo/python-list > When you see the net take the shot When you miss your shot shoot again When you make your shot you win! Just remember Offense sells tickets But defense wins championships! From jjl at pobox.com Sun Jul 6 16:22:30 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Jul 2003 21:22:30 +0100 Subject: Calculating Year, Month and Day of Life References: <3F07420E.BC640F@engcorp.com> Message-ID: <8765mfz9q1.fsf@pobox.com> Peter Hansen writes: [...] > Using mxDateTime's support for this instead will probably be easier. or maybe the standard library module datetime from 2.3? Haven't used it yet. John From MK at foo.com Sun Jul 20 09:07:48 2003 From: MK at foo.com (MK) Date: Sun, 20 Jul 2003 15:07:48 +0200 Subject: Importing WMI module into Python CGI script fails Message-ID: I'm working with IIS on W2K server. I'm trying to use module "wmi" in a CGI script but with no success. The following works: import cgitb; cgitb.enable() cgi.test() ... but the following isn't working: import cgitb; cgitb.enable() import wmi ## fails here, with msg "wmi undefined" cgi.test() Any ideas? I can import all the other modules (e.g. sys) except "wmi". Also, when I run the same script in IDLE (cgi stuff removed), it works. Sys.path has all the needed directories, including script's directory, and WMI's directory. From oussoren at cistron.nl Fri Jul 4 08:03:19 2003 From: oussoren at cistron.nl (Ronald Oussoren) Date: Fri, 4 Jul 2003 14:03:19 +0200 Subject: [Dream] A meta-wrapper module to interface any C dynamic library In-Reply-To: Message-ID: <8099BFD6-AE17-11D7-B5EC-0003931CFE24@cistron.nl> On Friday, Jul 4, 2003, at 12:59 Europe/Amsterdam, Francesco Bochicchio wrote: > Hi all, > > I was wondering if it would be possible to make a module which allows > to > do something like that: > > import c_interface > math_lib = c_interface.load('math.so', 'math.h' ) > sin_f = math_lib.get_function('sin') > print "sin(3.14) = %f" % sin_f (3.14) > > The idea would be to make a module that allows to use any C dynamic > library ( I used an hypothetical math.so only as example ) without > the need of a specific wrapper module. See http://starship.python.net/crew/theller/ctypes. Ronald From jar at mminternet.com Sun Jul 27 21:37:43 2003 From: jar at mminternet.com (james roush) Date: Sun, 27 Jul 2003 18:37:43 -0700 Subject: mxTidy References: <87k7a3a3bq.fsf@pobox.com> Message-ID: In article <87k7a3a3bq.fsf at pobox.com>, jjl at pobox.com says... > james roush writes: > > > What versions of Python will mxTidy work with. I'm using it with Python > > v2.1.x but want to upgrade to 2.3 when it is released > > > > Are there any alternatives to mxTidy? > > uTidylib > > Wrapper of the new tidylib. Not yet clear to me if and how it's > better, but it is more actively maintained than mxTidy. > > > John > Thanks, -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From skip at pobox.com Fri Jul 11 08:36:20 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Jul 2003 07:36:20 -0500 Subject: text file edit object In-Reply-To: References: Message-ID: <16142.44868.962403.270026@montanaro.dyndns.org> Facundo> myfile = open("foo.txt", "r") Facundo> mylines = myfile.readlines()[:-10] Facundo> myfile.writelines(mylines) Facundo> myfile.close() Facundo> I only see two problems with this: Facundo> - Poor performance on very big files Facundo> - Bad support on "hanging in the middle" Not to mention the fact that you can't write to myfile as defined. ;-) How about something like (not tested): import os, sys try: infile = file("foo.txt", "r") lines = infile.readlines()[:-10] infile.close() except IOError: print >> sys.stderr, "edit failed" else: try: outfile = file("foo.txt.new", "w") outfile.writelines(lines) outfile.close() except IOError: try: os.unlink("foo.txt2") except IOError: pass print >> sys.stderr, "edit failed" else: os.rename("foo.txt2", "foo.txt") ? On Windows I think you have to unlink foo.txt before calling os.rename(). Unfortunately, it quickly gets pretty baroque if you want to do things right. I'm not even sure IOError is the only exception that might be raised. Skip From hawkfish at trustedmedianetworks.com Wed Jul 30 13:55:37 2003 From: hawkfish at trustedmedianetworks.com (Richard Wesley) Date: 30 Jul 2003 17:55:37 GMT Subject: unittest problems References: <87el095733.fsf@pobox.com> Message-ID: In article <87el095733.fsf at pobox.com>, jjl at pobox.com (John J. Lee) wrote: > Richard Wesley writes: > > > I am trying to retrofit some units test into our code using the unittest > > module. I can get individual rewrites to work, but I am having trouble > > writing the "one test to run them all and in the darkness bind them" > > script. There are two main sources of trouble: > > > > - Test data that is stored next to the script that uses it; > > - Several levels of scripts (top/utils/tests) with tests/data scattered > > at all levels; > > > > Are there any good examples out there of a more complex set of tests in > > a multilevel tree/package with attached test data? What about standard > > conventions for hooking stuff together (suite(), etc.)? > > > x.com&rnum=1&prev=/groups%3Fas_q%3Dunittest%26safe%3Dimages%26ie%3DISO-8859-1% > 26as_uauthors%3Djjl%40pobox.com%26lr%3D%26num%3D30%26hl%3Den> > > http://tinyurl.com/ig2q Thanks. My problem turned out to be that the existing code had lots of relative import statements (from FileInSameDir import blah) which caused import to barf when called from a different level in the tree. Not to mention a few missing __init__.py files. Once I cleaned everything up, it all worked and the main unit_test.py will run everything. I used your code, driving it with the results of os.path.walk and parameterizing the pattern as a list (we have two test case file name patterns, one for intercaps and one for _). -- - rmgw ---------------------------------------------------------------------------- Richard Wesley Trusted Media Networks, Inc. "'And now', cried Max, 'let the wild rumpus start!'" - Maurice Sendak, _Where The Wild Things Are_ From tomg at em.ca Thu Jul 17 12:52:10 2003 From: tomg at em.ca (Tom Goulet) Date: Thu, 17 Jul 2003 16:52:10 -0000 Subject: hex to signed integer References: <33803989.0307170205.6cc6ffe@posting.google.com> Message-ID: Miki Tebeka wrote: > eval? > e.g.: >>>> eval("0x%s" % "FF") > 255 | >>> eval("0x"+"B2DE7282", {}, {}) | :0: FutureWarning: hex/oct constants > sys.maxint will return \ | positive values in Python 2.4 and up | -1294044542 There you have it. Using the function doesn't work on 2.4 and using the function doesn't work on 1.5.2. Besides, I want to avoid use of the function. -- Tom Goulet, tomg at em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html From lists at gregfortune.com Thu Jul 31 17:18:25 2003 From: lists at gregfortune.com (Greg Fortune) Date: Thu, 31 Jul 2003 14:18:25 -0700 Subject: Retrieve source filename References: <3f29207d$0$24768$626a54ce@news.free.fr> <3f2952da$0$49110$e4fe514c@news.xs4all.nl> Message-ID: <5zfWa.3639$Jk5.2894686@feed2.centurytel.net> If you are working with an executable script (ie, __name__ == "__main__"), import sys import os os.path.abspath(sys.argv[0]) will give it to you. Otherwise, import imp imp.find_module(__name__)[1] will work. It's pretty simple to detect between the two cases by simply checking __name__. Greg Fortune Fortune Solutions Irmen de Jong wrote: > Shrom wrote: > >> I know that you can retrieve main file name with sys.argv[0] and file >> name for a module with modulename.__file__ but is there a common way to >> retrieve file name for both main program and modules as the __FILE__ >> constant in PHP ? > > I don't know if it's the "right" way, but this works: > > import inspect > print inspect.getfile(inspect.currentframe()) > > > --Irmen From nospam at mega-nerd.com Sun Jul 13 22:48:01 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Mon, 14 Jul 2003 02:48:01 GMT Subject: AIFC (Python and audio files.) References: Message-ID: <3F1219D7.829F2F43@mega-nerd.com> Kelvin Chu wrote: > > Hello, Python Wizards... > > I'm trying to use Python to write an aiff file. I've used the aifc module > and I've set the parameters (# of channels, encoding rate, compression, > etc.) > > What does raw audio data look like? Is each word of the raw audio data a > frequency? If I encode 440 for each of the frames, will I get concert A? AIFC files contain digitally sampled sound, much like the data stored on a CDROM. Try looking up PCM (Pulse Code Modulation) on Google for a deeper explanation. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ The word "Windows" is a word out of an old dialect of the Apaches. It means: "White man staring through glass-screen onto an hourglass..." From cjw at sympatico.ca Mon Jul 28 13:45:38 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 28 Jul 2003 13:45:38 -0400 Subject: Interface Descriptions - was Re: Static typing In-Reply-To: <3f219c8d$1@nntp0.pdx.net> References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: <0jdVa.1266$Cx4.286824@news20.bellglobal.com> Scott David Daniels wrote: > Bruno Desthuilliers wrote: > >> Michael Muller wrote: >> >>> Is there currently any plan to introduce static typing in any future >>> version of Python? >> >> Seriously, why would you do that ? > > > You _might_ want some static typing information as program > documentation or to enable efficient program translation. The > types sig was interested in allowing type annotation where > possible. Remember, the type you might want may be more like > "what protocol must these objects (the ones passing through > this variable) follow" than "what are the construction details > of these objects". > > I would like to see interface descriptions describing what > kinds of parameters are required and results produced for > packages that I am considering using. If there were a single > central-python-endorsed form for those descriptions even better. > If the descriptions can be mechanically read, and at least > sometimes mechincally checked (possibly slowly, possibly only > for slow execution), I might use such a system to check a module > before announcing it to the world. > [and some other things] It would be helpful to have some sort of consensus as to what form these descriptions should take. As suggested, it's desirable that description be both human and machine readable. I would suggest that priority be given to the former. Colin W. From harrisonrj at ornl.gov Wed Jul 16 23:20:06 2003 From: harrisonrj at ornl.gov (Robert Harrison) Date: 16 Jul 2003 20:20:06 -0700 Subject: c/c++ implementation of python base and derived class References: <521f96c7.0307151943.7d987b2@posting.google.com> Message-ID: <521f96c7.0307161920.12996635@posting.google.com> Boost is indeed pretty powerful and cool, but I was trying to understand the actual implementation. A bit more searching shows that all is revealed in the relevant PEP http://www.python.org/peps/pep-0253.html From robin at reportlab.com Wed Jul 9 09:51:26 2003 From: robin at reportlab.com (Robin Becker) Date: Wed, 9 Jul 2003 14:51:26 +0100 Subject: ReportLab 1.18 Released Message-ID: Version 1.18 of the ReportLab Toolkit has been released. This release will be the last to attempt to keep compatibility with Python 1.52 - 2.1. We will allow 2.2 specific features into the code in future. There will be a branch called ReportLab_1_18_PRE22. So that enthusiasts can maintain it if required. Main changes since ReportLab 1.18: - Bug & leak fixes. - improvements to pyRXP which can now be used in 16bit mode. - Tables now can have row and column spanning. - renderPM can now do PICT images. - More charts and improvements to existing graphics classes. - Valuable contributions from Ian Sparks, Karl Putland, Igor Stroh, Dirk Holtwick, David Fraser, Sidnei da Silva, Henning von Bargen, Christoph Zwerschke, Stuart Bishop, Stephen Diehl, Ury Marshak, Dirk Datzert, Max Neunh?ffer & others. -- Robin Becker From mikael at isy.liu.se Wed Jul 16 02:46:12 2003 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 16 Jul 2003 08:46:12 +0200 Subject: newbie question: ImportError: No module named Numeric In-Reply-To: <20030715155428.C48367@meta.lo-res.org> References: <20030715155428.C48367@meta.lo-res.org> Message-ID: <20030716084612.2770d2dd.mikael@isy.liu.se> On Tue, 15 Jul 2003 16:04:03 +0200 (CEST) rmachne wrote: > I couldn't find out which path variable to change or add. Can anyone > help? import sys sys.path.append('/foo/bar/bah') /Mikael Olofsson ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 /"\ \ / ASCII Ribbon Campaign X Against HTML Mail / \ This message was sent by Sylpheed. ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com From tjreedy at udel.edu Fri Jul 25 14:17:40 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2003 14:17:40 -0400 Subject: Downloading Python files References: Message-ID: "Luke StClair" wrote in message news:slrnbi2j1n.ra.luke at stclair.homelinux.net... > Only marginally belonging in this newsgroup... but oh well. > > I've just started writing in python, and I want to make the files > available on the web. So I did the standard href="mypath/myfile.py"> and not surprisingly, it displays like a > webpage, but just the code. What browser on what system? As I remember, with IE6/Win98 with python installed, even left clicking brings up 'Downloading... open or save' box. And there is always right click 'Download as..' option. TJR From mauro.baraldi at bol.com.br Fri Jul 25 13:36:04 2003 From: mauro.baraldi at bol.com.br (Mauro Baraldi) Date: 25 Jul 2003 10:36:04 -0700 Subject: Get data from a Tkinter Text Object Message-ID: Hello World... Someone can help me with a Tkinter doubt. I need to get some data, from a Tkinter text objetc and write to a variable. And, sent to a text objetc some data from a var. Thanks for all... []' Mauro From peter at engcorp.com Tue Jul 8 12:24:48 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 12:24:48 -0400 Subject: path module References: Message-ID: <3F0AF050.A6D03CE1@engcorp.com> Nick Vargish wrote: > > Just van Rossum writes: > > > (Did I mention that / usually means divide in Python? ;-) > > I believe you did... But doesn't % usually mean modulo in Python? I believe you'll find it's more common for it to mean "format", but the point is that it is well understood that it means *either*, depending on context. Using / for this new concatenation-like behaviour is tantamount to adding new syntax to Python again... :-( -Peter From bokr at oz.net Mon Jul 14 11:51:54 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 15:51:54 GMT Subject: removing spaces from front and end of filenames References: <93f5c5e9.0307130843.3e3e3daa@posting.google.com> Message-ID: On 14 Jul 2003 00:38:56 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >Why not do the whole thing in one loop? (Ignore my prev post suggestion for final >renaming loop just for spaces): > >#XXX# untested !! >import re, os >percent2f_n_bad = re.compile(r'%2f|[*?<>/|\\]') # look for bad chars too >for root, dirs, files in os.walk('/home/rbt/scripts'): > for fname in files: > newfile = percent2f_n_bad.sub('-', fname) > newfile.strip() # and the space thing # ^^^^^^^^^^^^^^^ - does nothing useful like that ;-/ newfile = newfile.strip() # argh, just noticed. D'oh. What else escaped? Sorry ;-/ > if newfile != fname: # you really only need to know if something changed, right? > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,fname) > os.rename(oldpath,newpath) > print `oldpath` # backticks to get quoted repr, to see spaces > print `newpath` > >Or am I missing something? > Well, I did miss a least one thing ;-/ Regards, Bengt Richter From h.goebel at crazy-compilers.com Mon Jul 28 06:29:50 2003 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Mon, 28 Jul 2003 12:29:50 +0200 Subject: List of all python magic numbers? Message-ID: <3f24fb20$0$6758$9b4e6d93@newsread2.arcor-online.net> Hello, I'm looking for a list of all Python Magic Numbers and the related Python version -- starting a the last byte-code change towards 1.5. This should make 'decompyle' work with less problems. I managed finding some magic numbers but sometimes I get notice of a magic number which is not yet in my list. So a complete list would be good. Any help? Regards +++hartmut -- | Hartmut Goebel | We build the crazy compilers | | h.goebel at crazy-compilers.com | Compiler Manufacturer | From max at alcyone.com Mon Jul 21 00:04:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2003 21:04:29 -0700 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: <3F1B664D.2AC5A585@alcyone.com> Jeff Epler wrote: > I'd have expected something like 'TypeError: unslicable type' > meaning that you can't slice a dict, not that slice()s aren't > hashable. Slicing is not a feature of the mapping interface; it's not entirely clear what it should mean. All mapping interfaces need are keys that are hashable; it doesn't make any kind of requirements about how those keys related to each other. So slicing a mapping interface is something that simply may not make any sense at all in some cases. If you really _do_ want to take a range out of a dictionary and know that it has some meaning, you should probably do the slicing on the _list of keys_ (D.keys()) -- because there is no concept of an ordering of keys in a dictionary. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It is much safer to obey than to rule. \__/ Thomas a Kempis From owski at hotmail.com Mon Jul 14 00:03:59 2003 From: owski at hotmail.com (Adam Ruth) Date: 13 Jul 2003 21:03:59 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: Stephen Horne wrote in message news:... > On 13 Jul 2003 14:48:09 -0500, Ian Bicking > wrote: > > >On Sun, 2003-07-13 at 12:51, Stephen Horne wrote: > 1. Why are the values of mutable objects always forced to be accessed > via a pointer (or reference or whatever)? Because *all* objects are accessed via pointer, sorta. > Note that I am referring to a computer science, semantic > pointer/reference/whatever - not to any pointers or references that > may be used in the implementation of the binding of variables to > values. The use, behind the scenes, of lazy copying as an optimisation > is irrelevant to the computer science principles. > > 2. Why is there no way to reference an immutable object via a > pointer, other than stuffing it into a mutable object designed for > some purpose other than simple pointer behaviour? They *are* referenced by pointer, sorta. It's just that what is being pointed to cannot be changed. If you were using C and you had a pointer to a variable in a region of memory that you couldn't change, then you'd have, semantically, the equivalent. In that case, how you do modify the value? You don't, you only modify the *pointer*. If you want to change the pointer, you need to pass a pointer to a pointer. This is what doesn't exist in Python, and I think it's what you're having problems with. The same "problem" exists in Java, but for slightly different reasons. The Python method is completely consistent and all objects are treated the same. There are no *pointers* even though binding sometimes behaves like they. Binding doesn't always work like pointers, but it always works like binding. > > The truth is that this system is arbitrary, and that therefore this > excuse is invalid. The definition of what is and isn't immutable isn't arbitrary in the sense of "Determined by chance, whim, or impulse, and not by necessity, reason, or principle". I'd say that the choices were made on necessity, reason, and principle. Just not the necessity, reason, or principle you would have chosen. What happens in this case? char *myval = "my little pony"; myval[1] = 'e'; It would appear that C and C++ also have immutable types. And in this case the reason it's immutable bears no relation to the object or type, but to it's location in memory, I'd say that that appears more arbitrary. "Some strings are immutable and some aren't" is worse than "all strings are immutable". > >The problem you have is you are still thinking of variables as slots, > >which is not correct. Variables in Python are bindings. Assignment > >never copies anything, or creates anything except for changing the > >variable to point to a different address location. *Every* Python > >assignment (a=b) is like the C assignment (a=&b). > > The problem is that you are confusing implementation with semantics. > The meanings of 'variable', 'value', 'assignment' etc are defined by > computer science. Whether you arbitrarily change the meaning of > 'assignment' or whether you arbitrarily change the meaning of > 'variable', it amounts to the same thing. I don't see the arbitrary change. Python has one type of variable: A pointer that cannot itself be dereferenced. It's much more consistent then having 3 types of variables (in C++). > > > > >> Tell me one case where it is sensible for a function to behave such > >> that whether the caller sees a change in a variable it passed as its > >> argument should depend on the type. A function may see a change in a *value* not a variable. That should always depend on type and should depend on nothing else, a function should always know what types it's working on. In my C example above, it would depend on nothing that could be discernable in the function. If someone wrote a mutable integer class, then it would be a distinct type from an immutable integer, and the function could work with 3 types: immutable int, mutable int, and int. If the function doesn't know what it's working with, then the function writer should probably look for another career. > You miss my point. Your argument would equally apply to the need for > an integer-specific division operator, for instance. Its all about how > one function reacts in response to varying input. If you pass a > mutable value to a function which expects an immutable one, you get an > error. If you pass an immutable value to a function which expects a > mutable one, you get an error. There is no good reason for a function > to react to the distinction as evidenced by your own observation that > what actually happens (and what should happen) is that you have two > distinct variants of the function. Not true. If you pass a mutable to a function that expects an immutable, you'll get no error. There's nothing that can be done to an immutable that can't be done to a mutable. The opposite would give an error, and should. You wouln't call a function in C++ with an object that has no object::doSomething() function if the function expected it. Whether an object is immutable or not, is no different than knowing what methods it supports. You wouldn't program against an object without knowing its methods, likewise you need to know if it's immutable. This dicussion brings to light the fact that immutable/mutable isn't really special in any way. It just means that the object has no methods to support mutability. Just like the classic Dog class inheriting from Animal. Animal has no doBark() method, but Dog does. A function user shouldn't be surprised that a method that expects a Dog would choke on an Animal. > >> Tell me one case where an object storing values should care about > >> callers mutating values it holds *only* for certain types. > > > >Objects don't *store* values, they *refer* to values. You are still > >thinking like you're in C (or C++). This is why you are having a > >problem. > > No it is not. I'm thinking in terms of computer science, in which > terms like 'variable', 'value' and 'assignment' are abstract concepts > independent of the way in which they are implemented in a programming > language. The distinction is more to do with Dynamically version Static languages. You're quoting the definitions for Static languages like they apply universally to all computer science. They don't. In C you can have a variable that's an int, float, pointer, struct, etc. In Python you only get name (which can be read binding, or "limited" pointer). It's when you start forcing the semantics of value types onto variables that you get confused. Variable, value, and assignement do mean different things in dynamic vs. static languages, and that's because they're sematically different. While they both use the = operator to perform similar functions, they're different, and if you expect them to be identical, you're going to be frustrated. > One way or the other, Python is currently choosing not to respect the > computer science definition of those terms. It may have historic and > backward-compatability reasons, but that does not change the facts. > This deviation from computer science definitions, whatever the excuse, > is arbitrary, confusing and error prone. That is my problem. It's not respecting the static language definitions of those terms, but it shouldn't even try. There are different meanings for those words in mathematics, but you wouldn't try to express those definitions in terms of C, it would be equally frustrating. The static definitions are merely abstractions of the mathematic meanings, and the dynamic meanings are also abstract, but in a different direction. Adam Ruth From usenet_spam at janc.invalid Mon Jul 7 22:57:20 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 08 Jul 2003 02:57:20 GMT Subject: A story about Python... sort of References: Message-ID: John J Lee schreef: >> But remember "When Harley Was One" and he invented the G.O.D.? > > I don't get the reference there. It's a SF-novel from 1972 by David Gerrold, about a intelligent computer creating a new computer "intelligence" far superior to what any human being can understand. BTW: this book was also the first time a "computer virus" was mentioned. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From db3l at fitlinxx.com Wed Jul 9 18:00:53 2003 From: db3l at fitlinxx.com (David Bolen) Date: 09 Jul 2003 18:00:53 -0400 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> Message-ID: Kim Petersen writes: > I'm not arguing that thats not important - *but* paying 70$ > pr. customer, is the equivalent of paying you for 1hr of support for > each customer [not installation mind you], where our own > licence/supportcost is already getting lower and lower... I find that > _extremely_ steep - i could and would accept such a cost for the > python platform (no trouble!) [except in the few (from our view) cases > where the user just needs a small tool. Except that if you're going to resell a product, presumably you'd go for the per-developer fee ($1250). It'll beat the per-CPU license at about 18 customers (assuming one CPU per customer), and just continue shrinking on a per-customer basis after that. In effect, the per-developer license is a one time, royalty free, license, the marginal unit cost of which disappears over time. As with anything, the actual price is up to the owner to set, but on our part, we've found the economics reasonable for the functionality supplied within our commercial endeavors. Is it the only way to go for database access with Python - certainly not. But for us (Windows platform with ODBC sources) its worth it for the effort Marc-Andre has put in to best support ODBC in that environment. Just another data point for what it's worth. -- David From o_otaotao at hotmail.com Mon Jul 28 10:06:22 2003 From: o_otaotao at hotmail.com (PythonMan) Date: Mon, 28 Jul 2003 22:06:22 +0800 Subject: Can't compile, miss library/modules ............... ? References: Message-ID: Thx for yr reply.. and u are right , the exe is produced and can be run , but it operate in wrong way , eg. Suddenly Terminate when Checking exist file~~~~ what 's wrong ? @.@ -- "Thomas Heller" ???g???l???s?D :wue2kblq.fsf at python.net... > "PythonMan" writes: > > > warning: py2exe: * The following modules were not found: > > warning: py2exe: * SOCKS > > warning: py2exe: * rourl2path > > warning: py2exe: * ic > > > > when i compile btdownloadheadless.py of BitTorrent , justmsg is shown , the > > souce code should have no error , but why i get such error ? how get back > > this modules ? thx~~~ > > It's a warning, and the exe should work. From richie at entrian.com Wed Jul 30 05:01:53 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 30 Jul 2003 10:01:53 +0100 Subject: Seeing next character in an file In-Reply-To: References: Message-ID: [Bengt] > BTW, is there an ANSI C spec available free on line > (or an older, close-enough draft)? Not a complete one that I'm aware of, no, although some pieces exist at and around http://www.cs.vsb.cz/grygarek/tuox/sources/lib/ansi/Draft_g.txt I eventually found the seek/tell rule in a book errata at http://herd.plethora.net/~seebs/c/c_tcr.html then confirmed the standard and section numbers with the "Normative Changes to ISO/IEC 9899:1990" document at http://www.lysator.liu.se/c/tc1.html I can't remember exactly what I googled for to find those documents (and the query has already fallen off the end of my Google Toolbar's search history - I think I use Google too much! 8-) -- Richie Hindle richie at entrian.com From shagshag13 at yahooPLUSDESPAM.fr Sat Jul 5 04:32:19 2003 From: shagshag13 at yahooPLUSDESPAM.fr (shagshag13) Date: Sat, 5 Jul 2003 10:32:19 +0200 Subject: debian etc/python2.2/site.py lost ? Message-ID: <3f068c06$0$29650$626a54ce@news.free.fr> hello, i accidentally delete etc/python2.2/site.py on my debian system could some one help me to recreate this file as i didn't know what it contains ? thanks, From jbar at lf1.cuni.cz Fri Jul 11 12:03:20 2003 From: jbar at lf1.cuni.cz (Jiri Barton) Date: Fri, 11 Jul 2003 18:03:20 +0200 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> Message-ID: <3f0edfcb@shknews01> I store cookies on the server in MySQL database. Here's the schema of the table: CREATE TABLE `cookies` ( `id` int(10) unsigned NOT NULL auto_increment, `time` timestamp(14) NOT NULL, `ip` varchar(20) NOT NULL default '', `data` blob NOT NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM; id - sessionID time - using for session timeout ip - the remote IP address data - pickled data, urllib.quote'd, because of the control chars Disposing cookies: - when the session times out - after a number of requests (say 1000), approximately, I scan the table for outdated cookies and delete them -- if random.randrange (1000) == 0: #scan & remove cookies From stuart_clemons at us.ibm.com Sat Jul 12 15:46:51 2003 From: stuart_clemons at us.ibm.com (stuartc) Date: 12 Jul 2003 12:46:51 -0700 Subject: Newbie with sort text file question Message-ID: <86d2ca4.0307121146.3deb854a@posting.google.com> Hi: I'm not a total newbie, but I'm pretty green. I need to sort a text file and then get a total for the number of occurances for a part of the string. Hopefully, this will explain it better: Here's the text file: banana_c \\yellow apple_a \\green orange_b \\yellow banana_d \\green orange_a \\orange apple_w \\yellow banana_e \\green orange_x \\yellow orange_y \\orange I would like two output files: 1) Sorted like this, by the fruit name (the name before the dash) apple_a \\green apple_w \\yellow banana_c \\yellow banana_d \\green banana_e \\green orange_a \\orange orange_b \\yellow orange_x \\yellow orange_y \\orange 2) Then summarized like this, ordered with the highest occurances first: orange occurs 4 banana occurs 3 apple occurs 2 Total occurances is 9 Thanks for any help ! From djc at object-craft.com.au Mon Jul 14 19:39:07 2003 From: djc at object-craft.com.au (Dave Cole) Date: 15 Jul 2003 09:39:07 +1000 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: >>>>> "BogAl" == BogAl writes: BogAl> Thanks for the reply, Dave.... >> Try putting the .pyd in C:\Python22\Lib\site-packages BogAl> Unfortunately, I'm still getting the error message. Does it work if you put the csv.pyd file in the current directory? - Dave -- http://www.object-craft.com.au From bokr at oz.net Sun Jul 27 13:10:55 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2003 17:10:55 GMT Subject: looping through a file References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> <3f21903c$0$27898$626a54ce@news.free.fr> <87llukrdow.fsf@pobox.com> Message-ID: On 27 Jul 2003 01:55:11 +0100, jjl at pobox.com (John J. Lee) wrote: >Heiko Wundram writes: > >> On Fri, 2003-07-25 at 22:24, Bruno Desthuilliers wrote: >> > for line in thefile.readlines(): >> > doWhatEverWithTheLine() >> >> Or, if you're on a sufficiently new Python: >> >> for line in thefile: >> doWhateverWithTheLine() > >I recall that in an old Python you could get into an awful mess (as I >did) with this by having several 'for line in file' blocks in a row: > >for line in f: > if not line.startswith("magic"): continue # skip header > >for line in f: > ...process data... > What mess was that? (unless you meant to re-open the file to read from the beginning) >I gathered from a recent thread that this has changed -- the file is >its own iterator now. Was the old behaviour ever released in 2.2, or >was it just part of a 2.3 beta? > Curious what was changed ... Regards, Bengt Richter From ta-meyer at ihug.co.nz Mon Jul 7 00:58:59 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 7 Jul 2003 16:58:59 +1200 Subject: A story about Python... sort of In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1302394595@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AAB8@its-xchg4.massey.ac.nz> > A chess program > is different from a 3D game in that with a 3D game, you can > stop at some point and say, "ok, this is fast enough." There > is little point in making the game run at 1000 frames per > second if no human eye can see more than 60 (or whatever the > number is). This isn't really true. Sure you can say that the framerate is fast enough, but when do you stop and say "the graphics look real enough"? (I'm sure there is a point, but it's a distant point, like 'solving' chess). =Tony Meyer From paul at boddie.net Wed Jul 16 04:08:06 2003 From: paul at boddie.net (Paul Boddie) Date: 16 Jul 2003 01:08:06 -0700 Subject: Foreign characters References: Message-ID: <23891c90.0307160008.6e1eb71c@posting.google.com> tsurusennin at softhome.net (Tetsuo) wrote in message news:... > How do I get Python to work with foreign characters? When I try to > print them, I get a unicode error (characters not ASCII). Wasn't > unicode invented for the express purpose of working with non-ASCII > characters? Erm, yes. But the problem you're having is undoubtedly occurring when you try to send the Unicode data to your console or terminal. I'd recommend using the encode method on your Unicode objects as described in the thread "Characters in Python" - use groups.google.com to find that discussion. On the other hand, if you're using IDLE, I'd suggest trying out IDLEfork if you really want to be able to send Unicode data straight to the output window. IDLE in Python 2.2.x and below seems to have had various issues with Unicode and output, but that's discussed in that thread I mentioned. I note that the content of the most relevant entry in the Python FAQ can be regarded as being somewhat confusing: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp Notably this statement (in the context of the classic UnicodeError): "This error indicates that your Python installation can handle only 7-bit ASCII strings." I doubt that even if one makes the distinction between strings and Unicode objects, as I often do myself, that Python has ever been unable to handle 8-bit strings. Moreover, the statement gives the impression that various Python installations exist which know about Unicode (and related encodings) but can't deal with it. Perhaps the entry ought to be updated with some of the tips given in previous threads, and that more questions and answers need adding to the FAQ (which I'm happy to do, by the way, if it's seen as being worthwhile). Paul From tim.one at comcast.net Mon Jul 14 19:55:38 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 14 Jul 2003 19:55:38 -0400 Subject: anything like C++ references? In-Reply-To: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: [Stephen Horne] > ... > C++ references are tellingly also called self-dereferencing pointers. > They are not a distinct concept - they are syntactic sugar. I suspect > they mainly arise out of the modern desire to disguise pointers and > fantasize that they're not there, though they certainly work very well > in certain contexts. You don't have to guess -- Stroustrup's "The Design and Evolution of C++" explains his design rationales in detail. Section 3.7 is devoted to C++ references. The short course is that references were thought necessary to support usable operator overloading; see the book for concrete examples; a later "What Could and Should Have Been Different?" section explains why C++ references are a wart, but a pragmatically desirable wart. About "modern desire", the earliest computer languages didn't expose pointers at all (Lisp, COBOL, and Fortran are the prime early examples of this). Language exposure of machine addresses came in with lower-level systems-programming languages (of which C is the prime example today). From candiazoo at mac.com Sun Jul 13 23:08:01 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Mon, 14 Jul 2003 03:08:01 GMT Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: <130720032307414660%candiazoo@mac.com> Good luck, Elaine! Fwiw, I have been using wxWindows/wxPython and have found it fairly easy to pick up - and I ain't the brightest bulb, if you know what I mean. :) And what David said about Python becoming the one and only language you ever want to use is true. :) Mike J. In article , Elaine Jackson wrote: > David McNab wrote in message > news:pan.2003.07.13.03.27.44.711790 at 127.0.0.1... > > | Don't be intimidated if the Tkinter docs you come across urge you to > | approach it from a Tk viewpoint- there's an excellent guide at: > | http://www.astro.washington.edu/owen/TkinterSummary.html > > | David > > > Thanks for the tip. > > From tim.one at comcast.net Wed Jul 9 16:17:36 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 9 Jul 2003 16:17:36 -0400 Subject: Guido.moves_to(California) ? In-Reply-To: Message-ID: [Roman Suzi] > Reading PythonDev I've just found this > > [Guido announced he has a new job] > > I was not very surprised to hear that, but I wonder if it means new > licenses coming: No, the Python Software Foundation holds current Python copyrights, and current Python is distributed under the PSF license. By design, the PSF is a corporation independent of Guido's employer du jour. His new employer may, or may not, become a PSF member; if they do, they get one vote on PSF member matters, same as any other PSF member; if they don't, they get no vote on PSF member matters. Python's license is a PSF matter (although, strictly speaking, the license isn't up for a vote of PSF members, it's set by the PSF's Board of Directors). From jkpangtang at yahoo.com Tue Jul 22 20:46:38 2003 From: jkpangtang at yahoo.com (JW) Date: 22 Jul 2003 17:46:38 -0700 Subject: 'int' object is not callable Message-ID: <3607e8e4.0307221646.7d24707@posting.google.com> Hi, Suppose I have the following python method: def foo(aTuple): print len(aTuple) #line 1 print aTuple[0] # line 2 return 0 Then, suppose I call that python method from within a C function using: PyObject_CallObject(pFunc, pArgTuple); I get the following error at line 1: 'int' object is not callable If i remove line 1, then my foo() method does print out correct value for aTuple[0]. Why am I getting this error when i try using python len() built-in function? Thanks From bokr at oz.net Wed Jul 16 13:20:52 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 17:20:52 GMT Subject: String Manipulation References: <2c6431ab.0307151223.4173c4ee@posting.google.com> <45f7ff62.0307151851.f59129f@posting.google.com> Message-ID: On 15 Jul 2003 19:51:56 -0700, ee01b092 at ee.iitm.ernet.in (Vinoo Vasudevan) wrote: >lamar_air at hotmail.com (lamar_air) wrote in message news:<2c6431ab.0307151223.4173c4ee at posting.google.com>... >> I need a piece of code that takes a string like this string1 = >> "aaa/bbb/ccc/dd" and extracts a string containting the character after >> the last "/" >> >> So for this example the result would be "dd" >> >> like this: >> for i=0; string1.right(i) != '/'; i++ >> >> result = string1.mid(i, string1.length()) >> >> but in python. > >How about this: >string1 = 'aaa/bbb/ccc/dd' >result = string1[string1.rfind('/')+1:] > >Hope it's helpful, Sorry Vinoo, for some reason your post did not show up for me before I posted the same solution, even though your post is dated much before mine. I guess it has to do with delays in news servers forwarding and such. Regards, Bengt Richter From m.stenzel at allanime.de Mon Jul 7 10:42:46 2003 From: m.stenzel at allanime.de (Markus Stenzel) Date: Mon, 07 Jul 2003 16:42:46 +0200 Subject: Reverse Engineering of Windows Distribution In-Reply-To: <3F098251.426DB151@engcorp.com> References: <3F098251.426DB151@engcorp.com> Message-ID: Product : Experimental BitTorrent Client (c)Bram Cohen Modified: Eike Frost http://ei.kefro.st/projects/btclient/ License : MIT Source : Available (3.1-CVS-4, 3.2-1, 3.2.1b-1, 3.2.1b-2) The Experimental BitTorrent is a GUI upgrade of the well known BitTorrent file swarming application (c)Bram Cohen and released under the MIT license. Eike Frost modified the software to allow "bandwidth capping" to be selected from the GUI to allow ACK messages to pass the upstream during normal operation thus increasing overall efficiency. However all versions mentioned above in the line starting with "Source" _DO NOT_ run on Linux. 3.1-CVS-3, 3.2-1 and 3.2.1b-1 produce error messages due to a few bugs handling the command line parameters. The 3.2.1b-2 client DOES work on Linux but is running slowly and works for single files only. When working with "batch torrents" it routinely hangs during operation (even if it's not touched after it's launch) The author Eike Frost doesn't offer the pre-3.1-CVS-3 source. The windows version we have installed on Win32 is a pre 3-1-CVS-4 version. Now guess what.. ;)) > Technically it is possible, but it's not trivial, and seems like > a pretty bizarre thing to do if the author didn't intend it to > be used on Linux in the first place. (Which we can infer from the > choice of distribution method.) I hope the additional background info might make you giving a few little hints? *hopes* Markus Peter Hansen wrote: > Markus Stenzel wrote: > >>I have a Python software for Windows, packed into a single exe file and >>accompanied with a few dll and package files. >> >>Is there any way to reverse engineer this packet by extracting the >>source files so they can be used on Linux/Unix? I have checked the exe >>but it seems to be compressed by zlib. >> >>Some people on the mailing lists told my friend it's possible to get the >>code once you can "unpack" the files from the exe. > > > It seems likely that the source to this program would be available > to you already, wouldn't it? It *is* open source, right? > > If it is, you can probably find the source on the web, or just > contact the author for it. > > If it is not, you are probably violating your license agreement in > trying to do this. Did it come with a license? > > Technically it is possible, but it's not trivial, and seems like > a pretty bizarre thing to do if the author didn't intend it to > be used on Linux in the first place. (Which we can infer from the > choice of distribution method.) > > -Peter From 2002 at weholt.org Sat Jul 12 16:10:42 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Sat, 12 Jul 2003 22:10:42 +0200 Subject: Any pure-python relational databases? References: <2a897f11.0307121143.4a37113b@posting.google.com> Message-ID: <8XZPa.12712$Hb.219315@news4.e.nsc.no> "Wayne Pierce" wrote in message news:2a897f11.0307121143.4a37113b at posting.google.com... > David McNab wrote in message news:... > > [sniped] > > > 1) Any pure-python interface to MySQL? or > > If you cannot get the MySQL specific interface working, have you tried > a generic database interface? > > http://www.python.org/topics/database/DatabaseAPI-2.0.html > > > 2) Any kind of relational DBMS written in pure python that'll run on > > 1.5.2? > > While not relational, have you looked at Metakit? > > http://www.equi4.com/metakit/python.html Relational *and* simple install with good Python module; SQLite => http://www.sqlite.org/ Thomas From maciej at maciejsobczak.com Tue Jul 8 03:36:19 2003 From: maciej at maciejsobczak.com (Maciej Sobczak) Date: Tue, 08 Jul 2003 09:36:19 +0200 Subject: ANN: YAMI 2.1 lib for distributed programming available Message-ID: Hi, I would like to announce that the next version of YAMI library is available for download. http://www.maciejsobczak.com/prog/yami/ The download page is: http://www.maciejsobczak.com/prog/yami/impl/ YAMI is an Open Source project providing lightweight and portable infrastructure for message-oriented network communication. It supports C, C++, Python and Tcl on various platforms. -- Maciej Sobczak http://www.maciejsobczak.com/ From bokr at oz.net Thu Jul 31 01:35:37 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2003 05:35:37 GMT Subject: Upgrading python References: Message-ID: On Wed, 30 Jul 2003 15:52:59 -0400, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:bg93pm$72v$0 at 216.39.172.122... >> On 30 Jul 2003 06:43:22 +0200, martin at v.loewis.de (Martin v. >=?iso-8859-15?q?L=F6wis?=) wrote: >> >> >Stephen Boulet writes: >> > >> >> When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall >2.2.3? >> > >> >If you want to, you can have both 2.2 and 2.3 installed, side-by-side. >> >If you want to replace 2.2, you should uninstall it first. >> > >> How do I know what will happen to file extension associations and the [19:00] C:\pywk\clp>assoc |findstr/i py .py=Pythonfile .py = Pythonfile .pyc= .pyo= [19:00] C:\pywk\clp>ftype |findstr/i py Pythonfile=d:\python22\python.exe "%1" %* Pythonfile = d:\python22\python.exe "%*" Hm, I wonder if I did those with the extra spaces ;-/ Anyway, presumably at least one set of those will be replaced with python23 versions. Does python itself depend anywhere on these associations? I hope not. Also, shouldn't this be somewhere down the profile tree, so different users can have .html bring up their different browsers, etc.? I.e., this is really just configuring the operation of a users's shell, it's not like NTFS vs FAT32 on a disk partition. But that's not Python's fault. >system path search >> that takes unadorned python and finds some/path/to/python23.exe? >> >> And how does the old python22 find what it needs? Do I need to go through >a .cmd file that >> sets up its environment before running? How do I know everything it needs? >> Does the installation automatically modify the PATH (and PATHEXT??) environment settings? For everyone, or the installing user? >> IOW, how do you set up a clean way to run both 2.2.3 and 2.3 "side by >side" but separately, >> with default "python" going to 2.3? I am being lazy in not reading the >install docs yet, >> but does it cover the question fully? If so, the answer to this post can >just be "yes" ;-) > >As with most things having to do with installation, the answer is a bit >complicated. On Windows, Python keeps its information in separate >keys by major release, so there's a different key for Python 2.2 and Python >2.3. That's compiled into the executable, so anything that's in the registry >is kept nice and separate. So you can have two or more major releases >side by side. You can't have two minor releases, though, because they >use the same registry key. > >The keys aren't secret, so any outboard programs that need a specific >version of Python can go right to it. Where the difficulty lies is that >other things, such as the system path for finding executables and the >file name associations don't have the same facility. So if I wanted to >just be able to doubleclick on a .py or .pyc file and have it find the >correct executable, I'm out of luck unless I do some arcane system >programming. (That is, associate them with a program that figures >out from the directories or the "magic number" which version of >python is wanted, and then invokes it.) > I understand. But when you *do* install, does the installation unconditionally set associations and path to the new installation? >If all you want is for the default to be 2.3, then just make certain >that the system path goes to the proper directory. All your >file name associations will tag along as long as the command >keys didn't include full paths. Do I have to "make certain ..." by doing it manually, or just verifying if I'm worried? > >And I find that .cmd files are my friends. I use them to set the >Pythonpath so I don't have to figure out a path that's going to >work for everything, now and forever. And they work very >well for drag and drop targets for those little utilities that operate >on one file... > Yes, I use them a lot too, especially since i/o redirection doesn't work properly on NT4 without explicit invocation of python to run a python program. Well, under HKEY_LOCAL_MACHINE for python I grep out Key Name: SOFTWARE\Python Key Name: SOFTWARE\Python\PythonCore Key Name: SOFTWARE\Python\PythonCore\2.2 Key Name: SOFTWARE\Python\PythonCore\2.2\Help Key Name: SOFTWARE\Python\PythonCore\2.2\Help\Main Python Documentation Data: D:\Python22\Doc\index.html Key Name: SOFTWARE\Python\PythonCore\2.2\InstallPath Data: D:\Python22 Key Name: SOFTWARE\Python\PythonCore\2.2\InstallPath\InstallGroup Data: Python 2.2 Key Name: SOFTWARE\Python\PythonCore\2.2\Modules Data: Key Name: SOFTWARE\Python\PythonCore\2.2\PythonPath Data: D:\Python22\Lib;D:\Python22\DLLs;D:\Python22\Lib\lib-tk Which I take it influences the following [17:52] C:\pywk\clp>python Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.environ['PYTHONPATH'] c:\pywk >>> import sys >>> for p in sys.path: print p ... c:\pywk C:\pywk\clp D:\python22\DLLs D:\python22\lib D:\python22\lib\lib-tk D:\python22 D:\python22\lib\site-packages D:\python22\lib\site-packages\PIL apparently the first two entries are from os.environ['PYTHONPATH'] and the working directory that python was started in. The rest look like they're from the registry. I can see the pattern to expect for python23 etc. Is it possible to create a version 2.3a that would fit into this and go under a Key Name: SOFTWARE\Python\PythonCore\2.3a subtree in the registry. I mean with a single version id change someplace in the build, not manual heroics. Also, is there a way to have debug branches on these trees, or do you have to keep a whole separate thing even if most is duplicated, or do you just put some debug things into a regular tree and rely on backups to restore (as I have done with a couple experiments) Any gotchas? Regards, Bengt Richter From bhv1 at psu.edu Tue Jul 29 23:05:00 2003 From: bhv1 at psu.edu (Brian Victor) Date: Wed, 30 Jul 2003 03:05:00 GMT Subject: curses and use_default_colors() References: <7652139e.0307291843.2ade58c6@posting.google.com> Message-ID: Chris Reay wrote: > Brian Victor wrote in message > news:... >> I am attempting to write a curses-based program. I would like to use >> the default terminal background rather than a black one (a significant >> difference with transluscent terminals, regardless of one's opinion of >> them). > I don't know how much this'll help, but my home-brewed curses TextApp > class has a white-on-blue default, and TextApp.startWin() contains > these lines (inter alia) ... [snip] Thanks, but that's not quite what I'm looking for. Getting a solid background isn't a problem. Getting a subtly textured background to show through (or other windows on Mac) seems to be a bit tricker. Still hoping someone will hop in with "just use this curses extension" or "you can write a wrapper around that one function and integrate it with python's curses like this." But thanks for the input, anyway! -- Brian From danb_83 at yahoo.com Sun Jul 20 11:31:41 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Jul 2003 08:31:41 -0700 Subject: object as a reserved keyword References: <7dokhvgv12fdbha8sun6c6q658cth5uq2c@4ax.com> Message-ID: Lawrence Oluyede wrote in message news:<7dokhvgv12fdbha8sun6c6q658cth5uq2c at 4ax.com>... > On Sun, 20 Jul 2003 11:29:03 +0200, Lawrence Oluyede > wrote: > > >I'd like to avoid oddities like this: > > I just noticed that it's the same thing with other builtin types such > as list, dict and so on... Hope anyone ex[pl]ain me the reason to that. > Maybe is beyond my views... I understand his problem. When I write in other languages and need a meaningless variable name, I tend to use an abbreviation for the variable's type. public void foo(String str) {/* ... */} public void foo(List list) {/* ... */} As you can see, this convention doesn't carry over very well to Python. From kp at kyborg.dk Thu Jul 10 19:15:55 2003 From: kp at kyborg.dk (Kim Petersen) Date: Fri, 11 Jul 2003 01:15:55 +0200 Subject: Memory leak ?? In-Reply-To: References: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> Message-ID: <3f0df3ac$0$13186$edfadb0f@dread15.news.tele.dk> A.M. Kuchling wrote: > On Thu, 10 Jul 2003 14:34:05 +0200, > Kim Petersen wrote: > >>Using python-2.2.2-26 on RH9 (shrike) x86 -fully patched >> >>The following program slowly eats up more and more memory when run on >>large datasets... can anyone tell what the trouble is? > > > Your code uses eval(), which is pretty heavyweight because it has to > tokenize, parse, and then evaluate the string. I know - but speed is not an issue in this (at least not for the moment). > There have been a few memory > leaks in eval(), and perhaps you're running into one of them. Try using > int() or float() to convert strings to numbers instead of eval. As a bonus, > your program will be faster and much more secure (could an attacker tweak > your logfiles so you end up eval()ing os.unlink('/etc/passwd')?). Not likely - this file is error-output from a database population program - and the thing being eval'led is actually the python tuple that made the error occur - what my program essentially should do - is take that output - analyze it - fix the errors - and then put it into the database. But thanks, for the tip - i'll try and wrap up a parser for this instead then. (personally i had my suspecion on the generator - but thats prolly because i'm still thinking 1.5.2 ;-)) > > In general, using eval() is almost always a mistake; few programs need to > take arbitrary expressions as input. I agree completely - i've personally used eval something like 3 times totally in the time i've programmed python (5 years or so) - and in all cases it has been places where the input were secure. > > --amk From ianb at colorstudy.com Sun Jul 13 16:05:38 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2003 15:05:38 -0500 Subject: anything like C++ references? In-Reply-To: References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <1058126738.28456.424.camel@lothlorien> On Sun, 2003-07-13 at 14:39, Stephen Horne wrote: > The fact is that 'assignment' has a common meaning separate from the > choice of programming language, This just isn't true. The C++ assignment operator is not at all like the Python assignment statement. Python variables are not like C++ variables, no surprise assignment is different too. If you used languages outside of C++ and its like (e.g., Pascal), you would find Python's behavior common. (Admittedly, some confusion may occur because these very different operations use the same syntax: x = 10 x[0] = 10 obj.x = 10 The second and third are entirely different from the first.) Ian From duncan at NOSPAMrcp.co.uk Mon Jul 7 09:26:50 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 7 Jul 2003 13:26:50 +0000 (UTC) Subject: NNTP mirror of c.l.p? References: <2a897f11.0307070510.37a4ad41@posting.google.com> Message-ID: wayne at mishre.com (Wayne Pierce) wrote in news:2a897f11.0307070510.37a4ad41 at posting.google.com: > Does anyone know if there is a public server where I can download > c.l.p? I typically use GG, but want to test a program on my > Palm-based system for accessing NNTP servers. > > Thanks, > > -Wayne > Try news.freenet.de for public readonly access. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bokr at oz.net Fri Jul 11 21:58:13 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 01:58:13 GMT Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 11:16:12 +1200, dmbkiwi wrote: >On Fri, 11 Jul 2003 20:33:19 +0000, Bengt Richter wrote: > >> On Sat, 12 Jul 2003 07:34:18 +1200, dmbkiwi wrote: >> > > >Thanks for helping me with this. > > >>>def meterClicked(widget, meter, button): >>> #print "meterclick" >>> global dayshow, daypicrem, ddon, ddcon, buttonpressed >> # these globals -- where do they come from? What module? # Note that each >> module has its own globals, so is are there different modules # that think >> they're sharing globals but really aren't? There are ways to solve that, # >> but first, is that relevant? > >They don't come from a module, they come from different functions within >the script. To be honest, I don't think I've ever quite understood >globals, so I insert them where I think they should go - probably quite >incorrecly. Will this matter? It could. It depends. A script or a file (extension may vary, .py, .pyc, etc) that's imported is like a big room with a single cork bulletin board. Think of that bulletin board as the script's or module's global name space. It's where name tags can be tacked up with names associated with objects. You can think of the objects themselves as balloons attached to the name tags by strings (the houses have no roofs, so all the balloons occupy space someplace high up outside ;-) Note that according to this model, when you assign x=y what you are doing is finding the y-labled tag and following its string to the associated object-balloon and tying a new string to that same balloon, and then attaching that new string to a new tag labeled x and tacking this new tag on an appropriate bulletin board, resulting in two tags and their strings leading to the same object-balloon. Functions are like play houses inside the big room, and they each have their own bulletin boards inside, which is each function's local namespace. If you write "global xxx" inside a function, you are saying that when you are in that playhouse, you will not use the inside private bulletin board for name tags labeled xxx, but you will instead reach out and use the bulletin board in the big room. So xxx=123 means create an integer object-balloon with 123 value and make a tag labeled xxx and tie a string from the 123 balloon to that tag, and then reach out and tack the tag to the bulletin board in the big room. When you leave the playhouse, its inside bulletin board is cleared of name tags (and the strings detached). When you enter again, you start with a clean inside board with only name tags matching the formal parameter names (if any). If the last string is detached, it is grabbed by a balloon collector, who pops it to make sure there is always space in the sky for new balloons. Kind of ;-) If you don't write "global xxx" inside the function, the rules for name tags labeled xxx are different according to whether there's any code _anywhere_ in the function that tacks up that name tag (e.g., assigns to that name) or whether the code just looks for an existing tag (i.e., just uses it in an expression). If there's an assignment anywhere, it's an error to try to use it in an expression before the assignment. A legal assignment tacks the tag to the inside bulletin board. The balloon and string part is the same story wherever the tag goes. If there's no assignment, then the only other ordinary way it can be on the inside bb is if it is a parameter name, or it got tacked there by some other code that tacks name tags, like def foo... will make a foo name tag (the string goes to a function object), or class Bar... which would make a Bar name tag with string to a class object. Those are the main ways. If the name tag is not on the inside bb, it could still be on an enclosing playhouse's bulletin board (it is now possible to nest playhouses, not just have them all in the big room. If the name tag is not found on the bb of the immediately enclosing playhouse, it could be on the bb of yet another enclosing playhouse, and so on, until if it is not found on the bb of the big common room, it's a name error. BTW, the name-tag end of strings can also be tied to some balloons, which may have special eyelets taped to them. E.g., tuple-balloons come in variations according to how many fixed eyelets they have for attaching strings to other balloons. In the case of tuples, the eyelets are single-use. You can't cut and re-tie a single string, you have to make a new tuple-balloon and tie what strings you want there. If you cut the last string to a tuple-balloon, the baloon collector will grab it and eventually cut all the strings and pop the tuple-balloon, maybe right away. He may have secret deals with balloon makers for recycling material, but that's his business. List-ballons allow eyelet re-use, and also adding or removing eyelets. But every eyelet must have a string leading to some balloon, even if it is the None balloon. > >> >> # Second, are the globals accessible from multiple threads? Are you seeing >> hard-stuck errors or blue-moon errors? > >Now my newbiness will be evident. Multiple threads? I am not consciously >creating threads. Should I? Does python automatically create multiple >threads? What are hard-stuck/blue-moon errors? You shouldn't have multiple threads unless you made them on purpose or used some module that did it without your knowing. It should be prominent in the docs if so, though. Hard-stuck/blue-moon is not technical terminology ;-) I meant, do you get the error every time the code is executed, or only once in a blue moon. > >> >>> if (meter == mainpic) and (button == 1): >> # always here? > # yes >>> if ddcon == 0: >> # and here ? > # yes >>> if ddon == 1: >> # and here? > # no # so at least one if didn't just 'fall through'! >>> deleteDayDetail(widget, dayshow) >>> karamba.redrawWidget(widget) >>> createCurrentDetail(widget) >>> karamba.redrawWidget(widget) >>> else: >> # never here, you're saying, right? > # always here # very very weird. What evidence are you interpreting to come to these conclusions? >> # >>> else: >> # never here either, right? > always here # again weird**n >> # >> # get here though? > # yes >>> buttonpressed = 1 >>> If that is really happening, I wonder if you are somehow executing code from a different version or have some kind of mixed-up installation. Or are using incompatible extension modules? Do you have multiple versions installed? what are your versions, and what sym links are there? And what are the #! lines of your script(s)? >> I used tabs above to line up (maybe ;-) with your text, but maybe you >> should run your code through tabnanny or something to check for consistent >> usage. I never use tabs (though I use the tab key and gvim puts in 4 space > >Tabs seem to be fine in the actual code - I think it's the word wrapping >in either your/my newsreader that is causing problems, but your tab >positioning is correct. > >> indentation for me ;-) so I haven't used the tab checkers, but you might >> benefit, perhaps. > >I'm using kate here under KDE/linux. It has syntax highlighting for python, and >seems to deal with tabs nicely. >> >>>What these users are experiencing is that this portion of code is being >>>processed, and evaluating all if statements as true, however, as you can >>>see, they cannot all be true each time this function is called. Their >>>versions of python also ignore the else construct. >>> Their versions? Does that mean you are trying to run extensions or .pyc code with different version interpreters? That shouldn't work. Python source (.py) should work, unless an old interpreter runs into a new feature it doesn't know about. >>>Can anyone shed any light on what might be going on with these users? >>> >> I'd check on the globals and threading issues first. Then see about >> building a mousetrap. > >Why would these affect the interpretation of the if/else. Seems to me, >that if the if statement evaluates to true, then the else statement should be >ignored. However, it appears that for these users, python is just Sure, I didn't really believe what I was reading, I guess. Sorry. I thought the condition data was getting clobbered, not the condition machinery. >ploughing right on through, and running the else statement also. Or am I >missing something. What is a mousetrap? By mousetrap I meant some test code inserted to trap the problem mouse, metaphorically speaking. > >Any further help would be greatly appreciated. I guess version clash or some installation corruption looks most likely from here. Gotta go... Regards, Bengt Richter From bgailer at alum.rpi.edu Mon Jul 21 09:50:27 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 21 Jul 2003 07:50:27 -0600 Subject: ODBC to Oracle (data source name not found) In-Reply-To: <000601c34f88$88723b00$0500a8c0@MichaelVAIO> References: <5.2.1.1.0.20030721061538.01d49578@66.28.54.253> Message-ID: <5.2.1.1.0.20030721074926.029b3c50@66.28.54.253> At 06:03 AM 7/21/2003 -0700, Michael J. Moore wrote: >Oh great! Now what? > >Thanks for the info Bob. >Regards, >Mike Try cx_Oracle: http://www.computronix.com/utilities.shtml. Works for me. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From bokr at oz.net Thu Jul 24 00:18:39 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2003 04:18:39 GMT Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: On 24 Jul 2003 02:47:02 GMT, bokr at oz.net (Bengt Richter) wrote: >On Wed, 23 Jul 2003 16:40:00 -0600, Steven Taschuk wrote: > >>Quoth Bengt Richter: >> [borg vs singleton] >>> How about just >>> >>> import zerolengthfile as borginstancename >>> >>> and using it? E.g., [...] >> >>That would be fine in many cases, I'm sure. >> >>Modules don't do properties (or other descriptor magic), though. >> >Not insurmountable ;-) > >====< propmod.py >========================================== [...] >I thought it cute to make a property that is a kind of gateway to >the class attribute space, so that one can use the .properties attribute >of the propmod module to list, store, retrieve, and delete properties -- as well >as arbitrary class variables... Of course, propmod.__class__.xxx = yyy works as well as propmod.properties = 'xxx', yyy so it's kind of a silly exercise, but it does demo properties for a sharable "module." A much sparer approach: >>> import sys >>> sys.modules['simple'] = type('SimpleMod',(),{})() >>> import simple >>> simple.x = 123 >>> simple.__class__.hi = property(lambda self:'Hi ho') >>> simple.x 123 >>> simple.hi 'Hi ho' >>> file('impsimp.py','w').write('import simple as m\n') >>> import impsimp >>> impsimp.m.hi 'Hi ho' >>> impsimp.m.x 123 Regards, Bengt Richter From staschuk at telusplanet.net Wed Jul 16 22:01:40 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 20:01:40 -0600 Subject: Augmented Assignment question In-Reply-To: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com>; from dtolton@yahoo.com on Wed, Jul 16, 2003 at 06:13:51PM +0000 References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: <20030716200140.A656@tibia.amotlpaa.bogus> Quoth Doug Tolton: [...] > fnormal, ftruncated, fsemicolon = 0,0,0 > > // loop through a file and process all documents: > normal, truncated, semicolon = self.checkdoc(curdoc) > fnormal += normal > ftruncated += truncated > fsemicolon += semicolon > > This solution strikes me as inelegant and ugly. Is there a cleaner > way of accomplishing this? It seems possible that your normal, truncated and semicolon variables should be bundled into a single object: class DocumentStatistics(object): # ... def __iadd__(self, (deltanormal, deltatruncated, deltasemicolon)): self.normal += deltanormal self.truncated += deltatruncated self.semicolon += deltasemicolon Then you can just do docstats = DocumentStatistics() # ... docstats += self.checkdoc(curdoc) If these variables usually change in synch, this seems a natural way to organize them. You might also want to look into Numeric's arrays. (And there's always normal, truncated, semicolon = map(operator.add, (normal, truncated, semicolon), self.checkdoc(curdoc)) which I consider inferior to your straightforward approach with three augmented assignments.) -- Steven Taschuk staschuk at telusplanet.net "Please don't damage the horticulturalist." -- _Little Shop of Horrors_ (1960) From sjmachin at lexicon.net Wed Jul 23 08:28:04 2003 From: sjmachin at lexicon.net (John Machin) Date: 23 Jul 2003 05:28:04 -0700 Subject: lists and files question References: <3F1DCF52.7040607@hotmail.com> <3F1DF318.20308@hotmail.com> Message-ID: hokiegal99 wrote in message news:<3F1DF318.20308 at hotmail.com>... > "print fname" prints out the list of files in "setpath" w/o problem. How > does it do that if os.walk doesn't give it the path to the files? If you do open('x.txt') and your current directory is (say) /tmp, it will in effect be trying to open('/tmp/x.txt') which will presumably fail with the error that you saw because there's no such file ... hence Sean's advice to use os.path.join so that you are in effect doing open('/usr/hokiepokie/weird_files/x.txt') thus opening the file that you want and does exist -- unless of course some other process moved it or deleted it after the os.walk() and before the open() -- This is not a Python thingy nor a Linux thingy; implicitly assuming that a "short" filename is relative to the calling process's current directory/folder/group/whatever has been accepted behaviour with any hierarchical file system that I've ever seen. Now answering your question: fname contains (say) ['x.txt', 'foo.xls', 'bar.doc'] and root contains (say) '/usr/hokiepokie/weird_files'. So of course print fname manages to print ['x.txt', 'foo.xls', 'bar.doc'] without reference to root, just as zot = 42; print zot manages to print 42 without reference to root. > > Here's some output from "print fname": > > ['index.txt', 'CELL-MINUTES.xls', '.nautilus-metafile.xml'] ... large chunks of your life history snipped ... > Sheet.xls', 'application.pdf', 'budsum.pdf'] > > When I add os.path.join like this: > > setpath = raw_input("Enter the path: ") > for root, dirs, files in os.walk(setpath): > id = re.compile('Microsoft Excel Worksheet') > fname = files > print fname > content = open(os.path.join(root,fname[0]),'rb') > > I get a "IndexError: list index out of range" error. > > This is a Linux 2.4 computer running Python 2.3b2... if that matters. It's always good to tell the OS and Python version; however in this case it doesn't matter. Put your thinking cap on: "list index out of range" ... which list? what was the value of the index? ... "in range" means 0 <= index < length of list; which of those 2 constraints was violated? what does that tell you? From max at alcyone.com Tue Jul 1 22:22:12 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jul 2003 19:22:12 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: <3F0241D4.34010A5C@alcyone.com> Tom Plunket wrote: > I wouldn't mind creating a new class to wrap this up (that's what > I'd do in C++, and that class would have an operator() defined), > but I can't seem to discover how to make callable objects in > Python. The __call__ method is the equivalent of C++'s operator (). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Sometimes there's no point in giving up. \__/ Louis Wu From maxm at mxm.dk Sun Jul 6 15:51:04 2003 From: maxm at mxm.dk (Max M) Date: Sun, 06 Jul 2003 21:51:04 +0200 Subject: Search for mapping solution In-Reply-To: References: Message-ID: <3F087DA8.1000007@mxm.dk> Markus Joschko wrote: > Hi, > stated in a post befor, I'm a java programmer, fascinated about the elegant > way python solves iterations. Maybe you can show me a solution how to map > the following > > I have a List: > > Name - Number - Costs > > lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > > Now I want to have it in a dictionary(name,costs) Should look like > {'fred':'0,60' , 'sam':'1'} > > What's an elegant way to do it? I can use a lot of loops, but I assume, that > there is a better way of doing so. lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] costs = {} for name, items, price in lines: costs[name] = costs.setdefault(name, 0.0) + float(price.replace(',','.')) print costs >>> {'fred': 0.59999999999999998, 'sam': 1.0} regards Max M From http Sun Jul 20 21:11:03 2003 From: http (Paul Rubin) Date: 20 Jul 2003 18:11:03 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xllus94t8.fsf@ruckus.brouhaha.com> Message-ID: <7x1xwk8z14.fsf@ruckus.brouhaha.com> "Alan Dechert" writes: > Right. This receipt problem is way overblown. If we really thought this > was a big problem, absentee voting would be illegal. There are problems > with absentee voting but then look at Oregon -- they have gone to > vote-by-mail entirely. In fact absentee ballots are just about the favorite mechanism of ballot fraud. Absentee voting should be greatly curtailed if not banned outright. Instead, voters away from home should be allowed to cast their ballots at any official polling place they happen to be near, not just at the one in their home district. I have doubts about Oregon but its problems don't see nearly as bad as places like Florida (try Googling for "Xavier Suarez" and "fraud"). If they did mail-in voting in Florida, they would never get a reliable election result again. As for the receipt problem being overblown, IIRC, Benaloh's original paper described its motivation, citing examples of the Mafia telling people how to vote in Italian elections and demanding to see receipts. There would be similar problems in the US military from what I've heard. From ilyak at red.seas.upenn.edu Tue Jul 29 11:17:40 2003 From: ilyak at red.seas.upenn.edu (Ilya Knizhnik) Date: Tue, 29 Jul 2003 15:17:40 +0000 (UTC) Subject: PyQt Help and Advice Message-ID: Dear All, I am fairly new to Python. I have found it an easy language to learn and a very usefull one for many tasks. Currently I am working on a python project that involves a GUI and it was suggested that PyQt is the best way to design that GUI. However since PyQt is rather new, I have not found much documentation on it, or examples in it. The only useful tutorial/book I have found is at www.opendocspublishing.com/pyqt/ but it is not always clear for someone with almost no GUI experience. Does anyone have any suggestions? Ilya From mis6 at pitt.edu Mon Jul 21 09:33:12 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 21 Jul 2003 06:33:12 -0700 Subject: properties + types, implementing meta-class desciptors elegantly? References: <2259b0e2.0307190640.56266017@posting.google.com> <2259b0e2.0307200652.131ed45e@posting.google.com> Message-ID: <2259b0e2.0307210533.6fd22744@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Michele Simionato wrote: > > >"Mike C. Fletcher" wrote in message news:... > > > > > >As others before me, I am not sure of what you are trying to do > >and why you are doing so. I use descriptors in this way: > > > >class o(object): > > class p( object ): # descriptor class > > def __set__( self, client, value, *args, **named ): > > print '__set__', self, client, value, args, named > > self.v=value > > def __get__(self,obj,cls): > > return self.v > > v = p() > > > You are aware that you have just created a class-attribute, rather than > an instance attribute? The property/descriptor object exists within the > class 'o' namespace, not the instance namespace. Try creating two > instances of your o class and setting v on both of them. There is one > 'p' instance "self" to which you are assigning/retrieving an attribute > for all instances of o. Creating class variables is certainly a valid > use for descriptors, but I'm not sure if that's really what you were > trying to do. I have just copied your code, I thought you wanted a class attribute. It is is trivial to do the same for instance attributes: class o(object): class p( object ): # descriptor class def __set__( self, client, value, *args, **named ): print '__set__', self, client, value, args, named self.value=value def __get__(self,obj,cls): return self.value def __init__(self): self.v = self.p() I understand that you aware of this, but you don't like it. Still I do not understand why do you feel it to be ugly and/or inelegant. It seems to me quite idiomatic. > What I'm looking for, in terms of your code, is a method/function which > would do the proper thing instead of using "self.v=value", (or rather > client.__dict__['v'] = value (i.e. store the value in the client > dictionary)) for all of the major built-in types, such as > object-instances, classes (and object-instances with slots would be > nice). To the best of my knowledge, such a function does not exist > within Python; for instances, simply doing instance.__dict__[ key ] = > value is sufficient, but classes do not have a method exposed AFAIK > which allows an equivalent setting of a value *without* triggering the > descriptor machinery for the given key. Yes, I understand you want to be able to set class dictionaries just as object dictionaries, bypassing descriptors. Still, I am not sure if this would be a good idea. > I'm creating a slightly more involved pattern, by the way: > > class plugin( type ): > someHelperClass = common.ClassByNameProperty( > "someHelperClass", """Documentation for this meta-property""", > defaultValue = "some.package.module.ClassName", > setDefaultOnGet = 0, > ) > > class MyWorkingPlugIn( myBaseImplementation ): > __metaclass__ = plugin > > instance = MyWorkingPlugIn() > > Where the properties of the plugin meta-class are providing all sorts of > services for the MyWorkingPlugIn class, such as allowing it to find > "someHelperClass" related to the plug-in system while allowing that > property to be set manually if desired, or automatically calculating a > global identifier if the plug-in doesn't currently have a global > identifier. The value is primarily that the meta-class will use exactly > the same mechanisms as the rest of the system, and so will be readily > dealt with by the property-based meta-application system. > > There are certainly other ways to get around the particular problem (I > have already done that), I'm looking for the *elegant* solution to the > *general* case. > Elegance is in the eye of the beholder ;) > Enjoy, > Mike > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ Good luck with your project, Michele From shalehperry at comcast.net Mon Jul 7 23:05:17 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Mon, 7 Jul 2003 20:05:17 -0700 Subject: PyIrc module In-Reply-To: <20030707225250.7171.qmail@cs06.tgv.net> References: <20030707225250.7171.qmail@cs06.tgv.net> Message-ID: <200307072005.17077.shalehperry@comcast.net> On Monday 07 July 2003 15:52, sylvain HELLEGOUARCH wrote: > Hello everyone, > > This is my first message round here :) > > Well, my message is more or less an announcment of my pyirc module for > Python (uh uh surprise this is the right place :)). > > This module tries to implement both RFC 1459 and 2812 about IRC protocol. > I've decided to code my own module as Python has a lack of IRC ones. > Generally speaking, either they are not up-to-date anylonger or they are > written for a specific GUI. > not to downplay your work, but have you looked at Twisted? http://twistedmatrix.com/products/twisted From martin at v.loewis.de Sat Jul 5 04:07:47 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Jul 2003 10:07:47 +0200 Subject: sys.setedefaultencoding() References: Message-ID: "Batista, Facundo" writes: > Why? I *always* work with this type of enconding (I live in Argentina). What type of encoding is "this"? If you are using ISO-8859-1, and you want to print a Unicode string S to stdout, you should do this print S.encode("iso-8859-1") instead of trying this print S and hoping that the system default encoding will be ISO-8859-1. So you should always use implicit conversions, and never implicit ones, when it comes to encodings. Regards, Martin From tzot at sil-tec.gr Tue Jul 22 12:59:08 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 19:59:08 +0300 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: On Fri, 18 Jul 2003 20:25:20 +0100, rumours say that Alan Kennedy might have written: >It is also worth noting that your message and messages quoting it are >the only hits that turn up in a Google Groups search using the >original greek text as a search term: i.e. I go to Google Groups and >paste in the greek letters. If I may say it sideways, try searching for google for the french word "c?fe", as in "un c?fe s'il vous pla?t". Wanna bet my message will be the only one to be found? :) (I'd lose that bet. There would be two more posts, another one with the word incorrectly written --but it's excusable judging on the newsgroup name ;-) -- and one in swedish). The word you should be looking for is 'gignw/skw', not 'gi/gnwskw'. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=%CE%B3%CE%B9%CE%B3%CE%BD%CF%8E%CF%83%CE%BA%CF%89&btnG=Google+Search (one huge line) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From csad7 at yahoo.com Sun Jul 20 09:16:53 2003 From: csad7 at yahoo.com (christof hoeke) Date: Sun, 20 Jul 2003 15:16:53 +0200 Subject: Strings and Unicode References: Message-ID: - wrote: > I have a function that takes a string as an input parameter. This > function then urlencodes the string and sends it to a server with > telnetlib.Telnet > > The problem is that the string gets converted into what seems to be > Unicode. How can I check to see if the input-string is Unicode and > convert it to a different character set (in this case ISO-Latin1). to test if it is unicode simply check the type print type(string) converting seems to be working by using the encode function of unicode strings: isostring = unicodestring.encode('iso8859-1') i am not really experienced in python and its unicode processing but this worked at least partly for me chris From adalke at mindspring.com Sat Jul 19 18:53:17 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 19 Jul 2003 16:53:17 -0600 Subject: Strange (?) list comprehension behavior References: Message-ID: George Henry: > >>>[op for op in PSILex.ops if op.startswith("|| hello")] > > yields "AttributeError: 'int' object has no attribute 'startswith'," > however: > > >>>[type(op) for op in PSILex.ops] > > produces a list of objects, as would be expected. So, what is > op? Is it a string, an int, or something else? Can you copy&paste what you did, rather than interpret the output? There's no way to get both of these errors that I know, and I expect it to be more likely that you didn't see a somewhere in the output rather than a bug in Python. You can also try [type(op) for op in PSILex.ops if type(op) != type("")] Andrew dalke at dalkescientific.com From ady982 at ploiesti.astral.ro Mon Jul 7 06:47:00 2003 From: ady982 at ploiesti.astral.ro (Catalin) Date: Mon, 07 Jul 2003 13:47:00 +0300 Subject: Python vs PHP Message-ID: <3F094FA4.9030800@ploiesti.astral.ro> Can Python replace PHP? Can I use a python program to make an interface to a mysql 4.X database? If that's possible where can I find a tutorial? From corey.coughlin at attbi.com Tue Jul 8 14:50:56 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 8 Jul 2003 11:50:56 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: You know, I couldn't even figure out what the whole ':=' assignment did until I saw this message: bokr at oz.net (Bengt Richter) wrote in message > I don't know that I would totally dismiss the usage. It could be > a concise notation for a possibly polymorphic update operation. > > w = Widget(blah, blah) > w := ('blue','white') # changes fg/bg colors > w := (20,40) # changes position > w := Font('Times Roman', size=24) > w := 'some text appended to a text widget' > > Of course, you could use a property very similarly, e.g., > w.p = 'text ...' > > I guess it's a matter of what kind of sugar you like ;-) > So what we're talking about here is some form of type driven assignment? Where you can assign to properties of an object given a specific type of rhs expression? I guess that could be useful, but it sounds like it could only apply to a very small set of objects, namely objects where all the properties have different types. It seems like adding a new syntax to support a fairly small subset of objects is a long way to go to make things 'easier'. It looks like it would be easy to screw up, too. For instance: class Point(object): def __init__(self, nx, ny): self.x = nx self.y = ny def __typeassign__(self, whatever): # some magic # a = Point(3,4) # so far so good a := (3,4) # ok, that could work a := 3 # hmm... will it set x, or y, or x and y, or give an exception? or, let's go with the currency example: class Currency(object): def __init__(self, cval): self.amount = cval self.exchangerate = 1.0 def __typeassign__(self, whatever): #even better magic # a = Currency(7) a := 6 # so does this change the amount, or the exchange rate? So it looks like the behavior here would be at best unpredictable, unless you already have a deep understanding of what's going on in the object. (And if you have a deep understanding of what's going on in the object, would 'a.amount' be so tricky to use?) Now sure, there are lots of operations that aren't used by every object, but assigning values to object attributes is a pretty fundamental part of any object oriented language, and the way Python does it now seems to work for a lot of people. From the original example, it looks kind of like you want to define a sort of user-definable built in type, like integer or string, where there is always a singular piece of data that may have special functional attributes but no other data attributes. But in that case, you wouldn't want to assign it as a regular object, you'd want to build in a special syntax that Python could use to understand the built in type, so you would have to have: a = $7 a = $6 so I guess even that wouldn't work quite the way you want. So for now, I vote no to adding ':=' assignment. Sorry if this is too basic a look at this, it takes me a while to wrap my head around this complicated syntax stuff. From tim at remove_if_not_spam.digitig.co.uk Wed Jul 16 18:42:22 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Wed, 16 Jul 2003 23:42:22 +0100 Subject: Numarray for Python 2.3 References: <3F15A829.9090200@sympatico.ca> Message-ID: <05lbhvki5vlpfb8d349dsn8e3hbb2bmfuu@4ax.com> On Wed, 16 Jul 2003 15:31:53 -0400, "Colin J. Williams" wrote: >No, not the last time I tried. It seems that Python 2.3 looks for a >different .dll structure than python 2.2. Thanks. I don't need it just at the moment, but I was planning to learn it during quiet moments. I can wait. From nsmith at ilangua.com Mon Jul 28 10:06:32 2003 From: nsmith at ilangua.com (Neil Smith) Date: Mon, 28 Jul 2003 15:06:32 +0100 Subject: ANN: Python on ecademy Message-ID: <3F252DE8.3090106@ilangua.com> For those interested in promoting Python's use in the commercial world: I've been using Python in my businesses for nearly 10 years. Recently I also came across ecademy, an online business networking tool (in the human network rather than electronic network sense). ecademy is gaining traction and helping people realise business opportunities. With a view to using the network potential of ecademy for the greater promotion of Python in Business I have created a 'club' within ecademy. If you have an interest in the use and promotion of Python in business then I invite you to join ecademy and join the club (there is no charge). The aim is to raise awareness of opportunities and then network to find the catalyst that can turn an idea into reality. I envisage that the club and its members will be working together to influence the decision makers that also form part of the ecademy business network. This will be very much the guerilla marketing that complements the formal work carried out by the Python Business Forum and other like-minded organisations. If you feel you can contribute, or benefit from this effort, please use this link to join ecademy: http://www.ecademy.com/account.php?op=signup&xref=30738 The 'Python for Business' club can then be accessed through: http://www.ecademy.com/module.php?mod=club&op=page&c=618&xref=30738 Be aware that ecademy is not a mailing list, it is a mechanism for actively e-meeting business people to make things happen. Neil Smith From adalke at mindspring.com Tue Jul 22 18:11:07 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 22 Jul 2003 16:11:07 -0600 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: Alan Dechert: > catch it. If one percent of the electronic votes were altered (evenly > distributed), you will find one mismatch for sure after checking only a > dozen or two ballots. Actually, around 70 ballots. The odds of finding one ballot to be wrong is 1%, so there's a 99% chance that it's unaltered. There's a 0.99*0.99 chance that two are unaltered, and in general a 0.99**n chance that n are unaltered. To get even odds of noticing an error requires 0.99**n == 0.5 --> log(0.99)*n == log(0.5) >>> math.log(0.5) / math.log(0.99) 68.967563936528421 >>> about 70 verifications. Andrew dalke at dalkescientific.com From faizan at jaredweb.com Mon Jul 28 14:02:47 2003 From: faizan at jaredweb.com (Fazer) Date: 28 Jul 2003 11:02:47 -0700 Subject: Python vs. Perl vs. PHP? Message-ID: <7b454334.0307281002.41dae81b@posting.google.com> Hello, I am an avid user of PHP and I am just fooling around with Python for now. I originally wanted to know which one is faster. As in, works faster. So far, I think PHP is the fastest for dynamic web-content. Am I wrong? From peter at engcorp.com Wed Jul 9 05:57:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 05:57:30 -0400 Subject: Executables under Win32 References: <5vkngvs2epq6rv0a3rodeb839k5ls8bafj@4ax.com> Message-ID: <3F0BE70A.165B5274@engcorp.com> Fuzzyman wrote: > > IS there a tool to make Python Executables (binaries) under Win32... > or must people have a distribution of Python to use any scripts I > write ? > > I don't need to hide my source code - but would liek to make it easy > for a newbie to use my scripts. (Excellently asked question! We get this one often, but rarely so clearly. :-) There is py2exe and the Macmillan Installer, as well as some lesser known alternatives. py2exe runs on Windows only, the other on Windows and Linux (at least). A quick Google for either should get you there... -Peter From akineko at pacbell.net Wed Jul 9 15:46:45 2003 From: akineko at pacbell.net (Aki Niimura) Date: 9 Jul 2003 12:46:45 -0700 Subject: Python and freeze (something odd) Message-ID: Hello Everyone, I feel sorry to bother you guys as I posted another yesterday, too. Finally my script which accesses a web site from a Python script is functioning fully. It works very nicely (upload / download / does operations). Now I'm trying to "freeze" my script to a single executable file under Solaris using freeze. I have done such many times and it worked magically (until now). However, maybe I'm out of luck. When I started the generated executable, I got the following: Traceback (most recent call last): File "websc.py", line 284, in ? File "websc.py", line 276, in main File "websc.py", line 125, in upload_files File "websc_upload.py", line 173, in httprequest File "/usr/local/lib/python2.2/email/Message.py", line 113, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/local/lib/python2.2/email/Generator.py", line 103, in flatten self._write(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 131, in _write self._dispatch(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 157, in _dispatch meth(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 231, in _handle_multipart g.flatten(part, unixfrom=False) File "/usr/local/lib/python2.2/email/Generator.py", line 103, in flatten self._write(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 138, in _write self._write_headers(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 172, in _write_headers elif _is8bitstring(v): File "/usr/local/lib/python2.2/email/Generator.py", line 44, in _is8bitstring unicode(s, 'us-ascii') LookupError: unknown encoding: us-ascii // As I mentioned earlier, it works fine if it is invoked from .py files. Also, I created a simple test program which just does unicode(s, 'us-ascii'). The frozen version of such test program works without a hitch. Guido mentioned in a document for 'freeze' saying: "... It may still be confused -- it will not know about calls to the __import__ built-in function, ..." I guess my program confused 'freeze' as unicode is a built-in function. However, he didn't offer any further information. Any thoughts, any suggestions? Thanks in advance. Best regards, Aki Niimura (This is a repost as my previous posting seemed ignored) From skip at pobox.com Wed Jul 9 15:21:41 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 9 Jul 2003 14:21:41 -0500 Subject: check if dir exists In-Reply-To: References: Message-ID: <16140.27461.265158.768237@montanaro.dyndns.org> Geiregat> How can I check if a dir exists ? >>> import os >>> print os.path.isdir("/tmp") True >>> print os.path.isdir("/foo") False Skip From scook at elp.rr.com Wed Jul 2 22:51:17 2003 From: scook at elp.rr.com (Stan Cook) Date: Thu, 03 Jul 2003 02:51:17 GMT Subject: Date issue Win98 vs NT References: Message-ID: Thanks!! You were right on with that one. I've been working on the program at home and work. At work with NT and 98 at home. I changed all of the gmtime references to localtime and everything came out correct. Thanks again.... Stan "Christos TZOTZIOY Georgiou" wrote in message news:cb85gvgtf2657aon58qu4p3qorvfpbi79v at 4ax.com... > On Wed, 02 Jul 2003 03:50:10 GMT, rumours say that "Stan Cook" > might have written: > > >Has anyone else had this or a similar problem and is there a workaround? > > >This piece of code: > > >from time import gmtime, strftime > >_log = _log + "\\" + strftime("%m%d%y", gmtime()) + ".log" > > >produces a file with the name 'today's date.log' on NT, but creates a file > >called 'tomorrow's date.log' on Windows 98. I would really like to know > >why this happens. Any help offered is very much appreciated. > > Are you by any chance in Austin, Texas? > > I could guess that first you tried this code in Windows NT, and later > rebooted to Windows 98. Running your code on Windows 98 happened after > 6pm, your local time. > > By that time, I think it is already tomorrow in Greenwich, England > (which is what gmtime provides). Try localtime instead (assuming your > timezone is set correctly both in NT and 98). > -- > TZOTZIOY, I speak England very best, > Microsoft Security Alert: the Matrix began as open source. From viffer750 at hotmail.com Mon Jul 21 08:17:17 2003 From: viffer750 at hotmail.com (BDM) Date: Mon, 21 Jul 2003 08:17:17 -0400 Subject: Calling python from asp References: <3f17dc2c@cpns1.saic.com> Message-ID: <3f1b7758@cpns1.saic.com> I thought about that one too. I checked, and "Everyone" has access to site-packages and the folders below it. Is there any sort of library path setting I need for Python to work with ASP under Win2000? "Ulrich Petri" wrote in message news:bfa6uk$cdshr$1 at ID-67890.news.uni-berlin.de... > "BDM" schrieb im Newsbeitrag > news:3f17dc2c at cpns1.saic.com... > > Greetings, > > I'm having a difficult time calling a python module from within ASP. I > have > > narrowed the problem down the very beginning of my code, where I'm > > attempting to import a method. Below is a snippet of the code > > > > import sys > > print 'Imported Sys' > > from pscape.xml.handler import pscape_xml_parser > > print 'Imported XML Parser' > > > > The import sys statement works fine. The import of pscape_xml_parser is > > failing. pscape.xml.handler is within my site-packages directory. I have > > checked python's sys.path from within ASP, and > > c:\python22\lib\site-packages is in the path. This code runs fine when > > executed from within the python interpreter, but not when called from ASP. > > > > Any idea what I'm doing wrong here? I'm sure it must be something very > > simple. I'm running this under Windows2000 Server, IIS5.0, Python 2.2.2, > > and win32all-150. > > perhaps the webservers user (Normaly IUSR_......) has no rights to access > the files within site-packages? > > Ciao Ulrich > > From jjl at pobox.com Sat Jul 26 20:40:03 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 01:40:03 +0100 Subject: code coverage tool with emacs integration? Message-ID: <87u198ree4.fsf@pobox.com> Anybody know of one? Actually, I have a feeling that emacs understands a standard format for errors, which would make it really easy to implement this by having the coverage tool print results in that format -- anybody know where to find the details? I also wonder if some kind of graphical display might be useful somehow, having been inspired by this: http://kcachegrind.sourceforge.net/ (really, I just like the pretty pictures :) John From jfromm at jasc.com Wed Jul 2 09:04:12 2003 From: jfromm at jasc.com (Joe Fromm) Date: Wed, 2 Jul 2003 08:04:12 -0500 Subject: How to keep a Tkinter-Dialog on top of all other windows? References: <4b66f6d2.0307020435.345ff4f1@posting.google.com> Message-ID: <3f02d84a$0$43850$39cecf19@news.twtelecom.net> "Thomas N?cker" wrote in message news:4b66f6d2.0307020435.345ff4f1 at posting.google.com... > Hi! > > I am creating a dialog-box within my application, using tkinter. The > problem is the following: After the dialogbox is started, the main > application window comes again to top and the dialogbox is covered by > the window of the main application and must be "fetched" again via the > taskbar to continue. Is there a way to "force" the dialogbox on top of > all other windows? (I'm using MSWindows and Python22) > I had a similar problem using Python/tkinter embedded in a Win32 app, and never found a truly satisfactory solution. The best I was able to do was have the tk window call into my app, passing its window handle (which you can get via winfo_id()). In my app I have a timer running - as long as that window exists it will keep calling SetWindowPos with the HWND_TOP flag to move the Tk window on top of all the app windows. When given the Tk window handle you need to hunt up through it's parents until you find a window with no parent, and call SetWindowPos on that window. If the window being watched no longer exists I just kill the timer and clear the window handle. I'd love to find a solution that isn't such a grotesque hack. Joe Fromm From harry.g.george at boeing.com Thu Jul 10 10:07:32 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 10 Jul 2003 14:07:32 GMT Subject: Getting Started with python References: <3f0d2cb9$1@news.comindico.com.au> Message-ID: "Tony Steward" writes: > Hello All, > Ok i've decided to try Python can anyone point me at a simple demo of a > windows program operating a database (maybe an address book) so I can see > how it is done. > > Thanks in advance > Tony > > I'll assume you already know DBMS programming (and SQL syntax) from other contexts, so the problem is to learn "how do I do this in Python?" You probably want to start here: http://www.python.org/topics/database/ Notice the "DB-API spec 2.0". That is the generic interface. You write code to that API, and then use various databases (on various platforms) underneath. Next, see: http://www.python.org/topics/database/modules.html Notice that each DBMS binding has its own nuances, with its own documentation. The nuances tend to be in establishing the initial connection, and in the treatment of quotes in SQL statements. That is, they are all more or less compliant with the DBI-API. Finally, I haven't done work specifically on Windows databases, but if you are familiar with ODBC you might try: http://www.egenix.com/files/python/mxODBC.html -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From mwilson at the-wire.com Tue Jul 15 11:59:05 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 15 Jul 2003 11:59:05 -0400 Subject: Securing the Pyton Interpreter? References: Message-ID: In article , Stephen VanDahm wrote: >I'm looking for a way to install Python on a UNIX machine in a way such >that any user on the system can use it, but only to execute scripts that >are located in a certain directory. I do not have root access on the >machine that will be running Python, so my options are limited. I thought >about hacking the Python interpreter itself so that it will examine the >argument array and exit with an error if the script to be executed isn't >in the appropriate directory, but this seems pretty risky. The module >'site.py' is imported automatically upon initialization -- I've thought of >adding the check there instead. I don't think either of these solutions >are very elegant. Is there a better way? I would say, write a program that checks the directory, then invokes python if it likes what it sees. Make it suid as the owner of the installed python to keep people from sneaking around it. A shell script might be possible, but I seem to recall there are complications with suid on scripts .. though I don't recall what they are. This won't work if there's then a permission conflict with the data the programs are supposed to work on. Regards. Mel. From chris.gonnerman at newcenturycomputers.net Wed Jul 16 23:43:16 2003 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 16 Jul 2003 22:43:16 -0500 Subject: Distutils help needed (suggestions anyway) Message-ID: <000d01c34c15$8e87e240$2100000a@house> A user contacted me a week or so ago about problems building the new gdmodule version. A moment's study revealed the problem... the GD include file gd_io.h contains a structure which has changed somewhere between GD 2.0.1 and 2.0.8. In the earlier versions, the gdIOCtx structure had a member: void (*free)(struct gdIOCtx *); but in the newer versions the name of the member is gd_free. Ideally I'd like the setup.py script to detect and adapt to this; but before I go and invent an all-new wheel I thought I'd see if there is an existing solution for this sort of distribution problem. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jdhunter at ace.bsd.uchicago.edu Tue Jul 29 11:31:51 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 29 Jul 2003 10:31:51 -0500 Subject: pretty printing graphs In-Reply-To: (bokr@oz.net's message of "29 Jul 2003 04:30:02 GMT") References: Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> should be -- def showInPage(self, pageHeight=6*11, Bengt> pageWidth=78): return '\n'.join(self.boxlines(pageHeight, Bengt> pageWidth)) -- [...] I think I may have discovered another bug. In the longish example below, the children of n2 are n20 and n21 n2.children.extend([n20, n21]) These children are the branch: |------------------+ +-------+ +-------+ |3 4 5 6| |6 4 5 6| |3 4 5 6| |-------| |-------| |1 1 1 1| |1 1 1 1| +-------+ +-------+ However, if you run your pprint on this example, they appear below the n4 branch. Haven't had a chance to grok the code yet -- I just came across this bug when using your code on a test case for a projective clustering neural network algorithm I'm implementing. The example is from Cao and Wu, Neural Networks 15(2002) 105-120. http://www.sciencedirect.com/science?_ob=ArticleURL&_udi=B6T08-43T2MC4-1&_user=5745&_handle=W-WA-A-A-AD-MsSAYZA-UUW-AUCEZCZEBD-AZZEEDDUV-AD-U&_fmt=full&_coverDate=01%2F31%2F2002&_rdoc=10&_orig=browse&_srch=%23toc%234856%232002%23999849998%23290257!&_cdi=4856&view=c&_acct=C000001358&_version=1&_urlVersion=0&_userid=5745&md5=61f59ff40e082d56154538b436b0010e def test3(): n = Node(TextBox("""1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 6 7 8 9 1 2 3 4 3 4 5 6 2 3 4 5 6 4 5 6 4 2 3 1 6 7 1 2 4 5 6 7 ------- 0 0 0 0 """)) n0 = Node(TextBox("""1 2 3 4 1 2 3 4 4 2 3 1 ------- 0 1 1 0 """)) n1 = Node(TextBox("""2 3 4 5 2 3 4 5 ------- 1 1 1 1 """)) n2 = Node(TextBox("""3 4 5 6 3 4 5 6 6 4 5 6 ------- 0 1 1 1 """)) n3 = Node(TextBox("""4 5 6 7 4 5 6 7 ------- 1 1 1 1 """)) n4 = Node(TextBox("""6 7 8 9 6 7 1 2 ------- 1 1 0 0 """)) n.children.extend([n0, n1, n2, n3, n4]) n00 = Node(TextBox("""1 2 3 4 1 2 3 4 ------- 1 1 1 1 """)) n01 = Node(TextBox("""4 2 3 1 ------- 1 1 1 1 """)) n0.children.extend([n00, n01]) n20 = Node(TextBox("""3 4 5 6 3 4 5 6 ------- 1 1 1 1 """)) n21 = Node(TextBox("""6 4 5 6 ------- 1 1 1 1 """)) n2.children.extend([n20, n21]) n40 = Node(TextBox("""6 7 8 9 ------- 1 1 1 1 """)) n41 = Node(TextBox("""6 7 1 2 ------- 1 1 1 1 """)) n4.children.extend([n40, n41]) print n From newsgroups at jhrothjr.com Thu Jul 31 17:25:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 17:25:42 -0400 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> <87el06d2i6.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:87el06d2i6.fsf at pobox.com... > "John Roth" writes: > [...] > > That said, I've come to the conclusion that the editor should take > > care of these things for you. If you prefer a brace free notation, > > you should be able to tell your editor to present the program to you > > that way. If you prefer braces, then it should be able do that for > > you as well. That kind of stylistic thing doesn't belong in the > > language. > > 100% agreed: once-and-only-once dictates this. Manually maintaining > both braces and indentation (as in C, with some editors) is Just Plain > Bad for this reason. > > > > In fact, if I didn't have to deal with the braces, I think I'd come > > around to the view that the text should have them. Explicit is > > better than implicit, > > At least in the absence of proper research results, I think this part > of it *is* religious. To some people, it's obvious that whitespace is > better on the eyes. To others, it's obvious that whitespace + braces > is better on the eyes. One group may well be wrong <0.5 wink>. > > This argument (that braces are another visual cue which make code > easier to read -- provided that they're automatically maintained in > sync with the indentation), is the only argument against > pure-whitespace that has ever made any sense to me. I believe there was quite a bit of research on this issue in ABC, which was the research system that Guido learned on when he was in university. One of the fallouts from that is the colon at the end of block headers: it's syntactically unnecessary, but it does seem to help the eyes. I wouldn't characterize it as religious. Brains don't work the way most people think they do, and if you've programmed yours one way, it seems to depend on a proper choice of grandparents, or the proper diet, or maybe the phase of the moon whether you'll be comfortable changing it. > Irrespective of > whether you pick whitespace or braces as the thing the compiler takes > notice of, though, the optimal solution probably still involves an > editor that supports showing/hiding braces, so the syntax is > (theoretically!) a non-issue. In practice, editors don't seem to > currently support showing and hiding braces automatically. At least > editors do get you out of most mistakes caused by brace-y languages. > > Of course, whitespace *is* still superior because the storage format > doesn't duplicate state -- so people with poor editors can't produce > ambiguous code :-) (remember code can be ambiguous to *people* even if > it isn't to a compiler). OTOH, *Python's* scheme is inferior to a > pure-space-character indentation scheme because off the tab-vs.-space > issue :-( Well, that's been recognized as a problem for a long time. I believe that the intention is to mandate spaces only in Python 3.0. On the other hand, I'm not holding my breath waiting for Guido to decide he's had enough 2.x releases and start work on 3.0 To be frank about it, I don't see a crying need for 2.4 before 3.0, and if he's after mind share, he's got both Ruby and the redesign of Perl breathing down his neck. The new Perl regex package looks nice! Three years ago, he didn't have any credible competition in the high quality but easy to use scripting language arena. Now he does. > > and there are a few things that the > > automatic indentation makes rather difficult in the design area. > [...] > > What are those things?? Embedding Python in other languages, such as HTML, for starters. It can be done, but it isn't pretty. I've run across a couple of other places where I wished I had braces, but they weren't important enough to stick in my memory. John Roth > > > John From donn at drizzle.com Sun Jul 13 15:24:14 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 13 Jul 2003 19:24:14 -0000 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <1058124253.668436@yasure> Quoth Stephen Horne : | On 13 Jul 2003 12:19:08 -0400, aahz at pythoncraft.com (Aahz) wrote: | |> Whether one can mutate a specific object is simply an |> attribute of that object, rather than requiring a different syntax. |> Trying to focus on the mutable/immutable distinction is what causes the |> mental blowup -- keep your eye on the objects and bindings and you're |> fine. | | That's exactly it - you have to focus on whether an object is mutable | or immutable for that exact reason. | | While I admit I'm not sure, I believe that in early versions of Python | immutable values literally were copied. Mutable types were made | mutable because of efficiency concerns about copying overheads that | would occur otherwise. If an object is large enough that it is | worthwhile modifying items within it in-place then it tends to be | worthwhile trying to avoid copying overheads, even though these two | aspects of 'mutability' are actually quite distinct in principle. Sure, mutable values literally are copied today. If you have a tuple of time.localtime(x), for example, and you want that value but with tm_mday incremented, then you must copy the tuple to do that (except for tm_mday, for which you substitute your own value.) It is indeed inefficient - OK for this purpose but not for large sequences, and there we tend to prefer a mutable list. That's the efficiency argument. Assigment never copied values, in any version of Python that anyone cared about. We just don't want big immutable arrays that have to be copied just to change a single value. There isn't a tuple analogue for the dictionary because it wouldn't be so generally useful (the recently implemented struct tuple would have been nice to have earlier, though.) He's quite right, the notion of mutability is a red herring. It isn't that no one cares - the propagation of state changes in a program is critical to the operation of the program, and to reasoning about how the program will operate. It's just that when you're trying to come to grips with how assignment and argument passing works in Python, you don't want to have people start explaining things in these terms (``see, this object is mutable and that one isn't''), because you will understandably but incorrectly apply that to assignment and argument passing. Mutability in Python has no effect on assignment and argument passing, it is just an attribute of the passed or assigned object. Donn Cave, donn at drizzle.com From Robert at AbilitySys.com Tue Jul 15 00:01:06 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Mon, 14 Jul 2003 21:01:06 -0700 Subject: Stop Python from exiting upon error in Windows References: <3F136BEA.5B56562@engcorp.com> Message-ID: Thanks! I'm getting closer to what I want, but it raises two questions: 1. Is there an IDLE keystroke to indent a block of code? (just putting try: at the start of my program causes an error, expecting an indented block to follow which is my entire program!) 2. Is there a way to tell the environment I'm running under (python interpreter, IDLE window, or other)? I'd like to put a pause at the end of my program if and only if I'm running under the python.exe DOS-like program... - Robert "Peter Hansen" wrote in message news:3F136BEA.5B56562 at engcorp.com... > Tom Plunket wrote: > > > > Or- catch the error in your mainline, and do a sys.raw_input() > > call on exception. > > Tom meant just "raw_input()", which is a builtin, rather than > sys.raw_input which does not exist, of course. > > To answer your question in the other reply, yes, you can > nest exceptions. If you have a try/except and the raw_input > in the except, however, you won't see any exception traceback > printed at the console so you'll need something like the > traceback module and one of the functions from it, like > traceback.print_exc(). > > -Peter From imbosol at aerojockey.com Sun Jul 27 22:22:59 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Mon, 28 Jul 2003 02:22:59 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> Message-ID: <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Paul Rubin wrote: > I needed this for something I was doing just now. It came out pretty > enough that I thought I'd post it. It's like xrange, except for floating > point values. > > def frange(start, stop, step=1.0): > sign = cmp(0, step) > while cmp(start, stop) == sign: > yield start > start += step It's a nice little iterator. Three problems, though: 1. It can accumulate rounding errors 2. It can return an integer on the first iteration (minor) 3. The last iteration might not happen because of floating point uncertainties, even if rounding errors are minimized A more robust version would look something like this (but it still has problem #3): def frange(start, stop, step=1.0): sign = cmp(0,step) for i in xrange(sys.maxint): v = start+i*step if cmp(v,stop) != sign: break yield v The most robust way to handle this is to iterpolate, i.e., instead of passing start, stop, and step, pass start, stop, and n_intervals: def interiter(start, stop, n_intervals): diff = stop - start for i in xrange(n_intervals+1): yield start + (i*diff)/n_intervals An IEEE 754 (whatever) geek can probably point out even more accurate ways to do these. -- CARL BANKS From mday at apple.com Wed Jul 30 20:42:54 2003 From: mday at apple.com (Mark Day) Date: Wed, 30 Jul 2003 17:42:54 -0700 Subject: reading in lines from a file -FAST! References: Message-ID: <300720031742549961%mday@apple.com> In article , Rajarshi Guha wrote: > Hi > I have a file containing 168092 lines (each line a single word) and when > I use > > for line in f: > s = s + line > > it takes for ages to read it all in - so long in fact that it makes the > program unusable. Is there any way to do something like C's fread in > Python so that I can just slurp in 1.7MB of data at one go, rather than > reading line by line? How about: s = f.read() (assuming f is a file object) -Mark From peter at engcorp.com Thu Jul 17 11:06:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jul 2003 11:06:17 -0400 Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: <3F16BB69.660AEDC3@engcorp.com> thewrights at ozemail.com.au wrote: > > From the python grammar: > > funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite > > I want the statements in to be executed on a statement by statement > basis, with no particular restrictions on *what* those statements are. It's > the execution stepping I'm interested in... the I/O in my example was just > that. I understand that there will be all the problems on contention/race > etc (just like if the functions were going in separate threads) Okay, that's clear. It can't be done. :-) Now on to the next step: what are you actually trying to do. That is, *why* do you want the behaviour you say you want? That might give us a few ideas about what can really be done. Basically, what you describe would require the interpretation of Python at a higher level than it is interpreted now. It is actually *compiled* code, turned from source (the lines you refer to) into bytecodes, which are effectively machine code for the Python virtual machine. It is at the level of bytecodes that one might actually start to get the control you're talking about. Another approach would be if you reduced the problem from arbitrary statements to some kind of subset. Maybe evaluation of expressions only, without loops or most statements? Of course, that might be far too limited for you, but you haven't said why you want to do this yet. If you could take that approach, you would basically retrieve the source line by line and pass it to "exec" or maybe eval(). You could also just define your own mini-language, and write an interpreter for that which has the behaviour you need. Or, depending again on why you want all this, you could require construction of the code using generators or something, as others are suggesting. -Peter From amk at amk.ca Wed Jul 9 16:17:19 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 09 Jul 2003 15:17:19 -0500 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: On 09 Jul 2003 12:34:46 -0500, Ian Bicking wrote: > One of the big problems I also had was installation. Many of the > frameworks require non-trivial Apache configuration, which hinders > experimentation. Actually solving this is significant work, though -- > but also something which very much deserves solving. Why? The purpose is to let users compare the structure of applications, not benchmarking. I envision users browsing the code for each framework, never running anything until they've selected a framework and begun implementing an application. Solving web server configuration problems is out of scope. --amk From tracer at axiomfire.com Mon Jul 28 14:41:42 2003 From: tracer at axiomfire.com (Tracy Ruggles) Date: 28 Jul 2003 11:41:42 -0700 Subject: Fastest way to count your iterations? Message-ID: If you're writing a simple script and you want to give an update of its progress... Is this the fastest way to do it (assuming that what you're iterating through is very, very long and the time to process each item is relatively short)... def counter(items, f, sep=1000): i = 0 for item in items: f(item) i += 1 if i % sep == 0: print i [ is the modulus operator the quickest way to find out if you're really at the 1000th item? ] --T From dkuhlman at rexx.com Fri Jul 18 20:17:28 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 18 Jul 2003 17:17:28 -0700 Subject: Documentation examples needed References: <2259b0e2.0307170455.31ae2e11@posting.google.com> Message-ID: Michele Simionato wrote: > "Stuart D. Gathman" wrote in message > news:... >> I am still wanting to produce Python standard format >> documentation for >> Python extensions I have written. I have looked at the docs that >> come with Python itself, but I am new to Latex, and don't know >> how to add the document classes and styles from texinput for a >> new project. >> >> Is there a small project with documentation in the Python >> standard that I can use as an example? > > Dave Kuhlman reported on the docutils mailing list that it was > working on a docutils writer to produce standard Python > documentation. > > http://www.rexx.com/~dkuhlman/#docutilsdocpy Right. This extension to Docutils makes it easy to generate LaTeX files for input to the Python LaTeX documentation system. This method enables you to write reStructuredText (reST) documents, which have *minimal* mark-up, then translate them into LaTeX documents. Use this and you may be able to avoid learning LaTeX, which might *not* be a good thing. Also be aware, that this method lacks features that are supported by LaTeX mark-up described in "Documenting Python". Here are updated links: http://www.rexx.com/~dkuhlman/#docutils_pythonlatex http://www.rexx.com/~dkuhlman/rstpythonlatex_intro.html http://www.rexx.com/~dkuhlman/rstpythonlatex-1.0b.zip I've also written a document about how to set yourself up for processing documents with the Python LaTeX documentation system and the above mentioned reST-to-Python-LaTeX translator.. You can find it here: http://www.rexx.com/~dkuhlman/#pythonlatexsetup http://www.rexx.com/~dkuhlman/pythonlatexsetup.html http://www.rexx.com/~dkuhlman/pythonlatexsetup.zip Comments are welcome. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From mpeuser at web.de Tue Jul 22 04:46:03 2003 From: mpeuser at web.de (Michael Peuser) Date: Tue, 22 Jul 2003 10:46:03 +0200 Subject: Spinning OpenGL.Tk graphics Message-ID: Python's OpenGL.Tk binding makes simple 3D drawing a snap! The default mouse keys for panning and sizing is left and right, for rotation it seems to be the middle key which is on just very few people's mouse nowadays. Of course I tried obvious and not so obvious shift/alt/contrl/mouse combinations- without any success. Is there a work-around? The docu for the binding is somewhat obscure and one has to guess a lot ;-) I haven't figured out yet how to use AutoSpin .... I am using Windows2000 Thanks for suggestions and may be hints to more detailed documentation. Michael From _NOSPAM_nabugoon at moor.pe.kr_NOSPAM_ Wed Jul 30 11:36:16 2003 From: _NOSPAM_nabugoon at moor.pe.kr_NOSPAM_ (nabugoon) Date: Thu, 31 Jul 2003 00:36:16 +0900 Subject: gnome applet with python Message-ID: Hi all. I'm trying to write gnome applet program with python. But, it is too difficult to find any document about that. One web page I had found was old. (http://www.onlamp.com/pub/a/python/2000/07/25/gnome_applet.html?page=2) There is no AppletWidget attribute anymore and 'Gtk' prefix at gtk module functions Please let me know some sample code or website about that. TIA. From jzgoda at gazeta.usun.pl Wed Jul 23 16:29:32 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 23 Jul 2003 20:29:32 +0000 (UTC) Subject: Design tool References: <3f1e985d$0$236@hades.is.co.za> Message-ID: max pisze: >> Personally, I use Dia: >> http://www.lysator.liu.se/~alla/dia/ >> >> Some people use argo (which I find slow). > > .. but work on windoze... All work on Windows (ArgoUML is Java application). -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From gh at ghaering.de Wed Jul 23 10:56:16 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Jul 2003 16:56:16 +0200 Subject: How to link a C extension module on Mac OS X? In-Reply-To: References: Message-ID: <3F1EA210.7050900@ghaering.de> Fortepianissimo wrote: > Just started learning how to write a C extension module on Mac OS X. > Here is a simple module taken from Programming Python: [...] > ld: Undefined symbols: > _PyArg_Parse > _Py_BuildValue > _Py_InitModule4 > /usr/bin/libtool: internal link edit command failed > > This is Mac OS X 10.2.6 with latest Fink installed. I guess the fetal > one is the ld reporting undefined symbols. Any tip? Thx. Two words: Use distutils. -- Gerhard From jacek at jacek Thu Jul 17 08:51:13 2003 From: jacek at jacek (=?iso-8859-2?Q?Jacek_Potrymaj=B3o?=) Date: Thu, 17 Jul 2003 14:51:13 +0200 Subject: python.dll Message-ID: <3f169c26$1@newspilot.put.poznan.pl> Hi, I have a question about python installing. I try to install program which require Python 2.2. I installed this version of python software, but when I try to install software which use Python I have an error - incorrect version of python.dll is installed. I'm not a python specialist but I have to use it for this program. Answer me please if I have to set some environment variables for use python? I have windows XP version. I will be gratefull for help. regards Jacek Potrymaj?o From akaihola at ambi-no-spam-to-tone.com Mon Jul 28 06:41:11 2003 From: akaihola at ambi-no-spam-to-tone.com (Antti Kaihola) Date: Mon, 28 Jul 2003 13:41:11 +0300 Subject: locale.py strangeness References: Message-ID: Sun, 08 Jun 2003 16:44:25 +0200, Torsten Marek wrote: > I experienced some strange behaviour with locale.py from Python 2.2.3. So did I. When using an LC_COLLATE locale (I've tested fi_FI and en_US), locale.strcoll returns surprising (non-zero!) values when comparing accented characters to the corresponding un-accented ones. Here's the result of my test: None fi_FI en_US needed None ISO8859-1 ISO8859-1 strcoll(?, A) 1 4 4 4 strcoll(?, e) 1 [*] 1 [*] 3 0 strcoll(?, ?) 0 0 0 0 strcoll(?, ?) -1 -24 -10 -10 strcoll(?, o) 1 -10 -10 -10 strcoll(?, z) 1 -21 -21 -21 strcoll(?, A) 1 28 14 14 strcoll(?, e) 1 24 10 10 strcoll(?, ?) 1 24 10 10 strcoll(?, ?) 0 0 0 0 strcoll(?, o) 1 14 [*] 9 0 strcoll(?, z) 1 3 -11 -11 I've marked the strange lines with [*]. In the en_US locale, why doesn't strcoll return zero when comparing accented characters to the corresponding un-accented ones? The fi_FI locale should also do that for "e acute". The first column shows strcoll results before I touch the LC_COLLATE locale. The next two columns show the results with the Finnish and US English locales, and the last column is what I need for my application. Note that the distance from an accented and an un-accented character to another character is identical (e.g. ?-e and ?-? in the table). So, amazingly, the distances don't match: >>> assert strcoll('X', 'i') - strcoll('X', 'j') == strcoll('j', 'i') >>> assert strcoll('X', 'e') - strcoll('X', '?') == strcoll('?', 'e') Traceback (most recent call last): File "", line 1, in ? AssertionError Accented characters share the same distance to their un-accented cousins as some other un-accented characters: >>> from locale import * ; setlocale(LC_COLLATE, 'en_US') 'en_US' >>> strcoll('?', 'e'), strcoll('h', 'e') 3 3 >>> strcoll('x', 'o'), strcoll('?', 'o') 9 9 >>> setlocale(LC_COLLATE, 'fi_FI') 'fi_FI' >>> strcoll('f', 'e'), strcoll('?', 'e') 1 1 See http://akaihola.iki.fi/comp/python/strcoll for the code, including a work-around based on earlier discussions I've found on this newsgroup. From t_therkelsen at hotmail.com Thu Jul 10 16:33:47 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 10 Jul 2003 20:33:47 GMT Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: In article <6cd58b6.0307101214.34e99f2a at posting.google.com>, Steve Pinard wrote: > (Got a comm error trying to post first time, sorry if this > is a duplicate) > > New to Python, so please bear with me. > >>>> import sys >>>> print sys.modules.keys() # works fine > ['code', ...snip... ] >>>> print sys.modules.keys().sort() # returns None, why? > None > > According to my reference (Nutshell), keys() returns a > "copy" of the dict keys as a list, so I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? >From the documentation of the mutable sequence sort() method, note (7): "The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don't return the sorted or reversed list." Or, in other words, sort() always returns None. If you want to sort, you need to bind a name to the list you want to sort, first, then call sort() on it and then print the now sorted list. For example: sys_keys = sys.modules.keys() sys_keys.sort() print sys_keys Hope this helps, Troels Therkelsen From gumuz*NOSP at M*looze.net Thu Jul 24 20:46:08 2003 From: gumuz*NOSP at M*looze.net (Guyon Morée) Date: Fri, 25 Jul 2003 02:46:08 +0200 Subject: I am so impressed Message-ID: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> I've been looking for a nice python editor for a while. I was using a great general purpose editor called EditPlus. It did the job pretty good.... I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com and it's great! i had to share that with you guyon From elf at drizzle.com Tue Jul 1 14:39:04 2003 From: elf at drizzle.com (Elf M. Sternberg) Date: Tue, 01 Jul 2003 11:39:04 -0700 Subject: Python's CGI and Javascripts uriEncode: A disconnect. Message-ID: It's all Netscape's fault. RFC 2396 (URI Specifications) specifies that a space shall be encoded using %20 and the plus symbol is always safe. Netscape (and possibly even earlier browsers like Mosaic) used the plus symbol '+' as a substitute for the space in the last part of the URI, arguments to the object referenced (you know, all the stuff after the question mark in a URL). The ECMA-262 "Javascript" standard now supported by both Netscape and Internet Explorer honor RFC 2396, translating spaces into their hex equivalent %20 and leaving pluses alone. The Python library cgi.FieldStorage decodes it backwards, expecting pluses to be spaces and %2b to represent pluses. This behavior is present even in python 2.2, and arguably helps support older browsers. But when web applications are heavily javascript-dependent, this can cause major headaches. Other than override cgi.FieldStorage's parse_qsl, is there anyway to fix this disconnect? Elf From usenet_spam at janc.invalid Sat Jul 5 22:38:19 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 06 Jul 2003 02:38:19 GMT Subject: Frustration with spurious posts. References: <3F06FD11.967D8D8A@hotmail.com> Message-ID: Alan Kennedy schreef: > Bringing an end to the problem would probably involve a fairly > substantial admin effort on the part of the python.org admins. No, it's the admins that run an antivirus on their mail server or the users that use broken anti-virus/anti-spam tools that should fix their system. It's plain stupid and irresponsible to bounce or send a mail back to a *forged* and often randomly shuffled "From:" address, doubling or tripling the mail traffic generated by the virus itself. :-( (I have even seen one system "bouncing" virus mails with the attachment included, sending the virus to an innocent user...) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From wettering at comcast.net Sat Jul 12 15:40:56 2003 From: wettering at comcast.net (Mark VandeWettering) Date: Sat, 12 Jul 2003 19:40:56 GMT Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: In article , John Roth wrote: >> Nope. That's a reason why code colouring is evil. If you write code, >> and it isn't clear what you mean without the use of code colouring, >> you did something wrong. Your code shouldn't rely on a specific code >> colouring scheme to be understandable. > > This assumes that someone reading the code is going to be using > a brain-dead editor. We need to get beyond that some day, and > assume that people are going to be using decent tools. I don't use code coloring editors for a number of reasons. 1. Code coloring makes code harder to read. There are two obvious choices to pick for the background color of text editors: white and black. Against a white background, only darker colors have contrast. Against black, only lighter ones do. This drastically limits the number of colors that you can use. Recently my place of employment changed the default vi that people use to perform syntax coloring. The result: my comments became dark red against a black background. Some other class of keywords mapped to magenta and dark blue. About 30 seconds of it made me want to gouge my eyes out. 2. Code coloring is almost always done on the basis of a syntactic basis. Call me silly, but I've never found problems with syntax to be very confusing. Other features of advanced editors like class browsers and the like are useful because they relay some information which may not be obvious from context, but that never seems to be a problem with syntax. 3. Good programming style allows you to read programs from top to bottom. Syntax coloring encourages you to skip around by distracting the eye to other parts. It's similar to the overuse of font changes in the written word: it is a poor visual style. 4. Some people are color blind. Syntax coloring may not benefit them to any significant degree. I doubt anyone will find this arguments convincing, as this tends to be a bit of a religious argument, but the problem isn't just one of tools: I have access to such tools, I merely find them useless. > John Roth From jar at mminternet.com Tue Jul 29 13:22:51 2003 From: jar at mminternet.com (james roush) Date: Tue, 29 Jul 2003 10:22:51 -0700 Subject: Trustudio plugin for Eclipse IDE Message-ID: I've been trying, without success, to download the Trustudio plugin for the Eclipse IDE. I've been trying to get it from http://www.xored.com/download.php. Has anyone gotten it from somewhere else? -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From paulpaterson at users.sourceforge.net Sun Jul 27 20:20:48 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Mon, 28 Jul 2003 00:20:48 GMT Subject: How safe is modifying locals()? In-Reply-To: References: <3TIUa.107401$XV.6252339@twister.austin.rr.com> Message-ID: Bengt Richter wrote: > On Sun, 27 Jul 2003 04:51:11 GMT, Paul Paterson wrote: > > [...] > > >>To my eye, the [:] or [0] spelling of this makes the code look more >>complex than necessary, but I think you are on to something because if >>you spell it, >> >>def change(x, y): >> x = 'new x' >> y.update('new y') >> > > > For a general pointer, ISTM you want to be able to dereference it for both getting and setting. > The [:] or [0] syntax gets you that, and you could do it with p() for getting and p(val) for setting, > or p.getval() and p.update(), but all these get clumsy when you want to use the "pointer" on > both sides of an assignment statement, e.g., > > p.update(p.getval()+' added text for target') > > where you could write more readably (IMO), > > p.value = p.value + 'added text for target' Yes, this feels right. Visually you have only one element to recognize (p.value) which makes it not much more complex than the original code. A single search and replace could also get rid of the pointer semantics if it was later decided that they were not required. > > or > p.v += 'added text for target' > > > Below is a class PNS that lets you spell as immediately above, using .value > (and .v for concise use) bound to a property that implements the accessing of > what's pointed/referred to. I gave it a somewhat informative __repr__ method also, > so the test prints better. As you will note, this is now separate from any particular > name space. Any object that supports getattr and/or setattr can be used. I also > threw in a permissions parameter to control read/write/delete. See nsother and math > in examples. Note also that a pointer may point to another pointer, allowing cascaded > dereferencing spelled p.v.v etc. > > >>with the relevant changes to the Ptr class then it could certainly grow >>on me. The things I like are, >> >>- no new variable names in the 'change' function so it looks similar to >>the original code >>- the mechanism for propogating changes to the caller scope is explicit >>- 'y' can be passed on to another function if needed and things are >>still clear >> >>eg, >> >>def change(x, y): >> x = 'new x' >> change2(y) >> >>def change2(y): >> y.update('deep change in y') >> > > If you use PNS, that will be spelled > > def change(x, y): > x = 'new x' > change2(y) > > def change2(y): > y.value = 'deep change in y' Looks good! I like this a lot - it is much clearer than a bare namespace when you start passing these things around. In fact, I don't think the namespace can actually work in the change/change2 example above. Consider, def change(x, y): x = 'new x' change2(y) def change2(z): z = 'deep change to y' Using the bare namespace you would have to pass ns to 'change' and then address 'y' as ns.y ... but then when you pass it to change2 it has to be called z, but you can't call it ns.z ... Using the pointer system (or sisters?!) you pass the "pointer" and then always refer to it as localname.value. Neat! I'm not sure if I would recommend this in general but for my application it seems to be a nice approach. > >>Thanks for these thoughts and the time it took to post them, they really >>made me think! (I mean that in a good way, of course ;) ) >> > > You're welcome. Hope this adds another useful angle. Absolutely! Thanks again. Paul From postmaster at gensym.com Tue Jul 1 18:39:07 2003 From: postmaster at gensym.com (System Administrator) Date: Tue, 1 Jul 2003 18:39:07 -0400 Subject: Undeliverable: Re: Application Message-ID: <6AA1CFDDE237D51190160000F805064D038F7C8E@hqmail.gensym.com> Your message To: bhyde at gensym.com Subject: Re: Application Sent: Tue, 1 Jul 2003 20:38:31 -0400 did not reach the following recipient(s): bhyde at gensym.com on Tue, 1 Jul 2003 18:39:06 -0400 The recipient name is not recognized The MTS-ID of the original message is: c=US;a= ;p=Gensym;l=HQMAIL0307012238N4PJN1NK MSEXCH:IMS:Gensym:HQSITE:HQMAIL 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Application Date: Tue, 1 Jul 2003 20:38:31 -0400 Size: 1062 URL: From cybersamurai at mac.com Fri Jul 4 08:40:33 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Fri, 4 Jul 2003 09:40:33 -0300 Subject: Form using HTML on PythonCard Message-ID: <200307040940.33236.cybersamurai@mac.com> Somebody know how make html forms or python forms inside html to use as gui application? The idea is make a client application like a web site of my interprise for customers who don't have good connection, in this way the customer can select the products off line and connect only to execute the shop. The use of HTML is to have the same paradigm to application and to site. From staschuk at telusplanet.net Tue Jul 1 15:35:22 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 13:35:22 -0600 Subject: how to register private python codecs? In-Reply-To: ; from garabik-news-2002-02@kassiopeia.juls.savba.sk on Tue, Jul 01, 2003 at 02:20:21PM +0000 References: Message-ID: <20030701133522.A16070@tibia.amotlpaa.bogus> Quoth Radovan Garabik: [...] > Is there a (simple) way how to register this encoding so that the > file "kamenicky.py" can be in (let's say) current directory? See codecs.register(). -- Steven Taschuk Aral: "Confusion to the enemy, boy." staschuk at telusplanet.net Mark: "Turn-about is fair play, sir." -- _Mirror Dance_, Lois McMaster Bujold From mcherm at mcherm.com Tue Jul 1 17:30:57 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 1 Jul 2003 14:30:57 -0700 Subject: Identity inconsistency and unification of types and classes Message-ID: <1057095057.3f01fd917de67@mcherm.com> Rim writes: > With the great unification of types and classes, what will happen to the > following identity inconsistency? > > >>> class myint(int): pass > ... > >>> a=int(1); b=int(1) > >>> a is b > 1 > >>> a=myint(1); b=myint(1) > >>> a is b > 0 In all likelihood it will remain as it is. The current behavior is NOT what you think it is. For instance: ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = int(32000) >>> b = int(32000) >>> a is b 0 The *actual* rule is this: if two objects x and y are not immutable, then "x is y" will be false. Normally, you would want to use "x == y" instead, to see if two objects were equal, but if what you REALLY want to know is whether they will CONTINUE to be equal if one gets changed, then that's what "is" is used for. (Plus occasionally for performance reasons, and in the idiom "x is None", which isn't really any different from "x == None" except if you redefine None, which you shouldn't do.) For IMMUTABLE objects, there's no reason to EVER need "x is y"... since you can't change either one, "x == y" will tell you whatever you need to know. Thus Python is allowed to have "x is y" return either true OR false, as an optimization. Programmers shouldn't rely on the result (except, as always, if you really know what you're doing). Right now, Python allows "is" to return true between strings that are very short and strings that appear in the source code, but sometimes not between strings that are constructed at runtime. For integers, "is" will return true between numbers in the range [-1..99], and may return false for numbers outside that range. Both of these rules are specific optimizations and may change without warning. What you CAN assume is that if you create a mutable subclass of int (why would you do such a thing?), that "is" will return false on different instances. If your subclass is immutable, you can't assume anything. -- Michael Chermside From ny_r_marquez at yahoo.com Mon Jul 28 10:25:38 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 28 Jul 2003 07:25:38 -0700 Subject: Seeing next character in an file References: Message-ID: <8a27e309.0307280625.1f45adb3@posting.google.com> Grumfish wrote in message news:... > Is there a way to see the next character of an input file object without > advancing the position in the file? Here is a little class that I use on a little html parser that I wrote. You may be able to adjust it for your needs: class Characters: def __init__(self, String): self.Characters=String self.Char = "" self.index = 0 self.lenght = len(self.Characters) def GetNextChar(self): skipchar = 1 while skipchar ==1: try: self.Char = self.Characters[self.index] except IndexError: self.Char = None #print "End of File\n" return None self.index += 1 if self.Char != "\n": skipchar = 0 return self.Char def CheckNextChar(self): skipchar = 1 StartChar = self.Char StartIndex = self.index while skipchar ==1: try: self.Char = self.Characters[self.index] except IndexError: self.Char = None #print "End of File\n" return None self.index += 1 if self.Char != "\n": skipchar = 0 self.index = StartIndex NextChar = self.Char self.Char = StartChar return NextChar From andreas at andreas-jung.com Fri Jul 4 04:30:56 2003 From: andreas at andreas-jung.com (Andreas Jung) Date: Fri, 04 Jul 2003 10:30:56 +0200 Subject: enumerate example In-Reply-To: References: Message-ID: <2147483647.1057314656@[192.168.0.100]> for num ,item in enumerate( ['a','b','c']): print num, item 0 a 1 b 2 c --On Freitag, 4. Juli 2003 18:19 Uhr +1100 Egor Bolonev wrote: > Hello, All! > > Any useful example for enumerate, please. > > With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] > > -- > http://mail.python.org/mailman/listinfo/python-list From ngps at netmemetic.com Wed Jul 9 02:20:24 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 9 Jul 2003 06:20:24 GMT Subject: Python vs PHP References: Message-ID: According to Afanasiy : > Python web development is fragmented. www.waferproject.org: Wafer is a research project which compares the many open source web application frameworks which are available using a common example application. This research project is designed to compare the application frameworks on a level field by specifying an example application so that the application features become irrelevent and the merits of each framework becomes the focus. Java ones only. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From bh at intevation.de Tue Jul 15 05:18:18 2003 From: bh at intevation.de (Bernhard Herzog) Date: 15 Jul 2003 11:18:18 +0200 Subject: Python Mystery Theatre -- Episode 2: =?iso-8859-1?q?As=ED?= Fue References: <8f35dab2.0307141258.3da9b9d4@posting.google.com> Message-ID: <6qvfu4jgh1.fsf@salmakis.intevation.de> "Raymond Hettinger" writes: > [Jason Trowbridge] > > Act I > > I didn't know that python formatting could do that! I've always > > treated it like C's printf-style of statements, as that seems to be > > what it's primarily based off. > > That's why this one was included. > Hope everyone learned something new. C's printf can do this too. At least the one in the GNU libc can. It's docs don't say anything about this being a GNU extension so I guess it can be found in other libcs as well, though probably not in all. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From Robert at AbilitySys.com Tue Jul 15 00:02:01 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Mon, 14 Jul 2003 21:02:01 -0700 Subject: Stop Python from exiting upon error in Windows References: Message-ID: I hear ya. That's what I'm doing at the moment to spot something, but I wanted to "polish" the program a little... - Robert "Conrad" wrote in message news:pan.2003.07.15.03.21.44.980226 at zexcite.zcom... > Years ago, Nostradamus predicted that on Mon, 14 Jul 2003 20:06:14 -0700, > Tom Plunket would write, saying: > > > Robert wrote: > > > >> How can I stop the Python interpreter from exiting when an error occurs? > > > > create a batchfile, tell Windows that the association of Python > > files is to that batch file, and put this in the file: > > > > python.exe %1 > > pause > > > > > > Or- catch the error in your mainline, and do a sys.raw_input() > > call on exception. > > > > -tom! > > Or the third, and admittedly brute force solution > I use is to fire up the DOS shell, (click on START, > then RUN, then type "command"). Depending on which > Win you're running, you may want to run DOSKEY, > which lets you cursor back up to previous commands. > > Once you've got the command window up (and doskeyed), > cd to your python source directory, and type in > something like *C:\python22\python.exe mypythonfile.py* > (leave out the *s and be sure python is in the same > place on your machine.) > > This doesn't keep the python interpreter from exiting, > but it does keep the DOS window open to let you see > your error messages. > > I admit it's ugly, but hey, I mostly develop in > FreeBSD and Linux, where the CLI is your buddy ;-) > > Conrad > > From tdelaney at avaya.com Mon Jul 21 20:54:03 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 22 Jul 2003 10:54:03 +1000 Subject: recognizing empty iterators Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D4276@au3010avexu1.global.avaya.com> > From: Bengt Richter [mailto:bokr at oz.net] > > If iterators had a .peek() method for 1-item lookahead, maybe > that would > be easy to implement. If empty, it could raise StopIteration, > and otherwise > return what next() would return, without disturbing the state > w.r.t. next(). So create an iterator that has a `peek` method, and wrap all iterators in that. Easy! Tim Delaney From claird at lairds.com Sun Jul 27 06:40:53 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 27 Jul 2003 10:40:53 -0000 Subject: Floyd-Warshall Algorithem in Python References: Message-ID: In article , Dave wrote: >Hello, > >I'm looking for a Floyd-Warshall Python implementation. The only >implementation I have seen (searching this newsgroup) used a Python >library called "Numeric". This implementation doesn't work anymore. >I was wondering whether anyone knew of any FW implementations >elsewhere, or knew how I could convert the old example to Python code >that would run on Python 2.2? . . . Support for Python's Numeric project has been excellent. Numarray will soon replace it. If you are aware of an error in Numeric, I urge you to bring it to the attention of others. If you need help correcting a flawed imple- mentation, this newsgroup is far likelier to satisfy you after you've supplied references that allow others to examine source, provided minimal information about version numbers and platforms, and detailed what "doesn't work anymore" means to you. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From bgailer at alum.rpi.edu Sun Jul 27 16:55:28 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 27 Jul 2003 14:55:28 -0600 Subject: changing the List's behaviour? In-Reply-To: Message-ID: <5.2.1.1.0.20030727145149.02dda5e8@66.28.54.253> At 10:41 PM 7/27/2003 +0200, meinrad recheis wrote: >i am very annoyed by the List's index out of bouds exception >it forces me to complicate my code by adding length checking > >i might be spoilt by Ruby which returns nil for not existing indices. >i want to change the List so that it returns None if the index for >accesssing list elements >is out of bound. > >i am not very experienced in python, so i ask you for suggestions. Why is your code generating indexes that are out of range in the first place? You can always use try - except to catch index errors in the (hopefully) few places where there is a legitimate reason for an out of bound index. Returning None is not a good idea, as None could be a value in the list. But you can create a subclass of list with its own __getitem__ method that checks bounds and returns None. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 29 11:58:56 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 29 Jul 2003 15:58:56 GMT Subject: Python on a USB storage device? References: Message-ID: Eddie Corns enlightened us with: > Yes, I have an oldish windows Python distribution on a 128Mb stick. > It works quite nicely but you do have to be aware that without the > usual registry entries it won't search for libraries etc. so well. You can also install Linux on a USB storage device and hope the computer it has to run on supports booting from USB ;-) > It would work on Linux too except you need to have permission to > create mount tables etc. to get the filesystem. Running your own Linux off the USB stick solves that problem. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From pete at fenelon.com Thu Jul 3 11:08:44 2003 From: pete at fenelon.com (Pete Fenelon) Date: Thu, 03 Jul 2003 15:08:44 -0000 Subject: Collective memory References: <1057243309.793889@saucer.planet.gong> Message-ID: In alt.folklore.computers Rupert Pigott wrote: > > OCCAM used WS to denote block structure... For ...and was generally written with folding editors that just "got it right" ;) pete -- pete at fenelon.com "there's no room for enigmas in built-up areas" HMHB From rastm2 at aol.commorespam Sun Jul 27 03:13:48 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 27 Jul 2003 07:13:48 GMT Subject: Del's "except"ional PEP Rejection Message-ID: <20030727031348.05032.00000554@mb-m26.aol.com> Ladieees and Gentilmen and Pyth-O-neers of all ages. Step right up. Don't be shy. Come one come all. Be the first on your block TO GROK *THE* one *THE* only Exception you won't find any where but here! The Exception that's Exceptional! It's the "elif from lamdba except" Exception. (The only Exception that don't need an "except" clause, Because it *IS* one.) It's the story of Del, an intermitantly deaf, intermitantly nauseated importation executive with Print Global Inc. Del's a company man, and the 150 year old, family owned company needs someone to lead them all into the 21'st Century. Having over heard... ( It's amazing how some people who seem deaf at times can hear things from what was supposed to be a closed door meeting between ) ...the VP of Statis talking down to the 85 year old Chief of Data Processing ... ( History Note--that's what they used to call them you know -- worked his way up from crank turner -- but I digress ) ... what was I saying oh yeah Del over heard the VP telling the old guy, "Hell, my 12 year kid stuck *some* kinda snake, wait it was a python, yeah he stuck a python in an old Apple II that was in the attic a week ago Sunday and started typeing like mad and by Thursday he was telling me that he had gone GLOBAL and wouldn't need his allowance anymore. No it's time to upgrade. Shut down the ENIAC." Cut to the "ever butt kissing" Del, half deaf, sitting in Python school. Well, sorta sitting 'cuz' Del's got bowel problems and he needs another pass from the Instructor to go to the lav. Sitting on the pot, like a splash, a thought hits him. ( gosh I hope it was just a thought ) Ya see, Dan didn't just volenteer for this mission, he was holding back from the company. He new a litte "c" code. Just enough to be dangerous, and it made him sick to his stomach. But this Python Language! He truely understood and liked what he was learing. Python was indented so you could read it like a self respecting human being. It was impressive to him, the way you could write your code in the interpreter, and did't have to declare anything or agonize while you waited to see if it worked. He liked the way "elif" statements made case switches easier to code and understand. How "from" this "import" that made code re-usable. How "lamda" could define a function in a function without having to define a function for a function. How exceptions could be used to make programs that worked the first time. He loved the "while loops" and the list comprehensions that had little "for loops" and "if"s in them. He like how any one on the planet, with enough money to maintain a computer and an internet connection, could just be so very proud that they had their PEP rejected by the most intelligent, helpful, thoughtful, and kindest people on Earth. Sitting right there on the throne of inspiration he came up with the only exception that uses all the keywords, types all in one color in the editor, and makes sense to only him, so he sent in a PEP to be rejected... wait for it wait for it Bam! The elif from lambda except: statment elif from lambda except: while del is not def: [import exec for print global] try: continue or else: raise and return break pass in class finally: yeild if assert *PYTHON* *THE*WAY *GUIDO* *INDENTED* *IT*TO*BE* By Raymond St. Marie (Rastm2 at aol.com -- don't laugh, it's been free since I lost my job in January) From ianb at colorstudy.com Tue Jul 8 03:57:49 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 02:57:49 -0500 Subject: path module Message-ID: <1057651068.5348.386.camel@lothlorien> I think Jason Orendorff's path module is really nice: http://www.jorendorff.com/articles/python/path/ Beats the hell out of os.path, which is an ugly thing indeed. The OO interface means you could use the interface nicely to implement other things, like URLs. The problem? It's just some module. The various os functions (of which path replaces quite a few) have become idiomatic to me, and I'm sure others as well. I find myself reluctant to use it in code that's not essentially private, because it's changing something small and seemingly trivial, and people won't be familiar with it. The solution? It should be a builtin! Or, if not a builtin, included in the os module. But I actually like the idea of it being a builtin -- if open is a builtin, path stands right up there too. It would get rid of 90% of the use of the os module. Thoughts? Reactions? Ian From gh at ghaering.de Thu Jul 24 04:15:45 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 24 Jul 2003 10:15:45 +0200 Subject: How to do raw Ethernet under Win32? In-Reply-To: References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> <3f1ee77f$0$160$a1866201@newsreader.visi.com> Message-ID: <3F1F95B1.1070709@ghaering.de> Grant Edwards wrote: > In article , Gerhard H?ring wrote: > >>>It looks like I can _almost_ do what I want with the python >>>wrapper around the windows pcap lib. >> >>Where's PyLibpCap for Windows available? > > Here's where I got it from: > > http://ghaering.de/python/unsupported/pylibpcap/ ;) > > I'd take a whack at finishing it, but I don't have a Windows C compiler. The guy you got this from used MINGW, the free GNU compiler for Windows to do the original port: http://mingw.sourceforge.net/ :) -- Gerhard From brian.pedersen at mail.danbbs.dk Mon Jul 28 17:34:13 2003 From: brian.pedersen at mail.danbbs.dk (Brian Dam Pedersen) Date: Mon, 28 Jul 2003 23:34:13 +0200 Subject: Documenting properties created by property() properly Message-ID: Hi Group I'm trying to figure out the proper way to document object properties created with property() using the LaTeX styles coming with python. The closest thing seems to be \begin{memberdesc}, but that seems like a clumsy way to express it. Is there any "official" way to do this ? I can't seem to find any objects in the standard distribution that uses properties - if anyone has an example of that I can just copy that. Any opinions ? Thanks in advance -- Brian From sross at connectmail.carleton.ca Thu Jul 3 12:34:03 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 3 Jul 2003 12:34:03 -0400 Subject: 'For' loop symmetry with list comprehensions. References: <840592e1.0307021036.508d7d7d@posting.google.com> Message-ID: "Hannu Kankaanp??" wrote in message news:840592e1.0307021036.508d7d7d at posting.google.com... > One can currently say this with list comprehensions: > > [x.lower() for x in words if x.startswith('foo')] > > Wouldn't it be better if the normal 'for' syntax was symmetrical > with the notation used in list comprehensions? If we were trying to be symmetrical, then: >>> words = ("hello", "bonjour") >>> otherwords = ("foo", "bar") >>> msgs = ["%s %s"%(x,y) for x in words for y in otherwords] >>> msgs ['hello foo', 'hello bar', 'bonjour foo', 'bonjour bar'] (being symmetrical) we should also be able to write: >>> msgs = [] >>> for x in words: ... for y in otherwords: ... msgs.append("%s %s"%(x,y)) ... >>> msgs ['hello foo', 'hello bar', 'bonjour foo', 'bonjour bar'] as follows: msgs = [] for x in words for y in otherwords: msgs.append("%s %s"%(x,y)) If you really want symmetry, well, this is symmetrical. Do you want this as well? -0 Sean From peter at engcorp.com Fri Jul 4 14:22:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 14:22:08 -0400 Subject: How to get CGI request-URL References: Message-ID: <3F05C5D0.B4E9C5F3@engcorp.com> Hallvard B Furuseth wrote: > > How can I get the URL the user typed (except the part after '?') with > the cgi module? > > I expect the 'Host:' HTTP header + os.environ['SCRIPT_NAME'] would do > it, but I don't see how to find the Host header. The www server has > several names, so I can't just use the default host name. This might help: http://hoohoo.ncsa.uiuc.edu/cgi/env.html Found via Google.... From jdhunter at ace.bsd.uchicago.edu Mon Jul 7 12:00:11 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 07 Jul 2003 11:00:11 -0500 Subject: getting a submatrix of all true In-Reply-To: <52fe159d.0307041016.4dcb4a5c@posting.google.com> (wright@esrf.fr's message of "4 Jul 2003 11:16:41 -0700") References: <52fe159d.0307041016.4dcb4a5c@posting.google.com> Message-ID: >>>>> "Jon" == Jon writes: Jon> Sadly I can only give you a method which is certainly not Jon> optimal, but at least finds something which is probably not Jon> too bad, and fairly quickly. Uses the Numeric module to speed Jon> up, so that a few thousand by a few hundred is quickly Jon> computable. I'm curious to know if it does much better or Jon> worse than other algorithms. Hi Jon, thanks for the suggestion. For my data set, your solution performed a little better size-wise than my poor man's approach, which I gave in the original post. And it is certainly fast enough. I liked your idea of zero-ing out the elements when you made a decision to delete a row or column. When I was thinking about solutions using Numeric, I kept running up against the problem of deleting a row or column (which entails a whole array copy so is expensive). If anyone wants to try their algorithm on "real world data" which, unlike the ones discussed here, have lots of correlation between missing rows and columns that might be exploited, I have uploaded the missing data matrix to a web server. It can be loaded with: from urllib import urlopen url = 'http://nitace.bsd.uchicago.edu:8080/summer/jdh/missing.dat' L = [ [ int(val) for val in line.split()] for line in urlopen(url).readlines()] # L is 1072x83 I think I may adapt your algorithm to terminate when the percent missing falls below some threshold, removing the requirement that *all* missing values be removed. This will drop the worst offenders observation or variable wise. Then I can use a regression approach to fill in the remaining ones. Jon> Interesting problem! I agree. There are lots of extensions to the original formulation that are relevant to the missing value problem. As we have seen in the posts here, there are good exact solutions for smallish matrices, but for larger ones a statistical approach is required. The right statistical solution surely depends on the correlation structure of the matrix. Also, it would be nice to generalize to higher dimensions (eg 3D matrices). For my problem, I have N observations of M variables over D days. So this is the 3D version of the 2D problem above. Your solution is readily adaptable to this case. More generally, you might want to impose extra requirements, like, no days can be dropped, or at most 10% of the days can be dropped, or if you want to compute changes in variables over days, that no days can be dropped. The more general formulation is something like Given an N-D (N0, M0, P0, ...) boolean matrix X with a covariance matrix C, what is the largest submatrix of X of dimensions (N1, M1, P1, ...) such that the fraction of remaining dimensions satisfies (N1/N0, M1/M0, P1/P0, ...) >= (alpha, beta, gamma, ..) and the total percent true <= p. The original problem is a special case of this where alpha=0, beta=0, p=0 and C unspecified. Anyone looking for a dissertation project :-) ? John Hunter From alienoid at is.lg.ua Tue Jul 15 04:48:49 2003 From: alienoid at is.lg.ua (Ruslan Spivak) Date: Tue, 15 Jul 2003 11:48:49 +0300 Subject: how to compile python program to linux executable Message-ID: <3F13BFF1.2000604@is.lg.ua> Hello. Is it possible to convert python program to linux executable program? Thanks in advance. Best regards, Ruslan From aquarock7 at aol.com Tue Jul 22 20:45:37 2003 From: aquarock7 at aol.com (AquaRock7) Date: 23 Jul 2003 00:45:37 GMT Subject: python22_d.lib? References: Message-ID: <20030722204537.18340.00000316@mb-m15.aol.com> Or just put this in Python2.h: #ifdef _DEBUG #define _DEBUG_2 #undef _DEBUG #include #define _DEBUG #undef _DEBUG_2 #endif and then include Python2.h instead of Python.h. Defining _DEBUG makes python use python22_d.lib instead of python22.lib. Or you can just make all your builds release builds, but this kills all of your assert()'s. From bokr at oz.net Sat Jul 12 19:44:59 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 23:44:59 GMT Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: On Sat, 12 Jul 2003 21:07:48 GMT, "Elaine Jackson" wrote: >Wayne Pierce wrote in message >news:2a897f11.0307121139.21470fbb at posting.google.com... >| "Elaine Jackson" wrote in message >news:... >| > Can Python be compiled? If so, how? (I have the 2.2 version of the >interpreter.) >| > TIA for any and all helps >| >| If you want to be able to distribute your Python apps without the end >| user needing a Python interpreter take a look at the following: >| >| http://www.mcmillan-inc.com/install1.html >| >| Wayne > > >Thank you. > Hi, welcome to the neighborhood ;-) If you are also new to newsgroups, you may not know that most newsgroup participants cringe when they see top-posting. The reason is that if there is ongoing interchange with quoting and editing, it soon gets very hard to follow the sequence if people do not post below what they are commenting on or replying to. For a single interchange, it may seem convenient to see the latest at the top, but the price in later confusion is not worth it. Subject lines that indicate what you want also help ;-) Good luck with Python. I'm sure you'll find plenty of willing help here. Regards, Bengt Richter From fredrik at pythonware.com Tue Jul 15 18:51:55 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2003 00:51:55 +0200 Subject: String Manipulation References: <2c6431ab.0307151223.4173c4ee@posting.google.com> <3f148002$0$49112$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > While is is perfectly acceptable, you might want to consider another > solution if it is *path names* you are manipulating: > > >>> import os > >>> os.path.split("aaa/bbb/ccc/dd") > ('aaa/bbb/ccc', 'dd') > >>> os.path.split("aaa/bbb/ccc/dd")[1] > 'dd' or: >>> os.path.basename("aaa/bbb/ccc/dd") 'dd' (use os.path.dirname to get the directory part) From yunxian at proteome.org.au Thu Jul 31 22:17:59 2003 From: yunxian at proteome.org.au (Yunxian Mak) Date: Fri, 1 Aug 2003 12:17:59 +1000 Subject: How to run Python script on WindowXP Message-ID: <000001c357d3$20eee930$3cb06f89@APAF.local> Dear Sir/Madam, I'm doing my PhD in APAF and I installed Python 2.2 interpreter in WindowNT before and it worked OK on my old computer. However, our company has upgraded the systems to WindowXP recently. I installed Python2.2.3, which includes IDLE (Python GUI), Module Docs, Python (command line) and Python Manuals, on my new computer. I can open my Python code from IDLE (Python GUI), but I don't know how to run it. If you could please tell me whether the Python interpreter compatible to WindowXP and how to run the Python script on WindowXP, I'll be much appreciated. Thank you very much again. Best regards, Yunxian Mak -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand_soliton at yahoo.com Tue Jul 22 13:13:39 2003 From: anand_soliton at yahoo.com (Anand) Date: 22 Jul 2003 10:13:39 -0700 Subject: Is there a way to access/modify/add variables to caller from a sub function Message-ID: <3f5dc178.0307220913.62a7e92f@posting.google.com> Is there a way to access/modify variables of a caller function from within a sub function call? Function A: Calls subFuncB: var x Add var xx in Function A's name space?? var y var z From brian_l at yahoo.com Tue Jul 29 20:40:57 2003 From: brian_l at yahoo.com (Brian Lenihan) Date: 29 Jul 2003 17:40:57 -0700 Subject: Trustudio plugin for Eclipse IDE References: Message-ID: james roush wrote in message news:... > I've been trying, without success, to download the Trustudio plugin for > the Eclipse IDE. I've been trying to get it from > http://www.xored.com/download.php. > > Has anyone gotten it from somewhere else? http://sourceforge.net/projects/trustudio/ From vze4rx4y at verizon.net Wed Jul 30 04:42:59 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 30 Jul 2003 08:42:59 GMT Subject: metaclasses References: Message-ID: > >> It seems this is a more general way to build classes than inheritance. > >> Is this a reasonable viewpoint? > > It is a less general way for building classes. > > Actually, the question doesn't make sense. Metaclasses and > inheritance are two different dimensions of generality. Neither is > more or less general than the other, because they generalize in > different ways. > > However, his use of the built-in metatype 'type' is more general than > the class statement, which seemed to be what he was asking. One can > supply a list of bases which, unlike the class statement, need not be > a fixed length. In fact, the bases can be calculated dynamically. > Likewise with the class dict. I read his question as asking about the merits of subclassing type vs using type() directly. class MyMeta(type): . . . class MyClass: __metatype__ = MyMeta . . . vs. MyClass = type(n, b, d) Raymond Hettinger From alanmk at hotmail.com Thu Jul 3 08:28:56 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 03 Jul 2003 13:28:56 +0100 Subject: Assing a COM Interface to a Python object for callbacks References: <26caea2b.0307012335.1d717429@posting.google.com> Message-ID: <3F042188.5FFC45D3@hotmail.com> Mikko Ohtamaa wrote: > I have a following problem: > I am trying to do XML Schema validation using MSXML SAX parser through > PythonCOM API. > > MSXML offers two different interfaces for SAX: One for VB and one for > C++. C++ one is named ISAXXMLReader and VB one is named > IVBSAXXMLReader. I haven't found what is the basic difference between > these interfaces though I have carefully read MSXML SDK documentation. > I assume IVBSAXXMLReader might have some IDispatch functionality which > is requirement for PythonCom(?). > > The problem is that SAX Parser requires COM interface for callback. > You must assign a COM interface as a handler to the parser. When the > parsing begins, the handler calls this interface. > > saxReader.errorHandler = myErrorHandler <-- COM Interface > > I do not know how to turn Python class into COM interface on the fly. I'm not sure how Mark Hammond's Windows extensions handle this situation, if at all. But I do know that Thomas Heller's "ctypes" has a COM framework which addresses the problem. Only thing is, I don't know how robust the current support is, given that, in Thomas own words: "Warning: work in progress". http://starship.python.net/crew/theller/ctypes/sum_sample.html HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From schull at digitalgoods.com Mon Jul 14 15:40:54 2003 From: schull at digitalgoods.com (Jon Schull) Date: 14 Jul 2003 12:40:54 -0700 Subject: cgi-tb after os.chdir Message-ID: <2621b014.0307141140.650a234a@posting.google.com> I find that cgitb fails to show error context if I've changed my default directory, so I tried to subclass cgitb and get it to save the directory we were in when the program started. Didn't work. I'd appreciate your eyes. Problem--this apparently fails to find my sourcefile when #os.chdir is uncommented from this cgi program ......................... #! /usr/local/bin/python import cgitb cgitb.enable() import os #os.chdir('../') 1/0 ......................... What I thought would work: ......................... from cgitb import Hook import os import sys class myHook(Hook): def __init__(self, display=1, logdir=None, context=5, file=None,wkdir='xx'): self.wkdir=wkdir Hook.__init__(self, display=1, logdir=None, context=5, file=None) def handle(self, info=None): os.cwd(self.wkdir) Hook.handle(self,info) handler = myHook().handle def enable(display=1, logdir=None, context=5): wkdir=os.getcwd() sys.excepthook = myHook(display, logdir, context,wkdir=wkdir) ......................... But in fact, my exception handler doesn't even seem to get installed. (I get python's usual tracebacks) I'm probably over my head here, but... What's wrong with the program where I attempt to subclass myHook? Is this a reasonable way to get cgitb to survive directory changes? From adechert at earthlink.net Tue Jul 22 13:51:49 2003 From: adechert at earthlink.net (Alan Dechert) Date: Tue, 22 Jul 2003 17:51:49 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xbrvnmqzp.fsf@ruckus.brouhaha.com> <7x4r1exzqh.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x4r1exzqh.fsf at ruckus.brouhaha.com... > Marc Wilson writes: > > Ah. That's a whole load of trouble we don't have. To stand for election, > > here, you have to pony up a deposit, which you lose if you don't get a > > certain percentage of the vote. It's to discourage "frivolous" campaigns, > > supposedly. IIRC, it's around GBP 1000; about USD 1500. > > Here, you have to get a certain number of voter signatures on > petitions, plus pay a bunch of fees, to get your name actually printed > on the ballot. > I'm not sure if this is "uniformly" true. I once ran a petition drive to get a candidate on the ballot IN LIEU of the filing fee (for 1986 primary, U.S. House of Representatives, 12 CD in CA). It took 3,000 valid signatures, IIRC. > But when voting, you can write in the name of anyone > you want. > This too seems not uniformly true. In some states (e.g., Florida) write-ins are only valid if the candidates are "qualified." Write-ins have to file a petition or something like that. Otherwise, the write-ins don't count. So, if a contest has no qualified write-in candidates, the line for write-in does not appear on the ballot. Doug Jones has some on his web site. Here's one for Clay county in FL. Note that some contests have the write-in line but some don't. http://www.cs.uiowa.edu/~jones/voting/intent/samples/clay.pdf The way that write-ins are handled would probably change [for the better] if our uniform PC-based-open-source-with-a-printer voting system gets implemented. Write-ins pose significant overhead in election administration. In some cases, the actual name written in only gets read if there are enough write-in votes to impact the outcome. In other cases, write-ins have to be tallied by name regardless. With our system, write-ins would be taken care of (almost) automatically. So, a lot of the rules that are designed to cut down on the manual labor involved in tallying write-ins would no longer be needed. There would still be some issues but, for the most part, these will be easy to deal with. Spelling variations cause some challenge. For example, B WRIGHT BILL WRIGHT WILLIAM WRIGHT WILL WRIGHT WILIAM WRIGHT WILLIAM WRITE might all refer to the same peron. In the extremely rare instance where sorting this out could impact the outcome, it will be much easier to deal with on our system than on any system where votes are written in by hand. Existing DREs on the market also have this advantage over other systems but they don't have the penetration we hope to achieve. Alan Dechert From guettler at thomas-guettler.de Thu Jul 31 10:32:24 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 31 Jul 2003 16:32:24 +0200 Subject: regular expression References: Message-ID: Wiebke P?tzold wrote: > On Thu, 31 Jul 2003 14:24:01 +0200, Thomas G?ttler > wrote: > >>Wiebke P?tzold wrote: Please cut unimportant parts if you reply. > Can you tell me please on wich place in my program the if-statement > will be inserted? At the same place where you have it (if ...=="G") > And then I have another question too. After the if statement there > must be a print statement. I have no idea how I must write my program > so that it is right and executably. > Can you write it me exactly how this program should look like? You seem to be running on windows ("C:\..."). I think double-clicking on it should execute it. If you want to make it executable without python installed: Have a look at py2exe. Since you seem to be a german: Maybe my Python introduction helps you: http://www.thomas-guettler.de/vortraege/python/einfuehrung.html thomas From peter at engcorp.com Thu Jul 3 10:18:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 10:18:10 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <3F043B22.19FE79AE@engcorp.com> Max Khesin wrote: > > import flame.* > import sorry.* > Ok, with all my respect to python, the stuff about C++ is a bunch of hooey. > Compilation time is the problem? Give me a break. > 1) separate compilation? > 2) precompiled headers? > 3) tools that allow cluster compilation? > 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ > project. letter-envelope idiom to help compilation...etc. Sounds to me that if they've come up with so many and such a wide range of optimizations to improve compilation time, then it clearly *is* a problem... > Anyway, if you are coding so fast that compilation time becomes a serious > problem you are either > a) the smartest and fastest programmer on earth > b) are not thinking enough c) doing test-driven development I admit to not having done any C++ code for several years, certainly not since adopting TDD, but I would guess for a sizable project the compilation and link times could become a major annoyance -Peter From bokr at oz.net Wed Jul 9 08:30:55 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Jul 2003 12:30:55 GMT Subject: Unexpected (by me) exec behavior References: Message-ID: On 8 Jul 2003 08:18:06 -0700, mwright at pro-ns.net (Mark Wright) wrote: >I have a script that I use to control our build process. It is a >general purpose script that exec's other scripts that contain project >specific python code. In one of those other, project-specific, >scripts I exec a third script. That third script is failing because >it can't seem to 'import' successfully. It seems that if one 'exec's >a string that in turn 'exec's another string, the 'import's don't work >in the second string. I'm assuming that I'm misunderstanding >something about Python namespaces, but here's an example that >illustrates the problem: > I feel sure there is a better way to do what you want to do, though I'm not clear on what that is ;-) You're right that it's a name space thing. Choose [1], [2], [3], or [4] or [5] ;-) >---------------------------- ># filename = t.py >s1 = """ >s2 = \"\"\" >import socket # moving the import above to [1] will make it work >def xyz(): #def xyz(socket=socket): #[2] chg above to this will also bind the socket to a socket local to xyz #import socket #[1] > print socket.gethostbyname('somehost') # ^^^^^^^^^^-- suggest 'localhost' for quick result instead of error >if __name__ == '__main__': > xyz() # xyz(socket) #[3] another way to grab the imported socket and pass it to xyz where # # you could call it something different, e.g., # def xyz(skt): print skt.gethostbyname('localhost') >\"\"\" > >def abc(): > exec s2 # exec s2 in globals() #[4] this would bind socket from import globally (w.r.t. t.py) for xyz to see >if __name__ == '__main__': > abc() >""" > >exec s1 >----------------------------- > >Traceback (most recent call last): > File "t.py", line 24, in ? > exec s1 > File "", line 13, in ? > File "", line 11, in abc > File "", line 6, in ? > File "", line 4, in xyz >NameError: global name 'socket' is not defined > >Can anyone explain this to me? > I suspect that to generate code referring to a variable in a nested scope outside the local but not global -- like socket in your example, which is outside xyz but not global since it winds up bound local to abc -- the nesting needs to be part of the same compilation. In your example, s2 is not compiled until abc is executed, so the compilation of xyz is separate from abc, even though the resulting bindings are injected into abc's local space. However, when the compilation happens, the nesting is not visible, so I think you get code that either refers to locals in a defined function like xyz, or global, but not free. But the def code can assemble the function when it executes and binds the name to the constructed function. That includes a designated global directory, which can be abc's local directory if you specify exec s2 in locals() there. Updating locals will probably not work, so global declarations in xyz and assigning them would not be good, but looking for socket in an apparent global that is the abc locals() dict should work. The code example get another problem though, because __name__ is no longer t.py's __main__, so xyz won't be called unless you change the if test (the name apparently becomes __builtin__, so if you wanted to have a script you could execute like that as well as from the command line directly, you might make the test [5] ;-) if __name__ in ['__main__', '__builtin__']: xyz() and execute it something like xdir = {} exec s2 in xdir and potentially access results in xdir afterwards, to rebind them or print status messages or whatever wasn't already a side effect of the exec. The above is the way I'm guessing nested variable references work, but I haven't dug into the compiler etc to verify it, so I'd wait to hear from someone who can say for sure. I wonder if there are changes coming in name searching and rebinding etc. Regards, Bengt Richter From mjackson at alumni.caltech.edu Tue Jul 8 18:50:15 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 8 Jul 2003 22:50:15 GMT Subject: anything new on the ternary operator? References: <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com> <2UVsCJApkwC$EwTg@jessikat.demon.co.uk> Message-ID: Robin Becker writes: > the Middle East is certainly not in Europe at least according to > classical authors, historians & geographers. Asia begins across the > Hellespont so asiatic Turkey, Iraq, Syria, Palestine are not in Europe > and neither is the Israeli territory. I suspect Israelis would prefer to > be in America so that they wouldn't have to take part in the Eurovision > song contest. I'm sure there must be an opt-out clause for Eurovision contests - I certainly don't recall Israeli teams competing in It's a Knockout / Jeux Sans Frontieres back in 1977. On the other hand as part of America they might have gotten roped into Almost Anything Goes. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is necessary to be slightly underemployed if you want to do something significant. - James D. Watson From thedustbustr at aol.com Sat Jul 26 09:46:24 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 26 Jul 2003 13:46:24 GMT Subject: Loading and executing an arbitrary Python script from within Python Message-ID: <20030726094624.15169.00000599@mb-m13.aol.com> I'm writing a game in C++ that calls out to Python for scripting. The C++ kernel holds an instance of ScriptCtl and calls the load(filename) method to load a script, then run() to run all loaded scripts. [scriptctl.py] class ScriptCtl: threads=[] def load(self, filename): f=file(filename, 'r') contents=f.read() f.close() exec(contents) #contents exec'ed within the current scope and namespace, not within their own self.threads.append(main) def run(self): while self.threads: for g in self.threads: try: g.next() except StopIteration: self.threads.remove(g) [cutscene.py] from __future__ import generators def cutscene(): from time import time import sys from utility import sleep print "EVIL KNIGHT: I will kill you now!"; sys.stdout.flush() for s in sleep(1): yield None print "OUR HERO: I shall fight you to the death. Bring it on!"; sys.stdout.flush() for s in sleep(1.5): yield None print "***End of cutscene***"; sys.stdout.flush() main=cutscene() #initialize the generator for use by scriptctl This works, barely. As a result of using exec, each script is executed in ScriptCtl.load()'s namespace. Because of this, imports have to be done inside the script functions, or the imports go out of scope before the functions get called (in scriptctl.run()). Imports also have to be done as from scriptctl.py, even though scriptctl.py deeper in the package hierarchy (so instead of 'import core.utility' I must do 'import utility' because both utility.py and scriptctl.py are in the same folder (core). This sucks. How else can I solve this problem? Ideally, I'd use Stackless Python microthreads, but version 3.0 is not out yet and there is no documentation on the current was to do microthreads. Any ideas? I'm stuck. Thanks, Dustin From nagylzs at freemail.hu Thu Jul 3 06:37:04 2003 From: nagylzs at freemail.hu (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Thu, 03 Jul 2003 12:37:04 +0200 Subject: How to setup webserver for Python References: <3F040F17.25697.E24EF9@localhost> Message-ID: <3F040750.9020105@freemail.hu> > > >Hello, >I have a webhosting account with one company. >I can use python from command line through Telnet(SSH) but can not run successfully >Python program from a browser.(They use Apache web server.) >What must I do? >What permission must I set on directory and the python file? >Here is a simple program I would like to run >######## >#!/usr/bin/python >print "Content-Type: text/html" print >print"AAA" >######## >Thanks for help >Ladislav > >I look forward to hearing from you soon. > > I think you should configure Apache for you directory (containing the script) to be a CGI direcory. Option: ExecCGI. Please see Apache documentation. Probably you cannot change apache configuration directly on the site because it is a hosting site serving many clients. However, you can do almost the same with .htaccess files. Again, see Apache docs for details. About permissions. You should know who is the user running the apache process. (It is usually apache, nobody or www.) You should setup your CGI script in a way that the user running apache can run your CGI script too. Cheers, Laci 1.0 From andy at wild-flower.co.uk Sun Jul 13 17:21:39 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sun, 13 Jul 2003 22:21:39 +0100 Subject: Multiple Class Inheritance Question In-Reply-To: References: Message-ID: <200307132221.39770.andy@wild-flower.co.uk> On Sunday 13 Jul 2003 8:28 pm, YoTuco wrote: > Does (can) an inheritance scheme like this have any adverse effects > (pitt-falls) for the App class inheriting class 'A' twice? > > Thanx in advance for your input. > > class A: > A_attr = 'A' > ... > def A_methods(self): > ... > > class B(A): > def __init__(self): > ... > > class C(A): > def __init__(self): > ... > > class App(B,C): > def __init__(self): > B.__init__(self) > C.__init__(self) > ... Read guildo's essay on new style classes - that explains it all. In the 'old days' i.e. before Python 2.2.x the rules were different. Now a new algorithm is used which copes better with this. As I said, read the essay (it's on www.python.org - just search for 'new style classes essay'). hth -andyj From mwelsh at abwatley.com Tue Jul 15 07:32:56 2003 From: mwelsh at abwatley.com (Michael Welsh) Date: Tue, 15 Jul 2003 07:32:56 -0400 Subject: asyncore asynchat Message-ID: <200307150732.56310.mwelsh@abwatley.com> In order to learn sockets in Python I am trying to write a simple group chat server and client. I need a little nudge, please. My question contains some GUI but only as decoration. The root question is asyncore / asynchat. I have read that twisted makes this all simple, but, I wanted to get my hands dirty here for educational purposes. I've managed to build a small echo server with asyncore and asynchat that can handle any number of connections and repeat to all clients what was sent in by individual clients. The server seems to work well. The GUI client, wxPython, creates a socket on open. The user types some text and clicks [SEND]. The send event puts the text out to the socket then reads the response and adds it to list control. Everything works well. I'm now ready for the next step, to disconnect the send data from the recieve data. So a user who does not send text, still gets what others may have written. I need to somehow poll the thread so "add to list control" can be triggered on recieving the data. I've tried several approaches and can't seem to get it right. First I tried setting up a separate threading.Thread that created the socket. This way I could put a poll on the socket. I even created (borrowed) a custom event so when data was found, it could notify the GUI and call the "add to list control" But I must have been doing it wrong because it kept locking up in the loop.. I knew from the server side that asynchat has built in helpers with collect_incoming_data() and found_terminator(). (my terminator is appended when data is sent to the server) I could then use the asyncore.poll() in my threading.Thread to raise the custom event that sends data to the GUI, when something comes over the socket. I think I have the concepts right, but the execution breaks down here. I tried having the threading.Thread create an asyn_chat but I keep getting errors that I assume the asyncore.dispatcher takes care of. So... maybe I should use both core and chat on the client as well as the server. The only examples of dispatcher I can find open up an asyn_chat on "listen". The client needs to initiate the communication when it starts. The server is listening and will respond. I won't know on which port the response will come back. Here's some bits showing what I'm trying to do. You may find some of it familiar. I hope I didn't clip anything that may have been needed If anybody has time to point out where I'm going wrong it would be very helpful. Thank you if you were patient enough to get this far... import threading import time import socket import asyncore import asynchat from wxPython.wx import * # server is listening on ... REMOTE_HOST = '172.0.0.1' REMOTE_PORT = 50001 class MyTest(wxFrame): def __init__(self, parent, ID, title): # Initialize wxFrame wxFrame.__init__(self, ..... # start the thread self.network = NetworkThread(self) self.network.start() EVT_NETWORK(self,self.OnNetwork) # build rest of GUI... works fine # the network thread communicates back to the main # GUI thread via this sythetic event class NetworkEvent(wxPyEvent): def __init__(self,msg=""): wxPyEvent.__init__(self) self.SetEventType(wxEVT_NETWORK) self.msg = msg wxEVT_NETWORK = 2000 def EVT_NETWORK(win, func): win.Connect(-1, -1, wxEVT_NETWORK, func) class NetworkThread(threading.Thread): def __init__(self,win): threading.Thread.__init__(self) self.win = win self.keep_going = true self.running = false self.MySock = NetworkServer(REMOTE_HOST, REMOTE_PORT, self.received_a_line) self.event_loop = EventLoop() def push(self,msg): self.MySock.push(msg) def is_running(self): return self.running def stop(self): self.keep_going = 0 def check_status(self,el,time): if not self.keep_going: asyncore.close_all() else: self.event_loop.schedule(1,self.check_status) def received_a_line(self,m): self.send_event(m) def run(self): self.running = true self.event_loop.schedule(1,self.check_status) # loop here checking every 0.5 seconds for shutdowns etc.. self.event_loop.go(0.5) # server has shutdown self.send_event("Closed down network") time.sleep(1) self.running = false # send a synthetic event back to our GUI thread def send_event(self,m): evt = NetworkEvent(m) wxPostEvent(self.win,evt) del evt class NetworkServer (asyncore.dispatcher): def __init__ (self, host, port, handler=None): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((host, port)) def handle_connect (self): # I thought, maybe, the server would trigger this... nope ChatSocket (host, port, self.handler) def handle_read (self): data = self.recv (8192) self.send_event(self.data) print data def writable (self): return (len(self.buffer) > 0) def handle_write (self): sent = self.send (self.buffer) self.buffer = self.buffer[sent:] # send a synthetic event back to our GUI thread def send_event(self,m): evt = NetworkEvent(m) wxPostEvent(self.win,evt) del evt class ChatSocket(asynchat.async_chat): def __init__(self, host, port, handler=None): asynchat.async_chat.__init__ (self, port) def collect_incoming_data(self, data): self.data.append(data) def found_terminator(self): if self.handler: self.send_event(self.data) else: print 'warning: unhandled message: ', self.data self.data = '' class EventLoop: socket_map = asyncore.socket_map def __init__ (self): self.events = {} def go (self, timeout=5.0): events = self.events while self.socket_map: print 'inner-loop' now = int(time.time()) for k,v in events.items(): if now >= k: v (self, now) del events[k] asyncore.poll (timeout) def schedule (self, delta, callback): now = int (time.time()) self.events[now + delta] = callback def unschedule (self, callback, all=1): "unschedule a callback" for k,v in self.events: if v is callback: del self.events[k] if not all: break # ----------------------------------------- # Run App # ------------------------------------------- class TestApp(wxApp): def OnInit(self): frame = MyTest(None, -1, "Test APP") frame.Show(true) self.SetTopWindow(frame) return true app = TestApp(0) app.MainLoop() From jdhunter at ace.bsd.uchicago.edu Tue Jul 22 12:04:41 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Jul 2003 11:04:41 -0500 Subject: Iterating order of dict.items() In-Reply-To: <16469f07.0307220706.5e2fe1e4@posting.google.com> (robin.cull@pace.co.uk's message of "22 Jul 2003 08:06:28 -0700") References: <16469f07.0307220706.5e2fe1e4@posting.google.com> Message-ID: >>>>> "Robin" == Robin Cull writes: Robin> So, is the order of dict.items() defined? If so, what is Robin> that order? Is there any way to control the order my dict Robin> is iterated over? See the FAQ: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.091.htp The Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 And the usenet archives on http://groups.google.com search for: python order dictionary John Hunter From mcherm at mcherm.com Tue Jul 1 14:33:49 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 1 Jul 2003 11:33:49 -0700 Subject: Suggesting for overloading the assign operator Message-ID: <1057084429.3f01d40d6e1dd@mcherm.com> Rim writes: > I have been thinking about how to overload the assign operation '='. [...] > the > second assignment below ereases all Currency knowledge from variable > 'c', when the user only wanted to update the value of c, not its type: > > c=Currency(5) > c=7 > > I fully understand the workaround of doing c=Curreny(7) instead, but > users don't want to be bothered with that. I think you have a fundamental misunderstanding of how assignment works in Python. In some languages (C for example) variables are things that have a TYPE and a VALUE. You typically set the TYPE by declaring the variable and typically can't change it. You typically set the VALUE by assignment. In at least one case (C++ is the only example I know of) you can override the meaning of assignment to variables of a certain type. In Python, variables do NOT have a type and a value. Instead, variables have a single value, which is always some object. Objects have a type (and sometimes a class also... I'm not going to worry about this difference). But there's little connection between variables and types. When we assign (actually, a better term is "rebind") a variable it can be assigned to any object. >>> x = "a string" >>> x = 5 >>> x = Currency(7) I'm confident that what you want to achieve can be accomplished in Python, you just have to adjust your mindset. In Python it's useful to think of things in terms of namespaces. (See last line of "http://www.awaretek.com/zen.html".) Namespaces are just dictionaries -- and they're used throughout Python. When you write >>> x = "abc" you are simply performing __setitem__("x", "abc") on a namespace called the "module globals". If you want, you can get ahold of this dictionary via the function globals(), and you can see that manipulating it is just the same as using "=". >>> x = 'a string' >>> theGlobals = globals() >>> print theGlobals {'__builtins__': >> theGlobals["y"] = 7 >>> print y 7 Function definition is just another operation on this namespace... writing "def func(x): return x + 1" is (almost) the same as "globals()["x"] = lambda x: x + 1". When you use local variables within a function, you are manipulating another namespace, (for performance purposes it's not actually implemented as a dictionary, but it acts as if it were... just call locals() to see it as a dict). So when you say that you want your users to be able to do this: >>> x = Currency(5) >>> x = 7 and then have x be a Currency object, what you're *really* saying is that you want to take over control of the namespace that your users are working in so that they can't store just anything in it, but are forced to store only Currency objects. Or perhaps you mean for them to be able to store only Currency objects for any key which was previously used for a Currency object. Or maybe you mean that if they try storing a NUMBER in a slot which was previously used to store a Currency object that a new Currency object should be stored instead. Actually, I'm not quite certain what your requirements are, but it's pretty clear to me that what you want is a special namespace with custom behavior. Well, Python provides special namespaces with customizable behavior. They're called classes. Classes are just another namespace ("one honking great idea")... well, technically TWO namespaces: one for the class itself and one for the individual object. Normally, saying "myObject.x = 7" performs another dictionary assignment (this dictionary is accessible as "myobject.__dict__"), but you can use the special functions __getattr__, __setattr__, __delattr_, and perhaps __getattribute__ to customize its behavior. So I'm guessing that you can accomplish your objective by getting your users to store their values as fields in an object and providing customized behavior on that object. I was going to suggest that you create a custom dict type (here's one that just prints stuff out when modified... you could use any logic you wanted): >>> class NoisyDict(dict): ... def __setitem__(self, key, value): ... print 'setting %s to %r' % (key, value) ... dict.__setitem__(self, key, value) ... and that you then use it in an exec statement, like this: >>> exec "x = 7\nprint x" in NoisyDict() 7 Unfortunately, it didn't work (that printed "7", but didn't print "setting x to 7"), so you may need a slightly better guru than me to get this working. Or if you can better describe your PARTICULAR problem, I may be able to figure out how to approach it. But I'm almost certain that there's a much easier way than changing how Python does assignments. -- Michael Chermside From efkw at fawekm.com Fri Jul 25 16:29:15 2003 From: efkw at fawekm.com (Adam) Date: Fri, 25 Jul 2003 22:29:15 +0200 Subject: looping through a file In-Reply-To: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> Message-ID: Psybar Phreak wrote: > hi all - ive just started with python (after having done java and c) and am > having a little bit of trouble with the script. Im using as a login script. > > There's a users.dat file in the format > user1 > user1password > user2 > user2password > ... etc > > at the moment - the code i work, only checks the first and second lines (ie. > details of user1). but it appears that python doesn't have a do... while... > until loop. > > > can anyone help? > > thanks!! > > Ive attached the appropriate part of the code i have working > > ------------------------------- > > #!/usr/local/bin/python > > import cgi, string > > form = cgi.FieldStorage() > > if form.has_key('usernameField') and form.has_key('passwordField'): > users_username = string.strip(form['usernameField'].value) > users_password = string.strip(form['passwordField'].value) > > InFile = open('users.dat', 'r') > > file_username = string.strip(InFile.readline()) > file_password = string.strip(InFile.readline()) > > > > > authorised = 0 > > while file_username and file_password: > if file_username == users_username: > if file_password == users_password: # correct > authorised = 1 > break > else: # login matched but not > password > file_username = InFile.readline() > file_password = InFile.readline() > else: # neither match > file_username = InFile.readline() > file_password = InFile.readline() > > use the readline method. take advantage of the fact that readline returns an empty string when it reaches EOF, and do: while(line): line=readline From grante at visi.com Wed Jul 23 15:11:05 2003 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2003 19:11:05 GMT Subject: How to disable output messages of the child process, in spawnv( )? References: Message-ID: <3f1eddc9$0$160$a1866201@newsreader.visi.com> In article , nushin wrote: > I'd like to disable the output of the process spawned by spawnv( ) > API, but the catch is that i *have to* see the output of the parent > process making the spawnv( ) call. Has anyone done that? I have some > pointers that by using dup2( ) API i might be able to do that, any > ideas how? Also, i have to spawn as an asynch call, using P_NOWAIT, > e.g.,: > > os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) Nope. The ">" and "&" are things that a shell (like bash or ksh) handles. The python interpreter has no idea what to do with them. If you want to use ">" and "&", then spawn a shell, and pass it a command to run the python program with output redirected. -- Grant Edwards grante Yow! I'm RELIGIOUS!! I at love a man with a visi.com HAIRPIECE!! Equip me with MISSILES!! From h.b.furuseth at usit.uio.no Mon Jul 14 07:44:42 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 14 Jul 2003 13:44:42 +0200 Subject: path module References: Message-ID: Ian Bicking wrote: >On Tue, 2003-07-08 at 09:52, Hallvard B Furuseth wrote: >> If there is going to be a New Wonderful Path module, I suggest you give >> some thought to paths on systems that don't fit the simple Unix/Windows >> path model. A path to a filename may e.g. looks different from a path >> to a directory. (...) > > Interesting, but I think a bad idea. (...) If someone was using VMS > paths, I would assume they would subclass path for that OS, adding the > portions that applied. It would be pointless to include _data structures_ for components that are not supported on any system Python is ported to, but for subclassing to make sense, some of the _interface_ would have to be in place. Like the possibility of usin path.joindir() vs. path.joinfile() or something depending on whether the result should be a file or directory path. And just path.join() for people who don't care. Assuming there will be a join method, of course. Also, you may need some special handling of 'device:' on Windows. > I think it's unreasonable to expect people programming on normal > platforms to pay attention to components like version, so even > including it in a structured manner is asking for trouble. I dunno. People have already mentioned coming systems where versions will be availbale. -- Hallvard From cybersamurai at mac.com Fri Jul 11 09:40:05 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Fri, 11 Jul 2003 10:40:05 -0300 Subject: event on a panel inside of a wxHtmlwindow Message-ID: <3F0EBE35.2070508@mac.com> How I can handle events on a button in a panel inside of a wxHtmlwindow? From tim.one at comcast.net Sun Jul 27 18:25:35 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 27 Jul 2003 18:25:35 -0400 Subject: python assignment In-Reply-To: Message-ID: [dan] > ... > Can I always assume that an operation of this sort will return a new > object, even if it has no effect on one of the operands? Yup. From the "Objects, values and types" section of the Language (not Library) Reference Manual: ... for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after "a = 1; b = 1", a and b may or may not refer to the same object with the value one, depending on the implementation, but after "c = []; d = []", c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that "c = d = []" assigns the same object to both c and d.) Other implications are that, e.g., if L is a list and T is a tuple, after L2 = L + [] T2 = T + () "L2 is L" must be False, but "T2 is T" may be True or False. There aren't a lot of optimizations of the latter type in CPython today; most of them involve strings, where an empty-string operand is quite common: >>> s = "a string" >>> t = s + "" >>> id(s) == id(t) True >>> t = "" + s >>> id(s) == id(t) True >>> t = ''.join([s]) >>> id(s) == id(t) True >>> From belred1 at yahoo.com Mon Jul 14 02:28:09 2003 From: belred1 at yahoo.com (Bryan) Date: Mon, 14 Jul 2003 06:28:09 GMT Subject: anything like C++ references? References: Message-ID: "Stephen Horne" wrote in message news:rp94hvc8fg6h91oe7ctqq9jn9ku3nlud1k at 4ax.com... > On Sun, 13 Jul 2003 22:42:21 GMT, "Bryan" wrote: > > > > >> 3. Why is there no way to reference an immutable object via a > >> pointer, other than stuffing it into a mutable object designed for > >> some purpose other than simple pointer behaviour? > >> > > > >>>> a = (1, 2, 3) > >>>> b = a > >>>> id(a) > >15471760 > >>>> id(b) > >15471760 > >>>> print b[1] > >2 > >>>> > > > > > >i just referenced an immutable object via a "pointer" and i __did_not__ > >stuff it into a mutable object as you say. > >a and b "point" to the same object. > > Technically, but what is the point? You can't do pointer-style things > with it. You can't change the object in any way without changing the > id, and you can't use the mechanism to, for instance, allow 'var' > parameters. > can you show what functionality is missing by not being able to do "pointer-style things"? here are two variables: a = (1, 2, 3) b = [1, 2, 3] one immutable, one mutable. please show an example of what "pointer-style things" you would like to do. i've read this entire thread so far, and from a practical point of view (because that's all i really care about and what pays the bills), i really don't understand what the problem is. personally, i don't care about the strict definitions of computer science terms and what "variable" or "pointer" means. i do care about how fast problems can be solved, how much resources must be involved in solving that problem, and how much money can be made/saved. for me, python is a winner in all this area. not having pointers like c/c++ is such a blessing. i can't believe anyone would even suggest that pointers and/or doing things with pointers be brought into python. ok... one more time... let's bring this conversation down to something practical. please show an example of pointer-style functionality in any language that is missing/awkward/complicated in python. i'm not an expert in python, i'm just very curious to understand what the true practical issue is. thanks, bryan > In short, you are showing evidence of the use of pointers internally > within Python, but that is not the same as providing pointer-like > semantics. > From hokiegal99 at hotmail.com Wed Jul 16 08:57:33 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 16 Jul 2003 08:57:33 -0400 Subject: <> and != References: <3F154B63.3060503@hotmail.com> Message-ID: <3F154BBD.2060304@hotmail.com> that sould be: if newfile <> oldfile if newfile != oldfile From http Thu Jul 10 21:45:17 2003 From: http (Paul Rubin) Date: 10 Jul 2003 18:45:17 -0700 Subject: Securing 'pickle' References: Message-ID: <7x1xwxu98y.fsf@ruckus.brouhaha.com> Ben Finney writes: > Why not store the pickles on the server, and set a session cookie to > refer to them? That way, you only send a short session ID instead of > the whole pickle, and messing with the cookie doesn't alter the pickles. Because now you need a mechanism to store the session info on the server, and you might want it to work across multiple load-balanced servers that fail over to one another, etc. To the OP: I'd be very careful of any attempt to unpickle untrusted strings. At minimum I'd say you should authenticate your cookies to make sure no one has messed with them. Configure a secret string into the server, and use the hmac module to append a MAC to each cookie and check the MAC before unpickling. Or use that BitTorrent serializer but modify it to include floats if you need that. From madsurfer2000 at hotmail.com Mon Jul 21 14:01:31 2003 From: madsurfer2000 at hotmail.com (-) Date: 21 Jul 2003 11:01:31 -0700 Subject: Strings and Unicode References: Message-ID: sjmachin at lexicon.net (John Machin) wrote in message news:... > madsurfer2000 at hotmail.com (-) wrote in message news:... > > > > I would have expected the following: > > ['param=abc+%E6'] > > So would I. See below. However despite the fact that the last > character in your 'value' shows up as "small ae ligature" in MSIE, we > would really like to see some code of yours that *minimally* and > *unambiguously* shows the problem, and can be executed in the minimal > Python environment (i.e. sans gui, command prompt, again: see below). > Turns out it wasn't Python's fault. I used IDLE, and it saved the program in UTF-8 format. I didn't think of checking that before, because I assumed it wouldn't save in that format. When the parameters were sent to urlencode, it was interpreted as 8 bit characters. The '?'-character ("small ae ligature")is represented as 2 characters in UTF-8, so urlencode() encoded them separatly. The solution was to open the file in Notepad (!) and save it in a different format. When I ran the program again, it produced the expected results. Is there any way I can use IDLE, and still save in ISO-Latin1? The problem is probably related to the input from the keyboard. It seems that I can edit the file after I have converted it from UTF-8, and keep the encoding if I use the lower part of the character set. If I press the '?' key on the keyboard, the character is translated to a 2 byte representation, but the other characters are left alone. From lists at gregfortune.com Thu Jul 31 17:09:02 2003 From: lists at gregfortune.com (Greg Fortune) Date: Thu, 31 Jul 2003 14:09:02 -0700 Subject: SQL2000 database vs python, using mssqldb References: Message-ID: It appears you are using the api correctly assuming mssqldb provides the Python v2.0 db api. You can find that document at http://python.org/peps/pep-0249.html You'll have to check the mssqldb packages for specific documentation about any changes/limitations in that module. Greg Fortune Fortune Solutions Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > First of all, thanks for all the help guys! > > Until now, lots of install problems on all the recommended > packages/modules. > > For now, my best option was to make use of my existing Pyro framework > (thanks Irmen!) I already build a MSSQL (Pyro/server)service on the > windows box using mssqldb. My linux app will talk to this service. > This at least has been installed successful and my service can already > connect to the database. > > So far so good: Now, I can't find the API of MSSQL. Not on the website nor > in the installed folders. So, I tried to use the examples and only the > connections seems successful. When I try a select on a table, it tells me > that the table name is an invalid object name. > > Just tried a kind of a hello world example... > > import mssqldb > import MSSQL > db = MSSQL.connect('my_db_server', 'user', 'password', 'my_database') > ## so far, so good > > c = db.cursor() > c.execute('select * from my_table') > ## boom, error > > c.fetchall() > c.nextset() > > The ms sql enterprise manager shows me that the database and table is > there. Unfortunately, in python the error tells me: Invalid object name > 'my_table' > > Anyone with experience? > Where are the API's? > > Vincent From fale.delete at remove.skidata.com Thu Jul 24 06:39:27 2003 From: fale.delete at remove.skidata.com (Leopold Faschalek) Date: Thu, 24 Jul 2003 12:39:27 +0200 Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> Message-ID: "Grant Edwards" wrote in message news:3f1ed31a$0$181$a1866201 at newsreader.visi.com... > How does one do raw Ethernet under Win32? Ultimately, I want > to do it in a Python program, but if somebody can point me to a > clue on how to do it from C, I could probably figure out the > rest. > > I want to: > > 1) Send an arbitrary Ethernet packet. [Well, not completely > arbitrary, the source MAC will be "right", but the protocol > number is a proprietary (not IP) one, and the packet isn't > anything standard. > > 2) Receive any incoming packets with a specified protocl > number -- same proto number as in 1) above. > > I've got a program that works under Linux, and I'd like to be > able to port it to Win32... > the new winsock2.h supports more socket types: /* * Types */ #define SOCK_STREAM 1 /* stream socket */ #define SOCK_DGRAM 2 /* datagram socket */ #define SOCK_RAW 3 /* raw-protocol interface */ #define SOCK_RDM 4 /* reliably-delivered message */ #define SOCK_SEQPACKET 5 /* sequenced packet stream */ so you have only to define 3 as type in the socket() call greetings Leopold Faschalek > -- > Grant Edwards grante Yow! I have seen these > at EGG EXTENDERS in my > visi.com Supermarket... I have read > theINSTRUCTIONS... From reply.in.the.newsgroup at my.address.is.invalid Tue Jul 8 13:43:58 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 08 Jul 2003 19:43:58 +0200 Subject: COM Programming References: <6308fa3f.0307080220.5889317b@posting.google.com> Message-ID: Rene Pijlman: >http://safari.oreilly.com/JVXSL.asp?x=1&mode=section&sortKey=rank&sortOrder=desc&view=book&xmlid=1-56592-621-8&open=false&g=&srchText=python+win32&code=&h=&m=&l=1&catid=&s=1&b=1&f=1&t=1&c=1&u=1&r=&o=1&page=0 __eq__ http://safari.oreilly.com/1565926218 -- Ren? Pijlman From rnd at onego.ru Thu Jul 3 12:10:59 2003 From: rnd at onego.ru (Roman Suzi) Date: Thu, 3 Jul 2003 20:10:59 +0400 (MSD) Subject: Paul Baranowski (from Peekabooty) language of choice In-Reply-To: <33803989.0307030252.58dab0b0@posting.google.com> Message-ID: On 3 Jul 2003, Miki Tebeka wrote: >Hello All, > >FYI: >http://peek-a-booty.org/Docs/WhichLanguageDoYouRecommend.htm >coming from: >http://www.peek-a-booty.org/pbhtml/index.php I hope this will not lead to banning Python in China... Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From mis6 at pitt.edu Mon Jul 28 17:55:48 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 28 Jul 2003 14:55:48 -0700 Subject: mixin class References: <3F24F8D2.E1ADFB08@web.de> Message-ID: <2259b0e2.0307281355.34725f83@posting.google.com> Udo Gleich wrote in message news:<3F24F8D2.E1ADFB08 at web.de>... > Hi, > > I try to implement mixin classes. Thats why I > need to make a new class at runtime. > > --tmp.py------------------------------------- > > import new > > class K1(object): > pass > > class K2(object): > pass > > mixed = new.classobj("K1_K2", (K1, K1), {}) > new_instance = new.instance(mixed, {}) > > print new_instance > > --------------------------------------------- > > Making a new instance from the new class works > only if K1 is not derived from object. If I use > new style classes I get the following traceback: > > Traceback (most recent call last): > File "tmp.py", line 10, in ? > new_instance = new.instance(mixed, {}) > TypeError: instance() argument 1 must be class, not type > > I use Python 2.2.3 and Win2000. > > My question: How do I implement mixin classes > with new style classes? > > Thanks, > > Udo Why not simply class K1(object): pass class K2(object): pass mixed = type("K1_K2", (K1, K1), {}) new_instance = mixed() print new_instance ? "type" is described in http://www.python.org/2.2.3/descrintro.html (in one line very easy to miss ;) Michele From bgailer at alum.rpi.edu Wed Jul 2 11:37:45 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 02 Jul 2003 09:37:45 -0600 Subject: Problems with io. In-Reply-To: <8e35bad8.0307020516.55bb1ddc@posting.google.com> Message-ID: <5.2.1.1.0.20030702092803.023ccfe8@66.28.54.253> At 06:16 AM 7/2/2003 -0700, freone wrote: >Hello, >some time ago I started to learn python, today i wanted make a very >samll and simple program. >file = open("test.txt", "r+") >file.readlines() >file.close() >And it doesn't work... >Why? ATTENTION EVERYONE who submits a problem...PLEASE PLEASE PLEASE tell us what the problem is (how you are running it, expected behavior, actual results, exceptions, ...). Without that info we have NO way to help, and we are frustrated as a result. Having said that here's my guess. If you are running this code from a file (either by C>python filename.py or by import filename and you see no output then the program IS working. If you want output you'll need to use print, as in print file.readlines(). BTW file is a python builtin, and it's a good idea to not use it as a variable. In fact file is the new and preferred alternative to open: fileA = file("test.txt", "r+") fileA.readlines() fileA.close() Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From grante at visi.com Thu Jul 24 00:06:21 2003 From: grante at visi.com (Grant Edwards) Date: 24 Jul 2003 04:06:21 GMT Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> <3f1ee77f$0$160$a1866201@newsreader.visi.com> Message-ID: In article , Gerhard H?ring wrote: > >> It looks like I can _almost_ do what I want with the python >> wrapper around the windows pcap lib. > > Where's PyLibpCap for Windows available? Here's where I got it from: http://ghaering.de/python/unsupported/pylibpcap/ ;) I'd take a whack at finishing it, but I don't have a Windows C compiler. -- Grant Edwards grante Yow! Did you find a at DIGITAL WATCH in YOUR box visi.com of VELVEETA?? From bgailer at alum.rpi.edu Sat Jul 12 17:11:54 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 12 Jul 2003 15:11:54 -0600 Subject: any such thing as list interleaving? In-Reply-To: Message-ID: <5.2.1.1.0.20030712150942.02a9ee28@66.28.54.253> At 02:00 PM 7/12/2003 -0700, Tom Plunket wrote: >I find myself often doing the following sort of thing (sorry for >lack of whitespace, I don't want the line to break): > >for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)): > # ... > >This definitely seems like a roundabout way to loop through >parallel lists together. Is this map routine truly the easiest/ >best/most straight-forward way to do a for loop through parallel >lists, if I feel that the Python anti-idom of: > >for index in range(len(myList)): > entry = aList(index) > anotherEntry = anotherList(index) > # ... mergedList = zip(aList, anotherList) >This also brings up a similar problem for me when iterating over dictionaries: > >for key in myDict: > value = myDict[key] > # ... > >This seems a pretty sloppy way to go about it, imo. There must be >something more in the Python spirit! :) for key, value in myDict.items(): Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From BPettersen at NAREX.com Wed Jul 23 04:40:08 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 23 Jul 2003 02:40:08 -0600 Subject: python assignment Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE46E6@admin56.narex.com> > From: Juha Autero [mailto:Juha.Autero at iki.fi] > > "Tim Peters" writes: > > > It would be very unusual (because bad design) for the __iadd__ > > method of a mutable type to return a pre-existing object, though. > > I'm confused. I thought that the idea of __iadd__ is that for > *mutable* types it modifies existing object instead of returning new > one. So, was that a typo or are Python lists just bad desing: [...] "... mutable type to return a[nother] pre-existing..." "... return a pre-existing object [besides iteself]..." context?'ly y'rs -- bjorn From srovner at us.ibm.com Fri Jul 25 08:37:02 2003 From: srovner at us.ibm.com (Sonia Rovner) Date: 25 Jul 2003 05:37:02 -0700 Subject: How to import hackicon.dll References: <8a5a6d82.0307240417.494caa13@posting.google.com> Message-ID: <8a5a6d82.0307250437.72f9b29a@posting.google.com> 336699 at emailaccount.com (336699) wrote in message news:... > srovner at us.ibm.com (Sonia Rovner) wrote in message news:<8a5a6d82.0307240417.494caa13 at posting.google.com>... > > Hello, > > I'm using Python2.2.1 and Tcl/Tk 8.3 running on Win2000. I've been > > researching how to change the icon on the title bar and found that > > hackicon is the one I should pursue. However, hackicon package uses a > > dll. When I run the hi.py, I get an error saying > > ImportError: DLL load failed: The specified module could not be > > found. > > I copied hackicon.dll to various directories in my pythonpath but > > nothing happens. > > Use tkIcon > > http://effbot.org/downloads/index.cgi/tkicon-0.9-19980218.zip I didn't have much luck with tkIcon either. It required installing PIL so that the import image works. I was hoping not to have to install another libray. Maybe I don't have any choice. Thanks all. Sonia From maxm at mxm.dk Wed Jul 16 07:44:35 2003 From: maxm at mxm.dk (Max M) Date: Wed, 16 Jul 2003 13:44:35 +0200 Subject: How about using python to write a CMS? In-Reply-To: References: Message-ID: <3f153a2b$0$97201$edfadb0f@dread12.news.tele.dk> ?????? wrote: > To write a CMS, everyone is thinking about PHP, but, what do you think if I > am using python to write a Content Management System? It can be done, and better than in PHP, but do yourself the favour of checking out Plone. www.plone.org regards Max M From abelikov72 at hotmail.com Tue Jul 8 12:12:01 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 08 Jul 2003 16:12:01 GMT Subject: Python vs PHP References: Message-ID: On 8 Jul 2003 16:02:48 GMT, Jon Ribbens wrote: >In article , Afanasiy wrote: >> A couple other slight issues : >> >> * catch-all error handling not as flexible or non-existent >> * no equivalent to php_value auto_prepend_file "_header.php" >> * no equivalent to php_value auto_append_file "_footer.php" >> * not as intelligent form value handling >> * white space sensitivity is a unique problem when embedding > >Try jonpy (http://jonpy.sf.net/), it solves all of the above. >Also you may find FastCGI (which jonpy supports) helps with your >"safe mode" problem, although it might require a bit of hackery. No, CGI is not an option and I tried jonpy. I kept my notes about it... From h.goebel at goebel-consult.de Wed Jul 23 07:49:50 2003 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 23 Jul 2003 13:49:50 +0200 Subject: Perl -> Python hopeless? In-Reply-To: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> References: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> Message-ID: <3f1e7654$0$6755$9b4e6d93@newsread2.arcor-online.net> Helmut Jarausch schrieb: > Is there a tool to lesson the burdon of translation of Perl to Python? You may try bridgekeeper (http://www.crazy-compilers.com/bridgekeeper/). But typically it' better to completly rewrite the code since Python offers different features. Regards Hartmut Goebel -- | Hartmut Goebel | IT-Security -- effizient | | h.goebel at goebel-consult.de | www.goebel-consult.de | From piet at cs.uu.nl Sun Jul 13 10:08:59 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 13 Jul 2003 16:08:59 +0200 Subject: Any pure-python relational databases? References: <2a897f11.0307121143.4a37113b@posting.google.com> Message-ID: >>>>> David McNab (DM) wrote: DM> On Sat, 12 Jul 2003 12:43:25 -0700, Wayne Pierce paused, took a deep DM> breath, then came out with: >>> 2) Any kind of relational DBMS written in pure python that'll run on >>> 1.5.2? >> >> While not relational, have you looked at Metakit? >> >> http://www.equi4.com/metakit/python.html DM> I got Metakit to compile for Python 1.5.2 without undue drama, just a DM> couple of makefile hacks. DM> Uploaded the shared lib and the python wrapper to the host, and it runs DM> just fine. DM> What a sweet little dbms! You must, however, be aware of multitasking issues, certainly on a web site. When more than one request comes in at your site at approximately the same time and they want to make modifications in your database, the modifications may interact in a non-intended way, even to the point that they may corrupt your database. Some file locking should be applied to serialize the updates (and probably the reads as well with respect to the updates). Metakit doesn't have record locking, unfortunately. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From robin at jessikat.fsnet.co.uk Tue Jul 8 14:10:49 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 8 Jul 2003 19:10:49 +0100 Subject: anything new on the ternary operator? References: <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com> <40a939c9.0307080622.3118cfd7@posting.google.com> Message-ID: <2UVsCJApkwC$EwTg@jessikat.demon.co.uk> In article , Skip Montanaro writes > > >> [The consensus in EP was that Israel was in Europe] > > Alia> Sorry, I am confused: isn't Israel in the Middle East? > >Sure, but what continent is the the Middle East in, Europe, Asia or Africa? >I had to make the same decision in Musi-Cal. I decided that Israel was part >of Europe. The decision wasn't entirely arbitrary. Most concert dates we >list for Asia are in Japan, Korea or Hong Kong. There are almost never any >African concert dates listed. Israel was close enough to Europe that it >made sense to group it there. > >Skip > > the Middle East is certainly not in Europe at least according to classical authors, historians & geographers. Asia begins across the Hellespont so asiatic Turkey, Iraq, Syria, Palestine are not in Europe and neither is the Israeli territory. I suspect Israelis would prefer to be in America so that they wouldn't have to take part in the Eurovision song contest. -- Robin Becker From sismex01 at hebmex.com Mon Jul 14 16:38:23 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 14 Jul 2003 15:38:23 -0500 Subject: % operator -- did Python or C++/boost come first? Message-ID: > From: roy at panix.com [mailto:roy at panix.com] > Sent: Lunes, 14 de Julio de 2003 03:28 p.m. > > Up until recently, Python was the only language I'd ever seen that > used the % operator for string replacement. Today, I was perusing the > C++ Boost libraries, and discoverd that boost::format uses a very > similar syntax. The following lines print the same thing in Python > and C++, respectively. > > print "int->%i, string->%s" % (42, "wugga, wugga") > cout << boost::format ("int->%i, string->%s\n") % 42 % "wugga, wugga"; > > The question is, which came first? Did boost adapt the Python syntax, > or the other way around, or did they both evolve in parallel? I'm not > talking about the use of % in the C/printf style format specifier, but > the use of % as an operator to connect the format specifier with the > data to be formatted. > I don't think anybody copied anybody's idea, rather, it's quite logical to think up "%" as a string-formatting operator, because of it's ties with it's use in printf() style format strings. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From alanmk at hotmail.com Sun Jul 20 11:30:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 20 Jul 2003 16:30:49 +0100 Subject: xml processing and sys.setdefaultencoding References: Message-ID: <3F1AB5A9.1C8847E1@hotmail.com> christof hoeke wrote: > i wrote a small application which extracts a javadoc similar > documentation > for xslt stylesheets using python, xslt and pyana. > using non-ascii characters was a problem. That's odd. Did your stylesheets contain non-ascii characters? If yes, did you declare the character encoding at the beginning of the document, e.g. " > so i set the [python] defaultending to > UTF-8 and now everything works (at least it seems so, need to do more > testing though). If you don't put an encoding declaration in your XML documents (including XSLT style/transform sheets), then an XML parser would by default treat the document content as UTF-(8|16), as the XML standard mandates. Are you working from XML documents which are stored as strings inside a python module? In which case, your special characters will actually be encoded in whatever encoding your python module is stored. So you might need to put an encoding declaration on your python module:- http://www.python.org/peps/pep-0263.html > it may not be the most elegant solution (according to python in a > nutshell) > but it almost seems when doing xml processing it is mandatory to set the > default encoding. xml processing should almost only work with unicode > strings and this seems the easiest solution. It is always recommended to explicitly state the encoding on your XML documents. If you don't, then the parser assumes UTF-(8|16). If your documents aren't really UTF-(8|16), then you will get seemingly random mapping of characters to other characters. > any comments on this? better ways to work If you're not dealing specifically with ASCII, then declare your encodings, in both your python modules and your xml documents. Find out what is the default character set used by your text editor. Find out how to change which character set is in use. If you create, sell or maintain text editing or processing software, make it easy for your users to find out what character encodings are in effect. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ianb at colorstudy.com Sat Jul 12 18:56:57 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2003 17:56:57 -0500 Subject: anything like C++ references? In-Reply-To: <000301c348c7$3c501980$21795418@dell1700> References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <1058050617.28466.279.camel@lothlorien> On Sat, 2003-07-12 at 17:45, Brian Quinlan wrote: > > void change(int& i) > > { > > i++; > > } > > The idiomatic way to write this code in python would be: > > def change(val): > return val + 1 To be more specific, you would achieve the same effect with: def change(val): return val + 1 i = change(i) As opposed to the C++ where you'd do: change(i) // no assignment needed There is no direct Python equivalent to the C++ function, for all sorts of reasons (most of them very deliberate). Is there someplace in particular to reference people who need to learn about what Python variables are (that they are bindings, etc)? This question comes up in many forms all the time, particularly from people with a C background. Or rather, there are many questions all of which are answered by that explanation (so we can't expect people to stop asking, but maybe we can make the answers easier and clearer). Or maybe a general Python-for-C-programmers tutorial... Ian From jjl at pobox.com Sat Jul 12 18:03:34 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Jul 2003 23:03:34 +0100 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> Message-ID: <87y8z34d3d.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > In article <3F0FC088.3C56EDEA at alcyone.com>, > Erik Max Francis wrote: [...] > >> Prohibited: > > > >Is this some IDLE-specific thing? > > Nope, the point here is that > > raise Prohibited > > will always create a Prohibited() instance. (See also Peter's post > about One True Way for exceptions.) Perhaps Erik was wondering, as I was, where that "" came from. On my machine, 2.3b1 doesn't print that in response to Raymond's example code. Maybe it's from 2.3b2 (which I'm downloading ATM), or IDLE, or something else? John From skip at pobox.com Thu Jul 24 16:14:42 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jul 2003 15:14:42 -0500 Subject: Regex: Limiting Scope without capturing results In-Reply-To: <173ef463.0307240355.cf896bb@posting.google.com> References: <173ef463.0307240355.cf896bb@posting.google.com> Message-ID: <16160.15922.601581.172169@montanaro.dyndns.org> Gordon> If I remove the ()s around the string|float|color match it stops Gordon> matching anything, so is there an alternative to these ? Or a Gordon> way of telling them to limit the scope of the match without Gordon> capturing the result ? Sure, use (?:). Full details at 11: http://www.python.org/doc/current/lib/re-syntax.html Skip From hokiegal99 at hotmail.com Sun Jul 6 11:41:40 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sun, 06 Jul 2003 11:41:40 -0400 Subject: Calculating Year, Month and Day of Life In-Reply-To: References: Message-ID: Cousin Stanley wrote: > hokiegal ... > > I spent 1971-1978 as a graduate student at VPI > chained to a lab bench over in Davidson Hall, > so I actually know what a Hokie is ... > > Best of luck with your Python endeavors ... Thanks Cousin Stanley! I'm learning as much about Python as I can. I like it because it has both a theorhetical/academic side and a practical/get-stuff-done side. It also helps me to better understand C, C++ and Java. It's great. I was class of 1998 at Virginia Tech. The VT degree has been good for me! When it comes to tech schools... there's no place like Virginia Tech. Go Hokies!!! From tzot at sil-tec.gr Mon Jul 21 10:41:50 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 21 Jul 2003 17:41:50 +0300 Subject: Using Loops to track user input References: <3F08E00F.69360669@engcorp.com> Message-ID: On Sun, 06 Jul 2003 22:50:55 -0400, rumours say that Peter Hansen might have written: >Gerhard H?ring wrote: >> >> hokiegal99 wrote: >> > I don't understand how to use a loop to keep track of user input. Could >> > someone show me how to do what the program below does with a loop? >> >> Your text book or tutorial should show that quite well, but here we go: >[snip] >> If your prof is any good, (s)he reads this newsgroup as well ;-) > >You missed this one Gerhard. In another thread, hokiegal99 already >told us "I am a funeral director trying to write a small program that >calculates the number of years, months and days a person has lived by >entering the year, month and day of their birth. ..." This is true. However, doesn't hokiegal99's comment at the start of the example code: > #Write a program that reads 10 numbers from the user and prints out the > sum of those numbers. seem a little 'textbookish'? Who's the first person of this imperative sentence, and who's the user? :) Although it's not improbable that hokiegal99 is indeed a funeral director having their first contact with programming using a textbook. I remember that it took me a couple of days to understand loops (at the age of eleven)... BTW computers really spoil us... now that I visited the memory lane, I recall that, having a chemistry exam at the age of seventeen, it took me a quarter of an hour to solve a generic exercise and ten more minutes to remember how to do a division by pen and paper (ok, I should take anxiety into account, but it's still funny :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From dave at pythonapocrypha.com Thu Jul 3 13:44:05 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 3 Jul 2003 10:44:05 -0700 Subject: A story about Python... sort of In-Reply-To: <3F043B22.19FE79AE@engcorp.com> References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: <200307031044.05386.dave@pythonapocrypha.com> On Thursday 03 July 2003 07:18 am, Peter Hansen wrote: > Max Khesin wrote: > > import flame.* > > import sorry.* > > Ok, with all my respect to python, the stuff about C++ is a bunch of > > hooey. Compilation time is the problem? Give me a break. > > 1) separate compilation? > > 2) precompiled headers? > > 3) tools that allow cluster compilation? > > 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ > > project. letter-envelope idiom to help compilation...etc. > > Sounds to me that if they've come up with so many and such a wide > range of optimizations to improve compilation time, then it clearly *is* > a problem... Yep! I just read an article in the July issue of Game Developer that mentioned this topic (item #3 above) in passing. It was a post-mortem of the project and they cited as one of their life-savers a tool that used all computers in the office to assist in the compilation of the game - a compilation farm basically - so that the full rebuild of the game could be reduced to only 3 minutes. Obviously you don't need to do a "rebuild all" for every change to the code, but compilation and link time is a very real cost, especially as the project size grows. Even for small projects though, I'm much more likely to try out small, incremental changes in a language like Python than when I did C++ or Java because it's just so quick and easy to try it out. -Dave From kent at NOSPAMspringfed.com Mon Jul 21 07:32:56 2003 From: kent at NOSPAMspringfed.com (Kent Tenney) Date: Mon, 21 Jul 2003 06:32:56 -0500 Subject: distutils.core not in Debian python2.2 package In-Reply-To: References: Message-ID: David M. Cooke wrote: > At some point, Kent Tenney wrote: > > >>David M. Cooke wrote: >> >>>At some point, Kent Tenney wrote: >>> >>> >>>>Howdy, >>>> >>>>I did; >>>># apt-get install python2.2 >>>> >>>># python >>>>Python 2.2.1 >>>>... >>>> >>>>then checked docutils out of CVS >>>>and did; >>>> >>>>docutils# python ./setup.py install >>>> >>>>ImportError: No module named distutils.core >>>> >>>>How do I install distutils? >>> >>>Install the python2.2-dev package. >> >>It surprises me to find distutils in a package described as: >> >>"Header files and a static library for Python (v2.2)" >> >>Kent > > > > Except in the extended description, where it says > """ > Includes the python distutils, which were in a separate package up to > version 1.5.2. > """ > > In general, if you need to compile, or develop, you need the > corresponding *-dev packages. I didn't need to compile or develop, just install. I expected $ python ./setup.py install to work out of the box. Am I missing something? Thanks, Kent From martin at v.loewis.de Fri Jul 18 11:18:11 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Jul 2003 17:18:11 +0200 Subject: Unicode question References: <65m1yubd.fsf@python.net> <3F17C0C3.6040309@ghaering.de> Message-ID: Gerhard H?ring writes: > I feel like an idiot now :-( I do get the warnings when I run a Python > script, but I do not get the warnings when I'm using the interactive > prompt. So it's all good (almost). Why not also produce warnings at > the interactive prompt? Because it is out of the scope of the PEP: The PEP is about source code *files* only; interactive mode is completely different. In source code, you can't know what the encoding is. In interactive mode, you know it is the locale's encoding (assuming the computer is correctly administrated). In interactive mode, it would be tedious to enter an encoding declaration, as you would have to do so over and over again. In source code, it is not that bad, since you save the file, and the encoding declaration stays in the file. IOW, non-ASCII in string and Unicode literals should "just work" in interactive mode. It currently doesn't fully work, but there is little point in breaking what works for 2.3, just to restore it in 2.4. Regards, Martin From mwh at python.net Thu Jul 17 13:46:55 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jul 2003 17:46:55 GMT Subject: The ASPN compiler References: <4868482a.0307141418.a45699e@posting.google.com> <87smp8d32t.fsf@pobox.com> Message-ID: <7h3r84p128w.fsf@pc150.maths.bris.ac.uk> jjl at pobox.com (John J. Lee) writes: > Since all they wanted to demonstrate was that "the .NET runtime and > Intermediate Language were capable of supporting the language", I > think somebody should have told Microsoft about this guy called > Turing. With great foresight , he proved that the .NET runtime > *is* capable of supporting Python, which should have saved Mark & Greg > all that hard work. <0.5 wink> But not pay <1.0 wink>. Cheers, M. -- Indeed, when I design my killer language, the identifiers "foo" and "bar" will be reserved words, never used, and not even mentioned in the reference manual. Any program using one will simply dump core without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998 From bokr at oz.net Thu Jul 31 23:11:35 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Aug 2003 03:11:35 GMT Subject: Python speed vs csharp References: Message-ID: On Wed, 30 Jul 2003 23:09:22 -0700, Mike wrote: >Bear with me: this post is moderately long, but I hope it is relatively >succinct. > >I've been using Python for several years as a behavioral modeling tool for >the circuits I design. So far, it's been a good trade-off: compiled C++ >would run faster, but the development time of Python is so much faster, and >the resulting code is so much more reliable after the first pass, that I've >never been tempted to return to C++. Every time I think stupid thoughts >like, "I'll bet I could do this in C++," I get out my copy of Scott Meyers' >"Effecive C++," and I'm quickly reminded why it's better to stick with >Python (Meyers is a very good author, but points out lots of quirks and >pitfalls with C++ that I keep thinking that I shouldn't have to worry >about, much less try to remember). Even though Python is wonderful in that >regard, there are problems. > >Here's the chunk of code that I'm spending most of my time executing: > ># Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. 7.1.26) ># Fifth order approximation. |error| <= 1.5e-7 for all x ># >def erfc( x ): > p = 0.3275911 > a1 = 0.254829592 > a2 = -0.284496736 > a3 = 1.421413741 > a4 = -1.453152027 > a5 = 1.061405429 > > t = 1.0 / (1.0 + p*float(x)) > erfcx = ( (a1 + (a2 + (a3 + > (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) > return erfcx > >This is an error function approximation, which gets called around 1.5 >billion times during the simulation, and takes around 3500 seconds (just >under an hour) to complete. While trying to speed things up, I created a >simple test case with the code above and a main function to call it 10 >million times. The code takes roughly 210 seconds to run. I recoded the above and also in-lined the code, and also made a C DLL module version and timed them roughly: ====< erfcopt.py >===================================================== import math def erfc_old( x ): p = 0.3275911 a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 t = 1.0 / (1.0 + p*float(x)) erfcx = ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) return erfcx # You know that all those "constant" assignments are # actually executed every time erfc is called, # right? To move that to def-time instead of # call-time, you can write def erfc( x, # constants bound at def time, rparen moved down, commas added ): p = 0.3275911, a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429, exp = math.exp ): # just to make it stand out t = 1.0 / (1.0 + p*x) #XXX# don't need float(), since p is float return ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * exp(-x**2) #XXX# elim attr lookup on global math.exp # elim intermediate store of erfcx #XXX# return erfcx def test(): from time import clock from erfc import erfc as erfc_in_c # sanity check for x in range(20): assert erfc_old(x) == erfc(x) and abs(erfc_in_c(x)-erfc_old(x))<1e-18 t1=clock() for i in xrange(100000): erfc_old(1.2345) t2=clock() for i in xrange(100000): erfc(1.2345) t3=clock() # inlining code from old version: # constant assignments hoisted out of loop, of course p = 0.3275911 a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 x = 1.2345 for i in xrange(100000): t = 1.0 / (1.0 + p*float(x)) erfcx = ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) t4 = clock() for i in xrange(100000): erfc_in_c(1.2345) t5=clock() print 'old: %f, new: %f, inline: %f, in_c %f' %(t2-t1, t3-t2, t4-t3, t5-t4) import dis print '---- erfc_old code -----------------------------------' dis.dis(erfc_old) print '---- erfc --------------------------------------------' dis.dis(erfc) if __name__== '__main__': test() ======================================================================= Result is: [19:48] C:\pywk\cstuff>erfcopt.py old: 4.490975, new: 3.123005, inline: 3.051674, in_c 0.806907 I was surprised that the inline gain was not more, but I guess there was enough computation to obscure that cost. Anyway, moving some of the work to def-time paid off about 30%. But going to C cut 82%. I added the C version to the sanity check, and had to allow an epsilon. I suspect that this is because the C version probably keeps the whole problem in the FPU with 64 fractional bits of precision until returning the final double (which has 53 bits), wherease the Python algorithm presumably stores all intermediate values in memory with the 53-bit precision, and so loses in the overall. That's my theory, anyway. To see the extra work the old code is doing vs the new, you can see below: ---- erfc_old code ----------------------------------- 0 SET_LINENO 2 3 SET_LINENO 3 6 LOAD_CONST 1 (0.32759110000000002) 9 STORE_FAST 3 (p) 12 SET_LINENO 4 15 LOAD_CONST 2 (0.25482959199999999) 18 STORE_FAST 2 (a1) 21 SET_LINENO 5 24 LOAD_CONST 3 (-0.28449673599999997) 27 STORE_FAST 5 (a2) 30 SET_LINENO 6 33 LOAD_CONST 4 (1.4214137410000001) 36 STORE_FAST 4 (a3) 39 SET_LINENO 7 42 LOAD_CONST 5 (-1.453152027) 45 STORE_FAST 7 (a4) 48 SET_LINENO 8 51 LOAD_CONST 6 (1.0614054289999999) 54 STORE_FAST 6 (a5) Everything above here was unnecessary to do at run-time 57 SET_LINENO 10 60 LOAD_CONST 7 (1.0) 63 LOAD_CONST 7 (1.0) 66 LOAD_FAST 3 (p) 69 LOAD_GLOBAL 6 (float) 72 LOAD_FAST 0 (x) 75 CALL_FUNCTION 1 78 BINARY_MULTIPLY 79 BINARY_ADD 80 BINARY_DIVIDE 81 STORE_FAST 8 (t) 84 SET_LINENO 11 87 LOAD_FAST 2 (a1) 90 LOAD_FAST 5 (a2) 93 LOAD_FAST 4 (a3) 96 LOAD_FAST 7 (a4) 99 LOAD_FAST 6 (a5) 102 LOAD_FAST 8 (t) 105 BINARY_MULTIPLY 106 BINARY_ADD 107 LOAD_FAST 8 (t) 110 BINARY_MULTIPLY 111 BINARY_ADD 112 LOAD_FAST 8 (t) 115 BINARY_MULTIPLY 116 BINARY_ADD 117 LOAD_FAST 8 (t) 120 BINARY_MULTIPLY 121 BINARY_ADD 122 LOAD_FAST 8 (t) 125 BINARY_MULTIPLY 126 LOAD_GLOBAL 9 (math) <<--+-- replaced by a single LOAD_FAST 129 LOAD_ATTR 10 (exp) <<--+ 132 LOAD_FAST 0 (x) 135 LOAD_CONST 8 (2) 138 BINARY_POWER 139 UNARY_NEGATIVE 140 CALL_FUNCTION 1 143 BINARY_MULTIPLY 144 STORE_FAST 1 (erfcx) <<--+ | 147 SET_LINENO 13 <<--+ 150 LOAD_FAST 1 (erfcx) <<--+-- all eliminated 153 RETURN_VALUE 154 LOAD_CONST 0 (None) 157 RETURN_VALUE ---- erfc -------------------------------------------- 0 SET_LINENO 20 3 SET_LINENO 29 6 LOAD_CONST 1 (1.0) 9 LOAD_CONST 1 (1.0) 12 LOAD_FAST 1 (p) 15 LOAD_FAST 0 (x) 18 BINARY_MULTIPLY 19 BINARY_ADD 20 BINARY_DIVIDE 21 STORE_FAST 8 (t) 24 SET_LINENO 30 27 LOAD_FAST 2 (a1) 30 LOAD_FAST 3 (a2) 33 LOAD_FAST 4 (a3) 36 LOAD_FAST 5 (a4) 39 LOAD_FAST 6 (a5) 42 LOAD_FAST 8 (t) 45 BINARY_MULTIPLY 46 BINARY_ADD 47 LOAD_FAST 8 (t) 50 BINARY_MULTIPLY 51 BINARY_ADD 52 LOAD_FAST 8 (t) 55 BINARY_MULTIPLY 56 BINARY_ADD 57 LOAD_FAST 8 (t) 60 BINARY_MULTIPLY 61 BINARY_ADD 62 LOAD_FAST 8 (t) 65 BINARY_MULTIPLY 66 LOAD_FAST 7 (exp) <<-- 69 LOAD_FAST 0 (x) 72 LOAD_CONST 2 (2) 75 BINARY_POWER 76 UNARY_NEGATIVE 77 CALL_FUNCTION 1 80 BINARY_MULTIPLY 81 RETURN_VALUE <<-- 82 LOAD_CONST 0 (None) 85 RETURN_VALUE [19:49] C:\pywk\cstuff> Regards, Bengt Richter From xpm4senn001 at sneakemail.com Tue Jul 1 21:34:06 2003 From: xpm4senn001 at sneakemail.com (John Fitzsimons) Date: Wed, 02 Jul 2003 11:34:06 +1000 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: <7784gvck35se42ff9c629v34duu6ltjvu3@4ax.com> On Mon, 30 Jun 2003 22:17:43 -0700, "Cousin Stanley" wrote: < snip > >| When I get time though I might "rem" (is that # ?) out >| that/those line/lines so that I have a second URL sorting >| python executable that doesn't include the numbers. >Getting rid of the word_count >isn't too bad .... < snip > Thanks for the additional info. :-) Regards, John. From ulope at gmx.de Wed Jul 2 10:26:29 2003 From: ulope at gmx.de (Ulrich Petri) Date: Wed, 2 Jul 2003 16:26:29 +0200 Subject: undo tab References: <3F02E7D5.4060401@gmx.net> Message-ID: "Tom" schrieb im Newsbeitrag news:3F02E7D5.4060401 at gmx.net... > Hi, > > as we all know we need tabs if we use for, if ... commands. Sometimes I > find an easier way to do something and I can get rid of one or more for, > if ... loops. Unfortunately I couldn't find a convenient way to get rid > of the now unnecessary tabs. I am looking for something as convenient as > inserting tabs (mark everything and push the tab key). I tried shift+tab > and all other possible variations with alt/shift/ctrl. :-) > > Thanks for your help. > Tom > Would be helpful if you give us a clue what editor you are using.... Ciao Ulrich From tjreedy at udel.edu Sun Jul 27 17:43:34 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2003 17:43:34 -0400 Subject: Checking whether bool is a type References: <3F2442B2.E660E97@jandecaluwe.com> Message-ID: "Jan Decaluwe" wrote in message news:3F2442B2.E660E97 at jandecaluwe.com... > In my application I need to know whether bool is > available as a type (in Python2.3) or not. I just > realized I can use the following: > > jand> python > Python 2.3c1 (#1, Jul 21 2003, 12:40:39) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> type(bool) is type > True > > jand> python2.2 > Python 2.2.2 (#1, Oct 16 2002, 19:59:11) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> type(bool) is type > 0 > > Great isn't it ?! If all you care about is differentiating between 2.2 and 2.3, yes. But this raises NameError, I believe, on earlier verisons without 'bool' builtin. What is wrong with using sys.version[:3] >= '2.3'? (Anyone - has sys.version always been around?) Terry J. Reedy From gherron at islandtraining.com Thu Jul 31 18:53:32 2003 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 31 Jul 2003 15:53:32 -0700 Subject: Python's biggest compromises In-Reply-To: <3f294ba4$0$8919$626a54ce@news.free.fr> References: <899f842.0307310555.56134f71@posting.google.com> <3f294ba4$0$8919$626a54ce@news.free.fr> Message-ID: <200307311553.32991.gherron@islandtraining.com> On Thursday 31 July 2003 10:10 am, Bruno Desthuilliers wrote: > Anthony_Barker wrote: > (snip) > > > What to you think python largest compromises are? > > > > The three that come to my mind are significant whitespace, dynamic > > typing, and that it is interpreted - not compiled. > > IMHO these are not compromises, but features. What's more, these are three of Python's greatest *strengths*. We resist all attempts to change these, and we (at least I) avoid other languages because they do not supply these features. Gary Herron From lorenb2 at bezeqint.net Tue Jul 29 07:08:52 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Tue, 29 Jul 2003 13:08:52 +0200 Subject: gzip HTTP results problem Message-ID: <003401c355c1$cb6949f0$6400a8c0@EVOD31> Hey ppl, I've encountered a problem trying to decode gzip data returned from an HTTP server I communicate with (I use urllib2). I've tried to use both the gzip and zlib come-along python libraries but alas. Have anyone of you ppl succeeded in talking gzip with an HTTP server ? thanks in advance, ~B (btw I do not wish to change my Encoding-Type to deflate...) From alanmk at hotmail.com Wed Jul 9 08:11:44 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 09 Jul 2003 13:11:44 +0100 Subject: importing re in Jython References: Message-ID: <3F0C0680.69346F59@hotmail.com> Alexis Francart wrote: > Do you know how i can import the RE module in Jython? Works fine for me on Win2K, J2SDK1.4.2 and Jython 2.1:- Jython 2.1 on java1.4.2 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import re >>> rx = re.compile('[0-9]+') >>> for sn in ['1', '10', 's10']: ... m = rx.match(sn) ... if m: ... print "'%s' matches" % sn ... '1' matches '10' matches >>> Perhaps if you gave us some details, such as 1. Your OS 2. Your JRE version 3. Your jython version 4. What code you're using Then it might be easier to help out. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From Stephen.C.Waterbury at nasa.gov Fri Jul 25 16:42:19 2003 From: Stephen.C.Waterbury at nasa.gov (Stephen C. Waterbury) Date: Fri, 25 Jul 2003 16:42:19 -0400 Subject: Problem with pyOpenSSL and Python2.3c In-Reply-To: References: Message-ID: Ooops! It was my PYTHONPATH ... . Never mind! Rune Hansen wrote: > Hi, I've got no problems with pyOpenSSL with Python 2.3c1 on MacOS X > 10.2.x. I've only buildt pyOpenSSL with Python2.3b2 on RedHat 9, and had > no problems there either. I may be able to help you if you provide some > information about your setup and error messages. > > regards > /rune > > Stephen C. Waterbury wrote: > >> I'm trying to get pyOpenSSL to work with Python 2.3c on >> Red Hat 9, but there seems to be a Python C API incompatibility. >> I assume this just means that a new version of pyOpenSSL is >> needed for Python 2.3 -- is that correct? >> >> - Steve. >> > From richmond at ev1.net Tue Jul 8 14:27:03 2003 From: richmond at ev1.net (Charles Richmond) Date: Tue, 08 Jul 2003 18:27:03 GMT Subject: Collective memory (was: Good code patterns in Python) References: <3F09F136.6060000@srv.net> Message-ID: <3F0B2857.6EE3A30F@ev1.net> Kevin Handy wrote: > > [snip...] [snip...] [snip...] > > FORTRAN isn't indentation dependent, it is position dependent. > There is a big difference between the two. > > In FORTRAN, certial columns were allocated to specific purposes. > 1-5 for the line number, 6 for comment/continuation, 7-75 for the > program line, 76-80 for sequence numbers. [iirc] > > If you want a language that was even more position dependent than > fortran, look at RPG-II. You used printed forms for programming to > get the columns correct. One character in the wrong column would > change the meaning of that line. > IIRC, people who programmed RPG-II on a computer terminal...had a plastic overlay for the screen so they could see what column that things were being typed into. The "C" language gives white space significance...especially if it determines what a token will be. The tokenizer tries to build the longest token possible. So: x = i++ + j; is *not* the same as: x = i + ++j; and the statement: x = i+++j; is the same as: x = i++ + j; If you have: int *p, x, y; then: y = x/*p; is quite different from: y = x / *p; The first way, "/*" will begin a comment...the second way, you get the integer "x" divided by the integer pointed to by "p". -- +----------------------------------------------------------------+ | Charles and Francis Richmond richmond at plano dot net | +----------------------------------------------------------------+ From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 2 15:34:16 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2003 21:34:16 +0200 Subject: How Do You Get Redirected Input? In-Reply-To: References: Message-ID: <3f0333b6$0$49116$e4fe514c@news.xs4all.nl> not your business wrote: > I have a shell tool that accepts arguments on the command line. I would like > to check if the input is being piped in. That is, > > $ mytool.py < cmdlst.txt > > In this case sys.argv is empty. So I added > > pipein = os.read(sys.stdin.fileno(),256) > if (pipein): > input_args = pipein.split() > else: > input_args = sys.argv[1:] > > Problem is that if nothing is redirected in, the script waits for a Enter > pressed on the the keyboard. Anyone know a solution to this? Thanx in > advance for any help. Why not turn it around? First check if sys.argv is *not* empty, in which case the user provided command line arguments, and proceed to parse those. Otherwise (if sys.argv *is* empty), assume the input is piped in and proceed to read the standard input. --Irmen From vze4rx4y at verizon.net Wed Jul 30 05:37:16 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 30 Jul 2003 09:37:16 GMT Subject: looking for design pattern name References: Message-ID: "Andrew Dalke" wrote in message news:bg1lt6$81g$1 at slb2.atl.mindspring.net... > I'm looking for the name used for a pattern like what Qt uses for > it's container hierarchy. I'm doing this design for molecules, so I'll > use that as my example. > > There's a container, in this case, a Molecule. A Molecule has Atoms > and Bonds. When an Atom, it is passed the parent container as > part of the constructor, as in > > mol = Molecule() > O1 = Atom(mol, 8) # note the parent in the constructor > O2 = Atom(mol, 8) > Bond(O1, O2, 2) # (the parent is implicit - comes from the atoms) What happens in Bond() if O1 and O2 have different parents? When O1 is constructed, does mol get informed? IOW, after the four assignments, does mol know that it has two atoms and double bond? > I want to compare this to a design like > > mol = Molecule() > O1 = mol.add_atom(8) > O2 = mol.add_atom(8) > mol.add_bond(O1, O2) > > which does not allow a user-derived Atom and Bond class > > and one like > > mol = Molecule() > O1 = Atom(8) > mol.add_atom(O1) > O2 = Atom(8) > mol.add_atom(O2) > b = Bond(2) > mol.add_bond(b) How does this setup handle: mol1 = Molecule() mol2 = Molecule() b = Bond(2) mol1.add_bond(b) mol2.add_bond(b) Is there any way to detect that the same Atom or Bond being used in two different molecules? > > Anyone have good names for any of these three styles? Assuming that the first approach operates by constructing components and notifying parents that it is a new component, then I would call it the Widget pattern because it operates like Tk widgets: root = Tk() # root = Molecule() b1 = Button(root) # b1 = Atom(root, 8) b2 = Button(root) # b2 = Atom(root, 8) In Chapter 2 of The Art of Objects, the second and third approaches are called Collection Manager and Container. The key distinction is that a Container only contains the objects and is not responsible for creating them. Another idea is to name the patterns after the limitations inherent in each design. When Atoms are constructed implicitly, the design does not favor applications that break-up a molecule and re-attach some of the existing atoms into new molecules, so call it NoMix or some such. Still another ideas is to describe a pattern by its characteristic variant or invariant properties: * The first approach has components with fixed parents established at the time of component creation. Call the pattern SignUp since every new atom or bond has to immediately signup with an existing parent. * The second approach has captive components. This suggests the name MoleculeDriven to cover the idea that all component atoms or bonds are created from the molecule, thus assuring there can be no orphan atoms or bonds. * The third approach allows free mixing of components. This is suggestive of the name TinkerToy where all the molecular model components can lay separately on a table (sticks for bonds and cogwheels for atoms). Raymond Hettinger From m at moshez.org Mon Jul 14 02:02:54 2003 From: m at moshez.org (Moshe Zadka) Date: 14 Jul 2003 06:02:54 -0000 Subject: anything like C++ references? In-Reply-To: References: , <000301c348c7$3c501980$21795418@dell1700> Message-ID: <20030714060254.28299.qmail@green.zadka.com> On Sun, 13 Jul 2003, Stephen Horne wrote: > The problem is that you are confusing implementation with semantics. > The meanings of 'variable', 'value', 'assignment' etc are defined by > computer science. This is not just wrong, but as far as it is right, the semantics agree with Python's :) In computer science, the theoretical model one first learns is a turing machine. Turing machines have no variables or values, merely tapes. While I'm sure you can creatively translate the terms to turing machiens, this exercise seems fairly pointless. Ram machines are similar. More abstract models, like recursive functions, deal with integers only, so again you would need hard to associate terms with them [you can implement a list of integers with the p_1^n_1*....p_k^n_k, where p_1,...,p_k are distinct primes. I'm not completely sure how this would translate to Python, though :)] However, computer science did have a minor notational revolution: Lisp. Lisp was originally invented as an abstract way to express computations in a more natural, and yet well-defined, way. The fact that lisp can be *implemented* was somewhat of a shock, but it turned to be a fairly useful language. So as far as computer science defines the idea of "variable", "value" and "assignment", it can be said to give those terms the Lisp semantics, which are fairly similar to Python semantics. [Note that in Lisp conses, for example, are actually mutable. However, many functions treat them as immutable objects. This is perfectly fine, and was a concious design decision in Lisp. Similarily, Python wouldn't *need* tuples: they can be implemented as lists. The immutability allows the implementation to play tricks with memory usage, though.] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From bobx at linuxmail.org Tue Jul 8 10:29:14 2003 From: bobx at linuxmail.org (Bob) Date: 8 Jul 2003 07:29:14 -0700 Subject: ftp a file by date and name match Message-ID: <1001ff04.0307080629.7ef1e277@posting.google.com> I am trying to get the latest file from an ftp site that matches a pattern and is the latest one. I have it in Perl and would like to see the Python version for comparison. Perl version: # this matches the name only by looking at files # that start with 8 numbers (i.e. 20021203) foreach(@list) { if(m/\d{8}.*x86.exe/) { push(@match,$_) } } if(scalar(@match)) { my $file=$match[$#match]; $ftp->binary(); $ftp->get($file); } $ftp->quit; From bdesth.nospam at removeme.free.fr Sun Jul 13 18:12:26 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sun, 13 Jul 2003 22:12:26 +0000 Subject: =?ISO-8859-1?Q?=F1=EF=E5=F8=E8=E0=EB_=E4=EB=FF_=F0=EE=F1?= =?ISO-8859-1?Q?=F1=E8=E9=F1=EA=E8=F5_=EF=E8=F2=EE=ED=F9=E8=EA=EE=E2=29?= =?ISO-8859-1?Q?=29=29?= References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> Message-ID: <3F11D94A.7050208@removeme.free.fr> Irmen de Jong wrote: > Garber wrote: > >> ?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? >> exe-???? ?????????). > > > > Yes! > I think. > > ;-) > > On second thought, what's he saying? > He said : "?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? exe-???? ?????????)." It does seem clear enough, doesn't it ?-) From duncan at NOSPAMrcp.co.uk Fri Jul 4 10:45:37 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 4 Jul 2003 14:45:37 +0000 (UTC) Subject: Exceptions and modules References: <292c8da4.0307040627.59acda19@posting.google.com> Message-ID: westernsam at hotmail.com (sam) wrote in news:292c8da4.0307040627.59acda19 at posting.google.com: > So the Exception isn't recognised even though it has the same > namespace and name as the exception defined in the module. I have to > uncomment the 7th line to get my example to behave as I would like it > to. > > Is this a bug/feature? Is there any reason why it shouldn't work the > way I expect it to? It's a feature, and it probably ought to be in the FAQ in some form. When you run 'python module1.py' the code in the source file module1.py is compiled into a module called __main__. That means that the line: except MyException, err: is actually short for: except __main__.MyException, err: When module2 imports module1 the code is recompiled into a new module. Same source code, but otherwise no relation. You then raise module1.MyException which doesn't match __main__.MyException. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bokr at oz.net Mon Jul 7 22:15:38 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Jul 2003 02:15:38 GMT Subject: single/double quote escape interpolation References: Message-ID: On Mon, 7 Jul 2003 14:45:42 -0500, Skip Montanaro wrote: > > Simon> I was just wondering why python doesn't make a distinction > Simon> between single and double quotes - a bit like Perl does. > >In most instances it's helpful because you can avoid extra escapes, e.g.: > > "why don't we drop by the pub and quaff a few?" > >instead of > > 'why don\'t we drop by the pub and quaff a few?' > >There are also triple-quoted strings using """ and ''' as the string >delimiters. They mostly just make it easy to create multi-line string >literals, but they can also be used to avoid backslashes: > > '''Maury said, "Why don't we drop by the pub and quaff a few?"''' > > Simon> Obviously I realise there are no dollar signs so you can't > Simon> intrpolate a varaible in a string. > >You can interpret variables, the mechanism is just slightly different: > > "why don't we drop by the $where and $dowhat a few?" > >for Perl, vs. > > "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict > >for Python. Somedict is a dictionary having keys "where" and "dowhat" (at >minimum). The most common "somedict"s are probably "locals()" and >"globals()" though you can easily construct your own or take them from >different contexts, like SQL query results. > Might want to mention that somedict only has to act like a dict, not necessarily *be* a dict. I.e., supporting __getitem__ suffices, so you can synthesize anything you like from the key passed. E.g., >>> class AsIs(object): ... def __getitem__(self, key): return '%(' + key + ')s' ... >>> somedict = AsIs() >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the %(where)s and %(dowhat)s a few?" Maybe that was a little weird ;-) How about, >>> class RU(object): ... def __getitem__(self, key): ... res = list(key.upper()) ... res.reverse() ... return ''.join(res) ... >>> somedict = RU() >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the EREHW and TAHWOD a few?" >>> class RanWord(object): ... kinds = {'where': ['pub', 'office','theatre','boathouse'], ... 'dowhat':['quaff','program','watch','expend']} ... def __getitem__(self, key): ... w = self.kinds.get(key,['??']) ... return random.choice(w) ... >>> import random >>> somedict = RanWord() >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the pub and expend a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the boathouse and quaff a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the office and expend a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the boathouse and program a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the office and program a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the pub and expend a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the pub and program a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the boathouse and watch a few?" >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict "why don't we drop by the theatre and quaff a few?" Whatever ;-) Regards, Bengt Richter From sismex01 at hebmex.com Tue Jul 29 11:07:09 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 29 Jul 2003 10:07:09 -0500 Subject: variable assignment in "while" loop Message-ID: > From: Sybren Stuvel [mailto:sybrenUSE at YOURthirdtower.imagination.com] > Sent: Martes, 29 de Julio de 2003 07:09 a.m. > > Hi there, > > Is it possible to use an assignment in a while-loop? I'd like to do > something like "loop while there is still something to be read, and if > there is, put it in this variable". I've been a C programmer since I > was 14, so a construct like: > > while info = mydbcursor.fetchone(): > print "Information: "+str(info) > > comes to mind. Unfortunately, this doesn't work. Is there a similar > construct in python? > > Sybren > Well, you say you've programmed C since 14, but not how old you are now, so... you could be programming C for six months if you're 14-and-a-half ;-) Assignment, in Python, is not an expression, it's a statement; it doesn't "return" any value, it binds an object's reference to a name. Multiple chained assignments in Python don't work the same way as they do in C, because in Python they're merely syntactic sugar so you don't have to type them by hand. Anyhow... the best way to do what you wanna is simply: while 1: info = mydbcursor.fetchone() if not info: break print "Information:", info a-ha! you say; yes, the "print" statement ("STATEMENT", not function) automagically applies str() to the given object, so if you directly print an object, you don't have to str() it, print does that for you. "But it's so cumbersome" you think, looking upon an inconditional- turned-conditional loop. Don't worry, it'll become natural with practice, and after a bit you'll recall your previous C loops and think "ewww". Why? Because, the C compiler is doing exactly that, only implicitly, and hiding it from you. That's bad. You could also: info = mydbcursor.fetchone() while info: print "Information:", info info = mydbcursor.fetchone() and there's nothing wrong with this; the only "anti-aesthetic" thing here is the duplicated line which assigns to "info", but that's small potatos, really; don't worry about that. Another way, with more modern versions of Python, is to iterate directly over the cursor: for info in mydbcursor: print "Information:", info Why? Because cursors, if I recall correctly, are iterable objects, so you can iterate through them using for: or any other similar construct. Welcome to programming bliss :-) -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From akaihola at ambi-spam-me-not-tone.com Sun Jul 20 13:48:22 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Sun, 20 Jul 2003 20:48:22 +0300 Subject: Tk mainloop() In-Reply-To: References: Message-ID: > Hi, I have a question: how do you execute an arbitrary function in Tk fooBar.mainloop()? > I need to change the contents of a label every second, but I think I will also use some other functions as well... from Tkinter import * class MyApp(Tk): def __init__(self): Tk.__init__(self, className='MyApp') self.after(1000, self.label_timeout) # add whatever initialization you may need def label_timeout(self): # change label contents here self.after(1000, self.timeout) myapp = MyApp() myapp.protocol('WM_DELETE_WINDOW', on_close) myapp.mainloop() From edreamleo at charter.net Fri Jul 18 13:35:46 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 18 Jul 2003 12:35:46 -0500 Subject: wxPython questions References: Message-ID: Many thanks, Dave, for these most helpful responses. I think the next step is to do some prototyping... > For example, you don't have to use the wxSize class since you can always just use an (x,y) tuple (maybe there's an exception to that rule, but I haven't seen it yet). Ditto for strings. Oh bliss, oh rapture. Oh rapture, oh bliss :-) > P.S. There's a wxPython mailing list you may find more useful - check wxPython.org for details. Will do. In this case, though, your answer was just what I was hoping for. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From pyth at devel.trillke.net Fri Jul 25 16:46:38 2003 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 25 Jul 2003 22:46:38 +0200 Subject: path module In-Reply-To: <11234c14.0307251219.70e77a85@posting.google.com>; from jason.orendorff@lumigent.com on Fri, Jul 25, 2003 at 01:19:49PM -0700 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <11234c14.0307251219.70e77a85@posting.google.com> Message-ID: <20030725224638.R6906@prim.han.de> Jason Orendorff wrote: > holger krekel wrote: > > I think it's convenient enough to use "str(path)" if passing a 'path' > > instance as a string somewhere. > > Hmmm. If the plan were to convert the whole standard library to accept > path objects for pathnames, I would likely agree. But when you say > "str(p)" is "convenient enough", you're saying I need this rule in my head: > > Don't pass path objects to functions that take path arguments. > Pass string objects instead. Or even better, call the appropriate Path method :-) > This is a type rule. Such a thing has no place in Python. Oh, the stdlib has lots of places where it expects certain types in certain places. Look for e.g. 'isinstance'. > Furthermore, this rule is counterlogical! I would have to change > "mimetypes.guess_type(mypath)" to "mimetypes.guess_type(str(mypath))". I'd just call this a little inconvenient. And i wouldn't mind adding a guess_type method (which would work even better for URL's or subversion-urls). cheers, holger From cartermark46 at ukmail.com Thu Jul 10 12:37:07 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 10 Jul 2003 09:37:07 -0700 Subject: Calling Excel module functions from python [repost] References: Message-ID: Koczian wrote in message news:... > Mark Carter schrieb: > > > In Excel, I have a module named modCSV which has a function named > > SaveSheet(), which I want to be able to call from python. How do I do > > it? > > > > I've opened the workbook containing the module, and executed the code: > > > > from win32com.client import Dispatch > > xlApp = Dispatch("Excel.Application") > > xlApp.Visible = 1 > > wb = xlApp.ActiveWorkbook > > wbc = wb.VBProject.VBComponents("modCSV") > > wbc.SaveSheet() > > > > but I get the error message: [snip] > Try > > xlApp.Run('SaveSheet') It works! > That works with ordinary Excel macros, but I don't know about > VBProject.VBComponents. Possibly this might work: > > wbc.Run('SaveSheet'). It doesn't work. But that doesn't matter, because the first method works. A further tip: For a function taking arguments, use xlApp.Run("func", "arg1", "arg2", ...) Thanks From tomas at fancy.org Tue Jul 1 21:25:18 2003 From: tomas at fancy.org (Tom Plunket) Date: Tue, 01 Jul 2003 18:25:18 -0700 Subject: functors Message-ID: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> How can I create a functor object in Python? What I want (being a C++ coder ), is to be able to create an object that I is callable. The following is my attempt, but it doesn't work: class Countdown: def __init__(self): self.callback = None def SetCallback(self, time, callback): self.callback = callback self.timeRemaining = time def Update(self): if self.callback is not None: self.timeRemaining -= 1 if self.timeRemaining <= 0: print "Callback fired." self.callback() self.callback = None class SomeClass: def __init__(self): self.countdown = Countdown() self.countdown.SetCallback(30, lambda s=self: s.Callback) # I have also tried 'lambda: self.Callback' self.done = False def Callback(self): print "success!" self.done = True def Update(self): while not self.done: self.countdown.Update() if __name__ == "__main__": SomeClass().Update() *** I wouldn't mind creating a new class to wrap this up (that's what I'd do in C++, and that class would have an operator() defined), but I can't seem to discover how to make callable objects in Python. If there's a better way to do callbacks like I'm trying to do, also that would be handy to know. :) I don't want to poll the countdown object every time through the loop because it just seems "dirty"... :) thanks, -tom! From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 4 13:21:50 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 04 Jul 2003 19:21:50 +0200 Subject: Server Push In-Reply-To: References: Message-ID: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> John Bradbury wrote: > I want to send updates from a long running cgi. I have tried copying perl > examples of server push and can not get them to work. > Does anyone have an idiot proof example of a working server push or sending > output in chunks in Python? Check out: http://wp.netscape.com/assist/net_sites/pushpull.html There are basically two ways to do this. Either use the above mentioned "multipart response", which only seems to work on certain browsers (confirmed on netscape and mozilla, IE doesn't seem to work). The other method is just flushing your output and continue to write more data... but this won't allow you to 'clear the page' in the client's browser (multipart repsonses will). --Irmen From hokiegal99 at hotmail.com Wed Jul 16 11:18:09 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 16 Jul 2003 11:18:09 -0400 Subject: <> and != References: <3F154B63.3060503@hotmail.com> <3F154BBD.2060304@hotmail.com> <3jlahv8o1fcu2j0oij2p31c32nftnb3er8@4ax.com> <3F155B6D.8000205@hotmail.com> Message-ID: <3F156CB1.40606@hotmail.com> Duncan Booth wrote: > hokiegal99 wrote in > news:3F155B6D.8000205 at hotmail.com: > > >>Thank you, that is what I thought. What's the reason for having two >>symbols mean the same thing? >> > > Originally Python only had '<>' for the not-equal comparison. Version 0.9.3 > added a bunch of C like syntax, such as C's shifting and masking operators. > It also added C style '==' and '!=' comparison operators. The original '<>' > remains valid for backwards compatibility. > That makes sense. Thanks for the info!! From bgailer at alum.rpi.edu Mon Jul 14 09:10:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 14 Jul 2003 07:10:39 -0600 Subject: Newbie with sort text file question In-Reply-To: References: Message-ID: <5.2.1.1.0.20030714070241.01c54540@66.28.54.253> At 03:12 PM 7/13/2003 -0600, Andrew Dalke wrote: >Bob Gailer: > > [Pipeline] > >Huh. Hadn't heard of that one before. Thanks for the pointer. Since I am developing the Python version of Pipeline I wonder if you have any interest in it? Would like to be an early recipient? >(And overall, nice post!) > > > The Python version: > >Some stylistic comments > > > input = file('c:\input.txt') > >Since 'input' is a builtin, I use 'infile'. Agree. When I'm in a hurry I let details slip. >For the OP, you'll need 'c:\\input.txt' because the '\' has special meaning >inside of a string so must be escaped. Agree. When I'm in a hurry I let details slip. > > fruits = {} # a dictionary to hold each fruit and its count > > lines = input.readlines() > > for line in lines: > >Since you are using Python 2.2 (later you use "if fruit in fruits", >and "__in__" support for dicts wasn't added until Python 2.2, I >think, and the 'file' usage is also new), this is best written as > > for line in input: Agree. > > fruit = line.split('_', 1)[0] > > > if fruit in fruits: > > fruits[fruit] += 1 # increment count > > else: > > fruits[fruit] = 1 # add to dictionary with count of 1 > >Here's a handy idiom for what you want > > fruits[fruit] = fruits.get(fruit, 0) + 1 Don't you want setdefault() instead of get()? > > output1 = file('c:\output1.txt', 'w') > > for key, value in fruits.items(): > > output1.write("%s occurs %s\n" % (key, value)) > > output1.close() > > output2 = file('c:\output2.txt', 'w') > > output2.write("Total occurrences is %s\n" % len(lines)) > > output2.close() > >That's missing some sorts, so I don't think it meets the OP's requirements. The only reason for sort that I could see was to group things for counting. The output appears sorted descending, but that order was not specified, so I assumed random output. [snip] Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From anton at vredegoor.doge.nl Tue Jul 1 12:38:11 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 01 Jul 2003 18:38:11 +0200 Subject: does lack of type declarations make Python unsafe? References: Message-ID: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: > Stop. Probably too soon for the complete reversal technique. FYI I was trying to use your post as an example of the defensive psychological techniques people (not just you, me too, and probably a lot of the readers here) use when facing ambiguity. Introducing new language features or trying to do unfamiliar things -f.e. from other languages- with the language one is accustomed to produces exactly the kind of feelings of unsafety -and alas, the defensive postures and abuse- that this thread is about. I thank you anyway for serving as an example for this, stay here and maybe you'll reverse someday, be it more slowly, though we'll probably never marry :-| Anton From sanjiv at leopardlogic.com Tue Jul 29 18:15:40 2003 From: sanjiv at leopardlogic.com (Sanjiv Kumar) Date: Tue, 29 Jul 2003 15:15:40 -0700 Subject: Fw: Python-2.3c2.tgz installation References: <041d01c35614$542b3bc0$4901a8c0@beastjr> <200307291809.10354.drlinux@columbus.rr.com> Message-ID: <042e01c3561e$f55f58a0$4901a8c0@beastjr> Hi Dave, Thanks for your inputs !! I will try with gcc version 2.95.3. Best Regards, =Sanjiv= ----- Original Message ----- From: "Dave Reed" To: "Sanjiv Kumar" ; Sent: Tuesday, July 29, 2003 3:09 PM Subject: Re: Fw: Python-2.3c2.tgz installation > On Tuesday 29 July 2003 16:59, Sanjiv Kumar wrote: > > > > Hi, > > > > I am trying to build and install python-2.3 on a Solaris machine. It > give segmentation fault during build process ( I guess during build of > extensions to python i.e. running "build_ext"). I am using gcc > --version 2.95.2 on SunOS xyz 5.8 Generic_108528-15 sun4u sparc > SUNW,Ultra-60 machine. So any hint to get rid of this problem. > > > > Best Regards, > > =Sanjiv= > > If the compiler gives a segmentation fault, I would think it's a bug > in the compiler or it wasn't installed correctly. gcc 2.95.2 is pretty > hold and I suspect (well, all code that large has bugs) it had bugs - > there is a 2.95.3. > > I can report successful compilation of Python 2.3c2 on Solaris 9 using > gcc 3.2.3. > > I would first try upgrading your compiler to 2.95.3 or gcc 3.2.3 or > maybe even gcc 3.3 (I haven't looked to see how bug-free it is > supposed to be). The latest Red Hat beta does include it so they must > have got it to compile all their packages. > > Dave (who is patiently waiting for the final 2.3 so he can finish > updating software on Solaris 9 machines) > > From klapotec at chello.at Thu Jul 31 02:52:06 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 31 Jul 2003 06:52:06 GMT Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> Message-ID: <9rehivsavhereijf36nhla96krct4s1fmn@4ax.com> On Wed, 30 Jul 2003 15:20:46 -0500, "Michael Sampson" wrote: >How does the IDLE that comes with the latest release of python handle this? >When it automaticly indents does it do it with spaces or tabs? If you hit >tab in the IDLE will it just put 5 spaces in for you? > IDLE 1.0 (from Python 2.3) has a pretty configuration dialog, accessed via Options|Configure IDLE, which lets you define its behaviour - do you want it to insert tabs as tabs or spaces, and how many spaces do you want, the default seeming to be converting a tab to 4 spaces. And, as others have said, DON'T use 5. --Christopher From Mike at kordik.net Sun Jul 6 16:42:06 2003 From: Mike at kordik.net (Mike) Date: Sun, 06 Jul 2003 20:42:06 GMT Subject: python -c option Message-ID: I am very new to Python and read the docs section about having python run commands from the command line. I have been successful with: python -c "print 'Hello'" It prints Hello In the interpreter I can type 2+2 and it will return 4 but how do I do that from the command line? I have tried a few things without success. What I am really after is to do some command line processing where the output of grep is returning "prog=.01234" and I want to beautify it so it prints "12%" Maybe I should mess with bash but I am new to *nix in general and I wanted to learn Python. Thanks, Mike From clifford.wells at comcast.net Sat Jul 12 13:06:43 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 12 Jul 2003 10:06:43 -0700 Subject: The "intellectual property" misnomer In-Reply-To: References: Message-ID: <1058029603.4127.462.camel@devilbox.homelinux.net> On Fri, 2003-07-11 at 20:30, Ben Finney wrote: > On Fri, 11 Jul 2003 22:47:21 -0400, Tim Peters wrote: > > Ben Finney wrote: > >> Guido van Rossum wrote: > >> > The PSF holds the intellectual property rights for Python > >> Ugh. Please don't propagate this ridiculous, meaningless term. > > > > Guido isn't writing a treatise on the law, he's briefly explaining > > (part of) what the PSF does. > > The term he used doesn't explain anything, and only confuses. It would > have been *less* confusing to say "The PSF holds something unspecified > for Python". At least there is no pretence of explanation there. Right, I mean, why say anything at all since, you know, some lawyer somewhere might be offended. And we all care so much about lawyers. That's why I chose programming as a career, so I could deal with lawyers more. > > I doubt many are confused by what he said > > People may have an assumption about what is meant by the term, but they > are almost certainly wrong, since the fields of law that are sometimes > lumped together by that term have almost nothing in common. No, they are most certainly not wrong. Most people using Python have probably at least perused the license. Having done so, I doubt that they need to have it spelled out every time it is mentioned. > There is nothing useful indicated by the term "intellectual property > rights", because it presumes there is some commonality between fields of > law that deal with different intellectual concepts, impose different > restrictions, and presume different rights. That's like saying the word "food" is useless because there's nothing in common between a sandwich and a bowl of rice. > Those who are not confused by the term, are misguided as to what it > means. Or simply don't care. IANAL and I refuse (until properly sued) to worry about how lawyers think language should be used (although I probably should have used the word "allegedly" in there somewhere, just to be safe). > > and you proved you're not [confused by the term] > > [by listing some disparate fields of law that might be referred to by > > the term] > > This doesn't follow at all. I requested that the "rights" being > referred to should be stated, not handwaved with a term that presumes > that copyright, patent, trademark, trade secret, or many other disparate > legal areas can be lumped together. And they explicitly name those rights in a more appropriate place than here. If you want Guido to run every missive by a lawyer before posting, then perhaps it's time to ante up quite a donation to the PSF (which, ISTR, was the primary purpose of the post). > If PSF holds rights that are covered by *all* those fields of law, I'd > be very surprised; but if the "rights" are *not* covered by all those > different legal areas, then the term is useless. So I can't say I've eaten breakfast unless I've in fact eaten a bit of every possible breakfast food? Instead I'm required to list ad nauseum every item on my plate? > > So you somehow managed to divine Guido's intent from that "ridiculous, > > meaningless term" > > No, I requested that the term be clarified, because *I don't* know what > is meant by "The PSF holds the intellectual property rights for Python". > It's a meaningless statement as it stands. Only to those who haven't RTFM (or RTFL, in this case). > If the PSF holds software patents in Python, I imagine many would be > outraged. I don't believe it does. If it's not the case, why imply it > with an overbroad term? Or why use general terms at all for that matter? Why not make every statement an exacting mishmash of legalese? I think I would rather simply die. Wait... not me, you ;) > If the PSF holds trade secrets in Python, they are surely nullified by > the publishing of the code. If it's not the case, why imply it with an > overbroad term? Because it wasn't meant as a definitive statement regarding Python licensing terms. That has been done in an appropriate place already. > > I don't think pedantic verbosity makes it any clearer, but may mislead > > due to omission. > > And using a term that attempts to blanket wildly different legal rights > is *not* misleading due to omission? When you say "attempts" you seem to be implying intent. Being such a lawyerly person, you must know that proof of intent is one of the more difficult roads to tread in any argument. If you can prove Guido's intent was to mislead, then let's have it. Otherwise, please let it go. This thread is so boring and OT my eyes are starting to water. Regards, Cliff -- The cliffs around the crashing sea Unsolved and endless, wait for me -Siouxsie and the Banshees From skip at pobox.com Mon Jul 28 10:43:04 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 09:43:04 -0500 Subject: Debugging Python ? In-Reply-To: <008a01c354ad$5a52d840$6400a8c0@EVOD31> References: <008a01c354ad$5a52d840$6400a8c0@EVOD31> Message-ID: <16165.13944.763754.224629@montanaro.dyndns.org> Bill> I'd be happy to hear your techniques to debug python programs. Crude though it may seem, I find print statements quite effective. Works in all environments as well. ;-) Bill> Is there any interactive debugging environment by any chance ? Yes, there's pdb. Search the source tree. I'm sure some of the more advanced IDEs have debugging support these days as well. For a list, browse http://www.python.org/cgi-bin/moinmoin/PythonEditors Skip From ilya at cray.glas.net Wed Jul 16 08:56:40 2003 From: ilya at cray.glas.net (Ilya Etingof) Date: Wed, 16 Jul 2003 12:56:40 +0000 (UTC) Subject: pySNMP: SNMPget example References: <538fc8e.0307100356.4bf46554@posting.google.com> <538fc8e.0307140736.19eb777@posting.google.com> <538fc8e.0307150703.48466779@posting.google.com> Message-ID: > 1) Instead of writing '1.3.6.1.2.1.69.1.3.1', I would also like to be > able to write 'docsDevSwServer'. Any idea how I can do that? The right way is to use a MIB parser (for labels-to-oids translation) which is not a part of pysnmp. Try looking at Python backend to libsmi. If you expect to query just a small and definite set of OIDs, an alternative would be to hardcode labels-to-oid mapping somewhere in your script. -ilya From peter at engcorp.com Tue Jul 15 10:25:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 10:25:14 -0400 Subject: FCNTL module deprecation warning References: Message-ID: <3F140ECA.A29C7593@engcorp.com> Sybren Stuvel wrote: > > Meyer, Tony enlightened us with: > > C:\Program Files\Python23\lib\fcntl.py:7: DeprecationWarning: the > > FCNTL module is deprecated; please use fcntl > > Seems you're using windoze. > > > It seems to be saying that I shouldn't use "import FCNTL" (which gives > > the same warning), but "import fcntl", but that's what I _am_ doing. > > Windoze has a case insensitive filesystem, and thus it can't see the > difference between FCNTL and fcntl. Try removing the depricated FCNTL > from your harddisk, or rename it to FCNTL-dep.py. And check for any .pyc files that might be involved, like FCNTL.pyc, since they might be confusing things even more... From gh at ghaering.de Sat Jul 12 10:33:47 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 16:33:47 +0200 Subject: Any pure-python relational databases? In-Reply-To: References: Message-ID: <3F101C4B.5030104@ghaering.de> David McNab wrote: > Hi, > > I've been looking for some way to operat a relational database on a 3rd > party web server. > > The server runs Python 1.5.2, and does not have the MySQL-python module, > (nor does it have libmysqlclient), which means I can't just talk to MySQL. > > The web host is my client's choice, not mine, and there's very little > prospect of getting them to upgrade their python or install mysql-python. > > Is there: > > 1) Any pure-python interface to MySQL? or No. > 2) Any kind of relational DBMS written in pure python that'll run on > 1.5.2? Old versions of Gadfly, perhaps. > All help appreciated. One advice: don't try to make the impossible possible for such clients. If you need Pyhton and database access then just tell them that their current web host is inappropriate for this. -- Gerhard From gsmatthew at ozemail.com.au Sat Jul 19 16:02:45 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Sun, 20 Jul 2003 06:02:45 +1000 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> <9j3Sa.319$vD1.15038@nnrp1.ozemail.com.au> <3F195170.E60FB1A6@engcorp.com> Message-ID: <9uhSa.578$vD1.23592@nnrp1.ozemail.com.au> guys thanks so much you have all been a great help can t belive how easy it was in the end here is my code, please criticise it to death i wont take offence import threading, socket, sys from Queue import Queue from string import strip #TODO: Exception Handling #ON A MULTIPLE CPU MACHINE 2 SEPERATE SERVERS SHOULD BE RUN #THE INCOMING REQUEST WILL NEED TO BE SWITCHED BETWEEN SERVERS #THIS IS DUE TO THE GLOBAL INTERPRETER LOCK (GIL) IN PYTHON #-------------- global constants -------------------------------- THREAD_POOL_SIZE = 5 #The number of threads to run #WARNING increasing threads does not mean increased performance BUFFER_SIZE = 1024 #Buffer size for socket PORT = 6000 #Port server will listen on HOST = "localhost" ADDR = (HOST, PORT) BACKLOG = 5 #Backlog for server listen #---------------------------------------------------------------- class Job: def __init__(self, csocket, addr): self.csocket = csocket #Client Socket self.address = str(addr) #Address (Host:Port) Pair class ThreadPool: #TODO: investigate if Queue can be inherited ???? def __init__(self): self.pool = [] #Pool of threads self.queue = Queue() #Job stack FIFO #Initialise each worker thread and start for i in range(THREAD_POOL_SIZE): uq = UserRequestHandler(i,self) self.pool.append(uq) self.pool[i].start() class UserRequestHandler(threading.Thread): def __init__(self, tid, tpool): threading.Thread.__init__(self) self.tid = tid #thread id so i can test what is executing self.tpool = tpool #Reference to the threading pool def run(self): while 1: #keep calling queue, get method is blocking job = self.tpool.queue.get() self.execute(job) def execute(self,job): bufferChars = [] data = '' length = 0 recieved = 0 print "%d CONNECTED %s" % (self.tid , job.address) #Read in the first 20 bytes, all communication with this server needs #to place a 20 byte header into it, i.e. netstring type concept header = job.csocket.recv(20) #if a possible header was retrieved if header: #remove any pads to make up 20 bytes header = strip(header) #calculate length of the header. if error occurs #then its an invalid header #TO DO: If an error occurs create XML error string # send to view to produce error html try: length = long(header) except: job.csocket.send('Invalid Header') else: #Go into a continous loop until all the #bytes are recieved from the client while recieved != length: #keep sucking in data until header len matches buffer = job.csocket.recv(BUFFER_SIZE) recieved += len(buffer) #Record total length received bufferChars.append(buffer)#add buffer to array data = data.join(bufferChars) #Convert buffer array into string buffersChars = None #Destroy buffer array, we dont need it no more job.csocket.send("Server received") if job.csocket: job.csocket.shutdown(2) job.csocket.close() def startServer(): tpool = ThreadPool() server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) server.listen(BACKLOG) print """ Server running on %s Python %s Server listening for requests with %d threads in pool """ % (sys.platform,sys.version,THREAD_POOL_SIZE) while 1: (s, addr) = server.accept() job = Job(s,addr) tpool.queue.put(job) if __name__ == '__main__': startServer() "Peter Hansen" wrote in message news:3F195170.E60FB1A6 at engcorp.com... > Graeme Matthew wrote: > > > > ok so code like this is perfectly safe > > > > def run(self): > > > > while 1: > > > > job = queue.get() > > > > __processjob() > > It's almost like you aren't even seeing Aahz' replies. ;-) > > The above is certainly safe, but can't be terminated easily. > Just use the loop Aahz showed, which is the above plus the > ability to terminate. > > -Peter From timr at probo.com Wed Jul 16 23:02:29 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 16 Jul 2003 20:02:29 -0700 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: Jack Diederich wrote: > >My favorite example is comifying a list. >"1, 2, and 3" vs "1, 2 and 3" (journalist seem to prefer the later) > >"I dedicate this book to my parents, Jane, and God." >"I dedicate this book to my parents, Jane and God." This is actually something that is changing over time. It used to be that "no final comma" was a hard and fast rule, but many of the more recent style guides now suggest the comma. My 7th grader's English textbook advocates the final comma, and it led me to get her into trouble in one assignment. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From imbosol at aerojockey.com Sun Jul 20 23:51:59 2003 From: imbosol at aerojockey.com (Carl Banks) Date: 20 Jul 2003 20:51:59 -0700 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: <60dfb6f6.0307201951.4eea1930@posting.google.com> Alan Kennedy wrote in message news:<3F168011.3AEB3EFC at hotmail.com>... > So, the challenge to the ASCII proponents is: put the greek word > "gignooskoo" on everybody's screen, originating from a usenet message, > in the original greek, where "oo" -> greek letter omega. I accept. ____ ____ ___ _____ ___ | | | |\ | / \ \ | / / \ | | | | \ | | | \ | / | | | | | | \ | | | > |< | | | | | | \| \ / / | \ \ / | | | | | _\ /_ /____ | \ _\ /_ :-) -- CARL BANKS From someone at somewhere.com Sun Jul 27 08:39:53 2003 From: someone at somewhere.com (reh) Date: Sun, 27 Jul 2003 12:39:53 GMT Subject: eric3, pyqt, qscintilla - guru needed. Message-ID: Have installed on Redhat 9.0 in the following order; Qscintilla sip PyQt When I install eric3 (python install.py), I get this error; Sorry, please install QScintilla and/or reinstall PyQt with QScintilla support. It seems the errors occurs in the install.py file at: from qtext import QextScintilla >From qtext.py, I have typed in at the python prompt; >>> import libsip # ok here >>> from qt import QWidet # ok here >>> from qt import QObject # ok here >>> from qt import QPrinter # ok here >>> import libqtextc # error here Traceback (most recent call last): File "", line 1, in ? ImportError: libqscintilla.so.2: cannot open shared object file: No such file or directory >>> Been through all readme files, tried just about everything. Anyone have an idea what's wrong. -- robert redhat 9.0 From nospam at mega-nerd.com Sat Jul 19 23:24:23 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 20 Jul 2003 03:24:23 GMT Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: Message-ID: <3F1A0B1D.22DD9CE@mega-nerd.com> Raseliarison nirinA wrote: > > hi all, > i found an unanswered question at > http://www.faqts.com/knowledge_base/index.phtml/fid/538 > with possible response below. i've tried to send it at > faqt.python but can't figure out how to edit the page. so i put it here. > i want to kwon if this can convert all wave file. is there other > encodage than 8 or 16 bits for .wav files? Yes, dozens. As well as 8 and 16 bit integer PCM files, there are also 24 and 32 bit integer PCM, 32 and 64 bit floating point PCM, A-law, u-law, at least 6 different forms of ADPCM (adaptive differential PCM), GSM6.10, MP3 and many, many more. Fortunately other than the ones listed above, all the others are pretty rare. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ J. Headley: "God, root, what is difference ?" G. Haverland: "God can change the byte order on the CPU, root can't." From bokr at oz.net Fri Jul 25 23:15:57 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 03:15:57 GMT Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: On 25 Jul 2003 20:48:07 -0500, Ian Bicking wrote: >On Fri, 2003-07-25 at 20:10, Van Gale wrote: >> Interesting, I started a project modifying Jason's Path module to work >> on subversion trees as well. I didn't get too far before putting the >> project on a back-burner so I'm glad to hear someone else is thinking >> the same way :) >> >> My extensions to Path included an additional argument to "open" that >> included a version number, and a mechanism for retrieving some kind of >> "metadata" associated with the file. > >It's interesting that different kinds of filesystems (or >filesystem-like-things) have very different kinds of metadata >available. Like last-modified, last-accessed, inode (identity), >version, title, branch, mimetype, log message, etc. And then there's >information that's not quite metadata... like data, or the >volume name, the host, etc. > >I feel like a common interface for these different filesystems should >somehow degrade well in terms of metadata, or expedite introspection in >some fashion. > IMO a mounted file system per se should be represented by an object, and then that object should have the methods to deliver generic or file-system-specific file and path and walking objects etc. After all, even NT can see DOS partitions, vs NTFS vs raw floppy and HD images of potentially foreign formats. And my slackware linux sees one DOS partition that can be alternately booted, but can read from slackware via a mount. Cf. another post in this thread (which didn't get any response ;-) Regards, Bengt Richter From gumuz*NOSP at M*looze.net Sun Jul 20 18:50:00 2003 From: gumuz*NOSP at M*looze.net (Guyon Morée) Date: Mon, 21 Jul 2003 00:50:00 +0200 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> <1058561410.563105@smirk> <3F187ED4.6179CDDD@engcorp.com> <1058700676.64323@smirk> Message-ID: <3f1b1c98$0$45383$1b62eedf@news.wanadoo.nl> I vote for that to, it's a brilliant well-used system "James T. Dennis" schreef in bericht news:1058700676.64323 at smirk... > Peter Hansen wrote: > > "James T. Dennis" wrote: > > >> Sean 'Shaleh' Perry wrote: > > >>>> If my english was better I would love to help improve the python > >>>> documentation, most modules in the standard libraries lack good > >>>> examples how to *use* them with just a simple description. And a > >>>> short motivation for the design of a module if possible like "just > >>>> copied the C API" or "Because of efficiency ..." or "We use a class > >>>> framework here because ...". A gigantic task. The PSL book by effbot > >>>> is great but it's a book. And it needs a new version. > > >>> part of the reason why the docs are not but so great is that most of the > >>> library is Python code which means any questions can be answered by reading > >>> the source. I find myself doing this quite often. > > >> That's BS! > > >> As a dabbler in programming I have to say that poor documentation is not > >> excused by the availability of sources. > > > True, but poor documentation *is* excused quite nicely by the LACK > > of availability of _re_sources, specifically the human resources and time > > required to make them better. > > > Or was your flame an indirect offer to assist with improving the > > documentation of Python? If so, thank you! > > > (It's not like you've paid anything for the privilege of whining...) > > > -Peter > > Yes. Moreover my suggestion for an enhancement to the web site > docs would be a way to facilitate that. Go look at the PHP > documentation. Anyone reading it can attach comments; those can be > merged into the docs as appropriate. > > > > -- > Jim Dennis, > Starshine: Signed, Sealed, Delivered > From peter at engcorp.com Mon Jul 7 08:00:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 08:00:08 -0400 Subject: Will Python exceptions be documented? References: <33a013af.0307070318.73013d4@posting.google.com> Message-ID: <3F0960C8.93613E6D@engcorp.com> Vegard Bakke wrote: > > All know that asin(2) is wrong, but how do I know that ValueError is > the exception I should catch, and how do I know that is the only one? > (Sorry, try it is the wrong answere here.) See http://www.python.org/doc/current/lib/module-math.html where on this specific case, for example, it says Note: Specific exceptions raised in assorted error cases (and even whether some arguments are considered to be exceptional at all) are not defined in any useful cross-platform or cross-release way. For example, whether math.log(0) returns -Inf or raises ValueError or OverflowError is both platform- and release-dependent, and in cases where math.log(0) raises an OverflowError, math.log(0L) often raises a ValueError. -Peter From aahz at pythoncraft.com Sun Jul 13 12:19:08 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 12:19:08 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: In article , Stephen Horne wrote: >On 13 Jul 2003 10:37:01 -0400, aahz at pythoncraft.com (Aahz) wrote: >>In article , >>Stephen Horne wrote: >>> >>>One of the few things I hate about Python is that mutable objects are >>>implicitly shared using a reference system whereas immutable objects >>>are not. >> >>Well, that's incorrect. *ALL* Python objects are implicitly shared with >>bindings. The difference is whether updating the value referenced by a >>target requires *re*binding the target or simply updating an object. > >Fine - nit-pick. Believe it or not, it is *not* a nit-pick, it goes right to the core of Python's design and philosophy. >All you have proven is that it is the distinction between types that >get re-bound and those that don't (rather than the use of references) >that is unnecessarily confusing and error prone. Only for people who insist on thinking about it through the lens of some other way to do it. >A Python user is interested in how an object behaves - not how it is >internally implemented in the interpreter. Immutable objects don't >behave as references - the internal use of references for immutable >objects is basically a lazy copying optimisation and, apart from >performace and a couple of other technicalities (e.g. the 'is' >operator), has no relevance. Certainly it has no relevance to the >point I was making. That's precisely where you are wrong. Python's object model is extremely strict and simple and orthogonal. Everything works exactly the same way. Whether one can mutate a specific object is simply an attribute of that object, rather than requiring a different syntax. Trying to focus on the mutable/immutable distinction is what causes the mental blowup -- keep your eye on the objects and bindings and you're fine. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From steve.horsley1 at virgin.NO_SPAM.net Thu Jul 31 13:43:09 2003 From: steve.horsley1 at virgin.NO_SPAM.net (Steve Horsley) Date: Thu, 31 Jul 2003 18:43:09 +0100 Subject: Python speed vs csharp References: Message-ID: On Wed, 30 Jul 2003 23:09:22 -0700, Mike wrote: > Bear with me: this post is moderately long, but I hope it is relatively > succinct. > > I've been using Python for several years as a behavioral modeling tool for > the circuits I design. So far, it's been a good trade-off: compiled C++ > would run faster, but the development time of Python is so much faster, and > the resulting code is so much more reliable after the first pass, that I've > never been tempted to return to C++. Every time I think stupid thoughts > like, "I'll bet I could do this in C++," I get out my copy of Scott Meyers' > "Effecive C++," and I'm quickly reminded why it's better to stick with > Python (Meyers is a very good author, but points out lots of quirks and > pitfalls with C++ that I keep thinking that I shouldn't have to worry > about, much less try to remember). Even though Python is wonderful in that > regard, there are problems. > It might be worth having a look ay Jython. This allows python code to run on a java VM by emitting JVM bytecode rather than standard python interpreter bytecode. This gives you all the hotspot optimisations that have been invested in java runtime performance. Steve From gh at ghaering.de Fri Jul 11 20:21:33 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 02:21:33 +0200 Subject: The ASPN compiler In-Reply-To: References: Message-ID: <3F0F548D.9040108@ghaering.de> Fuzzyman wrote: > What's the score on this (the ASPN python compiler) There was a proof-of-concept implementation of a Python compiler for the .NET platform done by ActiveState and sponsored by Microsoft. > - is it a true > compiler for python ? Read the whitepaper, available on the ActiveState site. > - what does it output - binary or C++ for .NET > framework............ Read the whitepaper, available on the ActiveState site. > if the latter then it could be very cool as it > may work with the PocketPC 2003 SDK.... for producing binaries for > PDAs from python... cool... Forget it. Instead what you probably want is a Python implementation for Windows CE 3.0. There is one. > (I'm sure my terminology is way out of line here... sorry) > > Does it work yet ? Read the whitepaper, available on the ActiveState site. RTFM. STFW. etc. :-P -- Gerhard From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 14 04:44:08 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 14 Jul 2003 08:44:08 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 14) Message-ID: QOTW: "I'll claim without proof that how mixed-type comparisons work with Python classes is also beyond wizard prediction in all cases: the implementation of comparison in Python is crushingly complicated." -- Tim Peters "Honest to God, if it doesn't have coloured cells all over the place, then they [the engineers] kind of stare at you like rabbits caught in the headlights of an oncoming car." -- Mark Carter Discussion ---------- While syntax coloring sounds nice, Mark VandeWettering shows negative issues of syntax coloring in editors. Aahz explains what threading is most often used for and why Python usually doesn't have a scalability problem here. Ian Bicking brings up Jason Orendorff's path module, starting a discussion about a different Python interface to the filesystem. Bengt Richter and Peter Hansen use a helium-balloon metaphor while explaining Python's object naming principle. Paul Rubin takes a negative-for-Python - but arguably sound - stance in the Python versus PHP web-applications discussion. Raymond Hettinger intrigues with the first episode of a series of mysterious Python puzzles. Announcements ------------- Guido is moving to the US West Coast. His devotion to Python continues. Congratulations to ActiveAwards winners Mark Hammond, Uche Ogbuji, Mike Olson, and Martin von Loewis. PortalTransforms 1.0a1, part of Archetypes, a framework for the development of new Content Types in Zope/CMF/Plone. wxPyPlot 1.1, an enhanced derivative version of wxPlotCanvas to provide simple lightweight plotting in wxPython. Adept, a Declarative, Eval-based Program Tester. It is an unit testing tool where you define test cases as tuples. EmPy 3.0.3, a system for embedding Python expressions and statements in template text. PyObjC 1.01, a bridge between Python and Objective-C that allows full-featured Cocoa applications to be written in pure Python. Vb2py 0.1, a toolkit to aid in the conversion of Visual Basic projects to Python (using PythonCard). YAMI 2.1, a lightweight and portable infrastructure for message-oriented network communication. PyQwt 3.7, a set of Python bindings for the Qwt C++ class library. Qwt extends the Qt framework with widgets for scientific and engineering applications. SpamBayes 1.0a4, a Bayesian anti-spam filter. Spyce 1.3.11, a server-side language that supports simple and efficient Python-based dynamic HTML generation. ReportLab toolkit 1.18, a dynamic PDF generating solution. ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From mmueller at dgfz.de Wed Jul 9 11:08:31 2003 From: mmueller at dgfz.de (=?ISO-8859-1?Q?Mike_M=FCller?=) Date: 9 Jul 2003 08:08:31 -0700 Subject: tracebacks in embedded python Message-ID: <7049ba55.0307090708.36f2a696@posting.google.com> When I embed Python into C there is no traceback message on the screen after an uncaught exception. Using sys.exc_info() I can print may own traceback but I would need to insert try except statements at different places. Is there a way to "turn on" traceback writing to std.err (that also shows up at the screen)? Thanks Mike From newsgroups at jhrothjr.com Fri Jul 25 20:48:40 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 25 Jul 2003 20:48:40 -0400 Subject: How to detect typos in Python programs References: Message-ID: Make it a policy that your unit test suite has 100% statement coverage at all times. Then this particular thing won't happen. How do you do this without impacting your development? Try Test Driven Development. If you do it *properly*, you'll get close to 100% statement coverage without any extra effort. John Roth "Manish Jethani" wrote in message news:ZPaUa.6$gZ.133 at news.oracle.com... > Hi all, > > Is there a way to detect typos in a Python program, before > actually having to run it. Let's say I have a function like this: > > def server_closed_connection(): > session.abost() > > Here, abort() is actually misspelt. The only time my program > follows this path is when the server disconnects from its > end--and that's like once in 100 sessions. So sometimes I > release the program, people start using it, and then someone > reports this typo after 4-5 days of the release (though it's > trivial to fix manually at the user's end, or I can give a patch). > > How can we detect these kinds of errors at development time? > It's not practical for me to have a test script that can make > the program go through all (most) the possible code paths. > > -Manish > > -- > Manish Jethani (manish.j at gmx.net) > phone (work) +91-80-51073488 > > From akaihola at ambi-spam-me-not-tone.com Tue Jul 22 02:48:26 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Tue, 22 Jul 2003 09:48:26 +0300 Subject: Automatically filling in answers to interactive shell command questions In-Reply-To: References: Message-ID: <245Ta.424$HC4.387@reader1.news.jippii.net> > >>> import os > >>> outf = os.popen('addperson', 'w') > >>> inf = file('answer_file', 'r') > >>> outf.write(inf.read()) > >>> inf.close() > >>> outf.close() Would this work: import os, shutil shutil.copyfileobj(file('answer_file'), os.popen('addperson', 'w')) From pythonguy at Hotpop.com Sun Jul 20 11:21:39 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 20 Jul 2003 08:21:39 -0700 Subject: XML parser and py2exe Message-ID: <84fc4588.0307200721.970b9d9@posting.google.com> I am using the expat parser in the 'xml.parsers.expat' module in my code. The code works well as source, but the py2exe executable created using it does not. I get the following traceback. Traceback (most recent call last): File "", line 146, in ? File "imputil.pyo", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyo", line 216, in import_top File "imputil.pyo", line 271, in _import_one File "", line 128, in _process_result File "HarvestManConfig.pyo", line 110, in ? File "imputil.pyo", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyo", line 216, in import_top File "imputil.pyo", line 271, in _import_one File "", line 128, in _process_result File "HarvestManXMLParser.pyo", line 12, in ? File "imputil.pyo", line 132, in _import_hook File "", line 70, in _finish_import File "imputil.pyo", line 318, in _load_tail ImportError: No module named _xmlplus.parsers I am creating my py2exe executable like this. $python setup.py py2exe --packages=encodings -O2 Where the setup.py is the standard py2exe script for creating executables. (copied below). # setup.py # install script for py2exe from distutils.core import setup import py2exe setup(name="HarvestMan", scripts=["HarvestMan.py"], ) Thanks, ~Anand From eddie at holyrood.ed.ac.uk Mon Jul 14 11:57:10 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 14 Jul 2003 15:57:10 +0000 (UTC) Subject: Expressing time. References: Message-ID: "Sean" writes: >I'm playing around times and dates. I'd like to determine the age of >particular sets of data in a user friendly matter. >I've got everything ready but dealing with time in a user friendly manner. >What would be a good way to express (in python): > time.localtime()+30 days > time.localtime()+5 minutes > time.localtime()+2 months > time.localtime()-2 years >Is there any python facilities to make this an easier chore (aka >time.localtime()+months(3))? >(I included months as it is a special case in that you can't just >arbitrarily calculate months in seconds without being relative to a >particular month). mx.DateTime makes these sort of calculations easy. I have a similarish task in presenting users an easy way of specifying which day's log files to search (hence in this case it was always a date in the past but the principle would be similar). So I allow things like 'monday', 'tuesday' etc. and -n for n days ago and several other variations. The interesting one in this instance is: dm_reg = re.compile (r'^(-?\d\d?)[/.](-?\d\d?)$') this_day = today() # dd/mm (-ve dd means count from end of month, -mm is mm months ago) mt = re.match (dm_reg, user_input) if mt: dy,mon = map(int, mt.groups()) if mon < 0: mon = this_day.month + mon if mon <= 0: mon = 12 + mon dt = DateTime (this_day.year, mon, dy) if dt > this_day: dt = DateTime (this_day.year-1, mon, dy) return dt Which allows eg 1/-2 for the first of whatever month was 2 months ago or even -1/-1 for the last day of the previous month. mx.DateTime is doing all the hard work. You could cook up something similar to parse eg "-2m" "+2y" etc. Possibly the new time stuff in 2.3 will do this also, I haven't looked at 2.3 yet. Eddie From bitbucket at electron.me.uk Fri Jul 4 19:09:48 2003 From: bitbucket at electron.me.uk (Geoffrey Clements) Date: Sat, 05 Jul 2003 00:09:48 +0100 Subject: Eric3 segfaulting References: <3f060811$0$56603$bed64819@pubnews.gradwell.net> Message-ID: <3f06093a$0$56603$bed64819@pubnews.gradwell.net> Some more info: If I make line 75 a blank line by putting a return in it stills fails on that line! -- Geoff Registered Linux user 196308 Replace bitbucket with geoff to mail me. From staschuk at telusplanet.net Thu Jul 17 20:31:33 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 17 Jul 2003 18:31:33 -0600 Subject: Bug overriding operators in new-style classes? In-Reply-To: <00cb01c34c96$736685d0$2700000a@esss.com.br>; from nicodemus@globalite.com.br on Thu, Jul 17, 2003 at 04:05:56PM -0300 References: <00cb01c34c96$736685d0$2700000a@esss.com.br> Message-ID: <20030717183133.D931@tibia.amotlpaa.bogus> Quoth Nicodemus: > I found a surprising behavior regarding new-style classes operator lookup. > It seems that for operators, the instance methods are ignored. Observe: [...] > Is this a bug, or am I missing something? Any help would be appreciated. Working as designed, I think [1], though I've never actually seen it documented. As you have observed, invocation of a magic method (such as __add__ or __len__) by way of a special notation (such as + or len()) ignores the instance dict. That is, len(x) is not equivalent to x.__len__() (which would find __len__ in the instance dict by normal attribute access) but to type(x).__len__(x) (which obviously ignores the instance dict). We get this question fairly frequently. (Last time I think it was about the iterator protocol's .next() method.) It really ought to be documented somewhere; the obvious place would be (until the real documentation catches up). Anybody want to write a patch? [1] One reason I think it's intended is that these protocols specify a self argument; for new-style classes, this is provided by the descriptor machinery, which by design works only when the function is found in the class dict. -- Steven Taschuk staschuk at telusplanet.net "[T]rue greatness is when your name is like ampere, watt, and fourier -- when it's spelled with a lower case letter." -- R.W. Hamming From max at alcyone.com Mon Jul 7 03:45:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jul 2003 00:45:51 -0700 Subject: anything new on the ternary operator? References: Message-ID: <3F09252F.9B0F52BD@alcyone.com> Aahz wrote: > Guido made clear before the vote that only a clear statement from the > community would drive the addition of the ternary operator. Given > that > the vote did not present a clear result, he did what he said he'd do. > How's that a prbolem? Bob's phrasing of it was obviously overly confrontational, but I do find it at least a little unfortunate that the final decision on PEP 308 only came indirectly (meaning not as any form of widespread public announcement, but rather as a side point in a presentation at a local conference) and many months after the voting processes was resolved (which was in February, if I recall correctly). Even the PEP on the subject hasn't been updated, and only those who attended his particular presentation in a particular conference have found out this decision (which, of course, they communicated to us just now). (Mind you, after months of silence about the issue, it's not like the decision should at all be a surprise to anyone.) There isn't a problem that PEPs and such voting processes are worthless -- obviously the BDFL has the final say -- but perhaps it would have been a little nicer to get an official position on the subject earlier. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I am a gentlemen: I live by robbing the poor. \__/ George Bernard Shaw From ben at dadsetan.com Thu Jul 10 02:57:36 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Thu, 10 Jul 2003 08:57:36 +0200 Subject: Deleting specific characters from a string In-Reply-To: References: <3F0C851C.4000500@livinglogic.de><3F0C8AC3.5010304@dadsetan.com> Message-ID: Jeff Hinrichs wrote: > def stringReplace(s,c): > """Remove any occurrences of characters in c, from string s > s - string to be filtered, c - characters to filter""" > for a in c: > s = s.replace(a,'') > return s > > It wins also by being easy to understand, no filter or lambda. Not that I > have anything against filter or lambda, but when the speediest method is the > most readable, that solution is definitely the Pythonic champ. :) Well I really had nothing against the filter, but this solution looks also acceptable. Thanks. Ben. From mike at nospam.com Fri Jul 18 13:48:30 2003 From: mike at nospam.com (Mike Rovner) Date: Fri, 18 Jul 2003 10:48:30 -0700 Subject: Perl -> Python hopeless? References: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> Message-ID: "Helmut Jarausch" wrote in message news:3f182c9a$0$276 > having been a Perl fan for years I have nearly converted to Python. I went the same way, happy with python now and never looked back. > Still, there are LOTS and very good modules written in Perl. > Is there a tool to lesson the burdon of translation of Perl to Python? IMHO language differences leads to different style and I found that rewriting is better than semi-automatic translation. I had a project first implemented in perl, than rewrote in python. Some idioms are completely different, for ex. code blocks in perl are natural, classes are not. OTOH classes are natural in python and no unnamed code blocks exists. The list may be continued on and on. Just .02 Mike From tdelaney at avaya.com Mon Jul 7 18:09:22 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 8 Jul 2003 08:09:22 +1000 Subject: Using Loops to track user input Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE844849@au3010avexu1.global.avaya.com> > From: Peter Hansen [mailto:peter at engcorp.com] > > You missed this one Gerhard. In another thread, hokiegal99 already > told us "I am a funeral director trying to write a small program that > calculates the number of years, months and days a person has lived by > entering the year, month and day of their birth. ..." > > Not homework this time. :-) Of if so, a worthy attempt at deviousness that should be rewarded :) Tim Delaney From p-abel at t-online.de Wed Jul 16 07:00:37 2003 From: p-abel at t-online.de (Peter Abel) Date: 16 Jul 2003 04:00:37 -0700 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <13a533e8.0307160300.678d1c36@posting.google.com> "Allison Bailey" wrote in message news:... > Hi Folks, > > I'm a brand new Python programmer, so please point me in the right > direction if this is not the best forum for this question.... > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. > > I'm not really sure how to get started with this process. > I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), > using Microsoft Excel 10.0 Object Library, then > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") > > Then, I get errors when I try the following: > sh = wb.worksheets(1) > Try >>> sh=wb.Sheets[1] OR >>> sh=xl.Workbooks[0].Sheets[1] You need to have only 1 Workbook open or the one you want, must be the first one >>> xl.Workbooks[0].Sheets[1]==wb.Sheets[1] 1 Regards Peter > > I think I'm missing something fairly fundamental, but I've googled all > over the place and can't seem to find anything very introductory about > opening and using data from MS Excel using Python. Any suggestions, > including places to get more information are welcome. > > Also, do I need to run the makepy utility every time I run my script? > If so, how would I do it from within my Python program, rather than with > the GUI in the IDE? > > Thanks for your help, > > Allison > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Allison Bailey > TerraLogic GIS, Inc. > allisonb at terralogicgis.com > 425-673-4495 > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From martin at v.loewis.de Thu Jul 10 18:37:50 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jul 2003 00:37:50 +0200 Subject: A new view of gcmodule.c In-Reply-To: References: Message-ID: <3F0DEABE.4050205@v.loewis.de> Edward K. Ream wrote: > This outline makes clear just how good the code really is. I shall not soon > forget the dawning realization that this code is absolutely beautiful: > incredibly short, simple and elegant. This was my reaction when I first saw it also. Regards, Martin From donn at drizzle.com Sun Jul 13 20:30:20 2003 From: donn at drizzle.com (Donn Cave) Date: Mon, 14 Jul 2003 00:30:20 -0000 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <1058142619.577000@yasure> Quoth Stephen Horne : ... | One way or the other, Python is currently choosing not to respect the | computer science definition of those terms. It may have historic and | backward-compatability reasons, but that does not change the facts. | This deviation from computer science definitions, whatever the excuse, | is arbitrary, confusing and error prone. That is my problem. Well, there you have it - it does seem to be your problem. If we were talking about a practical problem, we might be able to resolve it with a few lines of code or an explanation of what really happens when the code in question runs. But in this case, we all seem to know perfectly well what happens, and how to write the code we need. Python's system works. It's simple, practical and reasonably elegant. If it doesn't work for you for some practical reason, I'd be surprised. If you object to it on principle for some reason related to computer science definitions, that really is your problem. I do suspect that it would be also be due to some confusion on your part about either how Python actually works, or what these computer science definitions really say and how consistent and unambiguous they are, but from prior experience with this type of thing I think it would be a mistake to try to pursue it further here. It's computer science's job to describe how Python works, not Python's job to match up with their terminology. If you're one of those computer scientists, (or if you're not) you're welcome to offer your interpretation. Donn Cave, donn at drizzle.com From jidanni at jidanni.org Fri Jul 25 23:26:28 2003 From: jidanni at jidanni.org (Dan Jacobson) Date: Sat, 26 Jul 2003 11:26:28 +0800 Subject: where is the awk to python translator program Message-ID: <87smounf2z.fsf@jidanni.org> An old dog can't learn new tricks, so where's the a2py awk to python translator? Perl has a2p. E.g. today I wonder how to do '{print $1}', well with a2p I know how to do it in perl, but with python I am supposed to hunker down with the manuals. From bgailer at alum.rpi.edu Wed Jul 2 16:53:57 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 02 Jul 2003 14:53:57 -0600 Subject: What's the use of module spaces? (was Re: Circular Inheritance) In-Reply-To: <1057174986.726.166.camel@lothlorien> References: Message-ID: <5.2.1.1.0.20030702145058.023d4c10@66.28.54.253> At 02:43 PM 7/2/2003 -0500, Ian Bicking wrote: >On Wed, 2003-07-02 at 10:03, Aahz wrote: > > In article , > > Ian Bicking wrote: > > > > > >You might encounter less problems if those classes go together in a > > >single module, but module boundaries are just there to help the > > >programmer organize code, they have little formal meaning. > > > > That's not true. Modules define a namespace, and Python's execution > > model makes heavy use of the "global" (read, current module's) namespace > > for name resolution. > >Certainly modules have considerable *semantics* and effect execution. >But they have little *meaning*. There's all sorts of semantics >associated with classes, but that's incidental to the meaning of a class >-- a class is a set up behaviors common to a kind of object. A module >is just a pile of stuff the programmer likes to keep together. It's >essentially a clerical feature. Reminds me of the question: "What's the function of mortar." Most will say "To hold bricks together." But it ALSO keeps them apart! I prefer to think of modules as a tool to keep various parts of a complex application apart, rather than having all of them in one module. This improves readability, maintenance and testing. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From ianb at colorstudy.com Thu Jul 31 23:16:43 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2003 22:16:43 -0500 Subject: Python's biggest compromises In-Reply-To: References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <1059707803.12752.479.camel@lothlorien> On Thu, 2003-07-31 at 16:27, John Roth wrote: > "Robin Becker" wrote in message > news:TBO13LAmBVK$Ewml at jessikat.fsnet.co.uk... > > In article , John Roth > > writes > > > > > ..... > > >High performance isn't Python's target. If PyPy ever gets their act > > >off the ground, then we will have a shot at a good quality JIT > > >interpreter. Then watch it fly. > > > > > .... doesn't psyco already attempt to do JIT? It certainly doesn't > > speed things up that much. If all the variables are known to be of a > > specific type then you could expect C like speeds from a good JIT, but > > without global analysis it's hard to see how we infer/guarantee python > > types. > > Well, that's certainly a problem, but Bicycle Repair Man seems to > do a pretty good job of type inference, at least for refactoring. And Java's JIT is based on (at least originally) work done on Self, which had to do type inference. And actually in many circumstances Java requires type inference, because you can substitute in an instance of a subclass. Anyway, JIT is all about runtime analysis -- if you could infer types completely before running the program, you would just put in the optimizations statically (i.e., compiling optimizations). JIT does those optimizations at runtime by definition. And Bicycle Repair Man is inspired by the Refactoring Browser, an IDE tool based on another dynamic language (Smalltalk), not on a tool from a static language (like Java). Ian From harry.g.george at boeing.com Tue Jul 22 09:17:55 2003 From: harry.g.george at boeing.com (Harry George) Date: Tue, 22 Jul 2003 13:17:55 GMT Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> Message-ID: "Alan Dechert" writes: > "Paul Rubin" wrote in message > news:7x65lv31hf.fsf at ruckus.brouhaha.com... > > "Alan Dechert" writes: > > > > 1. Software chooses 1% of votes to change (big enough to have an > > > > effect, small enough to maybe go unnoticed). > > > > > > > I don't think this is a possible scenario. However, it brings up an > > > interesting test for our full blown study (keep in mind, we're trying to > > > focus on getting the demo done even though people want to jump ahead to > > > speculate on every possible detail). > > > > But something like that seems to have happened in Escambia County, > > Florida, in 2000. Out of 21,500 absentee ballots cast, 296 (1.5% of > > the total) were overvotes with three or more presidential candidates > > checked. ZERO were overvotes with exactly two candidates checked. > > Ballot tampering after the ballots were received is the most plausible > > explanation. > > > But that's a different scenario. As you described it, the voter never had a > chance to see the alteration. The scenario Harry described is where the > voter has the altered ballot in hand but doesn't notice. > No, I said the paper and the CRT or LCD were correct. It was just the electronic storage that was altered. > > You said that in your system the paper ballots are > > supposed to take priority over the electronic count if there is a > > dispute (that's the whole point of having the paper ballots). So it > > doesn't matter if the paper and electronic results don't match, and > > the tampering doesn't have to happen while the voter can still see the > > ballot. > > > I don't see much of a point here. It will be very hard -- if not > impossible -- to tamper with the printout in a manner that would go > undetected. First of all, overvotes will not be possible at all. I can't > quite visualize how you figure someone will alter the printout. Take some > whiteout and cover one name and print in a new one? That would look pretty > obvious. Furthermore, the bar code would no longer match the text. In my > scheme, the tamperer would have no way to know how to alter the bar code to > match any alterations in the text. > > Post election checks (canvass period) would involve hand checks, and scanner > checks of the bar code and the text. It all has to match. > > > Reference: > > > > http://www.failureisimpossible.com/essays/escambia.htm > > > > Note: Paul Lukasiak, the main author of that article, did some of the > > most thorough analysis of the Florida debacle that I've seen. I hope > > you will read a lot of his stuff in designing your real system, so > > you'll be able to say how your system deals with the problems that he > > identified in Florida. > > > I read as much as possible and will continue to study all of this. Keep in > mind that some of the people on our team are leading experts in the field. > They know all this stuff inside out. We'll bring in more experts once the > study is funded. > > Nobody is saying this issue is simple. Almost everyone that has approached > the voting mess dilemma and tried to figure it out has grossly > underestimated the problem. I have to say I underestimated too but I have > stuck with it long enough and hard enough to get a handle on it. Our > Election Rules Database (the largest component of our proposed study) will > surface inordinate problems -- get them out in the open where we can deal > with them. > > Alan Dechert > > > > > > -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From FBatista at uniFON.com.ar Thu Jul 24 17:09:53 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 24 Jul 2003 18:09:53 -0300 Subject: Standard behaviour of a getSomething method Message-ID: Resending... get no answers, don't remember if this mail reached the list. When I want to know about a attribute (e.g.: myAttrib) of an object, I should use the specific method (e.g.: getMyAttrib). Considering that this attribute is always another object (everything is an object in Python), what should getMyAttrib do? 1) Return the object 2) Return a copy of the object How do I return a copy of the object? Thanks for all. . Facundo From bokr at oz.net Sun Jul 27 13:02:04 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2003 17:02:04 GMT Subject: How safe is modifying locals()? References: <3TIUa.107401$XV.6252339@twister.austin.rr.com> Message-ID: On Sun, 27 Jul 2003 04:51:11 GMT, Paul Paterson wrote: [...] >To my eye, the [:] or [0] spelling of this makes the code look more >complex than necessary, but I think you are on to something because if >you spell it, > >def change(x, y): > x = 'new x' > y.update('new y') > For a general pointer, ISTM you want to be able to dereference it for both getting and setting. The [:] or [0] syntax gets you that, and you could do it with p() for getting and p(val) for setting, or p.getval() and p.update(), but all these get clumsy when you want to use the "pointer" on both sides of an assignment statement, e.g., p.update(p.getval()+' added text for target') where you could write more readably (IMO), p.value = p.value + 'added text for target' or p.v += 'added text for target' Below is a class PNS that lets you spell as immediately above, using .value (and .v for concise use) bound to a property that implements the accessing of what's pointed/referred to. I gave it a somewhat informative __repr__ method also, so the test prints better. As you will note, this is now separate from any particular name space. Any object that supports getattr and/or setattr can be used. I also threw in a permissions parameter to control read/write/delete. See nsother and math in examples. Note also that a pointer may point to another pointer, allowing cascaded dereferencing spelled p.v.v etc. >with the relevant changes to the Ptr class then it could certainly grow >on me. The things I like are, > >- no new variable names in the 'change' function so it looks similar to >the original code >- the mechanism for propogating changes to the caller scope is explicit >- 'y' can be passed on to another function if needed and things are >still clear > >eg, > >def change(x, y): > x = 'new x' > change2(y) > >def change2(y): > y.update('deep change in y') > If you use PNS, that will be spelled def change(x, y): x = 'new x' change2(y) def change2(y): y.value = 'deep change in y' See test() code below. I used your original class Namespace: pass as the main namespace. > >To do this using the original namespace approach gets a little tricky >because you have to merge the namespaces as you go. The pointer idea >flattens that structure. > ====< pns.py >========================================================== class PNS(object): """ Pointer to Name Space PNS instance holds ns ref and vname for access to ns.vname Read, write, delete access permitted if r,w,d in perms, respectively. Typical: ptr_to_x = PNS(ns, 'x') """ __slots__ = 'ns vname ok_r ok_w ok_d'.split() class PNSError(Exception): def __init__(self, ptr, msg): Exception.__init__(self, '%s for %r' %(msg, ptr)) def __init__(self, ns, vname, perms='rwd'): self.ns=ns; self.vname=vname self.ok_r = 'r' in perms self.ok_w = 'w' in perms self.ok_d = 'd' in perms def _getv(self): """Typical read access: x = ptr.value (x = ptr.v works too)""" if self.ok_r: return getattr(self.ns, self.vname) raise self.PNSError(self, 'Value read prohibited') def _setv(self, v): """Typical write access: ptr.value = 'new x' (ptr.v = 'new x' works too)""" if self.ok_w: setattr(self.ns, self.vname, v) else: raise self.PNSError(self, 'Value write prohibited') def _delv(self): """Typical del access: del ptr.value (del ptr.v works too)""" if self.ok_d: delattr(self.ns, self.vname) else: raise self.PNSError(self, 'Value deletion prohibited') value = v = property(_getv, _setv, _delv) # .v for short def __repr__(self): return ''%(self.vname, self.ns) class Namespace(object): pass def test(): ns = Namespace() ns.x = 'x value' ns.y = 'y value' print 'Before change:' print 'ns.x=%r, ns.y=%r' %(ns.x, ns.y) print 'Making pointer py point to ns.y ...' py = PNS(ns, 'y') # prefixing pointer names with 'p' is not mandatory, just mnemonic print 'ptr py=%r' % py def change(x, y): # prefixing pointer names with 'p' is not mandatory, just mnemonic x = 'new x' y.value = 'new y' print 'Calling change(ns.x, py) ...' change(ns.x, py) print 'After change:' print 'ns.x=%r, ns.y=%r' %(ns.x, ns.y) def change1(x, y): x = 'new x' change2(y) def change2(y): y.v = 'deep change in y' print 'Before change1/change2:' print 'ns.x=%r, ns.y=%r' %(ns.x, ns.y) change1(ns.x, py) print 'After calling change1(ns.x, py):' print 'ns.x=%r, ns.y=%r' %(ns.x, ns.y) pz = PNS(ns, 'z') print '\nNew pointer to non-existent ns.z:\n%r' % pz print 'Trying to access as yet nonexistent ns.z ...' try: ns.z except Exception, e: print '%s: %s'% (e.__class__.__name__,e) else: print 'ns.z accessed ok' print 'Passing pz to change(ns.x, pz)...' change(ns.x, pz) print 'Result: ns.x=%r, ns.z=%r' %(ns.x, ns.z) print '\nBefore deleting ns.y via py.v:' print 'ns.y=%r, py.v=%r' %(ns.y, py.v) print '\nDeleting ns.y by del py.value ...' del py.value print 'Trying to access ns.y ...' try: ns.y except Exception, e: print '%s: %s'% (e.__class__.__name__,e) else: print 'ns.y accessed ok' print '\nCreating nsother name space to put pz in as a value ...' nsother = type('AnotherNS',(),{})() print nsother nsother.pz = pz print 'Creating pointer ppz pointing to nsother.pz' ppz = PNS(nsother,'pz') print 'ppz = %r'% ppz print 'ppz.value = %r'% ppz.value print 'ppz.value.value = %r'% ppz.value.value print 'ppz.v.v= %r'% ppz.v.v print '\nDemo read-only pointer to pi in namespace math (the module) ...' import math ppi = PNS(math,'pi', 'r') # read only print 'math = %r' % math print 'ppi = %r' % ppi print 'ppi.v = %s' % ppi.v print '\nAttempting to set math.pi via ppi.v=3.14 (will work via math.pi, BTW !)' try: ppi.v = 3.14 except Exception, e: print '%s: %s'% (e.__class__.__name__,e) else: print 'ppi.v set ok: %r' % ppi.v if __name__ == '__main__': test() ======================================================================== Result of run: [10:03] C:\pywk\clp>pns.py Before change: ns.x='x value', ns.y='y value' Making pointer py point to ns.y ... ptr py=> Calling change(ns.x, py) ... After change: ns.x='x value', ns.y='new y' Before change1/change2: ns.x='x value', ns.y='new y' After calling change1(ns.x, py): ns.x='x value', ns.y='deep change in y' New pointer to non-existent ns.z: > Trying to access as yet nonexistent ns.z ... AttributeError: 'Namespace' object has no attribute 'z' Passing pz to change(ns.x, pz)... Result: ns.x='x value', ns.z='new y' Before deleting ns.y via py.v: ns.y='deep change in y', py.v='deep change in y' Deleting ns.y by del py.value ... Trying to access ns.y ... AttributeError: 'Namespace' object has no attribute 'y' Creating nsother name space to put pz in as a value ... <__main__.AnotherNS object at 0x007F92C0> Creating pointer ppz pointing to nsother.pz ppz = > ppz.value = > ppz.value.value = 'new y' ppz.v.v= 'new y' Demo read-only pointer to pi in namespace math (the module) ... math = ppi = > ppi.v = 3.14159265359 Attempting to set math.pi via ppi.v=3.14 (will work via math.pi, BTW !) PNSError: Value write prohibited for > [10:03] C:\pywk\clp> > >Thanks for these thoughts and the time it took to post them, they really >made me think! (I mean that in a good way, of course ;) ) > You're welcome. Hope this adds another useful angle. Regards, Bengt Richter From bostic at sleepycat.com Mon Jul 14 13:58:28 2003 From: bostic at sleepycat.com (Keith Bostic) Date: 14 Jul 2003 10:58:28 -0700 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: Terence Way wrote in message news:... > Two companies that make money spring to mind: > 1. sleepycat software (they support Berkeley DB); and > 2. the MySQL folks (they support, um, MySQL) > > They have different licenses, MySQL being dual licensed: > GPL and proprietary, while sleepycat is custom and > OSI-compatible. A minor clarification -- Sleepycat Software also does dual licensing. The public Berkeley DB releases have a BSD-style, OSI-compatible license, but we also release under a pretty standard, proprietary license. Regards, --keith =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Keith Bostic bostic at sleepycat.com Sleepycat Software Inc. keithbosticim (ymsgid) 118 Tower Rd. +1-781-259-3139 Lincoln, MA 01773 http://www.sleepycat.com From jeremy at alum.mit.edu Fri Jul 18 17:09:15 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 18 Jul 2003 17:09:15 -0400 Subject: Python 2.3 release candidate 1 Message-ID: <1058562554.22833.38.camel@slothrop.zope.com> I am very happy to announce the release of Python 2.3 release candidate 1. The python-dev crew has fixed almost 50 bugs since the beta release last month. You can find the downloads at the usual place: http://www.python.org/2.3/ All major reported bugs have been fixed for this release. If we do not discover any major bugs in the next week, we will re-release this code as Python 2.3 final. We encourage potential users of Python 2.3 to try the release candidate with their programs and report any bugs as soon as possible. To report a new bug, use the SourceForge bug tracker http://sourceforge.net/bugs/?func=addbug&group_id=5470 This release of Python does not have any big changes, but it does have many small changes that improve the libraries, fix bugs, and increase stability. According to some simple benchmarks, Python 2.3 is 25-30% faster than Python 2.2.3. There are about 15 new or significantly revised standard library modules, and a few new builtins. Andrew Kuchling's What's New in Python 2.3 describes the most visible changes since Python 2.2 in more detail: http://www.python.org/doc/2.3c1/whatsnew/ Have fun! -- Jeremy Hylton From troy at gci.net Tue Jul 29 16:54:32 2003 From: troy at gci.net (Troy Melhase) Date: Tue, 29 Jul 2003 12:54:32 -0800 Subject: Factories in Python References: <73b00f0c.0307290721.7a19e3d0@posting.google.com> Message-ID: Dave Kuhlman wrote: > I'd be interested in other reasons for using factories. My most frequent reason for using factories is to insulate client code from refering directly to a class name. I find I do this most often when I have code that's likely to change soon or change frequently. This approach allows me to leave client code unchanged although the actual class names and implementations may vary greatly. Consider: class MightBeWhatIWant: pass class HelperForThat: pass def build(): return MightBeWhatIWant() As the problem is revealed thru elbow grease, this might change: class ThisIsWhatIReallyNeeded: pass class SomethingIMissedEarlier: pass def build(): return ThisIsWhatIReallyNeeded() Granted, these aren't factories in the strictest GoF sense, but I think the intent is clear. troy From Kepes.Krisztian at peto.hu Fri Jul 25 04:25:30 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Fri, 25 Jul 2003 10:25:30 +0200 Subject: The protection of resources Message-ID: Hi ! In this time I use the Lock() for thread synchronization, and resource protection. But in the new project I must reorganize this thing. The program must be run in lin/win, so I cannot use the winapi. I need to protect resources from concurrent r/w. Possible that the modules are not threads but are tasks. In the Delphi and WinAPI I use the Mutex, that is a simple, opsystem protected thing to signaling. It is a simple signal (1/0). I search for this in python, but I see only mutex with "procedure queue". I cannot see a signal like thing. I want to only signaling: the resource are taken or not. I don't want to wait for the non used state (not block !). So these my questions: - 1. How to use the py mutex object ? Please send an example to me ! - 2. Have the py an signal object ? (platform !!!) - 3. Is any solution is a file locking. Have the py a possibility of exclusive file opening ? Thx: KK From jdhunter at ace.bsd.uchicago.edu Wed Jul 9 18:17:46 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jul 2003 17:17:46 -0500 Subject: Deleting specific characters from a string In-Reply-To: <3F0C8AC3.5010304@dadsetan.com> (Behrang Dadsetan's message of "Wed, 09 Jul 2003 23:36:03 +0200") References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: >>>>> "Behrang" == Behrang Dadsetan writes: Behrang> is going to finally be what I am going to use. I not Behrang> feel lambdas are so readable, unless one has serious Behrang> experience in using them and python in general. I feel it Behrang> is acceptable to add a named method that documents with Behrang> its name what it is doing there. If you want to go the functional programing route, you can generalize your function somewhat using a callable class: class remove_char: def __init__(self,remove): self.remove = dict([ (c,1) for c in remove]) def __call__(self,c): return not self.remove.has_key(c) print filter(remove_char('on'), 'John Hunter') Cheers, Jh Huter From mis6 at pitt.edu Mon Jul 21 08:51:16 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 21 Jul 2003 05:51:16 -0700 Subject: classes References: Message-ID: <2259b0e2.0307210451.203db2ef@posting.google.com> Steven Taschuk wrote in message news:... > For the particular problem you're interested in -- singletons -- > here are a few approaches: > > First, use __new__ trickery: > > _the_instance = None > class MySingleton(object): > def __new__(self): > global _the_instance > if _the_instance is None: > _the_instance = object.__new__(self) > return _the_instance Why are you using a global here and not something like class MySingleton(object): _the_instance = None def __new__(cls): if cls._the_instance is None: cls._the_instance = object.__new__(self) return cls._the_instance ? > Example use: > > >>> x = MySingleton() > >>> y = MySingleton() > >>> x is y # same object! > True > > In this approach, users create instances of MySingleton as they > would for any other class (rather than by calling a getInstance > classmethod) -- that action just happens to return the same object > always. > > One gotcha with this approach can be observed by adding > > def __init__(self): > print 'running __init__ on instance %s' % id(self) > > Then we see > > >>> x = MySingleton() > running __init__ on instance 1075795852 > >>> y = MySingleton() > running __init__ on instance 1075795852 > >>> x is y > True > > As shown, each "instantiation" runs __init__ on the single > instance again. If you have initialization which should occur > only when the single instance is actually created: > > _the_instance = None > class MySingleton(object): > def __new__(self): > global _the_instance > if _the_instance is None: > _the_instance = object.__new__(self) > _the_instance._my_init() > return _the_instance > def _my_init(self): > pass # one-time initialization here > > (Another possible issue with this approach arises when subclassing > MySingleton. Details left as an exercise.) > > Second approach: Use a metaclass. See > Unfortunately, I see that this recipe is not very recommendable. I have just submitted a fix which seems to work: class Singleton(type): def __init__(cls,name,bases,dic): super(Singleton,cls).__init__(name,bases,dic) cls.instance=None def __call__(cls,*args,**kw): if cls.instance is None: cls.instance=super(Singleton,cls).__call__(*args,**kw) return cls.instance Here is how it works under inheritance and avoids the problem with calling __init__ twice: class C: __metaclass__=Singleton def __init__(self): print "C: initializing ",self class D(C): def __init__(self): print "D: initializing ",self c1=C() # => C: initializing <__main__.C object at 0x4031c0ac> c2=C() # no output d=D() # D: initializing <__main__.D object at 0x4031c02c> print c1 is c2 # => yes > Third: forget about singletons and use a Borg. See > > (With Borgs, multiple instances may exist, but they share state.) > > Fourth: rethink the idea that a database connection should be a > singleton. See > > and linked pages for discussion on the merits of singletons. HTH, Michele From jdhunter at ace.bsd.uchicago.edu Tue Jul 1 11:13:32 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 01 Jul 2003 10:13:32 -0500 Subject: Partition names with Python In-Reply-To: ("Artur M. Piwko"'s message of "Tue, 1 Jul 2003 10:53:27 +0000 (UTC)") References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: >>>>> "Artur" == Artur M Piwko writes: Artur> And /proc/partitions. Best yet! import os fh = file('/proc/partitions') fh.readline() # eat the header fh.readline() # eat the blank line partitions = [line.split()[-1] for line in fh.readlines()] print partitions From mcherm at mcherm.com Wed Jul 9 08:48:25 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 9 Jul 2003 05:48:25 -0700 Subject: Python Global Constant Message-ID: <1057754905.3f0c0f19cf868@mcherm.com> Krisztian Kepes wrote: > How [do] I create an global constant in [a] module [that] is > accessable in from other modules ? Christoph Becker-Freyseng replies: > What about using __builtins__ wouldn't make this the constant > really global? While adding it to __builtins__ *would* work like you're thinking, it's not necessary, or appropriate. Python provides lots of ways for "power users" to "get under the covers" and change things. This is useful in those situations where you really need it (some other languages provide NO way to get at fundamental language features), but such deep black magic should be reserved for those cases when you really need it. Modifying __builtins__ definitely falls into such a category: if you aren't sure whether you need to do it, then you don't. If you *think* you need to do it, then you shouldn't. If you understand what's going on so well that you are *certain* that you *must* modify it to achieve what you want... well, go ahead! In this case, the OP (original poster) was asking about a very common and straightforward situation: module level constants that need to be visible from other modules. There is a standard and straightforward way to create these: just assign a value to the variable in your module, then use it from other modules by importing the module. Spell the variable with ALL_CAPS to clearly mark that it is intended to be a constant and others shouldn't modify it. You'll need to watch out for cyclic import dependencies, but other than that this is a really easy solution. Now, some might complain that the variable isn't "constant"... spelling it with all caps tells others that they SHOULDN'T modify it, but doesn't PREVENT them from doing so. Really, that's a lot like the issue with __builtins__ that I mentioned above. It's very Pythonic to have a clear *indication* that something shouldn't be messed with (being in all caps or marking with double underscore), but not to *enforce* it -- if someone wants to change it they do so at their own risk. However, if you REALLY wanted to keep them from changing the "constant" (perhaps it controls the security level for running untrusted code) there are ways to do so -- check out the Python Cookbook for some examples. -- Michael Chermside ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From tnienstedt at telesyn.com Thu Jul 24 11:20:05 2003 From: tnienstedt at telesyn.com (Ted Nienstedt) Date: Thu, 24 Jul 2003 11:20:05 -0400 Subject: ImportError: /usr/lib/python2.2/site-packages/libusermodule.so: undefined symbol: PyUnicodeUCS4_AsUTF8String Message-ID: <002801c351f7$0f9e2420$2e1210ac@telesyn.corp> I upgraded python to 2.2.3 on Linux Redhat 9 and now some linux services don't work . For example, attempting to launch 'Users and Groups' or running /usr/bin/redhat-config-users results in: Traceback (most recent call last): File "/usr/share/redhat-config-users/redhat-config-users.py", line 25 in ? import libuser ImportError: /usr/lib/python2.2/site-packages/libusermodule.so: undefined symbol: PyUnicodeUCS4_AsUTF8String I used the rpm files on http://www.python.org/2.2.3/rpms.html I installed tkinter and python-tools also. I also, probably foolishly, used the -replacefiles option of the rpm command. What did I do wrong? How do I recover? Thanks, Ted Nienstedt Telesyn 919-645-4915 tnienstedt at telesyn.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Jul 31 20:51:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2003 20:51:16 -0400 Subject: Python speed vs csharp References: Message-ID: "David M. Cooke" wrote in message news:qnkn0eutndk.fsf at arbutus.physics.mcmaster.ca... > At some point, Mike wrote: > > Here's the chunk of code that I'm spending most of my time executing: > > > > # Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. 7.1.26) > > # Fifth order approximation. |error| <= 1.5e-7 for all x > > # > > def erfc( x ): > > p = 0.3275911 > > a1 = 0.254829592 > > a2 = -0.284496736 > > a3 = 1.421413741 > > a4 = -1.453152027 > > a5 = 1.061405429 > > > > t = 1.0 / (1.0 + p*float(x)) > > erfcx = ( (a1 + (a2 + (a3 + > > (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) > > return erfcx Does inlining the constants give any speedup? or is local lookup so fast that it does not matter? TJR From h.b.furuseth at usit.uio.no Fri Jul 18 09:15:29 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 18 Jul 2003 15:15:29 +0200 Subject: How to get CGI request-URL References: <3f070d44$0$49099$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Glad to be of assistance, but you didn't tell us what the > actual solution to your problem was... 'https://' + os.environ['SERVER_NAME'] + os.environ['REQUEST_URI'] -- Hallvard From alanmk at hotmail.com Wed Jul 16 11:08:00 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 16 Jul 2003 16:08:00 +0100 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: <3F156A50.EA9242AF@hotmail.com> Duncan Booth : >> On question 8, I'm not aware that Python borrowed anything from Java. Aahz: > Lib/threading.py, line 1 Other areas where Java has "had an influence" on python. 1. Logging. Isn't Vijay Sanip's logging package, derived from pretty much a copy of Java's log4j? Comment from "Lib/logging/__init__.py": "Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system." http://www.red-dove.com/python_logging.html 2. Weak References. Influenced by Java, as well as other systems. http://www.python.org/peps/pep-0205.html 3. Unittest module. Comment from the lib\unittest.py "Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework." Junit being the javanese unit test framework of choice. Python and Java are such a natural fit, I foresee that there will be even more cross-fertilisation between the two in the future. So I'm hoping anyway. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From newsgroups at jhrothjr.com Thu Jul 31 11:10:01 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 11:10:01 -0400 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling References: Message-ID: "Bram" wrote in message news:bgbaj5$kgv$2 at news4.tilbu1.nb.home.nl... > Hi, > Summ: "What is the best way to handle int8,16 and 32 data in python?" > > Im currently working on a class to implement the gui protocol of > mldonkey. (http://mldonkey.lemmster.de/wiki/index.php/GuiProtocol) > However this requires to send int32 and int16 and even int8 integers. > > To create data I'm using the work-around of converting everything to hex > values, and then converting the hex values to a data string which I put > on the socket (e.g. "\x00\xF0"). > I could do the same on the recieving end: chop it up in bytes and > convert them to numbers (combining the hi and lo bytes of the int16 with > some calculations) > > However, there must be a better way of doing this. > Can anyone help me on this problem? I took a quick look at the Wiki describing the protocol. For something like this, I'd expect that interoperability would be an issue, so the actual data format in the packets would be part of the protocol specification. That being the case, look at the struct module. I think it does exactly what you need. John Roth > > Bram > > > From g2h5dqi002 at sneakemail.com Wed Jul 9 23:49:22 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 10 Jul 2003 15:49:22 +1200 Subject: format discs. In-Reply-To: References: Message-ID: Taka wrote: > Yes, but since file partitions are usualy bigger than your physical RAM, > you cannot do > > import string > partition.write (string.zfill('0', partition.getsize('/dev/hda10')-1) Given that, it would have been advisable to have used xrange instead of range. :-) All he needs then is a Python implementation of mkfs and he's done... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From hanzspam at yahoo.com.au Sat Jul 26 05:58:18 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 26 Jul 2003 02:58:18 -0700 Subject: I am so impressed References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> Message-ID: <840592e1.0307260158.77b9c471@posting.google.com> "Guyon Mor?e" wrote in message news:<3f207dcc$0$137$1b62eedf at news.wanadoo.nl>... > I've been looking for a nice python editor for a while. I was using a great > general purpose editor called EditPlus. It did the job pretty good.... > > I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com > and it's great! > > i had to share that with you Thanks for sharing, it's a nice editor. I've got few complaints though, do you know how to fix these: - I can't comment / uncomment multiple lines - I have to press backspace 4 times to erase one level of indentation. In IDLE I could do it with one backspace press. Those two are pretty constant annoyances. Otherwise I'd love to use it. From ulope at gmx.de Sun Jul 20 20:57:07 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 21 Jul 2003 02:57:07 +0200 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> <7x7k6cu2rx.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" schrieb im Newsbeitrag news:7x7k6cu2rx.fsf at ruckus.brouhaha.com... > "Ulrich Petri" writes: > > Here in germany we also have elections where more than one thing is voted > > upon but if that is the case we have a seperate ballot for each of those > > descisions and they all go into different "boxes" and are counted by > > different people. > > What is a typical number of such boxes? > > In a US election, the number of "boxes" that would be needed is > usually more than 20 and can be as many as 50. Not just politicians > but also judges, sheriffs, and ballot questions like whether to build > a new school in a given location, all get voted on. > > Do you really want to fill out 50 separate pieces of paper in a voting > booth, and then make sure to deposit each one in its own correct > separate box? wow i wasn't aware that it is that much... Here the ballots are usually printed on colored paper so you can tell which box is for what by the color. The *maximum* of different things voted on in a single election is about 5 here... So finally i see your problem.... Ciao Ulrich From stephen at theboulets.net Tue Jul 29 22:17:35 2003 From: stephen at theboulets.net (Stephen Boulet) Date: Tue, 29 Jul 2003 21:17:35 -0500 Subject: Upgrading python Message-ID: When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3? -- Stephen From bvelkur at yahoo.com Fri Jul 11 16:30:55 2003 From: bvelkur at yahoo.com (0wl) Date: 11 Jul 2003 13:30:55 -0700 Subject: Using xml.xpath question. References: <23891c90.0307110057.bbe91e3@posting.google.com> Message-ID: Works like a charm!!!!! My Ignorance shines bright.... :-). Anywhere I can read about this stuff.. Thanks --Bipin. paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0307110057.bbe91e3 at posting.google.com>... > bvelkur at yahoo.com (0wl) wrote in message news:... > > Hi, > > > > I am trying to get the value of child from > > > > xmlstr = """ > DataType="String">Hellpppp""" > > > > using > > doc=parseString(xmlstr) > > nodeList = xml.xpath.Evaluate("/p:root/p:child/text()", doc) > > > > and am getting the following exception: > > > > xml.xpath.RuntimeException: Undefined namespace prefix: "p". > > The problem is that the XPath query engine doesn't know what the > prefix "p" is, and it won't automatically deduce it from your XML > document. In other words, the prefixes used in your query are > effectively independent from those used in your document, although > this does give you the luxury of changing either your query or your > document without having to go through the other adjusting the prefixes > to match. > > Try this: > > >>> c = xml.xpath.Context.Context(doc) > >>> c.setNamespaces({"p" : "http://tempuri.org/string"}) > > This makes a context and then adds the definition of the prefix for > the XPath query engine. I think xml.xpath.CreateContext(doc) may be > more appropriate, but I always use the above style. Also, you could > probably specify the prefix/namespace definitions in the Context > constructor, but this is just as easy. > > >>> e = xml.xpath.Compile("/p:root/p:child/text()") > > I compile the expression in order to allow the context to be used. We > need a context because there apparently isn't any way of specifying > the prefix/namespace definitions directly in an Evaluate call. > Therefore, we have to set up a context first to contain those > definitions. > > >>> e.evaluate(c) > [] > > Yes, it works! ;-) > > Paul From just at xs4all.nl Tue Jul 8 06:07:48 2003 From: just at xs4all.nl (Just van Rossum) Date: Tue, 8 Jul 2003 12:07:48 +0200 Subject: path module In-Reply-To: <1057655734.3738.7.camel@lothlorien> Message-ID: Ian Bicking wrote: > On Tue, 2003-07-08 at 03:17, Just wrote: > > I would greatly appreaciate such a module in the std library, but > > while Jason's module has some very cool features, to my taste it > > goes a bit too far with overloading operators. I really don't like > > overloading a/b to mean os.path.join(a, b) and I don't think the > > default iterator should do a listdir (although list(mypath) is > > indeed cute). If it were toned down a bit in this area I think we > > may be able to make a good case for including it in the std library. > > I've never wanted to iterate over a string, and find that an annoying > feature in Python (I'd *much* rather get an exception), It's basically a side effect of having a __getitem__ that takes integers. > so covering > up the previous string behavior doesn't seem a big deal to me. It's not just that, but iterating over a path could _also_ mean to iterate over the path elements, so it's not obvious it should iterate over the directory contents. Also, what if path points to a file? > But I > can see why iterating over a path may be a little too magic. But > paths are also containers (at least if they point to a directory), so > iterating over them seems only natural. I could see something like > mypath.dir() being reasonable alternative (mypath.list() also, but > that looks funny to me because "list" is special to my eye). I'd say path.listdir() is most natural. > I do like the /, though. mypath.joinpath(filename) is rather > long-winded (since he wisely avoids reusing the join method). / has > no meaning for strings, so it's not really overloading the operator, > merely adding it in a specific context. It'll confuse the hell out of people who expect / to mean "divide" ;-) > Several operators are reused > for different meanings, % in particular comes to mind, this doesn't > seem that bad. I like the way it looks and feels. It feels better > to me than using + for string concatenation ;) -- maybe because > division is not all that common an operation anyway. I tend to think that this whole discussion shows that _maybe_ it's not such a good idea to subclass str/unicode after all. (Aside: path.py taught me about the existence of os.path.supports_unicode_filenames in 2.3, but at least on my platform (OSX) it has the wrong value. I opened a bug, #767645.) Some string methods are handy on paths, such as .endswith(), while others are not, like .upper() or .splitlines(). Other string method names or operators would make sense for paths, but -- as you say -- are out of the question since their meaning would be quite different, eg. .join() and +. I find overloading / unneccesary, since it's not like you'll have to write a.join(b).join(c).join(d) but rather a.join(b, c, d) which I don't think is all that bad. Btw. long ago (2001, before Jason's path module) I posted a balloon to python-dev about this subject: http://mail.python.org/pipermail/python-dev/2001-August/016663.html There was hardly any response, and Guido said we wasn't too enthusiastic about the idea, so we might have to work hard to pull this off ;-). Also, with unicode, Guido's suggestion that any object that implements __str__ can be used with open() seems to be no longer true. At least I can't get it to work. Just From bokr at oz.net Sun Jul 6 17:28:09 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Jul 2003 21:28:09 GMT Subject: Search for mapping solution References: Message-ID: On Sun, 06 Jul 2003 21:17:36 +0200, Markus Joschko wrote: >Hi, >stated in a post befor, I'm a java programmer, fascinated about the elegant >way python solves iterations. Maybe you can show me a solution how to map >the following > >I have a List: > >Name - Number - Costs > >lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > >Now I want to have it in a dictionary(name,costs) Should look like >{'fred':'0,60' , 'sam':'1'} Should same-name costs just be added, and the number just be ignored? Assuming so, do you actually want the costs in the final dict to be represented as localized strings, or should they be floating point numbers -- or, should they be fixed point in effect? > >What's an elegant way to do it? I can use a lot of loops, but I assume, that >there is a better way of doing so. > If the names were all different, it would be a snap >>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] >>> d = dict([(name,cost) for name,num,cost in lines]) >>> d {'sam': '1', 'fred': '0,50'} but, your example seems to have further requirements, so maybe: ====< jocsch.py >============================================== lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] # might want to use locale-sensitive fixed point for currency, but we'll fake it here ;-) def str2num(s): return ',' in s and int(s.replace(',','')) or 100*int(s) # units of 0,01 def num2str(n): h,u = divmod(abs(n),100); s='-'[:n<0]; return u and '%s%d,%02d'%(s,h,u) or '%s%d'%(s,h) d={} for name,num,cost in lines: cost = str2num(cost) # units of 0,01 d[name] = d.get(name, 0) + cost # accumulate same-name costs in integral units for name in d.keys(): d[name] = num2str(d[name]) # mixed literal string syntax again print lines print d =============================================================== Result: [14:27] C:\pywk\clp>jocsch.py [['fred', '333', '0,10'], ['sam', '444', '1'], ['fred', '333', '0,50']] {'sam': '1', 'fred': '0,60'} A uniform format (i.e., '1,00' instead of '1') would have simplified conversions a little ;-) Regards, Bengt Richter From max at cNOvSisiPonAtecMh.com Wed Jul 23 11:42:57 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Wed, 23 Jul 2003 15:42:57 GMT Subject: htaccess & urllib Message-ID: <52yTa.21249$On.2682411@twister.nyc.rr.com> Is there a way to access an htaccess-protected directory with urllib, password being known? thanks, max -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] From luke at stclair.homelinux.net Fri Jul 25 11:26:49 2003 From: luke at stclair.homelinux.net (Luke StClair) Date: Fri, 25 Jul 2003 15:26:49 +0000 (UTC) Subject: Downloading Python files Message-ID: Only marginally belonging in this newsgroup... but oh well. I've just started writing in python, and I want to make the files available on the web. So I did the standard and not surprisingly, it displays like a webpage, but just the code. If I gzip it, and then link to the new file, it will download, but its so small I don't want it zipped. How can I make this into a downloadable file SIMPLY? The other thread seems a bit complicated... Thanks -- Luke St.Clair | "Ask and it will be given to you; seek and you clairst at uiuc.edu | will find; knock and the door will be opened ---------------------| to you." - Matthew 7:7 --- Posted via news://freenews.netfront.net Complaints to news at netfront.net From staschuk at telusplanet.net Sat Jul 5 17:44:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sat, 5 Jul 2003 15:44:02 -0600 Subject: 'self' disappearing In-Reply-To: ; from daniel.nouri@con-fuse.org on Fri, Jul 04, 2003 at 04:19:29PM +0000 References: Message-ID: <20030705154402.A916@tibia.amotlpaa.bogus> Quoth Daniel Nouri: > The idea of my simple piece of code is to start from a given module and > wrap all functions and methods in that module and submodules. FunWrapper is > the class that I use for wrapping. [...] > It appears that 'instance.method()' is not the same as > 'klass.method(instance)' in this case. But why? And how do I deal with > that? Your function wrapper implements only the __call__ protocol; you also need to handle the descriptor protocol, which is used to implement the bound/unbound method business. For example: class FunWrapper(object): def __init__(self, fun): self.fun = fun def __call__(self, *args, **kwds): print 'Calling', self.fun.__name__ self.fun(*args, **kwds) def __get__(self, *args): print 'Getting', self.fun.__name__ return FunWrapper(self.fun.__get__(*args)) class Foo(object): def bar(*args): print 'called with args', args bar = FunWrapper(bar) foo = Foo() foo.bar('a', 'b', 'c') You might find Raymond Hettinger's writeup of descriptors useful to understand what's going on here: -- Steven Taschuk staschuk at telusplanet.net "I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein From eed132 at psu.edu Tue Jul 15 00:46:15 2003 From: eed132 at psu.edu (Evan) Date: 14 Jul 2003 21:46:15 -0700 Subject: % operator -- did Python or C++/boost come first? References: Message-ID: <3f25c666.0307142046.2936c1b3@posting.google.com> roy at panix.com (Roy Smith) wrote in message news:... > Up until recently, Python was the only language I'd ever seen that > used the % operator for string replacement. Today, I was perusing the > C++ Boost libraries, and discoverd that boost::format uses a very > similar syntax. The following lines print the same thing in Python > and C++, respectively. > > print "int->%i, string->%s" % (42, "wugga, wugga") > cout << boost::format ("int->%i, string->%s\n") % 42 % "wugga, wugga"; > > The question is, which came first? Did boost adapt the Python syntax, > or the other way around, or did they both evolve in parallel? I'm not > talking about the use of % in the C/printf style format specifier, but > the use of % as an operator to connect the format specifier with the > data to be formatted. If you haven't already, I reccomend reading the design rationale for any extensions you're interested in (and that have it of course). The one for format is at http://boost.org/libs/format/doc/choices.html. Python's use of the same syntax is mentioned, along with many other reasons for the choice of the operator (and many more for why << is a bad choice). So it would appear that Python came first. From akineko at pacbell.net Mon Jul 7 20:14:59 2003 From: akineko at pacbell.net (Aki Niimura) Date: 7 Jul 2003 17:14:59 -0700 Subject: upload file via web form (Re: to Trent Mick's posting) References: Message-ID: akineko at pacbell.net (Aki Niimura) wrote in message > I found the 'body' doesn't have CRLF ('\n\r') which some servers may > consider it as a line terminator (for MIME headers). > > After I inserted the following line: > body = string.replace(body, '\n', '\r\n') > It is working correctly. The above is not correct. The body may have '\r\n' already (such as from Windows). Applying string.replace() to such document produces '\r\n\n'. You need to limit the conversion to the MIME header portion or you can fix the code where MIME header is generated. Sorry for messing up. Best regards, Aki Niimura From sshark97 at hotmail.com Thu Jul 3 06:18:33 2003 From: sshark97 at hotmail.com (TH Lim) Date: 3 Jul 2003 03:18:33 -0700 Subject: How to spawn a program with redirection as it parameter Message-ID: Hi, How do I do a simple thing like /bin/cat myfile.txt >> yourfile.txt in unix? I tried with the script shown below but not successful. Am doing it right? Pls. advise. thank you. #!/usr/bin/python import os os.spawnl(os.P_WAIT, "/bin/cat" , "/bin/cat", "myfile.txt >> yourfile.txt") print "Done" From dtolton at yahoo.com Wed Jul 16 18:17:40 2003 From: dtolton at yahoo.com (Doug Tolton) Date: Wed, 16 Jul 2003 22:17:40 GMT Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: <3gjbhv0qk20q2qqunpj17329atq092muon@4ax.com> On 16 Jul 2003 16:51:38 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>, >Doug Tolton wrote: >> >>I did some reading and it seems that an augmented assignment is >>specifically verboten on tuples and lists. Is there a clean way to >>accomplish this? > >Really? > >>>> l = [] >>>> l+=[1] >>>> l >[1] >>>> l+=['foo'] >>>> l >[1, 'foo'] I mis-spoke, lists are not included. You cannot do augmented assignments on tuples or multiple targets. you can do what you typed, but you can't do. >>> a,b = 0,0 >>> a,b += 1,1 SyntaxError: augmented assign to tuple not possible or this: >>> a,b = [],[] >>> a,b += [1],[1] SyntaxError: augmented assign to tuple not possible That is specifically the point I was getting at. Forgive the technical slip of including lists in the discussion. Doug From carsten at gehling.dk Thu Jul 17 04:46:45 2003 From: carsten at gehling.dk (Carsten Gehling) Date: Thu, 17 Jul 2003 10:46:45 +0200 Subject: SV: Choosing the right framework In-Reply-To: Message-ID: > -----Oprindelig meddelelse----- > Fra: python-list-admin at python.org > [mailto:python-list-admin at python.org]P? vegne af David McNab > Sendt: 17. juli 2003 01:32 > Til: python-list at python.org > Emne: Re: Choosing the right framework > I've been working on an HTML generation framework called 'pyWeb'. Just > posted to this ng yesterday, calling for testers. > > You might like to visit http://www.freenet.org.nz/python/pyweb and have a > look. This I did - to be honest, I'm no real fan of frameworks where you make objects/functions to represent html-tags. It's IMHO not a good way to seperate logic and presentation. I'm more to the kind of templates where you write your own html snippets and embed som sort of template markers inside. But thanks anyway. :-) I actually did this myself in PHP, but in a greater level of abstraction. I needed a fast way of creating "user interfaces" (dialog forms etc.), so I created a class hierarchy with tab-pages, layout managers, input controls, etc. that all conformed to the general design. The complete script for an dialog form to edit eg. an article would look like this (mind you - it's PHP): ------------------------------------- $dlg = new UI_TabDialog("Edit article"); $dlg->form_action = "artikel_update.php"; $dlg->add_hidden_field("id", $id); $page = new UI_TabPage("Article"); $layout = new UI_Layout_row(array( array(100), array(100), array(100), array(50, 50), array(100) )); $c = new UI_Control_static("Edit your article and click on "Save"); $layout->add_control($c); $c = new UI_Control_input("title", "Header", ""); $layout->add_control($c); $c = new UI_Control_textarea("body", "Main article text", "", 190); $layout->add_control($c); $c = new UI_Control_date("releasedate", "Release the article on", date("Y-m-d")); $layout->add_control($c); $c = new UI_Control_date("expiredate", "Expire the article on", date("Y-m-d")); $layout->add_control($c); $c = new UI_Control_image("image_id", "Attach image to article", ""); $c->url_template = IMAGE_UPLOAD_PATH . "image_%d.jpg"; $layout->add_control($c); $page->add_control($layout); $dlg->add_page($page); $dlg->draw(); ------------------------------------- - Carsten From bignose-hates-spam at and-zip-does-too.com.au Sun Jul 13 08:50:10 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 13 Jul 2003 22:40:10 +0950 Subject: The "intellectual property" misnomer References: Message-ID: On Sun, 13 Jul 2003 13:33:32 +0200, Anton Vredegoor wrote: > Probably nothing good can come from using it. I am not saying that it > cannot be used to prevent something bad, but that it's probably better > to try to do something good ... Thank you. I am in complete agreement with this sentiment, but you've expressed it simpler than I did. > if an idea has any quality it almost always depends on the ideas of a > lot of other people. Therefore ideas are very unlikely to be > "undivided" property, unless the intellectual level is very low. This was in large part my basis for stating the term was meaningless. -- \ "Jealousy: The theory that some other fellow has just as little | `\ taste." -- Henry L. Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From m at moshez.org Thu Jul 17 08:05:46 2003 From: m at moshez.org (Moshe Zadka) Date: 17 Jul 2003 12:05:46 -0000 Subject: Python Asynchronous Services In-Reply-To: References: Message-ID: <20030717120546.24653.qmail@green.zadka.com> On Thu, 17 Jul 2003, "Graeme Matthew" wrote: > Hi all, I have hit a serious snag ... ... > please any help or examples as I have now been on this for 2 days without > any luck. I have looked at asyncore and asynchat, problem is once the server > socket input is completed then their will be an area that is CPU bound where > it will need to call the model, database etc and produce the html request, > this means that control will only be handed back to IO operations when this > is finished, effectively blocking all other requests .... Well, I can recommend Twisted. Twisted uses a producer/consumer model to send large file, which is fairly transparent [there is a good cut'n'pastable example of usage of this in twisted.web.static.File]. This should be enough to handle the network part. You claim there is a CPU-bound operation after that -- if this is really true [and in my experience, in many of the cases the operation are short enough that it is not required] -- you can use Twisted's deferToThread to treat those operations as though they were completely asynchronous. This uses Twisted's internal threadpool support. More information: http://twistedmatrix.com/ [Disclaimer: I am part of the Twisted developement team] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From aahz at pythoncraft.com Sat Jul 5 17:23:02 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Jul 2003 17:23:02 -0400 Subject: Python Open Source Project for Live Support References: Message-ID: In article , Sergio Lobo wrote: > >I have developed a simple Online Support System which is running at >www.supportdrive.com. The system is divided in 3 parts: > >1- Server - Implemented in Python >2- Client - Delphi 6 >3- Web Client - PHP + Javascript Anti-JavaScript FAQ: http://www.rahul.net/aahz/javascript.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From paul at boddie.net Tue Jul 22 05:39:05 2003 From: paul at boddie.net (Paul Boddie) Date: 22 Jul 2003 02:39:05 -0700 Subject: [OT] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: <23891c90.0307220139.1909fc63@posting.google.com> clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) wrote in message news:<4868482a.0307211336.4ca9493a at posting.google.com>... > > I realize that this is OT, but SCO's action strikes at the heart of > Open Source. Somebody with the right patents can try to tax or shut > down the rest of us, regardless of the validity of their claims. If > IBM, Red Hat, and the decide that the the cost of settling is less > than the cost of litigation, we all loose. Fortunally, the claim > against IBM is so big, $3B that they may fight it instead of settling. (Insert footage of an office in IBM's legal department: the camera pans upward from a stack of papers representing SCO's claims; hysterical laughter can be heard as the camera pans across to one of the lawyers; "I love this job!" he exclaims.) Despite the wider implications of this case, plus the implications of other recent developments (for me, that would have to include the increased interest by various European Union factions in the introduction of software patents), this really isn't the right forum for constructive discussion about such issues. However, it must be said that far too many people are unaware of such goings-on, or are virtually apathetic about them ("as long as the free stuff keeps coming", "it's not my place to think about it" and "if it's made illegal, my employer will retrain me"). But thanks for the reminder that we really are lucky to be able to use technologies and tools like Python, that the climate in which they have been developed has so far been favourable to such innovation, and that we should strive to maintain such a favourable environment through the appropriate forums and channels. Paul From gh at ghaering.de Thu Jul 31 10:17:51 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 16:17:51 +0200 Subject: SQL2000 database vs python In-Reply-To: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> References: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> Message-ID: <3F29250F.6040403@ghaering.de> Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Ok I was too happy. > > mssqldb doesn't help me to connect my python app on a linux OS to a sql2000 (windows os) database. > I can't even compile the package, I guess it is missing sybase stuff (sybdb.h and sybfront.h), > which is correct because I don't have that database. There should be an option to compile it against FreeTDS (http://www.freetds.org/) It's probably best to ask further questions on the mailing list for this database adapter. > Also, mssqldb supports ms sql server 7.0, my hope is that that won't be a problem in using ms sql 2000. Don't give up so fast :) I'm pretty sure this can be made to work. If this ultimately fails, there are other alternatives like an ODBC-ODBC bridge, SQLRelay, or something like http://sourceforge.net/projects/pyxsqmll But the last project seems to be *quite* inactive. -- Gerhard From jjl at pobox.com Sun Jul 27 20:43:21 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:43:21 +0100 Subject: mxTidy References: Message-ID: <87k7a3a3bq.fsf@pobox.com> james roush writes: > What versions of Python will mxTidy work with. I'm using it with Python > v2.1.x but want to upgrade to 2.3 when it is released > > Are there any alternatives to mxTidy? uTidylib Wrapper of the new tidylib. Not yet clear to me if and how it's better, but it is more actively maintained than mxTidy. John From ianb at colorstudy.com Fri Jul 11 14:39:37 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 11 Jul 2003 13:39:37 -0500 Subject: Securing 'pickle' In-Reply-To: <87k7apyuor.fsf@pobox.com> References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <87k7apyuor.fsf@pobox.com> Message-ID: <1057948777.28274.6.camel@lothlorien> On Fri, 2003-07-11 at 10:00, John J. Lee wrote: > Ian Bicking writes: > [...] > > Security isn't a big deal -- or rather, securing cookies isn't a big > > deal. > > I don't understand. The problem is that pickles can be constructed > that can damage systems when unpickled, is that right? If that's > true, then surely unpickling cookie data is unsafe, because stuff > coming in from the network has to be regarded as malevolent. Are you > saying that web server environments are sufficiently-well bolted down > that no pickle attack will work? But belt-and-braces is the best > policy, isn't it? I should have said "securing cookies isn't hard", so that's not the reason not to use them (though you shouldn't just use plain-vanilla cookies). Ian From intentionally at blank.co.uk Tue Jul 15 17:20:16 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 22:20:16 +0100 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> <20030714172215452-0600@news.xmission.com> <2259b0e2.0307150532.1b6b20b7@posting.google.com> Message-ID: On 15 Jul 2003 06:32:48 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >Tim Roberts wrote in message news: >> Whether or not I agree with you, you have made me think. That's worth the >> price of my Internet connection this month. > >+1 QOTW Thanks for saying so. Not sure if Tims 'civil and intellectual' thing counts any more from my side. I've let it get to me, I suppose. Time to shut up and leave it alone. Of course, I said something similar some time ago :-( From lorenzo at mysurname.net Sat Jul 12 07:48:46 2003 From: lorenzo at mysurname.net (Lorenzo Bolognini) Date: Sat, 12 Jul 2003 11:48:46 GMT Subject: Old post about XML overhyped Message-ID: Hi all, i'm googling for an old post appeared here about XML overhyped. I do remember a sentence that sounded like this (more | less): "Management thinks that webservices are good because xml is good and exchainging data between different platforms is good" I'm not able to find it could somebody point to the original post and help me find it... it was a very interesting thread and want to read it more carefully! ;-) Lorenzo From bokr at oz.net Fri Jul 25 11:03:07 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 15:03:07 GMT Subject: Don't want to do the regexp test twice References: Message-ID: On 25 Jul 2003 02:17:24 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >You can spell > > ... elif setattr(obj,'mat', pat.search(line)) or obj.mat: > ... print repr(obj.mat), obj.mat.groups(), obj.mat.group() > >a little slicker if you make a special object to hold a binding to >the pat.search result, e.g., h is the Holder instance in the following, >which remembers the last thing passed to it and immediately returns it, >and also returns that last thing on being called without an arg: > > >>> mylist > ['', 'a', 'bc', 'def', 'ghij'] > >>> h = Holder() > >>> for line in mylist: > ... if 1==2: 'naw' > ... elif 3==4: 'neither' > ... elif h(pat.search(line)): > ... print repr(h()), h().groups(), h().group() > ... elif 4==5: 'haw' > ... else: > ... print 'final else' > ... > final else > final else > final else > <_sre.SRE_Match object at 0x007F6FC0> () def > <_sre.SRE_Match object at 0x007F6F80> () ghi > >Obviously > ... print repr(h()), h().groups(), h().group() >could have been > ... mat=h(); print repr(mat), mat.groups(), mat.group() >instead. > Sorry, I seem to have snipped out a Holder definition, in case anyone cares: >>> class Holder(object): ... def __call__(self, *args): ... if args: self.val = args[0] ... return self.val ... >>> h = Holder() >>> h(123) 123 >>> h() 123 >>> h(345),h(),h(678),h() # result depends on left-to-right eval here (345, 345, 678, 678) Regards, Bengt Richter From newsgroups at jhrothjr.com Thu Jul 31 11:00:19 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 11:00:19 -0400 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: "Anthony_Barker" wrote in message news:899f842.0307310555.56134f71 at posting.google.com... > I have been reading a book about the evolution of the Basic > programming language. The author states that Basic - particularly > Microsoft's version is full of compromises which crept in along the > language's 30+ year evolution. > > What to you think python largest compromises are? > > The three that come to my mind are significant whitespace, dynamic > typing, and that it is interpreted - not compiled. These three put > python under fire and cause some large projects to move off python or > relegate it to prototyping. > > Whitespace is an esthetic preference that make Andrew Hunt and David > Thomas (of Pragmatic Programmer fame) prefer Ruby. Personally, I love > it - but I can see why some people might not like it (30 years of > braces). Since I'm not particularly masochistic, I will respectfully disagree. Unnecessary braces are one of the reasons I haven't looked at Ruby. That said, I've come to the conclusion that the editor should take care of these things for you. If you prefer a brace free notation, you should be able to tell your editor to present the program to you that way. If you prefer braces, then it should be able do that for you as well. That kind of stylistic thing doesn't belong in the language. In fact, if I didn't have to deal with the braces, I think I'd come around to the view that the text should have them. Explicit is better than implicit, and there are a few things that the automatic indentation makes rather difficult in the design area. > Dynamic typing causes the most fuss. I like Guido's answer to the > question - > > "Doesn't dynamic typing cause more errors to creep into the code > because you catch them later than compile time?". > > "No, we use Unit Testing in Zope". > > That said, obvious Basic compromised by using things such as "Option > Explicit", thereby allowing both dynamic and more static style > variables. Yahoo groups moved from python to C due to dynamic typing. Basic was compromised from day 1. Its designers tried to water down Fortran to produce something that they could use to teach programming in an interactive system. The late Ejdsger Dykstra called Fortran an "infantile disorder". While he was rather outspoken, he had his reasons. The only reason that Basic exists today is that Bill Gates has a certain fondness for that interpreter he wrote that got him his start in the business. > Non-compiled - obviously there are times when performance matters more > than other things. Google I believe uses python to prototype (or used) > and then turns to c++ for heavy lifting. High performance isn't Python's target. If PyPy ever gets their act off the ground, then we will have a shot at a good quality JIT interpreter. Then watch it fly. > What about immutable strings? I'm not sure I understand Guido's > preference for them. Immutable objects make it much easier to do dictionaries. That's why Python has both lists and tuples. The actual problem with immutable strings is performance. While you can concatinate strings with '+', if you've got more than two strings to put together, it's faster (and clearer) to use the '%' formatting operator. This isn't real obvious to experianced programmers that are new to the language, though. I don't see any of these as compromises. Python has a specific location on the spectrum that makes it better for certain things than for others. John Roth > > Anthony > http://xminc.com/anthony From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 24 02:12:36 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Jul 2003 16:02:36 +0950 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> <3F1F5CB2.7FB4C205@alcyone.com> <3F1F6C4B.BE9CCA25@alcyone.com> Message-ID: On Wed, 23 Jul 2003 22:19:07 -0700, Erik Max Francis wrote: > Ben Finney wrote: >> This doesn't match Bryan's nested structure above, which you blessed >> as not "overkill" (in his words). > It doesn't have the same nested pattern, but try/finally isn't at > issue here. Judging by Bryan's responses elsewhere in this thread, the multiple nested 'try...finally' is indeed what he was asking about. The question seems to be answered now. -- \ "Those who will not reason, are bigots, those who cannot, are | `\ fools, and those who dare not, are slaves." -- "Lord" George | _o__) Gordon Noel Byron | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From martin at v.loewis.de Wed Jul 9 15:35:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jul 2003 21:35:25 +0200 Subject: Shared vs static link performance hit --and Windows? References: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> Message-ID: Andrew MacIntyre writes: > The important distinction between Win32+OS/2 and Unix is that the dynamic > linkage uses relocation fixup records to relocate Windows (& OS/2) DLLs, > whereas the dynamic linkage on Unix does not support the relocation action > for shared objects - hence the use of PIC on Unix. That is not the case. Most recent Unix versions (Solaris, Linux, most likely others) support dynamic relocations in shared libraries just fine. Linux, for example, maps all code segments copy-on-write, so sharing is given up only for the pages that need relocations. On such systems, use of PIC is only for performance, to save the relocations. Notice that this use is often questioned, as you have to trade runtime efficiency due to the loss of general-purpose registers to the PIC implementation, on particular on x86. So for long-running applications, it would be better to accept the relocations at start-up time, and get better performance during the computations. Regards, Martin From adechert at earthlink.net Mon Jul 21 03:44:42 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 07:44:42 GMT Subject: Python voting demo discussion Message-ID: Thanks for the interesting discussion yesterday afternoon about the voting software development project I am working on putting together. Almost all of the discussion had nothing to do with my question, but that's okay. Actually, I knew it would probably go that was but I could not very well say, "don't ask me all those other questions." It was reasonable for you to ask. Ian Bicking and Andrew Dalke did say they thought Python should be fine for the demo but I didn't get much detail about why we should prefer it over some of the other possibilities: HTML, XML, Perl, Java, PHP, C, C++, C#, C, etc. If you have anything to add regarding this specific issue, I would be interested to hear it. Thanks again for your time. -- Alan Dechert From max at alcyone.com Wed Jul 23 15:18:56 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 Jul 2003 12:18:56 -0700 Subject: Shallow vs Deep copies [was Re: python assignment] References: <1jr2v-vd.ln1@grendel.myth> Message-ID: <3F1EDFA0.ED78E04F@alcyone.com> Jim Richardson wrote: > A shallow copy of an object, returns an object that contains > references > to objects within the copied object, yes? > > so a list consisting of [1,2,a,"a"] when copied shallowly, will return > exactly that, but when copied deeply, will reture [1,2,"whatever a > points to","a"] yes? No, that's what the first list already consists of: >>> a = "whatever a points to" >>> l1 = [1, 2, a, "a"] >>> l1 [1, 2, 'whatever a points to', 'a'] A shallow copy makes a new object of the object passed in, and maintains the same reference. A deep copy makes a new object, _and_ a new object of all references it contains, and on down the line. The difference between shallow and deep copying is not apparent when you're talking about immutable objects, since immutable objects need not ever be literally copied. Consider a simpler case of a list containing a single element, which is an instance of a custom class: >>> class C: pass ... >>> c = C() >>> x = [c] >>> y = copy.copy(x) >>> x is y 0 >>> x[0] is y[0] 1 >>> z = copy.deepcopy(x) >>> x is z 0 >>> x[0] is z[0] 0 >>> x[0] <__main__.C instance at 0x810ba8c> >>> z[0] <__main__.C instance at 0x814c9fc> Shallow copying makes a duplicate of the parent object. Deep copying makes a duplicate of everything. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Of war men ask the outcome, not the cause. \__/ Seneca From jepler at unpythonic.net Wed Jul 9 23:49:05 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 9 Jul 2003 22:49:05 -0500 Subject: Embedding Python, threading and scalability In-Reply-To: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> References: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> Message-ID: <20030710034901.GA4856@unpythonic.net> On Thu, Jul 10, 2003 at 11:14:47AM +0800, Simon Wittber (Maptek) wrote: > Seriously though, this is an issue, which is a major hurdle Python *has* > to cross if it is ever going to be seriously considered for use on large > projects, on large SMP hardware. Has anybody proposed "how to get there from here" for this problem (useful multithreading of non-blocking pure Python code)? I'm not bright enough to see how, that's for sure. Especially if you are talking about an incremental approach, not the mythical "Python 3000". What I mean is that you have to work this magic *and* somehow let existing modules written in C work, with at worst a recompile. (as someone who doesn't *need* threads, but works on a project with piles of Python modules written in C, that's my bias anyway) Someone nearby mentioned lua, but I don't know what it did for threading. Perl and tcl both seem to have taken the approach of having each thread be a distinct interpreter with nothing shared. While this means you never have to worry about locking against a reader or modifier in another thread, it means you might as well be using the processes that the angry Unix Gods gave us in the first place. <1/3 overstatement> I'm pretty sure that this approach has been explicitly ruled out by that other angry God, Guido van Rossum, anyway. I've written Python programs that use threads in a way that was expedient to get a user interface running without long seizures, while I've never written a thread in tcl or perl. OTOH if I'd had to treat everything as explicit message passing (a la tcl threading), I'd have just found another way (like "after idle" and "update" in tcl) Jython will give you Java's thread model today, for Python code, won't it? Back when I benchmarked it, Jython code and Python code ran at fairly similar speeds (in pybench), if only you had a machine that could keep the Jython interpreter from swapping... Jeff From ianb at colorstudy.com Wed Jul 9 22:40:56 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 09 Jul 2003 21:40:56 -0500 Subject: Sample Web application (Re: Python vs PHP) In-Reply-To: <20030710021451.24619.qmail@green.zadka.com> References: <1057801996.3737.1223.camel@lothlorien> , <20030710021451.24619.qmail@green.zadka.com> Message-ID: <1057804855.3738.1235.camel@lothlorien> On Wed, 2003-07-09 at 21:14, Moshe Zadka wrote: > On 09 Jul 2003, Ian Bicking wrote: > > > I think installation is a major hindrance to Python's > > adoption as a web programming language -- a combination off difficult > > installation, and a lack of robustness and generality in installation > > methods. > > Since PHP is widely adopted as a web programming language, I assume > you think PHP's installation methods are robusts and general? > Let me assure you, having done PHP configuration in Apache, it > is far from it -- in fact, it is buggy and annoying beyond all > measure. [I was *shocked* to discover, for example, I can't associate > all .html files in a directory with PHP. I am sure it is a great > visibility booster for PHP to have pages end with .php, but I didn't > care much for it.] PHP's installation is difficult, but fairly robust. The result is a system where pages can be added easily, multiple users can coexist, server health is generally maintained, and administrator overhead *after* installation is pretty good. For a large set of applications, you don't have to interact with the administrator during installation or development of your application. Interacting with system administrators usually does not make developers happy, so that's a big plus. PHP certainly sucks in a whole bunch of ways, installation included, but it gives administrators what they want (simplicity and delegation), and gives users what they want (an available environment with a relatively decent learning/usage curve). Ian From kkto at csis.hku.hk Tue Jul 22 21:08:29 2003 From: kkto at csis.hku.hk (Isaac To) Date: 23 Jul 2003 09:08:29 +0800 Subject: Search for a string in binary files References: Message-ID: <7ihe5edp82.fsf@enark.csis.hku.hk> >>>>> "Fran?ois" == Fran?ois Pinard writes: Fran?ois> [hokieghal99] >> One last question: does grep actually open files when it searches >> them? Fran?ois> I did not look at `grep' sources for a good while, I might not Fran?ois> remember correctly, read me with caution. `grep' might be Fran?ois> trying to `mmap' the files if the file (and the underlying Fran?ois> system) allows this, and there is system overhead associated Fran?ois> with that function, just like `open'. Mmap requires the file descriptor of the file as argument, so the file still has to be opened. In general "open" is the OS interface to request for access to file data, so there is no way around it. Regards, Isaac. From pythonguy at Hotpop.com Wed Jul 30 09:11:41 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 30 Jul 2003 06:11:41 -0700 Subject: How to get success/failure in case of thread References: <20030728175542.A23857@cs.unipune.ernet.in> <16165.10847.483917.787182@montanaro.dyndns.org> <84fc4588.0307290442.7c203e35@posting.google.com> Message-ID: <84fc4588.0307300511.11b4db5b@posting.google.com> If you can post some actual code here I could be of more help. Cheers ~Anand vivek at cs.unipune.ernet.in wrote in message news:... > I think I have asked the wrong question :-( . I think the question should be : > > How can I use multiple threads in SimpleXMLRPCServer ??? > > I tried the following things: > > 1. added a queue object in the handler class > 2. called the _dispatch mathod on a separate thread > 3. in the _dispatch method after getting the reqult put it in queue > 4. called another function that will send the response that was previously > send by the dispatch method. > > But when I tried this it failed miserably :-( > > I even don't know whether I tried in the right direction or not ?? > > Any help/pointers. ??? > > TIA and Kind Regards > Vivek Kumar From janeaustine50 at hotmail.com Fri Jul 11 06:30:10 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 11 Jul 2003 03:30:10 -0700 Subject: Is re module thread-safe? Message-ID: As the subject says, is re module thread-safe? I have a couple of threads using re module. Is it thread-safe? or should I use something like lock acquire/release? Jane From hokiegal99 at hotmail.com Mon Jul 21 17:19:59 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 21 Jul 2003 17:19:59 -0400 Subject: Search for a string in binary files Message-ID: Hello, How could I use python to search for a string in binary files? From the command line, I would do something like this on a Linux machine to find this string: grep -a "Microsoft Excel" *.xls How can I do this in Python? From logiplex at qwest.net Wed Jul 30 17:38:05 2003 From: logiplex at qwest.net (Cliff Wells) Date: 30 Jul 2003 14:38:05 -0700 Subject: gnome applet with python In-Reply-To: References: Message-ID: <1059601084.8920.4234.camel@software1.logiplex.internal> On Wed, 2003-07-30 at 08:36, nabugoon wrote: > Hi all. > > I'm trying to write gnome applet program with python. > But, it is too difficult to find any document about that. > One web page I had found was old. > (http://www.onlamp.com/pub/a/python/2000/07/25/gnome_applet.html?page=2) > There is no AppletWidget attribute anymore and 'Gtk' prefix at gtk module > functions I don't use that toolkit, but I know a lot of the Redhat utilities do. If you're on RH, take a look at /usr/share/rhn/rhn_applet/rhn_applet.py which seems a good place to start. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From tjreedy at udel.edu Thu Jul 17 17:43:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 17:43:22 -0400 Subject: Replacing rexec References: Message-ID: "Tim Gerla" wrote in message news:mailman.1058378245.3305.python-list at python.org... > (I apologize if I've dug up a long-dead horse, It is perhaps one worth digging up about now (with 2.3 about out). > but I haven't found any > posts in the archive on this that really explain what I'm asking.) The discussion of this issue was last fall and winter mostly on PyDev - the development discussion list - and not on c.l.py. Aahz + Tim Peters have given a fair summary, but for more details, consult the (bi)monthly summaries which Brett Cannon resumed last October (available on python.org) and perhaps then the archives themselves. Terry J. Reedy From genew at mail.ocis.net Sat Jul 5 23:56:51 2003 From: genew at mail.ocis.net (Gene Wirchenko) Date: Sun, 06 Jul 2003 03:56:51 GMT Subject: Collective memory References: <3f06af11$0$49113$e4fe514c@news.xs4all.nl> Message-ID: <3f071e0c.4620472@news.ocis.net> Irmen de Jong wrote: >Charles Shannon Hendrix wrote: > > Python uses it for actually determining the logic in your program, which > > IMHO is dangerous. Not at all. It just means that I will never use Python if it is at all avoidable. My backhanded compliments: it is actually less safe than C. > > if > > > > > > > > > > Is part of the if statement, or did someone with different > > tab settings from the author make a mistake and align it accidentally? > >To catch such mistakes, Python has the -tt command line option: >-t : issue warnings about inconsistent tab usage (-tt: issue errors) What is inconsistent about the tab usage above? That is, why would it be flagged? >There's also tabnanny.py in the standard library to check things >before executing code. I'm not sure, but I suspect that PyChecker >also checks this. Sincerely, Gene Wirchenko Computerese Irregular Verb Conjugation: I have preferences. You have biases. He/She has prejudices. From pinard at iro.umontreal.ca Mon Jul 14 16:12:45 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 14 Jul 2003 16:12:45 -0400 Subject: Confusing automated translators. In-Reply-To: <16146.53798.759651.430032@montanaro.dyndns.org> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3F12CE17.76A0A5@hotmail.com> <16146.53798.759651.430032@montanaro.dyndns.org> Message-ID: [Skip Montanaro] > >> Another similar classic, for French, is "Le pilote ferme la > >> porte.". > Not being any sort of French speaker, I don't understand the "pilote ferme" > one at all. Fran?ois? Just to repeat publicly the content of a private reply, the two meanings could be: "The driver closes the door." "The firm driver is carrying her." The second meaning is clearly wrong to most listeners, but an automated system has no real clue about this (unless it does wider context analysis with the surrounding sentences, but this is fairly difficult.) -- Fran??ois Pinard http://www.iro.umontreal.ca/~pinard From mwilson at the-wire.com Tue Jul 15 12:13:52 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 15 Jul 2003 12:13:52 -0400 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> Message-ID: In article , Duncan Booth wrote: >"richardc" wrote in >news:3f13bd77$1 at mail.hmgcc.gov.uk: >> 3. How do I reverse iterate through a loop ... is there an easier way >> than something like the following >> l = ['some', 'text', 'in', 'a', 'list' ] >> for i in range( 0, len( l ) ): >> do something to l[ i ] > >The usual way is simply to reverse the list before iterating over it. > > l = ['some', 'text', 'in', 'a', 'list' ] > l_reversed = l.reverse() > for item in l_reversed: > do something to item Trouble. l.reverse() reverses l in place. So just l.reverse() for item in l: ... Regards. Mel. From bokr at oz.net Tue Jul 15 22:07:18 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 02:07:18 GMT Subject: anything like C++ references? References: <3f67hvgi36s7rmtn59rajj2gpir8hhfiph@4ax.com> <3F13ADDD.57BF2969@alcyone.com> Message-ID: On 15 Jul 2003 10:41:52 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article <3F13ADDD.57BF2969 at alcyone.com>, >Erik Max Francis wrote: >> >>The value is the object. The object is the value. > >Actually, that's not quite true, and it's something I've been wrestling >with how to describe. What's the value of a file object? I think in a >very real sense, a file object doesn't have a "value". You could try >arguing that the file contents are the value, but that value is not >contained within the object -- the object is a proxy. Saying that the >filename is the value doesn't work, either, especially when you want to >talk generically about file-like objects (such as StringIO and sockets). ISTM the trouble is that in causual talk about "value" there is an implicit mapping function involved which usually doesn't need mentioning. The mapping is from a concrete "thing-supposed-to-have-value" representation to a member of an abstract set of values, such as integers. E.g., a suitable function can map "15" to the same abstract and unique value as another function maps "F" to. Note that "15" can map to the same as "twentyone" depending on the function applied. The point is that a representation has no instrinsic value, it corresponds to a value in a particular abstract set by way of a particular valuation function. Thus I would say that the "value" of a file object depends on the valuation function you apply. Without specifying the latter, there can be no value. Concretely, a valuation function can only return another representation, but that can be useful in getting closer to a simple abstraction. E.g., StringIO.getvalue() or f.seek(0);f.read() returning string representations, whose value may be an octet sequence, which is easy to think of in the abstract, or it could be a sequence of abstract glyph-set members, identified by a mapping through ord() and indexing the ordered glyph set. I.e., a mapping function may be a composition of a conventional series of function applications. Anyway, ISTM "value" usually presupposes a conventional choice of mapping function. Regards, Bengt Richter From jwhitlark at attbi.com Mon Jul 14 21:01:55 2003 From: jwhitlark at attbi.com (Jason Whitlark) Date: 14 Jul 2003 18:01:55 -0700 Subject: A framework for recording, editing, and executing macros in Python? Message-ID: One of the benefits of python always thrown about is how easy it is to use as a macro language. While this certainly has wide applicably, I have always been interested in a little more; namely, the ability to record and then edit macros, as in MS Word, Excel, etc. A recent post http://groups.google.com/groups?threadm=mailman.1056722085.11922.python-list at python.org convinced me that this was possible, so I spend a few hours this weekend and hacked up a basic system as a proof of concept. While I was doing this, I found nothing on the net about the particulars of what I was trying to do. While it hasn't been too hard, I feel that there should be a document of the general techniques possible, what design decisions affect this, (eg. Command pattern, events, and direct calls to an underlying class.), and other relevant points. While I would be willing to write this, I feel that I do not know enough about what other people might need from this. My request is that you post your thoughts on the subject, different ways to do it, what might be useful in such a framework, whether this is worth making a full project like py, formerly pycrust, or if it should just be posted on the cookbook sites, etc. Please let me know what you think; I have this code and ideas and do not know what do with them! From max at cNOvSisiPonAtecMh.com Fri Jul 18 13:48:14 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Fri, 18 Jul 2003 17:48:14 GMT Subject: Perl -> Python hopeless? References: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> Message-ID: Answer: I think they are working on somethig that will allow perl lib usage in python. Question: Can someone in the know drop a line? -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Helmut Jarausch" wrote in message news:3f182c9a$0$276$ba620e4c at reader0.news.skynet.be... > Hi, > having been a Perl fan for years I have nearly converted to Python. > Still, there are LOTS and very good modules written in Perl. > > Is there a tool to lesson the burdon of translation of Perl to Python? > I am completely aware of the fact that a fully automatic translation > to readable Python source is hard if not impossible. > But such a tool could lots of the tedious work like replacing > braces by proper indentation and and similar things. > > Thanks for a pointer (if there is one) > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > From lale at fotonation.com Mon Jul 7 08:40:07 2003 From: lale at fotonation.com (Ilariu Raducan) Date: Mon, 07 Jul 2003 13:40:07 +0100 Subject: PythonWin dynamic toolbar Message-ID: Hi All, I'm trying to create a dynamic toolbar. This function tries to create the toolbar and add a button to it. It craches at tbctrl.SteBitmapSize(32,32) What is wrong with it? Thank you, Lale def OnCreateClient(self,context,obj): window.MDIChildWnd.OnCreateClient(self,context,obj) parent = self style = win32con.WS_CHILD | win32con.WS_VISIBLE | afxres.CBRS_SIZE_DYNAMIC | afxres.CBRS_TOP | \ afxres.CBRS_TOOLTIPS | afxres.CBRS_FLYBY self.toolbar = tb = win32ui.CreateToolBar (parent, style) tbctrl = tb.GetToolBarCtrl() tbctrl.SetBitmapSize(32,32) bmp = win32ui.CreateBitmap() bmp.LoadBitmapFile(open('importimages.bmp','r')) bmpIndex = tbctrl.AddBitmap(1,bmp) tbctrl.AddStrings('rect\0point\0poligon\0') tbutton = tbctrl.TBUTTON tbutton[0]=(bmpIndex,868,win32con.TBSTATE_ENABLED, win32con.TBSTYLE_BUTTON,None,0) tbctrl.AddButtons(1,tbutton) tb.EnableDocking(afxres.CBRS_ALIGN_ANY) tb.SetWindowText("Test") parent.EnableDocking(afxres.CBRS_ALIGN_ANY) parent.DockControlBar(tb) print tbctrl.GetButtonCount() return 1 From vze4rx4y at verizon.net Fri Jul 18 03:09:40 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 18 Jul 2003 07:09:40 GMT Subject: How do I get info on an exception ? References: Message-ID: "Frank" wrote in message news:fc07672ed11f5dcad539bcf9bf0d051f at news.1usenet.com... > Using Python 2.2.2, > I want to catch all exceptions from "socket.gethostbyaddr(ip)" > > From IDLE, I can generate: > >>> socket.gethostbyaddr('1.2') > Traceback (most recent call last): > File "", line 1, in ? > socket.gethostbyaddr('1.2') > herror: (11004, 'host not found') <=== what I want when I catch > > When I run this code: > try: > hostname, aliases, hostip = socket.gethostbyaddr(ip) > return (hostip, hostname) > except: > print sys.exc_info() > print sys.exc_type > return > How do I get the "(11004, 'host not found')" part? You could catch it with: except socket.herror, inst: print inst.args or more broadly with: except socket.error, (errno, string_message): print code, message > More importantly, where is the answer documented that I should > have looked? The list of possible socket exceptions is in the docs for sockets. It also describes the (errno, string) return tuple value of inst.args. Raymond Hettinger From mertz at gnosis.cx Mon Jul 7 12:34:41 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 07 Jul 2003 12:34:41 -0400 Subject: anything new on the ternary operator? References: <3F09252F.9B0F52BD@alcyone.com>, Message-ID: Moshe Zadka wrote previously: |I'm sorry, I was going to let this slide by, but this comment made it |impossible. How the hell do you figure EuroPython, the biggest Python |conference in Europe and largely equivalent to the size of PyCon, is a |"local" conference? Yeah, but Donald Rumsfeld has let us 'merkins know that Old Europe is now irrelevant. What could be more clear? -- 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 max at alcyone.com Sun Jul 20 19:40:11 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2003 16:40:11 -0700 Subject: Newbie! I'm a newbie! What's wrong with this program? References: <5da8e4b3.0307191800.48dc0a6d@posting.google.com> <9a410299.0307201529.4485efa@posting.google.com> Message-ID: <3F1B285B.693B3C3C@alcyone.com> klappnase wrote: > The "None" comes from: > > > def newLine(): > > print > > What you meant was: > def newLine(): > print "\r" No, that isn't where it comes from. > (I must admit that I am not familiar with line endings on windoze, in > linux it is "\n", on windoze it might be "\r" or "\r\n", I don't know > for sure, however you don't need this function at all) If sys.stdout is opened in text mode then '\n' will get translated to the appropriate form regardless. So this is a red herring you're after. > You might try something like: > > print "There are " + str(minHour(x_hours)) + " minutes in " + > str(x_hours) + " hours" That would still print exactly the same thing. The problem is that minHour is returning None (implicitly). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ All your slick moves / They were once innocent moves \__/ Sade From vze4rx4y at verizon.net Thu Jul 31 01:27:41 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 31 Jul 2003 05:27:41 GMT Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: "Rick" wrote in message news:8b36138c.0307281644.f6569ea at posting.google.com... > I have been given an assignment to collect 5 papers on Python and > write a report on each of the papers. I went ahead and researched and > collected 9 papers; all from the internet with most of them coming > from the International Python Conference. > > But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal > papers in the history of Python in the opinion of members of this > newgroups? Hmm, do PEPs count as papers? They are generally written by experts, are well referenced, have a standardized format, go through peer review, have a clear record of their disposition (influence as measured by actual implementation), and represent an attempt to keep Python on the cutting edge of technology. Raymond Hettinger From maxm at mxm.dk Sun Jul 13 09:58:41 2003 From: maxm at mxm.dk (Max M) Date: Sun, 13 Jul 2003 15:58:41 +0200 Subject: Newbie with sort text file question In-Reply-To: <86d2ca4.0307121146.3deb854a@posting.google.com> References: <86d2ca4.0307121146.3deb854a@posting.google.com> Message-ID: <3F116591.80701@mxm.dk> stuartc wrote: > Hi: > > I'm not a total newbie, but I'm pretty green. I need to sort a text > file and then get a total for the number of occurances for a part of > the string. Hopefully, this will explain it better: > > Here's the text file: > > banana_c \\yellow > apple_a \\green > orange_b \\yellow > banana_d \\green > orange_a \\orange > apple_w \\yellow > banana_e \\green > orange_x \\yellow > orange_y \\orange > > I would like two output files: > > 1) Sorted like this, by the fruit name (the name before the dash) > 2) Then summarized like this, ordered with the highest occurances > first: > > orange occurs 4 > banana occurs 3 > apple occurs 2 > > Total occurances is 9 fruity = """banana_c \\yellow apple_a \\green orange_b \\yellow banana_d \\green orange_a \\orange apple_w \\yellow banana_e \\green orange_x \\yellow orange_y \\orange""" # print sorted list fruits = fruity.split('\n') fruits.sort() print '\n'.join(fruits) print '' # count occurences counter = {} for fruit in fruits: sort_of, apendix = fruit.split('_') counter[sort_of] = counter.get(sort_of, 0) + 1 # sort by occurences decorated = [(counter[key], key) for key in counter.keys()] decorated.sort() decorated.reverse() # print result sum = 0 for count, sort_of in decorated: print sort_of, 'occurs', count sum += count print '' print 'Total occurances is', sum regards Max M From puccio_13 at yahoo.it Tue Jul 1 04:32:38 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Tue, 01 Jul 2003 10:32:38 +0200 Subject: DOM with HTML Message-ID: <3GbMa.4404$FI4.118833@tornado.fastwebnet.it> Hi, I need to get a sort of DOM from an HTML page that is declared as XHTML but unfortunately is *not* xhtml valid.. If I try to parse it with xml.dom.minidom I get error with expat (as I supposed), so I was told to try in this way, with a "forgiving" html parser: from xml.dom.ext.reader import HtmlLib reader = HtmlLib.Reader() dom = reader.fromUri(url) # 'url' the web page FIRST ISSUE: It seemed to me, reading the source code in $MY_PYTHON_INSTALLATION_DIR/site-packages/_xmlplus/dom/ext/reader/ , that these are 4DOM APIs , so from what I know of python distributions, they are extra packages, or not? I would like to use *only* libs that are available in the python2.2 suite, not any extra. SECOND ISSUE: If the above libs were included in python (and so I would continue using them), how do I print a string representation of a (sub) tree of the DOM? I tried with .toxml() as in the XML tutorial but that method does not exist for the FtNode objects that are involved there... Any idea?? Thanks so much for who can help me -- bye Alessio Pace From rreagan at attbi.com Sun Jul 6 22:13:15 2003 From: rreagan at attbi.com (Russell Reagan) Date: Mon, 07 Jul 2003 02:13:15 GMT Subject: anything new on the ternary operator? References: Message-ID: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> "Bob Gailer" wrote > I was looking forward to having it. "Sean Ross" wrote > - (if C: x else: y) won the vote I'm still learning python, so don't flame too much :-) What is superior about using the proposed ternary operator instead of using the 'and' and 'or' operators to simulate inline logic? From ijones at syntaxpolice.org Tue Jul 1 15:49:35 2003 From: ijones at syntaxpolice.org (Isaac Jones) Date: Tue, 01 Jul 2003 15:49:35 -0400 Subject: Haskell distutils-type system Message-ID: <87d6gu3u40.fsf@syntaxpolice.org> Hello Python Community. I bring greetings from the Haskell community (http://www.haskell.org) ;) There has been a lot of discussion of late about creating a grand-unified build & distribution system for "3rd party" Haskell libraries (those not distributed with the compilers). Python's Distutils has come up a few times. The Haskell Library Infrastructure Project's web page is just a wiki page which can be found here: http://www.haskell.org/hawiki/LibraryInfrastructure. I'm running this project. I also wear another hat in that I'm interested in maintaining Debian packages related to Haskell, so I want to make my job easier by 1) writing software support, and 2) making it easy for other people to maintain Debian packages so I don't have to :) I've read much of the documentation at http://www.python.org/sigs/distutils-sig/doc/. I've also made a toy Python program that uses distutils. It occurs to me that the issues that were facing the Python community are strikingly similar to those facing the Haskell community now, except perhaps for the fact that there are at least 3 very strong Haskell "compilers" that we want to support. One idea for this distribution system, which we're calling the Library Infrastructure Project, is to create a nice gmake-based build system, document it, and leave it at that. Another idea is to use a Haskell-based Distutils type system. Now I think that the Haskell-based system should work out-of-the-box for pure-haskell modules (no extensions), and maybe wrap a more complex make-based system where necessary (as when interfacing with C or using preprocessors). I definitely want to optimize for the common case of joe-haskell-programmer wanting a nice way to distribute modules to his friends, but of course I also want to allow Haskell developers to do more complex things. The main issues facing us are: 1) there are a variety of Haskell "compiler" implementations, one of which is an interpreter :) 2) not all Haskell implementations are available on all architectures (ghc for instance) 3) just about every Haskell "compiler" and release is binary-incompatible, (except maybe for nhc98). That is, if we were going to distribute binary libraries, we'd need different binaries for ghc4, ghc5, and ghc6. Also we'd need different binaries for profiling versions of the libraries, etc. For instance, if I were to create a binary package HUnit, which is a simple case since its pure Haskell code, I would need: hunit-{hugs,nhc98} hunit-ghc{4,5,6} hunit-ghc{4,5,6}-prof And whenever a new version of GHC6 is released (for instance), all of the packages like hunit-ghc6 would need to be updated at the same time. That doesn't even get into the issues of the wide variety of preprocessors that are common in this rapidly advancing language[1]. So all of this suggests to me that we want to keep a global list of installed libraries and recompile them whenever a new Haskell "compiler" gets installed. This is why I want an abstraction layer above make. So I want to ask you if you can think of any obvious things we should watch out for if we try to do something similar to what Python is doing. Also, there was some mention (in the related "summary of the Developer's Day session") of Python's distutils creating a Makefile and wrapping calls to make, is this what you're doing? Do you / did you find yourself duplicating a lot of what make already does, ie dependencies, etc, or do you utilize make? What about configuration, do you typically interface with autoconf somehow, or does distutils have its own way to figure out configuration details? Is a typical distutils setup.py program pretty much like what we see in the example documentation? The developer provides some meta-data and gets a distribution tool? Is there any support for more complex stuff like interfacing with external systems? Does distutils handle dependencies? I've hacked together something that creates a source tarball and a basic Debian package from a Haskell version of the distutils-type metadata. I can make that available in a few days if anyone is interested. peace, isaac [1] Haskell is designed to have a "stable" version, Haskell98, and the compilers come with a variety of extensions so that it is very useful as a research language as well. From sanjiv at leopardlogic.com Tue Jul 29 16:59:35 2003 From: sanjiv at leopardlogic.com (Sanjiv Kumar) Date: Tue, 29 Jul 2003 13:59:35 -0700 Subject: Fw: Python-2.3c2.tgz installation Message-ID: <041d01c35614$542b3bc0$4901a8c0@beastjr> ----- Original Message ----- From: Sanjiv Kumar To: help at python.org Cc: Sanjiv Kumar Sent: Tuesday, July 29, 2003 1:56 PM Subject: Python-2.3c2.tgz installation Hi, I am trying to build and install python-2.3 on a Solaris machine. It give segmentation fault during build process ( I guess during build of extensions to python i.e. running "build_ext"). I am using gcc --version 2.95.2 on SunOS xyz 5.8 Generic_108528-15 sun4u sparc SUNW,Ultra-60 machine. So any hint to get rid of this problem. Best Regards, =Sanjiv= -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at drizzle.com Wed Jul 16 00:18:12 2003 From: donn at drizzle.com (Donn Cave) Date: Wed, 16 Jul 2003 04:18:12 -0000 Subject: Library for pop over ssl? References: Message-ID: <1058329089.889337@yasure> Quoth JanC : | Marco Herrn schreef: |> Hi, I know of poplib, which does what I need except that it doesn't |> support SSL encryption. imaplib has SSL-support. But I want it with |> pop3. Is there a library available that does this or do I have to |> implement it myself? | | You can always use stunnel to SSL-ize a "normal" protocol... | You can also SSL-ize a protocol in Python. I'm surprised to read that imaplib has SSL support, because I don't see it in the library module searching by 'ssl' or 'SSL'. I've had to do it the Python way, so to speak: subclass IMAP4, implement a fileobject-like object, etc. This should be feasible for POP3 as well - a quick look suggests that it might be enough to copy its __init__ and rewrite it. The fileobject emulation is to get pop3.file.readline et al. to call sslobject.read. Donn Cave, donn at drizzle.com From colinsm.spam-me-not at picsel.com Wed Jul 9 05:20:49 2003 From: colinsm.spam-me-not at picsel.com (Colin S. Miller) Date: Wed, 09 Jul 2003 10:20:49 +0100 Subject: UTF-16-LE and split() under MS-Windows XP Message-ID: Hi, I'm trying to parse a UTF-16-LE encoded file, that contains colon delimited records. The data files was generated by XP's Notepad editor, and contain a BOM mark. I'm using Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 My code works if I change the encoding to UTF-16-BE, however for little endian, it dies with C:\>unicode_test.py Traceback (most recent call last): File "C:\unicode_test.py", line 36, in ? parse_file("c:\unicode.txt") File "C:\unicode_test.py", line 27, in parse_file line = file.readline() File "c:\Python22\lib\codecs.py", line 330, in readline return self.reader.readline(size) File "c:\Python22\lib\codecs.py", line 252, in readline return self.decode(line, self.errors)[0] UnicodeError: UTF-16 decoding error: truncated data C:\> The source code and unicode data files are attached. (I know attaching is frowned on, on most groups, but they are small and I don't want them getting mangled) Where have I gone wrong, and what is the correct method to verify the BOM mark? This snippet bom = file.read(2) if (bom != "\xff\xfe"): print "Data file is not in UTF-16-LE" return failes beause "UnicodeError: ASCII encoding error: ordinal not in range(128)" According http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=3ee7885a_6%40corp.newsgroups.com&rnum=3&prev=/groups%3Fq%3DUnicodeError:%2BUTF-16%2Bdecoding%2Berror:%2Btruncated%2Bdata%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D3ee7885a_6%2540corp.newsgroups.com%26rnum%3D3 (comp.lang.python 11 Jun 2003 'UTF-16 encoding line breaks?') readline() isn't supported on UTF-16, but doesn't give any alternative suggestions TIA, Colin S. Miller -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unicode_test.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unicode.dat URL: From owski at hotmail.com Mon Jul 14 14:44:02 2003 From: owski at hotmail.com (Adam Ruth) Date: 14 Jul 2003 11:44:02 -0700 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Message-ID: Stephen Horne wrote in message news:<1br3hv4434gn7p2pdg1bgtg8dtlak3id3s at 4ax.com>... > I've said my piece on meanings derived from computer science (and in > turn from mathematics, as it happens - variables as placeholders for > values predate electronic computers by quite some time. The mathematics I'm used to has a very different concept of assignment than does a static language like C. Here's why. In math there are global unchanging objects called numbers, 1, 2, 3, etc. If I have 2 variables, x and y and they both equal 500, then they both are names bound to the value 500. They are not each copies of the value 500, math has no such concept, there is only one 500. C, and most static languages, have the concept of memory location, which doesn't exist in math. In C a variable is bound to a memory location which contains a value, not like math where the variable itself contains the value. Therefore I can have two variables, x and y, that point to their own distinct copy of 500 and when I assign a value, it copies the 500 into the memory location bound to x. Now, what if I have x and y bound the the same memory location? If I change X I also change Y. That's not how mathematics works. If X and Y are to have to same value, they do so because of some relation to their meaning, and they are both bound to 500, not simply because I changed the value of X. This is a concept that simply doesn't exist in mathematics. Python is more like the math form. There is only one instance of the number 500 and a name (variable) is bound to it or it isn't. To change the value of 500, then I must rebind the name, exactly in mathematics. However, Python differs from math in that math doesn't have mutable values (well it may when you get into real complex calculus, I don't know, never been there). Adam Ruth From thewrights at ozemail.com.au Thu Jul 17 09:39:46 2003 From: thewrights at ozemail.com.au (thewrights at ozemail.com.au) Date: Thu, 17 Jul 2003 23:39:46 +1000 Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3F16A34A.5742F54F at engcorp.com... > thewrights at ozemail.com.au wrote: > > > > I have an application in which I want the users to be able to create python > > functions: > > > > def f1(): > > print "1-1" > > print "1-2" > > print "1-3" > > > > def f2(): > > print "2-1" > > print "2-2" > > print "3-3" > > > > and when my application runs, I want to execute these functions in > > "lock-step", so that the output looks like: > > > > 1-1 > > 2-2 > > 1-2 > > 2-2 > > 1-3 > > 2-3 > > I think the problem is underspecified. What do you mean by the quoted > phrase "lock-step"? Your example includes only simple print statements, > which generate output to sys.stdout. What are you really trying to > accomplish? Do you want individual bytecodes to be executed one at a > time from a series of functions? Do you want any output to be interlaced > on a line-by-line basis? Any call to any I/O routine? Need more detail. > > -Peter OK. Thanks. I was just giving some simple examples...but I hope this is better: >From the python grammar: funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite I want the statements in to be executed on a statement by statement basis, with no particular restrictions on *what* those statements are. It's the execution stepping I'm interested in... the I/O in my example was just that. I understand that there will be all the problems on contention/race etc (just like if the functions were going in separate threads) From simon_place at whsmithnet.co.uk Sun Jul 6 13:40:28 2003 From: simon_place at whsmithnet.co.uk (simon place) Date: Sun, 06 Jul 2003 18:40:28 +0100 Subject: PEP idea. ( removing __slots__ ) In-Reply-To: References: <3f073594$1_2@news1.vip.uk.com> <3f083043$1_3@news1.vip.uk.com> Message-ID: <3f085fa7_3@news1.vip.uk.com> i can't think of a point for __slots__ except to save the overhead of a dict, this is why you DON'T HAVE a __dict__ when __slots__ is defined. __slots__ should generally be used to improve the performance/footprint of small/transient classes, ( it also prevents new instance variables but this appears to be more of a side effect.) The point of the combining is to simplify, you know, based on the idea that keeping the language simply ( and logical ) aids comprehension. From jane.doe at acme.com Tue Jul 29 14:11:30 2003 From: jane.doe at acme.com (Jane Doe) Date: Tue, 29 Jul 2003 20:11:30 +0200 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f24f3f7@shknews01> Message-ID: <12edivkt08vec9epm7dk5r0q9qlb1kgej6@4ax.com> On Mon, 28 Jul 2003 10:59:05 +0100, "Remi Delon" wrote: >Having said that, I think that CherryPy definitely meets your >requirements... (sorry, I couldn't help saying it :-))) I second that. CherryPy is the Python framework that was the easiest to grasp as a newbie. Other frameworks that look similar to CherryPy (ie. URLs are actually calls to classes and methods) are WebWare + Cheetah, Skunkweb. If someone knows of others, I'm all ears :-) JD. From woooee at yahoo.com Thu Jul 3 15:58:16 2003 From: woooee at yahoo.com (Curly Joe) Date: Thu, 3 Jul 2003 12:58:16 -0700 (PDT) Subject: Building Python - how to set include and lib paths? Message-ID: <20030703195816.7774.qmail@web20503.mail.yahoo.com> Lack Mr G M wrote (snipped): I'm trying to build (compile and link) Python2.2.3, However, I need to indicate where it can find various library and header files for other extensions which I have already built (things like ssl etc.). There are two simple ways that I know of: 1 - add it to, and export the PYTHONPATH variable - mine is in ~/.bash_profile on a Gentoo Linux box. Your shell and/or profile file name may be different. 2 - probably not what you want, but .../python/site_python should be in your PYTHONPATH and so you could place you programs there. There probably is a way to compile it in, but I prefer to use the PYTHONPATH solution as it is simple and straight forward. HTH __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From postmaster-smtp-am at msxssc.shell.com Thu Jul 3 10:12:21 2003 From: postmaster-smtp-am at msxssc.shell.com (postmaster-smtp-am at msxssc.shell.com) Date: Thu, 3 Jul 2003 09:12:21 -0500 Subject: Delivery Report (failure) for RM186061@shellus.com Message-ID: This report relates to your message: Subject: Re: Movie, Message-ID: <200307031402.JAA04039 at mailgate1.shellus.com>, To: of Thu, 3 Jul 2003 08:54:56 -0500 Your message was not delivered to RM186061 at shellus.com for the following reason: A problem with the message content was found Infected with the W32/Sobig.e at MM virus !!! The header of the original message is at the end -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/rfc822-headers Size: 747 bytes Desc: not available URL: From jdhunter at ace.bsd.uchicago.edu Mon Jul 7 18:47:31 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 07 Jul 2003 17:47:31 -0500 Subject: getting a submatrix of all true In-Reply-To: (John Hunter's message of "Mon, 07 Jul 2003 11:00:11 -0500") References: <52fe159d.0307041016.4dcb4a5c@posting.google.com> Message-ID: >>>>> "John" == John Hunter writes: John> I think I may adapt your algorithm to terminate when the John> percent missing falls below some threshold, removing the John> requirement that *all* missing values be removed. This will John> drop the worst offenders observation or variable wise. Then John> I can use a regression approach to fill in the remaining John> ones. I think I have found a major improvement on your algorithm Jon, by changing the rule which determines whether to drop a row or a column after you have found the worst offenders for each. The original approach was to keep the one with the most valid (zero) elements, which makes sense since that is the quantity you are trying to maximize. But consider the case where there is correlation so that true values on a row or column tend to be correlated with other true values on that row or column, as in X = 1 0 1 0 1 0 1 0 1 0 0 0 0 0 Your algorithm would keep the column, since keeping a row gives you only one zero whereas keeping a column gives you 2. By looking at the *fraction* of ones in the worst offending row and column, you can do much better. By deleting the row or column with the greatest fraction of ones, you reduce the likelihood that you'll encounter a one in future iterations. Using this approach, I was able to find a 893x67 submatrix with a score of 59831 versus the 462x81 submatrix with a score of 37422. I have also added thresholds to the code, so that you can terminate with a fraction of missing values remaining. By setting the thresholds to zero, you get the special case of no missing values. The example below also includes a no-copy optimization that Jon emailed me off list. The algorithm run time for a 1073x82 matrix is around 30ms on my 700MHz machine. John Hunter from __future__ import division import sys, time from urllib import urlopen from Numeric import * def trim_missing(a, thresh=(0.05,0.05) ): """ a is a numObservations by numVariables boolean matrix thresh = (othresh, vthresh) are the observation and variable thresholds that trigger deletion remove any rows where percent missing vars > vthresh remove any cols where percent missing obs > othresh This is done iteratively rechecking the percent missing on each iteration or row or col removal, with the largest offender removed on each iteration return value is score, rowInd, colInd where the two ind arrays are the indices of the rows and cols that were kept """ othresh, vthresh = thresh # theshold for deletion dr=zeros(a.shape[0]) # Arrays to note deleted rows... dc=zeros(a.shape[1]) # ... and columns sizeleft=list(a.shape) # Remaining dimensions sr=sum(a,1) # Column scores = ij's to remove sc=sum(a,0) # Row scores while 1: # Keep deleting till none left mr=argmax(sr) # index highest row score mc=argmax(sc) # index highest column score fracRow = sr[mr]/sizeleft[1] fracCol = sc[mc]/sizeleft[0] if fracRow<=vthresh and fracCol<=othresh: break # stop when missing criteria are satisfied if fracRow-vthresh Message-ID: In article <6f03c4a5.0306301931.3f15fbb7 at posting.google.com>, Rim wrote: > >I have been thinking about how to overload the assign operation '='. >In many cases, I wanted to provide users of my packages a natural >interface to the extended built-in types I created for them, but the >assign operator is always forcing them to "type cast" or coerce the >result when they do a simple assign for the purpose of setting the >value of a variable. Borrowing an example from this newgroup, the >second assignment below ereases all Currency knowledge from variable >'c', when the user only wanted to update the value of c, not its type: > >c=Currency(5) >c=7 > >I fully understand the workaround of doing c=Curreny(7) instead, but >users don't want to be bothered with that. If you have users who don't want to learn Python, give them a special Python-like language. I won't say it's trivial, but it's not that hard. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From staschuk at telusplanet.net Thu Jul 31 07:19:46 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 05:19:46 -0600 Subject: Is there a standard module library function to access /etc/passwd or /etc/group In-Reply-To: ; from adalke@mindspring.com on Wed, Jul 30, 2003 at 08:19:48PM -0600 References: <16469f07.0307300416.351ba776@posting.google.com> <16469f07.0307301458.59e73736@posting.google.com> Message-ID: <20030731051946.A11888@tibia.amotlpaa.bogus> Quoth Andrew Dalke: [...] > When you're stuck because you don't know which module something > might be in (eg, I was just looking for XMLRPC server code in > xmlrpclib - wrong place!), try the full index at > http://python.org/doc/current/lib/genindex.html And don't forget the full-text searching capabilities at pydoc.org. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From grante at visi.com Wed Jul 16 11:15:47 2003 From: grante at visi.com (Grant Edwards) Date: 16 Jul 2003 15:15:47 GMT Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> Message-ID: <3f156c23$0$166$a1866201@newsreader.visi.com> In article <3F156952.AD24AAB8 at engcorp.com>, Peter Hansen wrote: >>> Of course, I'm not suggesting that whitespace is *meaningless* >>> in Python outside of indentation... Python is much like C (and >>> many, many others) in that regard. >> >> Note that Fortran (at least historic Fortran - not sure about >> those upstart 9x variants) is *not* among the "many, many >> others." One can write any of >> >> DO 10 I = something >> DO10I = something >> D O 1 0 I = something >> >> and leave it to the compiler to figure out whether you're >> starting a DO-loop or assigning a value to the variable DO10I. > > If you are saying that you leave it up to the compiler to > decide how to interpret any of the three above statements, then > clearly whitespace is *not* meaningless. IIRC (it's been a _long_ time) it's not up to the compiler. All three of the above are required to be treated the same by the compiler (a DO loop). > It might be compiler-dependent or something, but no > meaningless. Unless you are saying that on a given FORTRAN > compiler, only one possible interpretation of all three > statements above is possible. I don't think it's "on a given FORTRAN compiler", I think it's more like "according to the language definition for FORTRAN IV". > That would be surprising. Yup. I found a lot of things in FORTRAN surprising. Python is so much nicer in that respect. Though I was recently surprised that the remove() method for lists uses "==" and not "is" to determine what to remove. It's documented that it works that way. But, it wasn't what I excpected, and it took me a while to figure out that it was using my class's __cmp__ method rather than the object ID. -- Grant Edwards grante Yow! Go on, EMOTE! I at was RAISED on thought visi.com balloons!! From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 21:01:22 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Aug 2003 10:51:22 +0950 Subject: A very simple question References: Message-ID: On Thu, 31 Jul 2003 17:13:36 -0800, Arnaldo Riquelme wrote: > I'm getting familiar with Python and I have a simple question: > > class abc: > x = 100 > y = 200 > z = 300 > > > ac = abc() > > Shouldn't I have a attribute named __dict__ for ac that contains a > dictionary of all the variables? No. The attributes x, y, and z are associated with the class, not any particular instance. (As your experiment with abc.__dict__ shows.) If you want attributes that are bound to a particular instance, set them in the class's __init__() method. -- \ "It ain't so much the things we don't know that get us in | `\ trouble. It's the things we know that ain't so." -- Artemus | _o__) Ward (1834-67), U.S. journalist | Ben Finney From amk at amk.ca Tue Jul 8 21:46:53 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 08 Jul 2003 20:46:53 -0500 Subject: Python vs PHP References: Message-ID: On 8 Jul 2003 17:59:12 GMT, Jon Ribbens wrote: > I don't understand why you keep saying "CGI is not an option" when > nobody has suggested that you use it. Jon, there's no point in debating Afanasiy about CGI. He's convinced packages for Python web programming support are inadequate (*all* of them), is unable to explain what the problem is or what his requirements are, and doesn't seem to really understand the subject (e.g. thinking FastCGI is basically the same as regular CGI). Ignoring him is the best course. --amk From rastm2 at aol.commorespam Tue Jul 22 03:07:01 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 22 Jul 2003 07:07:01 GMT Subject: List of declared variables in interactive Python session? References: Message-ID: <20030722030701.23831.00000292@mb-m27.aol.com> Bengt Richter informs Ray St.Marie that... >I sometimes find it handy to leave out underscore items: > >>> [name for name in dir() if not name.startswith('_')] > [] >>> x=123 >>> [name for name in dir() if not name.startswith('_')] > ['name', 'x'] <<<_see Below > >vs. > >>> dir() > ['__builtins__', '__doc__', '__name__', 'name', 'x'] > > >Regards, >Bengt Richter Cool and now I do too ...you ... tip monster you ! Thanks - (giggling with that "you b at stard" grin on my face) (Why is it the simplest things make ya laugh.) But this - the true beauty in your example is that... You didn't enter an iterater 'name' into the dir ( ) before you displayed it. Nice trick. In fact you never have to in a dir( ) call. The only reason 'name' <<<_see above is in the dir( ) now is because this is your second for loop. I mean to say that the dir( ) was displayed first the first time then 'name' was added --- am I right? Now it's there for the second call. Yet in the examples that ... ...that they were working on, it was pretty obvious that you had to have an iterater variable established first for the vars( ) call. If I don't put the ' v ' in the dir( ) before the call to vars( ) first I get the Traceback because I'm changing the size of the dictionary >>> for d in dir( ): print d ... __builtins__ # i Know i know ive learned nothing sorry __doc__ __name__ name pywin >>> for v in vars( ): print v ... name # okay there's the first variable and then Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration >>> And the point to the second gentilman in the thread was that his call to >>> for v in vars( ).copy( ): print v only works because the call to copy( ) does this first just like declaring the ' v ' in my example -- only it a one liner. :>) When I was new at this and, dir( ) and vars( ) were something I learned early on, It didn't seam that intuitive to me. ........and so i go on and on and on about something only I could find intersting, and I shall never more on this subject Sorry Y'all. Ray St. Marie Stating the obvious since birth... Whaaaa. From carsten at gehling.dk Tue Jul 22 04:31:01 2003 From: carsten at gehling.dk (Carsten Gehling) Date: Tue, 22 Jul 2003 10:31:01 +0200 Subject: SV: How to save web pages for offline reading? In-Reply-To: Message-ID: > -----Oprindelig meddelelse----- > Fra: python-list-admin at python.org > [mailto:python-list-admin at python.org]P? vegne af Will Stuyvesant > Sendt: 22. juli 2003 08:38 > Til: python-list at python.org > Emne: Re: How to save web pages for offline reading? > There is no "man wget" on Windows :-) > And unfortunately the GNU Windows port of wget I have (version > 1-5-3-1) does not have that --page-requisites parameter. Well since you ARE on Windows: Open the page in Internet Explorer, choose "File" and "Save As...". Voil?! You've now saved all necessary files. > I thought this whole thing would be easy with all those Python > internet modules in the standard distro: httplib, urllib, urllib2, > FancyURLxxx etc. Being able to download a "complete" page *from > Python source* would be very nice for my particular application. Well it's doable with those libraries, but you have to put your own meat on the bones. 1) Use httplib to get the page first. 2) Parse it for all "src" attributes, and get the supporting files. The parsin can be done with a html-parser library (can't remember the name) or with regular expressions. REMEMBER: All paths must be corrected to paths relative to the main document. - Carsten From bgailer at alum.rpi.edu Thu Jul 10 11:28:46 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 10 Jul 2003 09:28:46 -0600 Subject: Calling Excel module functions from python [repost] In-Reply-To: Message-ID: <5.2.1.1.0.20030710092612.0275eea8@66.28.54.253> At 02:42 AM 7/10/2003 -0700, Mark Carter wrote: >In Excel, I have a module named modCSV which has a function named >SaveSheet(), which I want to be able to call from python. How do I do >it? > >I've opened the workbook containing the module, and executed the code: > >from win32com.client import Dispatch >xlApp = Dispatch("Excel.Application") >xlApp.Visible = 1 >wb = xlApp.ActiveWorkbook >wbc = wb.VBProject.VBComponents("modCSV") >wbc.SaveSheet() > >but I get the error message: > >Traceback (most recent call last): > File "C:\Documents and Settings\mcarter\My >Documents\cvs-tree\project\2195\code\temp.py", line 17, in ? > wbc.SaveSheet() > File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", >line 454, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) >AttributeError: .SaveSheet > >It apparently likes the line wbc = ... , but then hates >wbc.SaveSheet(). *Sigh* To call a function in a VBA module: wbc.Run('SaveSheet') Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From hokiegal99 at hotmail.com Tue Jul 22 19:57:06 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Tue, 22 Jul 2003 19:57:06 -0400 Subject: lists and files question Message-ID: <3F1DCF52.7040607@hotmail.com> This code: import os, re, string setpath = raw_input("Enter the path: ") for root, dirs, files in os.walk(setpath): id = re.compile('Microsoft Excel Worksheet') fname = files # print fname content = open(fname[1],'rb') Produces this error: IOError: Error[2] No such file or directory 'Name of File' The strange thing is that it correctly identifies the file that it says doesn't exist. Could someone explain why this is? Also, is "files" a nested list? It looks like one, but I'm not entirely sure as I'm still relatively new to Python. Thanks! From gh at ghaering.de Fri Jul 25 10:45:19 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 25 Jul 2003 16:45:19 +0200 Subject: CGI "download" prompt? In-Reply-To: <77dd287a.0307250619.7c2ec441@posting.google.com> References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> <77dd287a.0307250619.7c2ec441@posting.google.com> Message-ID: <3F21427F.9030004@ghaering.de> Daniel Orner wrote: >>Try setting the Content-Type: header to something other than text/html, >>such as: application/octet-stream [...] Erhm. Let's suppose you want to send an RTF file and have the browser pop up a save dialog with a certain filename preconfigured: Then send these headers: Content-Type: application/rtf Content-Disposition: attachment; filename=mydocument.rtf -- Gerhard From bogus at antispam.com Mon Jul 21 01:13:23 2003 From: bogus at antispam.com (Alex) Date: Mon, 21 Jul 2003 01:13:23 -0400 Subject: PythonQuestions forum - does it exist? Message-ID: Hello, I'm wondering if there is a help forum for Python on the web similar to LinuxQuestions.org? Alex From stuart at bmsi.com Mon Jul 7 10:24:07 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 07 Jul 2003 10:24:07 -0400 Subject: Frustration with spurious posts. References: <3F06FD11.967D8D8A@hotmail.com> <3F081C10.8CF6B57@hotmail.com> Message-ID: On Sun, 06 Jul 2003 08:54:40 -0400, Alan Kennedy wrote: > But if an email is sent from an individual to an individual, then such > "you sent me a virus!" emails can be very useful information. It's only > when an email address is associated with lots of subscribers that it > becomes a problem. Or, as you pointed out, when the from address is > forged. The from address is always forged.  I get literally hundreds of bounces daily from various viruses. My Bayesian filter had not yet learned to distinguish them from real bounces. I did not send any of them. For the bounces that include the original email in an rfc822 attachment, this can be verified by looking at the 'Recieved' headers. It never went anywhere near my system. I don't even run Windows - and these are Windows viruses. I also receive email threatening bodily harm for sending spam. A less clueless admin sent me email saying that he had contacted my ISP and had my account cancelled - and included a ticket # to prove it. I looked at the ticket, and there was indeed an account cancelled at some ISP I'd never heard of. Since the admin was smart enough to look at the headers to track down the real ISP, you would think he would be smart enough to realize that any From headers in spam are completely bogus. Sending any kind of reply to a spam or viral email is clueless and counterproductive under any circumstances. All it accomplishes is annoying yet another innocent bystander. From max at alcyone.com Mon Jul 28 14:57:05 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 28 Jul 2003 11:57:05 -0700 Subject: Fastest way to count your iterations? References: Message-ID: <3F257201.9A697F3A@alcyone.com> Tracy Ruggles wrote: > If you're writing a simple script and you want to give an update of > its progress... Is this the fastest way to do it (assuming that what > you're iterating through is very, very long and the time to process > each item is relatively short)... > > > > def counter(items, f, sep=1000): > i = 0 > for item in items: > f(item) > i += 1 > if i % sep == 0: > print i > > > > [ is the modulus operator the quickest way to find out if you're > really at the 1000th item? ] The modulus operator is typically pretty expensive, though I don't know with the object creation overhead in Python it would be all that significant (I haven't checked). If you don't need to keep track of the total count (that is, you're just maintaining i for the purposes of determining when it is a multiple of sep), then you can simply count i up to sep and then reset it: i = 0 for ...: i += 1 if i == sep: ... do something every `step' iterations ... i = 0 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I would rather understand one cause than be king of Persia. \__/ Democritus From glenfant at NOSPAM.bigfoot.com Wed Jul 2 06:27:27 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Wed, 2 Jul 2003 12:27:27 +0200 Subject: PyQT and Mandrake 9.1 References: Message-ID: mailto:gilles at pilotsystems.net "Michael 'Mickey' Lauer" a ?crit dans le message de news: bdsi0k$10jkr7$2 at ID-192111.news.dfncis.de... > Politics and polemics aside - how 'bout an attempt to help the OP? > > Did you install libqt3-devel ? Didn't find it in the 3 CDs of Mandrake 9.1 But I found rpm packages at sourceforge http://sourceforge.net/project/showfiles.php?group_id=61057 Thanks --Gilles From steve at ferg.org Sat Jul 5 04:12:26 2003 From: steve at ferg.org (Stephen Ferg) Date: 5 Jul 2003 01:12:26 -0700 Subject: ANN: Python language slideshow presentation References: Message-ID: Thanks for the feedback! I've fixed a number of reported errors and infelicities. It is not perfect, but it is much better! -- Steve From ianb at colorstudy.com Tue Jul 8 13:42:45 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 12:42:45 -0500 Subject: path module In-Reply-To: References: Message-ID: <1057686165.3738.54.camel@lothlorien> On Tue, 2003-07-08 at 05:07, Just van Rossum wrote: > > Several operators are reused > > for different meanings, % in particular comes to mind, this doesn't > > seem that bad. I like the way it looks and feels. It feels better > > to me than using + for string concatenation ;) -- maybe because > > division is not all that common an operation anyway. > > I tend to think that this whole discussion shows that _maybe_ it's not > such a good idea to subclass str/unicode after all. (Aside: path.py > taught me about the existence of os.path.supports_unicode_filenames in > 2.3, but at least on my platform (OSX) it has the wrong value. I opened > a bug, #767645.) > > Some string methods are handy on paths, such as .endswith(), while > others are not, like .upper() or .splitlines(). Other string method > names or operators would make sense for paths, but -- as you say -- are > out of the question since their meaning would be quite different, eg. > .join() and +. True... and as I think about it, a lot of the actually interesting string methods wouldn't be performed on the entire path anyway. Things like path.name.startswith('img'), or path.ext == 'jpg'. You could also do things like override equals, so that two Windows paths would match case-insensitively, and other things that would be bad to change in a string subclass. > I find overloading / unneccesary, since it's not like you'll have to > write > > a.join(b).join(c).join(d) > > but rather > > a.join(b, c, d) > > which I don't think is all that bad. And you could reuse the join method, which is better than joinpath (but joinpath is better than overriding string's join, if you are subclassing string). > Btw. long ago (2001, before Jason's path module) I posted a balloon to > python-dev about this subject: > http://mail.python.org/pipermail/python-dev/2001-August/016663.html > > There was hardly any response, and Guido said we wasn't too enthusiastic > about the idea, so we might have to work hard to pull this off ;-). > > Also, with unicode, Guido's suggestion that any object that implements > __str__ can be used with open() seems to be no longer true. At least I > can't get it to work. You don't want to use open() anyway, that breaks the possibility of alternate filesystems. There should be an open method, like path.open('w'). Then a URL object (called maybe url?) would also have an open method, that obviously would do a much different thing. (And just as I'm thinking of a url class, things like .exists() would be surprisingly useful, even though urllib doesn't expose these file-like operations very directly) The only other way is if a new magic method -- __open__ -- came into being. That would be interesting (where "interesting" can be read several ways ;). Ian From gelbardn at tripwire.com Mon Jul 28 17:08:52 2003 From: gelbardn at tripwire.com (Nate Gelbard) Date: Mon, 28 Jul 2003 14:08:52 -0700 Subject: minidom xml attribute creation Message-ID: Hello, I have python 2.2.3 on my RH 7.2 box. When I create an XML Element and set an attribute on that element, the name of the attribute is truncated to one letter. On a RH 7.3 box, this error does not occur. I thought my libexpat version was old, so I upgraded and relinked python, but this did not help. Here is a code example: from xml.dom.minidom import Document class Test: def __init__(self): self.doc = Document() def toXml(self): root = self.doc.createElement("root") root.setAttribute("name","bug") self.doc.appendChild(root) print self.doc.toprettyxml() if __name__ == "__main__": t = Test() t.toXml() Output: The output should be: Any ideas? Thanks --( Nate Gelbard, QA Engineer --( Tripwire, Inc., The Integrity Assurance Company From peter at engcorp.com Wed Jul 16 11:03:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jul 2003 11:03:46 -0400 Subject: Python Quiz References: Message-ID: <3F156952.AD24AAB8@engcorp.com> Mark Jackson wrote: > > Michael Chermside writes: > > Of course, I'm not suggesting that whitespace is *meaningless* in Python > > outside of indentation... Python is much like C (and many, many others) in > > that regard. > > Note that Fortran (at least historic Fortran - not sure about those > upstart 9x variants) is *not* among the "many, many others." One can > write any of > > DO 10 I = something > DO10I = something > D O 1 0 I = something > > and leave it to the compiler to figure out whether you're starting a > DO-loop or assigning a value to the variable DO10I. If you are saying that you leave it up to the compiler to decide how to interpret any of the three above statements, then clearly whitespace is *not* meaningless. It might be compiler-dependent or something, but no meaningless. Unless you are saying that on a given FORTRAN compiler, only one possible interpretation of all three statements above is possible. That would be surprising. -Peter From iambrenNOSPAM at sympatico.ca Tue Jul 22 17:51:02 2003 From: iambrenNOSPAM at sympatico.ca (Bren) Date: Tue, 22 Jul 2003 17:51:02 -0400 Subject: Problem building extension sample with Python 2.2.3 References: <7h34r1eznbq.fsf@pc150.maths.bris.ac.uk> Message-ID: On Tue, 22 Jul 2003 13:53:53 GMT, Michael Hudson wrote: >iambren at sympatico.ca (Bren) writes: > >> Hi, >> >> I'm trying to build the sample extension file from >> http://www.python.org/doc/current/ext/simpleExample.html. >> >> I get a linker error: >> >> Linking... >> spam.obj : error LNK2001: unresolved external symbol >> __imp__Py_InitModule4TraceRefs >> >> Also, I find it necessary to ignore python22_d.lib and link >> python22.lib explicitly when I make a Debug build. > >There's your problem, I think. You seem to be trying to build a debug >version of your module against a release version of Python. This >won't work. Thanks, that worked! Now, I am working on embedding python in a C/C++ app, so I would like very much to be able to debug the code in C/C++ functions when they are called by Python. Is it possible I could get a debug version of this lib/dll somewhere to let me do this? Is there a python22_d.lib? -----= 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 skip at pobox.com Tue Jul 8 09:45:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 08:45:36 -0500 Subject: Shared vs static link performance hit --and Windows? In-Reply-To: References: Message-ID: <16138.51968.519912.647940@montanaro.dyndns.org> Christos> .... I did some speed comparisons, and pystone reported ~6090 Christos> pystones for the shared and ~7680 pystones for the (default) Christos> static build. Christos> This is quite a difference, and while I do know what impact Christos> position independent code has on libraries, this was the first Christos> time I measured a difference of 25% in performance... It's possible that the Python interpreter makes (percentage-wise) more calls through the indirect links of the position-independent code. We know it makes lots of function calls (often to extension modules) to implement its functionality, so it's quite possible that the interpreter takes a much larger hit than your typical C program would. Skip From mwh at python.net Tue Jul 22 09:48:28 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 13:48:28 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: <7h3znjbzscu.fsf@pc150.maths.bris.ac.uk> <7h3n0f8yspt.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h38yqqznks.fsf@pc150.maths.bris.ac.uk> "Mike C. Fletcher" writes: > Michael Hudson wrote: > > >Michael Hudson writes: > > > > > >>"Mike C. Fletcher" writes: > >> > >> > >>>So, does anyone have a pattern which allows setting an attribute on > >>>a class which doesn't go through the setattr machinery (i.e. can be > >>>used within a descriptor)? > >>> > >>No. Fun problem to think about, though :-) > >> > > > >Actually, that was a lie. Check this horror out: > > > > > >I'm quite proud of this one :-) > > > Rightly so, all evil geniuses should always gloat over their mad > creations :) > > Unfortunately, it appear to tickle a Python 2.2.3 bug where setting > a descriptor on a meta-class doesn't reinstate capturing of the > __get__ for the attribute. I filed a bug report for that here: > > https://sourceforge.net/tracker/index.php?func=detail&aid=775328&group_id=5470&atid=105470 And I'll close it again: MetaProp is a non-data descriptor, and hence overridden by the contents of __dict__. Adding a dummy __set__ to the MetaProp in the bug report makes the asserts pass. > Other than that, and it's intrinsicly *evil* nature, it does, > indeed, do what I was looking for. I actually thought that the automatic __dict__ overriding was part of what you were looking for! > BTW, you're creating a property whose *value* (albeit a static value) > is shared by all instances of the meta-class, rather than one that's > specific to the individual class. Well, yah. Making an interesting property *value* didn't seem to be the point of the excercise :-) [...] > But really, I don't think either of us will deploy that particular > pattern in a production system. Phew :-) > Still, fun proposal, thanks for playing, we have lots of marvelous > parting gifts for you :) . > > BTW: You know this, but in case others are wondering why it's not > usable in real life: it's possible to have threads get/set the value > without triggering the descriptor if they happen to ask for it during > the period when the descriptor is deleted. That's one of the obvious flaws, yes. You could up the insanity quotient still further by having a per-property-instance Lock() around the descriptor machinations :-) Another, more serious (to me, given that I don't use threads) is the lack of coping with inheritance. Cheers, mwh -- we're already scrubbing the face of intuition with steel wool, setting it on fire, then putting it out with an axe . -- Tim Peters, on comparing recursive structures From alanmk at hotmail.com Fri Jul 25 04:28:13 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 25 Jul 2003 09:28:13 +0100 Subject: SSH and Windows References: Message-ID: <3F20EA1D.78B4603E@hotmail.com> Isaac Raway wrote: > Hello. I'm writing a Python program that connects to servers through > telnetlib to execute a few commands. I've discovered that some of the > servers that I have to connect to with this program run only SSH, so I > need to add support for SSH to the program. I'm looking for a library > that behaves similarly to telnetlib for SSH connections. Does anyone > know of one? I was going to try using pexpect to control the Windows > telnet command, but pexpect only works on Unix. > > Any help is appreciated. Perhaps you might be able to use stunnel, which is a encrypting proxy that will secure any socket connection, does not require code changes in client or server code, and is quite straightforward to use. http://www.stunnel.org/ HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From rreagan at attbi.com Mon Jul 7 16:57:18 2003 From: rreagan at attbi.com (Russell Reagan) Date: Mon, 07 Jul 2003 20:57:18 GMT Subject: A story about Python... sort of References: Message-ID: "Bob Gailer" wrote > Physically impossible? or impractical. If it can be solved by Turing > machine computation then it is physically possible, even though it might > take more time/resources than anyone cares to expend. Or more time and resources than anyone has, which would make it impossible, for now. There are two ways to go about it. One is storing all of the positions and their distance to a theoretical result (win in N plies, draw), using a retrograde approach. This is how current endgame tablebases work. The other is on the fly depth first search. Currently neither are anywhere close to producing a practical solution. It's been said that there are more chess positions than there are atoms in the universe, so no current technology could possibly store the required information, even if we had the time to generate all of those positions, which we don't. So that leaves it to the search which requires only a tiny amount of information storage. Unfortunately, the search increases exponentially as the depth increases. A quick estimate, judging from the abilities of current programs and estimated hardware in about 18 months (10GHz, Intel), it would take about 19,365,300,260,498,916 years to search to a depth of 60 ply (30 full moves), and it is very unlikely that there is a forced win in the first 30 moves anyway, with both sides playing perfectly. So, for now it's impossible and impractical. From tomas at fancy.org Mon Jul 14 23:48:54 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 20:48:54 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> Message-ID: Stephen Horne wrote: > True enough. And if someone creates a language in which '+' does > subtraction, I'm sure people could get used to that to. Doesn't mean > it's the right thing, though. It's often more useful to do what users want than it is to blindly adhere to what's right and correct. My field is video games. Correct physics in video games is fun for such a small percentage of players that it would be considered niche (although it actually makes up a few niches). A game will get far more players by allowing those players to feel like superheroes. Players love the games I've worked on even though the main character can jump from a standstill up to grab onto a ledge 12 feet (3.6m) above the ground. They say that it seems realistic. In the same ways, the most popular programming languages are not necessarily those that are most technically correct, they are those languages that solve problems for people the way they want to think about the problems. A language truly becomes used when it becomes useful, regardless of correctness. -tom! From usenet at fomps.net Tue Jul 15 07:42:02 2003 From: usenet at fomps.net (Stephen VanDahm) Date: Tue, 15 Jul 2003 11:42:02 +0000 (UTC) Subject: Securing the Pyton Interpreter? Message-ID: I'm looking for a way to install Python on a UNIX machine in a way such that any user on the system can use it, but only to execute scripts that are located in a certain directory. I do not have root access on the machine that will be running Python, so my options are limited. I thought about hacking the Python interpreter itself so that it will examine the argument array and exit with an error if the script to be executed isn't in the appropriate directory, but this seems pretty risky. The module 'site.py' is imported automatically upon initialization -- I've thought of adding the check there instead. I don't think either of these solutions are very elegant. Is there a better way? Thanks for your time, Steve VanDahm vandahm at norge.freeshell.org From ulope at gmx.de Mon Jul 14 08:22:01 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 14 Jul 2003 14:22:01 +0200 Subject: How to give a custom object instance a type name ? References: Message-ID: "Graeme Matthew" schrieb im Newsbeitrag news:DAwQa.168$O05.9536 at nnrp1.ozemail.com.au... > > Here is a custom Dispatcher class that I have written > > >>> from BI.System.Controller.Dispatcher import Dispatcher > >>> x = Dispatcher() > >>> type(x) > You did Java before ;)? > How do I get the same as with instance 'm' above where the type displays the > actual object instance name, however my > custom dispatcher instance is just a generic 'instance', is there some > builtin where this is set ? > how about >>> x.__class__.__name__ HTH Ciao Ulrich From duncan at NOSPAMrcp.co.uk Tue Jul 22 08:53:34 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 22 Jul 2003 12:53:34 +0000 (UTC) Subject: weakref and thread safety (in python 2.1) References: Message-ID: "Ames Andreas (MPA/DF)" wrote in news:mailman.1058872336.14143.python-list at python.org: > I've noted that, when thread2 incidentally blocks on the queue > (because it's full), while thread1 deletes the queue, the weak > reference isn't deleted and thread2 keeps blocking forever. That's because when the only way to use a weak reference is to convert it into a strong reference. So when you call: myweakref.put(item) you create a strong reference that exists until the put method returns (and in fact some more references are created such as the self parameter inside the put method). > > I came up with the following destruction scheme for the queue (within > thread1; q is the 'strong' ref to the queue), which *seems* to solve > my problem (as of some preliminary tests): > > qw = weakref.proxy(q) # a second weak reference (this time within > # thread1) > del q > try: > qw.get_nowait() # if thread2 blocks on the (weakrefed) queue, > # qw still exists here; the get_nowait() call > # wakes thread2 up. I *hope* that its > # weakreference will be destroyed when it can > # block again in its next call to put() > # (leading to a weakref.ReferenceError) > except: > pass > > Is this thread-safe? I don't know enough about the implementation of > the weakref module to decide if it is guaranteed that thread2's weak > reference to the queue will be destroied *before* thread2 can call > 'put()' (or rather before thread2 can block) for the next time. No, this isn't thread safe. You have again got a strong reference while calling the method, so the only place the weak reference could be destroyed is outside the method call, and by that time thread2 could have blocked on the queue again. However, if you repeatedly try to pull data out of the queue, you should eventually get somewhere. qw = weakref.ref(q) # a second weak reference (this time within # thread1) del q while qw: qw().get_nowait() There is still a problem though as your code is free-running: if the queue gets empty before it is released you may use a lot of CPU before it eventually gets freed. Also you are depending on the memory behaviour of C Python, if Zope ever gets ported to Jython you will probably find that weak references don't go away until the garbage collector kicks in. A much better way to do this would be to make the termination explicit. e.g. (untested code) class MyQueue(Queue): def __init__(self, maxsize=0): Queue.__init__(self, maxsize) self.terminated = False thread2, with queue a normal reference to a MyQueue instance: while 1: item = produce() queue.put(item) if queue.terminated: break # Stop processing queue thread1 can then terminate the queue with: queue.terminated = True queue.get_nowait() # Ensure any blocked put completes. No weak references needed. -- 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 agentgt at yahoo.com Thu Jul 10 12:16:37 2003 From: agentgt at yahoo.com (Adam Gent) Date: 10 Jul 2003 09:16:37 -0700 Subject: for in sequence problem... possible new operator to add to python Message-ID: <3a8fc6c5.0307100816.634c83a3@posting.google.com> I was fooling around subclassing a dictionary object and noticed that when I do the standard "for in :" that I have no control on how python gets that sequence. For example: class Blah(dict): pass bl = Blah() for b in bl: #b will be a key and not a value #no matter how I subclass Blah However I want b to be the values with out doing: for b in bl.values() I could be wrong on this but I believe python is missing an operator for looping over objects. I think there should be a __sequence__ or __forsequence__ operator that returns a sequence when "for x in object" syntax is used. So for b in bl: == for b in bl.__sequence__ From http Tue Jul 29 21:39:22 2003 From: http (Paul Rubin) Date: 29 Jul 2003 18:39:22 -0700 Subject: Bottleneck: easy obscurity "encryption" via xor References: Message-ID: <7xwue0pzcl.fsf@ruckus.brouhaha.com> Tino Lange writes: > Hmmm, do you have some better implementation ideas? Some optimizing > tricks? (Besides coding in C to avoid immutable string problems) > I already took the operator module to speed up a bit - but it seems > that's not enough... Use the array module. See . From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 10 18:16:32 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 11 Jul 2003 00:16:32 +0200 Subject: Securing PyDoc and CGIHTTPserver In-Reply-To: References: <2621b014.0307100535.449ad06f@posting.google.com> Message-ID: <3f0de5c0$0$49113$e4fe514c@news.xs4all.nl> Shane Hathaway wrote: > What about binding only to the local (loopback) interface? That way, > the system won't even listen for external connections. It's like a > built-in firewall. > > The change is a one-liner. The DocServer computes the hostname for the > loopback interface but then binds to all interfaces. So change this line: > > self.address = ('', port) > > to: > > self.address = (host, port) > I think Shane meant: self.address = ('localhost',port) --Irmen de Jong From drs at ecp.cc Wed Jul 9 15:52:42 2003 From: drs at ecp.cc (drs) Date: Wed, 09 Jul 2003 19:52:42 GMT Subject: .join() question Message-ID: why does >>> ''.join(lst) not automatically do >>> ''.join([str(i) for i in lst]) ? That is, is there ever a time when one does not want .join to make everything into a string? This seems like reasonable default behavior, but maybe I'm missing something? -doug From nospamjynyl at yahoo.co.nz Mon Jul 28 14:06:30 2003 From: nospamjynyl at yahoo.co.nz (Peter) Date: Tue, 29 Jul 2003 06:06:30 +1200 Subject: default import path References: <3f24c37e@news.maxnet.co.nz> <3f24e61d$0$24786$626a54ce@news.free.fr> Message-ID: <3f2566cf@news.maxnet.co.nz> this quote is from Fabien SK of Mon, 28 Jul 2003 20:59 : > Peter wrote: >> >> How can I edit the default import path for Python under Windows? > > I added this key in the registry: > HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.2\PythonPath\Some_name Thanks, seems rather un-python-like to have to do this via an edit to the registry. I'm comfortable editing config on my Linux PC, but I'd rather not mess with the registry as Windows is too frail (and it is a friend's PC). Maybe, it would be better to use a addpath statement in each python script where I want to use this module. thanks for you help Peter From bdesth.nospam at removeme.free.fr Fri Jul 25 16:15:48 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 25 Jul 2003 22:15:48 +0200 Subject: Static typing In-Reply-To: References: Message-ID: <3f218e1e$0$27907$626a54ce@news.free.fr> Michael Muller wrote: > Is there currently any plan to introduce static typing in any future > version of Python? AARGGHHHH ! NO !! DON'T DO THAT !!! NEVER AGAIN !!!! (sorry, uncontrolable nervous reaction... 3 valiums latter... : ) (I'm not entirely sure that "static typing" is the right > term: what I'm talking about is the declaration of types for variables, > parameters and function return values). This is the right term. This is also the wrong thing for Python IMHO. > I know there was a "types SIG" which introduced several proposals, but it > expired quite a while ago, and I was wondering whether whether some > consensus has been reached on the subject Yes : dynamic typing is good a Good Thing(tm), static typing is Evil(tm) !-) Bruno From rimbalaya at yahoo.com Tue Jul 1 13:07:04 2003 From: rimbalaya at yahoo.com (Rim) Date: 1 Jul 2003 10:07:04 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <6f03c4a5.0307010907.302b931c@posting.google.com> "Terry Reedy" wrote in message news:... > "Rim" wrote in message > news:6f03c4a5.0306301931.3f15fbb7 at posting.google.com... > > Hi, > > > > I have been thinking about how to overload the assign operation '='. > > Assignment is a statement, not an operator, and therefore not > overloadable . This is an intentional design decision that GvR will > not change. Well, what about the idea of providing another statement, the one I proposed in the original post? '=' statement assigns type and value ':=' statement assigns value only Rim From jdhunter at ace.bsd.uchicago.edu Thu Jul 10 22:49:48 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 10 Jul 2003 21:49:48 -0500 Subject: python mode problem in emacs In-Reply-To: <3097083.1057868749@dbforums.com> (pygeek's message of "Thu, 10 Jul 2003 20:25:49 +0000") References: <3097083.1057868749@dbforums.com> Message-ID: >>>>> "pygeek" == pygeek writes: pygeek> Hi everyone. I've just installed emacs 21.3.1 on my WinXP pygeek> machine. I wanted to switch to Python mode then realized pygeek> that my emacs lacked the 'python-mode.el' file. After pygeek> downloading from python.org and byte-compiling the file, I pygeek> went on to look for the file '.emacs' or 'emacs.el' to pygeek> include a few lines of command so that emacs would load pygeek> python-mode. I looked through and searched my hard drive, pygeek> and there wasn't such a file by the name '.emacs' or pygeek> 'emacs.el'. What's going on here? Where are the files? pygeek> Can somebody help me? Thanks in advance. The easiest way to do it is to put your .emacs in C:\ (or $HOME if you have set that environment variable). By default, on windows, emacs will look in $HOME and then C:\\ On win32, I usually put python-mode.el in the site-list dir of the emacs distribution, then make a minimal .emacs which includes, among other essentials (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) JDH From andy at post.tau.ac.il Tue Jul 22 13:43:06 2003 From: andy at post.tau.ac.il (Andy Worms) Date: Tue, 22 Jul 2003 20:43:06 +0300 (IDT) Subject: CGIHTTPServer security Breach Message-ID: <1058895786.3f1d77aa315c5@webmail.tau.ac.il> I'm using CGIHTTPServer to try some scripts, apparently as a first step of building a real server. The CGIHTTPServer source code has a comment that warns of potential security problems: SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL -- it may execute arbitrary Python code or external programs. Does someone know how can an outsider execute arbitrary python code or external problems? Are there simple ways to correct the code? ----------------------------- Andy Worms ----------------------------- From manuelbastioniNOSPAM at tin.it Fri Jul 25 14:52:00 2003 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Fri, 25 Jul 2003 18:52:00 GMT Subject: decimal to binary References: <200307250653.18754.gherron@islandtraining.com> Message-ID: > We probably need more information than that to answer your question. I'm writing a script for Blender to make a true displacement feature. This is a sample: http://www.kino3d.com/forum/files/test4.jpg and this is the discussion: http://www.elysiun.com/forum/viewtopic.php?t=13135&postdays=0&postorder=asc& start=0 Please, excuse me for my poor english, it's very hard for me to explain a development question, because I'm italian, and I've little time to study other language...Really I prefer study 3D and python. :-P The main problem with newsgroup it that after send the message I can't modify it... :-( This is the first time that I try to handle binary file. I read a tga file, and store all bytes in a list: --------------------------------------- #LETTURA DEL FILE TGA listByte = [] try: f = open(filename,'rb') except IOError,(errno,strerror): msgstring = "I/O error(%s): %s" % (errno, strerror); Draw() return fileReaded = f.read(); msgstring = "Parsing tga..."; Draw() for i in range(len(fileReaded)): listByte.append(ord(fileReaded[i])) f.close() ------------------------------------------ I use ord() to convert the value of byte in integer, if I don't make this, I've the ASCII symbol... But, for listByte[17], I must read the sequence of 0 and 1, because I must know the 4? and 5? bit: this bits specify the image origin. How I can read the 4? and 5? bit from listByte[17]? Thanks, Manuel Bastioni From __peter__ at web.de Mon Jul 28 08:46:14 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jul 2003 14:46:14 +0200 Subject: changing the List's behaviour? References: Message-ID: meinrad recheis wrote: > i want to change the List so that it returns None if the index for > accesssing list elements > is out of bound. If you really need it, you can write a class similar to the one below: class DefaultList(list): def __init__(self, sequence=[], default=None): list.__init__(self, sequence) self.default = default def __getitem__(self, index): try: return list.__getitem__(self, index) except IndexError: return self.default if __name__ == "__main__": theList = DefaultList("abc", "?") print theList[1] print theList[99] theList = DefaultList(default="X") print theList[1] From bdesth.nospam at removeme.free.fr Mon Jul 7 15:44:47 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 07 Jul 2003 19:44:47 +0000 Subject: Python vs PHP References: Message-ID: <3F09CDAF.4040906@removeme.free.fr> News M Claveau /Hamster-P wrote: > Hi ! > > PHP-5 let down MySql, for Sql-Lite (rumor ?) PHP 5 won't come bundled with a default MySql lib, but anyone is still free to link against the official MySQL lib, one way or another... And yes, the default 'bundled-in' SQL lib should be Sql-lite. Bruno From tim.one at comcast.net Sun Jul 27 13:17:50 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 27 Jul 2003 13:17:50 -0400 Subject: multiple file objects for some file? In-Reply-To: Message-ID: [Gary Robinson] > For some code I'm writing, it's convenient for me to have multiple > file objects (say, 2 or 3) open on the same file in the same process > for reading different locations. > > As far as I can tell, there is no problem with that but I thought it > might be a good idea to ask here just in case I'm wrong. Provided they're "ordinary" on-disk files (not, e.g., sockets or pipes wrapped in a Python file object), that should be fine. Each file object has its own idea of the current file position, and they'll all (of course) see the same data on disk. You can get in deep trouble if the file mutates, though. Python's file objects are wrappers around C's streams, and each C stream has its own buffers. So, for example, a mutation (a file write) made via one file object won't necessarily update the buffers held by the other file objects (it depends on how your platform C works, but I don't know of any that automagically try to update buffers across multiple streams open on the same file), and then reading via some other file object may continue to see stale data (left over in its buffer). For example, I bet this program will fail on your box before a minute passes: """ f = open('temp.dat', 'wb') chars = ''.join(map(chr, range(256))) chars = chars * 1000 f.write(chars) f.close() f1 = open('temp.dat', 'r+b') f2 = open('temp.dat', 'r+b') f1.seek(0, 2) n = f1.tell() assert n == len(chars) import random while True: f = random.choice((f1, f2)) start = random.randrange(n) f.seek(start) len = random.randrange(500) data = f.read(len) assert data == chars[start : start+len] print '.', if random.random() < 0.1: print len, data = ''.join([random.choice(chars) for dummy in xrange(len)]) f.seek(start) f.write(data) chars = chars[:start] + data + chars[start+len:] """ If you change f = random.choice((f1, f2)) to f = f1 it should never fail (then there's only one file object getting mucked with). If instead you change if random.random() < 0.1: to if 0: it should also never fail (then there are multiple file objects, but no file mutations). From tdelaney at avaya.com Mon Jul 7 18:14:53 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 8 Jul 2003 08:14:53 +1000 Subject: python scripting game The Temple Of Elemental Evil update Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE84484B@au3010avexu1.global.avaya.com> > From: Geoff Gerrietts [mailto:geoff at gerrietts.net] > > I can't speak for the Temple of Elemental Evil in particular, but this > pattern holds true in dozens of similar titles. If they're doing > something different, they're doing something really very different. Troika have specifically said that it is being used in the AI (presumably NPC and PC if the player turns on PC AI during combat). The dialog system is basically an upgraded version of the Arcanum dialog system, so whether that's been augmented with Python I have no idea. That's as in-depth as I know. Tim Delaney From pinard at iro.umontreal.ca Wed Jul 23 13:10:54 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 23 Jul 2003 13:10:54 -0400 Subject: The global statement In-Reply-To: References: Message-ID: [David Hitillambeau] > I want to enable some sharing between the two functions (foo and bar) > using one global variable in such a way that each function can have read > and write access over it. [...] I've read about "The global statement" > in python's documentation and still can't figure out it's use. You do not have to use a `global' declaration in global scope, but you ought to use `global' in local scope whenever you modify that variable in that scope. ----------------------------------------------------------------------> # Initialisation has to be done somewhere, not necessarily here. variable = INITIAL_VALUE def foo: # This function looks at `variable', a global, but does not modify it. # A `global variable' declaration may appear, but is not required. def bar: # This function may either look or change `variable', which is global. global variable ----------------------------------------------------------------------< The problem with globals is that when can easily abuse them, and have a program that looks a bit disorganised. I try to avoid them wherever possible. The usual best way to share data between functions is to use classes, a bit like this: ----------------------------------------------------------------------> class Item: def __init__(self): self.variable = INITIAL_VALUE def foo(self): # Look at or modify self.variable. def bar(self): # Look at or modify self.variable. item = Item() ----------------------------------------------------------------------< you can then use `item.foo()' or `item.bar()' as needed. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From klappnase at freenet.de Sun Jul 20 19:13:15 2003 From: klappnase at freenet.de (klappnase) Date: 20 Jul 2003 16:13:15 -0700 Subject: Newbie Questions? References: <504413fa.0307200626.3fceb85a@posting.google.com> Message-ID: <9a410299.0307201513.7ba29781@posting.google.com> KodeKruncherDude at aol.com (Adam Petrosh) wrote in message news:<504413fa.0307200626.3fceb85a at posting.google.com>... > Hail all. Are newbie questions allowed here, or is there a different > Newsgroup for that? Thanks. Hi, I think you may ask whatever you want, seems like you are not the only one around here. Michael From gh at ghaering.de Wed Jul 30 04:06:27 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 30 Jul 2003 10:06:27 +0200 Subject: Upgrading python In-Reply-To: References: Message-ID: <3F277C83.60900@ghaering.de> Stephen Boulet wrote: > When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3? There's no need to. -- Gerhard From ruach at chpc.utah.edu Mon Jul 28 16:14:50 2003 From: ruach at chpc.utah.edu (Matthew) Date: 28 Jul 2003 13:14:50 -0700 Subject: octet string conversion Message-ID: I am working on some software that uses SNMP to get information from routers and switches. I am using the pysnmp module (v2.0.8) to do the snmp part. The problem that I am having is that when I query a router for mac addresses pysnmp returns octetstrings like this: \000\002\263\254\264\351 \010\000 \301F\021 \010\000 \300\303[ \000\002\263\254\264\241 what I need though is hex strings like this: 0:e0:7d:de:5:48 0:e0:7d:c8:dc:9f 8:0:36:4:3b:de 0:80:ad:3a:9e:2b Can anyone tell me how to convert the octet strings to hex strings? Thanks very much -matthew From gh at ghaering.de Thu Jul 31 07:03:15 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 13:03:15 +0200 Subject: Misuse of In-Reply-To: <9rehivsavhereijf36nhla96krct4s1fmn@4ax.com> References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> <9rehivsavhereijf36nhla96krct4s1fmn@4ax.com> Message-ID: <3F28F773.8030306@ghaering.de> Christopher Koppler wrote: > [tab settings] > And, as others have said, DON'T use 5. I'd still like to hear a reason for this. -- Gerhard From peter at engcorp.com Mon Jul 21 16:48:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 16:48:59 -0400 Subject: Voting Project Needs Python People References: <3F1C31B1.B44774BA@engcorp.com> <2oWSa.113024$Io.9679242@newsread2.prod.itd.earthlink.net> Message-ID: <3F1C51BB.AC355795@engcorp.com> Alan Dechert wrote: > > "Peter Hansen" wrote in message > news:3F1C31B1.B44774BA at engcorp.com... > > Alan Dechert wrote: > > > > > > We are pulling together a great voting modernization projects. [snip] > > > > Is there a word missing in the above? I can't parse it as-is, but it > > looks like it wants the word "many" after the word "great"... > > > Editing error. I started to say, "the mother of all voting modernization > projects." > > You get the idea. I do now. Thanks. "The mother of all" has a distinctly different character than "pulling together a great many". One hopes there will not also be dozens of other such projects going on in parallel, wasting resources. -Peter From gherron at islandtraining.com Thu Jul 24 02:10:30 2003 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 23 Jul 2003 23:10:30 -0700 Subject: python 2.2 string conversion ? In-Reply-To: References: Message-ID: <200307232310.30779.gherron@islandtraining.com> > > >>> x="e10ea210" > >>> y=long(x) > > Traceback (most recent call last): > File "", line 1, in ? > y=long(x) > ValueError: invalid literal for long(): e10ea210 > What am I doing wrong? You didn't specify what you are trying to do here, but I'll make a wild *guess* that the string in x is a hexadecimal (i.e., base 16) value. However, Python can't go around making such a guess, so you have to explicitly specify your radix (radix being another term for base) like this: >>> print long("e10ea210",16) 3775832592 or tell it to infer the radix from a '0x' prefix: >>> print long("0xe10ea210",0) 3775832592 Here are the relevant portions of the manual: long(x[, radix]) Convert a string or number to a long integer. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace; this behaves identical to string.atol(x). The radix argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). int(x[, radix]) Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace; this behaves identical to string.atoi(x[, radix]). The radix parameter gives the base for the conversion and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. If radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. Gary Herron From pipen at beast_tu_kielce.pl Thu Jul 10 15:04:11 2003 From: pipen at beast_tu_kielce.pl (Artur M. Piwko) Date: Thu, 10 Jul 2003 19:04:11 +0000 (UTC) Subject: wxPython - question Message-ID: How can I remove program entry from taskbar (not tray)? Artur -- Before the Goat of Mendes... we all must take our turn | Artur M. Piwko Into the magic circle... where still the fire burns | mailto:s/_/./ We're spinning round and round... until one takes a fall | -- Mercyful Fate The fallen one will not return, the fallen one must burn | "Witches' Dance" From jarausch at skynet.be Thu Jul 17 12:28:47 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Thu, 17 Jul 2003 18:28:47 +0200 Subject: IDEStudio (Linux Python cvs-version TclTk 8.4.3 tix-8.1.4) Message-ID: <3f16cebf$0$269$ba620e4c@reader0.news.skynet.be> Hi, has anybody managed to get IDEStudio running on Linux with Python 2.3b2+ (cvs) plus TclTk 8.4.3 + tix-8.1.4 ? After a minor correction to src/idledev/IDEStudio.py to set 'srcdir' correctly (otherwise Tide.py is not found) I get only a tall black column. What did I miss? Thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jepler at unpythonic.net Tue Jul 29 17:59:09 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 29 Jul 2003 16:59:09 -0500 Subject: bisect uses __cmp__()? In-Reply-To: References: Message-ID: <20030729215909.GA5176@unpythonic.net> On Tue, Jul 29, 2003 at 04:05:46PM -0400, Gary Robinson wrote: > I'm wondering if bisect.insort is guaranteed to use a __cmp__ method, for > now and for future python versions, if it exists, for the items being > inserted? I don't know for certain what (if anything) is guaranteed, but my guess is that insort is defined to use only the < operator to compare items. This means that you can meet the requirements of the bisect module by defining __cmp__ or by defining __lt__ (or even by defining __gt__!). See http://python.org/dev/doc/devel/ref/customization.html for how "rich comparison" works to perform comparisons. __cmp__ is used "if rich comparison is not defined". Thus, existing code with __cmp__ still works just fine. Jeff From staschuk at telusplanet.net Tue Jul 1 23:42:49 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 21:42:49 -0600 Subject: whitespace and ?asc()? In-Reply-To: <3F02086D.9010300@ihug.co.nz>; from rtomes@ihug.co.nz on Wed, Jul 02, 2003 at 10:17:17AM +1200 References: <3F02086D.9010300@ihug.co.nz> Message-ID: <20030701214249.A192@tibia.amotlpaa.bogus> Quoth Ray Tomes: [...] > Also, in trying to find the ASCII (or is it ANSI) values for characters I The only thing nobody else commented on: The character code standard is ASCII (American Standard Code for Information Interchange, if memory serves), but it is an ANSI standard (the American National Standards Institute). (There's an equivalent ISO standard, I think... ISO 646?) In some communities, "ANSI" is used metonymously to refer to some specific ANSI standard for terminal control codes, I think. But this has nothing to do with ASCII. > I had to do this yucky thing to decode whitespace ... > > import string > x=string.whitespace > for b in x: > for i in range(256): > if chr(i) == b: > print i Note also that at the interpreter prompt you can (some of) those ASCII codes in hex just by looking at the value of the string: $ python ... >>> import string >>> string.whitespace '\t\n\x0b\x0c\r ' If your ASCII chart doesn't have hex, continue with >>> 0x0b, 0x0c (11, 12) to obtain the decimal values. -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From wim_wauters at skynet.be Tue Jul 15 11:03:02 2003 From: wim_wauters at skynet.be (WIWA) Date: 15 Jul 2003 08:03:02 -0700 Subject: pySNMP: SNMPget example References: <538fc8e.0307100356.4bf46554@posting.google.com> <538fc8e.0307140736.19eb777@posting.google.com> Message-ID: <538fc8e.0307150703.48466779@posting.google.com> Hi, I was wondering if you could help me: I want to create an SNMP application and would need the following: 1) Instead of writing '1.3.6.1.2.1.69.1.3.1', I would also like to be able to write 'docsDevSwServer'. Any idea how I can do that? 2) I have downloaded some MIBs. How can I make my program aware of the existence of these MIBs. Basically I want to write a program that allows the user to browse to these MIBs and then import them into a GUI. Any ideas? Wim Ilya Etingof wrote in message news:... > I'd suggest you to refer to "high-level" API documentation at > http://pysnmp.sourceforge.net/docs/3.x/ for getting used to > basic operations on SNMP objects (such as apiGetPdu(), apiSetVarBind()). > > Also, note, that pysnmp s/w (the third branch) has been closely aligned > with the APIs introduced by SNMP RFCs, so reading these RFCs may be > helpful too. > > If you got more specific questions, please, let me know. > > -ilya > > WIWA wrote: > > Thanks Ilya, > > > This has been very helpful. I'm able to get data out of my 'device > > under test'. > > > I must be honnest and say that I understand the sample code, but could > > not write or produce it myself. > > > How do you know e.g that > > req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) can be > > written? I've read through the documentation and could not find > > anything similar. Of course, I could overlook it. > > > Isn't there a tutorial out there that summarizes pysnmpv3 and gives > > examples of snmpget, snmpset, snmpwalk, etc... > > > Thanks in advance for helping me out. > > > Regards, > > > Wim > > > > > > > Ilya Etingof wrote in message news:... > >> > 2) when using: 'from pysnmp import role' (found on > >> > http://pysnmp.sourceforge > >> > .net/examples/2.x/snmpget.html), I get the message 'ImportError: > >> > >> You seems to use pysnmp 2.x API which differs from the latest 3.x branch > >> (though, a compatibility layer exists in 3.x distribution). That's why > >> I suggest you looking at the 3.x docs and examples at: > >> > >> http://pysnmp.sourceforge.net/docs/3.x/index.html > >> > >> > 3) A general question: how can I get a list of what I can type after > >> > the 'from > >> > pysnmp import ...' > >> > >> dir() may help but in this case I'd better see an example. > >> > >> > 4) How can I use: 'from snmpget import snmpget'. It does not accept > >> > this. > >> > >> There is no such module as snmpget in pysnmp. > >> > >> > 5) Anyone has a simple example for the following application: I have a > >> > cable > >> > modem (which has an SNMP agent inside). I want to make a script where > >> > I can > >> > do SNMPgets (and later SNMPSet and SNMPwalk). > >> > >> Python 1.5.2 (#3, Aug 25 1999, 19:14:24) [GCC 2.8.1] on sunos5 > >> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >> >>> from pysnmp.proto import v1 > >> >>> from pysnmp.proto.api import generic > >> >>> from pysnmp.mapping.udp import role > >> >>> req = v1.GetRequest() > >> >>> req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) > >> >>> tr = role.manager(('router-1.glas.net', 161)) > >> >>> (answer, src) = tr.send_and_receive(req.encode()) > >> >>> rsp = v1.GetResponse() > >> >>> rsp.decode(answer) > >> >>> vars = rsp.apiGetPdu().apiGetVarBind() > >> >>> print vars > >> [('.1.3.6.1.2.1.1.1.0', OctetString('Cisco Internetwork Operating System > >> Software\015\012IOS (tm) 5400 Software(C5400-JS-M), Version 12.2(11.8b), > >> MAINTENANCE INTERIM SOFTWARE\015\012 Copyright (c) 1986-2002 by cisco > >> Systems, Inc.\015\012 Compiled Tue 30-Jul-02 19:02 by pwade'))] > >> >>> > > >> > 7) What is the difference between snmpget and getrequest in pysnmp? > >> > >> The only difference is the SNMP request object (GetRequest vs GetNextRequest) > >> you create when building SNMP message. > >> > >> -ilya From lol at lolmcNOSPAM.com Fri Jul 4 16:58:51 2003 From: lol at lolmcNOSPAM.com (Rogue 9) Date: Fri, 04 Jul 2003 21:58:51 +0100 Subject: Importing of packages problem Message-ID: <3f05ea75@shknews01> Hi All, I am developing a program called oop_lb.py and it's package structure is as below: oop_lb | -------------------------------------- | | | analysis process tests I am using the unittest module and taking a leaf out of the Xtreme programming philosophy in as much as I am creating test modules for each module in the program and placing them in the tests package.The analysis and process packages contain a number of modules and I only encounteredproblems when I started writing the modules and tests for the analysis package. Put simply my problem is that modules in the analysis package reference modules in the process package and I can't seem to find a way of writing the import statements so that the tests and oop_lb.py will both execute without errors such as: Traceback (most recent call last): File "CalculateMedianTest.py", line 14, in ? import oop_lb.analysis.CalculateMedian File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 13, in ? from process import GetDraw ImportError: No module named process If I change the import statement so that the test works then the oop_lb.py module will not run and gives the following message: Traceback (most recent call last): File "oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 13, in ? from oop_lb.process import GetDraw File "/home/lol/disk/python/lotto/oop_lb/oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file ImportError: cannot import name CalculateMedian I hope I haven't been too ambiguous in my request and choice of listings to illustrate what I mean.If you can help that would be great and if I need to add something to make it clearer what it is I mean just let me know. Thanks ,Lol -- Remove NOSPAM from my email address to use it,please. From imbosol at aerojockey.com Mon Jul 28 00:48:05 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Mon, 28 Jul 2003 04:48:05 GMT Subject: Question regarding HTMLParser module. References: Message-ID: <9W1Va.9538$AO6.361@nwrdny02.gnilink.net> Adonis wrote: > When parsing my html files, I use handle_pi to capture some embedded python > code, but I have noticed that in the embedded python code if it contains > html, HTMLParser will parse it as well, and thus causes an error when I exec > the code, raises an EOL error. I have a work around for this as I use > different set of characters rather that use something like (tag) then > revert it back to via another function, I was wondering if there is a > way to tell HTMLParser to ignore the embedded tags or another alternative? > > Any help would be greatly appreciated. > And another note, I am well aware of Zope, Webware, CherryPy, etc... for > py/html embedding options, but I want this to be a learning experience. Unfortunately, HTMLParser (and the similar sgmllib) miserably fail to process inline text. I know this very well; I have an HTML-generating package that uses a lot of scripting and verbatim text. What's happening in your case is that HTMLParser, when processing a ". HTMLParser thinks the > in closes your " or just ">".) A workaround is to do something like this: where obviously, \x29 is the hex code for >. That's not quite as bad as replacing characters, although it's still not perfect. Another possibility is to use sgmllib, but that's probably way more trouble than it's worth, and still far from perfect. Basically, sgmllib parsers have an method called verbatim, that turns of HTML tag processing, although entities and closing tags are still processed. (Entities and closing tags you can kind of reconstruct into the original text, although the whitespace is lost.) This is what I do in my own HTML-generating package. I'll probably contribute some badly-needed remedies to HTMLParser sometime, as the limitations of it and sgmllib are starting to get on my nerves. -- CARL BANKS From wil.koenen at hetnet.nl Sun Jul 6 08:57:00 2003 From: wil.koenen at hetnet.nl (Wil Koenen) Date: Sun, 6 Jul 2003 14:57:00 +0200 Subject: problem with GTK on Windows Message-ID: Hi, When importing (parts of) gtk, here's what I get: >>> import gobject Traceback (most recent call last): File "", line 1, in ? import gobject ImportError: DLL load failed: One of the library files needed to run this application cannot be found. (similar messages for other modules, including gtk, atk , _gtk). This message tells me something, but not all. Is the gobject.pyd which is not found? Or is a 'real' .dll from the GTK package that cannot be found. I've installed (Windows '95): Python-2_2_1.exe in C:\Program Files\Python. GTK+-Runtime-Environment-2.2.0.1.exe in C:\Program Files\Common Files\Gtk pygtk-1.99.16.win32-py2.2.exe in C:\Program Files\Python\Lib\site-packages\gtk-2.0 and added some .pth files in the site-packages directory. The sys.path includes the following: C:\PROGRA~1\PYTHON\Tools\idle C:\Program Files\Python\Lib\site-packages\gtk-2.0\gtk C:\PROGRAM FILES\PYTHON\DLLs C:\PROGRAM FILES\PYTHON\lib C:\PROGRAM FILES\PYTHON\lib\lib-tk C:\PROGRAM FILES\PYTHON C:\PROGRAM FILES\PYTHON\lib\site-packages C:\Program Files\Common Files\GTK\2.0\lib C:\Program Files\Common Files\GTK\2.0\lib\gtk-2.0\2.2.0\engines C:\Program Files\Common Files\GTK\2.0\lib\gtk-2.0\2.2.0\immodules C:\Program Files\Common Files\GTK\2.0\lib\gtk-2.0\2.2.0\loaders C:\Program Files\Common Files\GTK\2.0\lib\pango\1.0.0\modules C:\PROGRAM FILES\PYTHON\lib\site-packages C:\PROGRAM FILES\PYTHON\lib\site-packages\gtk-2.0 (1) When I use the explorer, I find a file gobject.pyd in C:\Program Files\Python\Lib\site-packages\gtk-2.0 but it doesn't have python icon. Would it be possible that this file is not recognized (by Python) as a module? (2) Before trying to import gtk, I imported pygtk , which looks like a setup-script. May this have ruined my setup. (3) Does the sys.path have any relation at all to the search path for .dll's ? Thanks in advance for any help, Wil From harry.g.george at boeing.com Thu Jul 24 16:29:14 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 24 Jul 2003 20:29:14 GMT Subject: Tokenize References: <8%VTa.133$313.72262@news.uswest.net> Message-ID: "Ken Fettig" writes: > Does Python have an equivelent to the Java StringTokenizer? If so, what is > it and how do you implement it? > Thanks > Ken Fettig > kenfettig at btinet.net > kfettig at state.nd.us > > > See shlex (in the main distribution) or see a variety of lexer/parser tools such as Ply, Yapp.py, shlex is about the level of complexity you want. See the Library Reference Manual for instructions. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From staschuk at telusplanet.net Mon Jul 21 20:36:40 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 21 Jul 2003 18:36:40 -0600 Subject: [OT] sentances with two meanings In-Reply-To: ; from mwilson@the-wire.com on Sun, Jul 20, 2003 at 03:28:16PM -0400 References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <2259b0e2.0307170416.e2bc998@posting.google.com> Message-ID: <20030721183640.B188@tibia.amotlpaa.bogus> Quoth Mel Wilson: [Latin verbs for 'to know'] > Me too, but it's in Bantam's _The New College Latin & > English Dictionary_. 'Cognovisse' seems to be some > modification of cognoscere. [...] It is, in fact, the perfect infinitive of . According to Wheelock, means "to learn" (etc.), and *in perfect tenses* means "to know". Note that you know something (present tense) iff you have learned it (perfect tense). So if Bantam lists as a translation of "to know", I see no reason to object. It would be surprising if they list it as a head word, as if it were the infinitive of a (purely notional) verb cognovi, cognovisse, cognoveram, cognitus eram (which are analogues of the usual principal parts under the mapping present -> perfect). -- Steven Taschuk staschuk at telusplanet.net "Please don't damage the horticulturalist." -- _Little Shop of Horrors_ (1960) From alanmk at hotmail.com Thu Jul 17 06:53:05 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 11:53:05 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> Message-ID: <3F168011.3AEB3EFC@hotmail.com> JanC wrote: > The verb "gignooskoo" (trying to write it with Latin letters ;) Why limit yourself to that nasty little us-ascii alphabet? >;-) Here it is in a format where almost everybody will be able to see the original greek verb on their screen. #--------- γίγνωσκω #--------- For anybody who has MS Internet Explorer 5+, Netscape 6+, Mozilla 1+, i.e. any browser that supports XML, simply save this to a disk file and open it in your chosen browser. Of course, I could also have used charset "iso-8859-7", in which case the character codes would be one-byte-only. But I don't think that would have travelled well over UseNet to most of you. Or I could have used UTF-16, in which case every character would have been two-bytes. But the same UseNet problems apply. So, the challenge to the ASCII proponents is: put the greek word "gignooskoo" on everybody's screen, originating from a usenet message, in the original greek, where "oo" -> greek letter omega. Obviously, it could also be represented in python itself. But I think it is fair to exclude python, given that not everyone reading this message will have python available to them (think of people stumbling across this posting while searching the archives for information about the origin of the word "science" for example). I expect you won't find it as simple as the XML above, although I'm also completely prepared to be proven wrong (Alan tries to cover his a** in advance ;-). -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From eniac at sdf-eu.org Tue Jul 22 16:53:28 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Tue, 22 Jul 2003 22:53:28 +0200 Subject: wxPython probleme Message-ID: Hey, here's my piece of code : class HtmlWindow(wxHtmlWindow): def __init__(self,parent,id): wxHtmlWindow.__init__(self,parent,id) class channelTree(wxTreeCtrl): def __init__(self,parent,id): wxTreeCtrl.__init__(self,parent,id) self.root = self.AddRoot("Sites") for i in range(len(names)): self.AppendItem(self.root,names[i]) EVT_TREE_SEL_CHANGED(self,105,self.OnCelChanged) def OnCelChanged(self,event): item = event.GetItem() print self.GetItemText(item) class MainSplitter(wxSplitterWindow): def __init__(self,parent,id): wxSplitterWindow.__init__(self,parent,id) self.html = HtmlWindow(self,-1) self.html.LoadPage("welcome.html") self.SplitHorizontally(self.html,wxWindow(self,-1),500) self.Show(1) If you look at the channelTree class I've created a wxTreeCtrl when you change a sel a execute onCelChanged Now I would like that when you change a sel he loads an other page into the HtmlWindow. But I don't really have an idea on how to do this any help ? From harry.g.george at boeing.com Tue Jul 15 15:18:05 2003 From: harry.g.george at boeing.com (Harry George) Date: Tue, 15 Jul 2003 19:18:05 GMT Subject: newbie question: ImportError: No module named Numeric References: Message-ID: rmachne writes: > Hi there, > > Sorry, if there is a newbie list or this question is answered in tutorials > - I tried but without succes :-( - here is my question: > Using linux, > I need the 'Numerical Python' package, and I installed it on my local > computer (not with the other packages in /usr/local/...) using > > ~/programs/Numeric-23.0>python setup.py install --home=/scratch/raim > > but now the Numeric package / module can't be found: > > ~/programs/Numeric-23.0/Test> python test.py > Traceback (most recent call last): > File "test.py", line 2, in ? > import Numeric > ImportError: No module named Numeric > Exit 1 > > I couldn't find out which path variable to change or add. Can anyone > help? > (Test.py works fine when called from within the lib folder with > Numeric.py) > > best > rainer > You can set an env variable: export PYTHONPATH=/scratch/raim (or whatever your shell syntax is) This adds the path to your normal defaults. You can also do this 'export' in a shell script which runs the application. This is useful if you have several variants of a given module, and want to use one or the other in a specific case. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From andy at wild-flower.co.uk Sat Jul 19 08:28:39 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sat, 19 Jul 2003 13:28:39 +0100 Subject: using functions and file renaming problem In-Reply-To: <3F1871A5.3020702@hotmail.com> References: <3F174E76.4000302@hotmail.com> <3F1871A5.3020702@hotmail.com> Message-ID: <200307191328.39732.andy@wild-flower.co.uk> On Friday 18 Jul 2003 11:16 pm, hokiegal99 wrote: > Thanks again for the help Andy! One last question: What is the advantage > of placing code in a function? I don't see how having this bit of code > in a function improves it any. Could someone explain this? > > Thanks! 8<--- (old quotes) The 'benefit' of functions is only really reaped when you have a specific need for them! You don't *have* to use them if you don't *need* to (but they can still improve the readability of your code). Consider the following contrived example: ----------8<------------ # somewhere in the dark recesses of a large project... . . . for filename in os.listdir(cfg.userdir): newname = filename for ch in cfg.badchars: newname.replace(ch,"-") if newname != filename: os.rename(os.path.join(cfg.userdir,filename), os.path.join(cfg.userdir,newname) . . . . . . # in another dark corner... . . . for filename in os.listdir(cfg.tempdir): newname = filename for ch in cfg.badchars: newname.replace(ch,"-") if newname != filename: os.rename(os.path.join(cfg.userdir,filename), os.path.join(cfg.userdir,newname) . . . # somewhere else... . . . for filename in os.listdir(cfg.extradir): newname = filename for ch in cfg.badchars: newname.replace(ch,"-") if newname != filename: os.rename(os.path.join(cfg.userdir,filename), os.path.join(cfg.userdir,newname) . . . ----------8<------------ See the repetition? ;-) Imagine a situation where you need to do something far more complicated over, and over again... It's not very programmer efficient, and it makes the code longer, too - thus costing more to write (time) and more to store (disks). Imagine having to change the behaviour of this 'hard-coded' routine, and what would happen if you missed one... however, if it is in a function, you only have *one* place to change it. When we generalise the algorithm and put it into a function we can do: ----------8<------------ . . . . . . # somewhere near the top of the project code... def cleanup_filenames(dir): """ renames any files within dir that contain bad characters (ie. ones in cfg.badchars). Does not walk the directory tree. """ for filename in os.listdir(dir): newname = filename for ch in cfg.badchars: newname.replace(ch,"-") if newname != filename: os.rename(os.path.join(cfg.userdir,filename), os.path.join(cfg.userdir,newname) . . . . . . # somewhere in the dark recesses of a large project... . . . cleanup_filenames(cfg.userdir) . . . . . . # in another dark corner... . . . cleanup_filenames(cfg.tempdir) . . . # somewhere else... . . . cleanup_filenames(cfg.extradir) . . . ----------8<------------ Even in this small, contrived example, we've saved about 13 lines of code (ok, that's notwithstanding the blank lines and the """ docstring """ at the top of the function). There's another twist, too. In the docstring for cleanup_filenames it says "Does not walk the directory tree." because we didn't code it to deal with subdirectories. But we could, without using os.walk... Directories form a tree structure, and the easiest way to process trees is by using /recursion/, which means functions that call themselves. An old programmer's joke is this: Recursion, defn. [if not understood] see Recursion. Each time you call a function, it gets a brand new environment, called the 'local scope'. All variables inside this scope are private; they may have the same names, but they refer to different objects. This can be really handy... ----------8<------------ def cleanup_filenames(dir): """ renames any files within dir that contain bad characters (ie. ones in cfg.badchars). Walks the directory tree to process subdirectories. """ for filename in os.listdir(dir): newname = filename for ch in cfg.badchars: newname.replace(ch,"-") if newname != filename: os.rename(os.path.join(cfg.userdir,filename), os.path.join(cfg.userdir,newname) # recurse if subdirectory... if os.path.isdir(os.path.join(cfg.userdir,newname)): cleanup_filenames(os.path.join(cfg.userdir,newname)) ----------8<------------ This version *DOES* deal with subdirectories... with only two extra lines, too! Trying to write this without recursion would be a nightmare (even in Python). A very important thing to note, however, is that there is a HARD LIMIT on the number of times a function can call itself, called the RecursionLimit: ----------8<------------ >>>n=1 >>>def rec(): n=n+1 rec() >>>rec() . . . (huge traceback list) . . . RuntimeError: maximum recursion limit reached. >>>n 991 ----------8<------------ Another very important thing about recursion is that a recursive function should *ALWAYS* have a 'get-out-clause', a condition that stops the recursion. Guess what happens if you don't have one ... ;-) Finally (at least for now), functions also provide a way to break down your code into logical sections. Many programmers will write the higher level functions first, delegating 'complicated bits' to further sub-functions as they go, and worry about implementing them once they've got the overall algorithm finished. This allows one to concentrate on the right level of detail, rather than getting bogged down in the finer points: you just make up names for functions that you're *going* to implement later. Sometimes, you might make a 'stub' like: def doofer(dooby, doo): pass so that your program is /syntactically/ correct, and will run (to a certain degree). This allows debugging to proceed before you have written everything. You'd do this for functions which aren't *essential* to the program, but maybe add 'special features', for example, additonal error-checking or output formatting. A sort of extension of the function idea is 'modules', which make functions and other objects available to other 'client' programs. When you say: import os you are effectively adding all the functions and objects of the os module into your own program, without having to re-write them. This enables programmers to share their functions and other code as convenient 'black boxes'. Modules, however, are a slightly more advanced topic. Hope that helps. -andyj From fredrik at pythonware.com Wed Jul 16 04:29:20 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2003 10:29:20 +0200 Subject: tkinter References: <3114992.1058316065@dbforums.com> Message-ID: "sprmn" wrote: > does anyone know of any sites with good tutorials on tkinter > on them? start here: http://www.python.org/topics/tkinter/ From tekkamangoogle at yahoo.com Thu Jul 31 13:30:51 2003 From: tekkamangoogle at yahoo.com (barry g) Date: 31 Jul 2003 10:30:51 -0700 Subject: Win32All InvokeTypes exception after upgrade Message-ID: When trying to upgrade my Win32All package from build 148, that came in the ActiveState install, to any of v150 thru v156 I start receiving an exception. It apparently is related to the "output arguments" in the ActiveX control's methods. If I leave the output parameters off I get the message at the bottom. If I fill the arguments the function performs happily. Am I missing some step or setting that makes the output parameters optional again? I could change all my code to supply dummy values, but we have a large enough number of COM controls and function calls that I'd prefer to maintain the old calling style if possible. obj.DeviceToLatLon(x,y,10,10) #works in either 148 or 156 (35.453, -75.2214) obj.DeviceToLatLon(x,y) #used to return a tuple - now generates exception Traceback (most recent call last): File "ChartNotebook.py", line 978, in OnMouseMove lat, lon = obj.DeviceToLatLon(x, y) File "C:\Python22\lib\site-packages\win32com\gen_py\8754AEB3-1466-11D4-A779-0050DA6B8675x0x1x2.py", line 62, in DeviceToLatLon return self._oleobj_.InvokeTypes(37, LCID, 1, (24, 0), ((3, 0), (3, 0), (16389, 0), (16389, 0)),x, y, lat, lon) com_error: (-2147352571, 'Type mismatch.', None, 3) Thanks, Barry From bdelmee at advalvas.REMOVEME.be Sat Jul 12 09:40:18 2003 From: bdelmee at advalvas.REMOVEME.be (Bernard Delmée) Date: Sat, 12 Jul 2003 15:40:18 +0200 Subject: Old post about XML overhyped References: Message-ID: <3f100fe2$0$6529$afc38c87@sisyphus.news.be.easynet.net> > i'm googling for an old post appeared here about XML overhyped. Could you possibly be referring to this here thread: http://mail.python.org/pipermail/python-list/2003-June/169716.html Cheers, Bernard. From martin at v.loewis.de Sun Jul 20 16:56:47 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Jul 2003 22:56:47 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> Message-ID: Alan Kennedy writes: > Hmm, I fail to see the connection here. Fair enough, I made a mistake > in structuring my original xml snippet. I didn't attempt to address > the fact there are still some browsers out there that don't do XML. You should consider that this is Usenet, though (atleast for those of use who read comp.lang.python instead of python-list at python.org). I don't even use a Web browser to read your message, or to reply to it. And I definitely don't want to have HTML in email or usenet messages, since my software cannot display it at all. Regards, Martin From mwilson at the-wire.com Sun Jul 6 11:05:35 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 06 Jul 2003 11:05:35 -0400 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: In article <3F082031.3010503 at netscape.netNOTthisBIT>, Donald 'Paddy' McCarthy wrote: >Charles Shannon Hendrix wrote: >> Python uses it for actually determining the logic in your program, which >> IMHO is dangerous. >> >> if >> >> >> >> >> Is part of the if statement, or did someone with different >> tab settings from the author make a mistake and align it accidentally? >Well, no matter WHAT the language, I find tabs are evil little things >that introduce special cases and the need for code to handle them. >That said though, I find python block structure (sans tabs), just fine >thanks. The C equivalent is to hide a `;}` in the middle of what looks like a huge function call. >It would be nice if tabs as indentation for Python was deprecated but >failing that, If you don't use tabs, its wonderful. If you only use tabs it's also wonderful. The worldwide Python community has settled on spaces. I expand tabs in any code I share with the world, and everybody seems happy. Regards. Mel. From appleseed-cast at breathe.com Wed Jul 2 12:46:32 2003 From: appleseed-cast at breathe.com (paul h) Date: 2 Jul 2003 09:46:32 -0700 Subject: what is self? Message-ID: <6071d159.0307020846.7653afaa@posting.google.com> hi there, i've been programming cgi with python for a couple of months now, and i am now moving into some gui programming, using pygtk2. looking into the code, i see a lot of references to "self" ie self.window = ... however, i have no idea what self is? can anyone enlighten me... thanks very much... -- paul From proto at panix.com Sat Jul 12 15:37:34 2003 From: proto at panix.com (Walter Bushell) Date: Sat, 12 Jul 2003 15:37:34 -0400 Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: <1fxzcfa.1hreb3q17skz74N%proto@panix.com> John Roth wrote: > "Abigail" wrote in message > news:slrnbgt6ls.ab5.abigail at alexandra.abigail.nl... > > Walter Bushell (proto at panix.com) wrote on MMMDC September MCMXCIII in > > : > > ++ Charles Richmond wrote: > > ++ > > ++ > int *p, x, y; > > ++ > > > ++ > then: > > ++ > > > ++ > y = x/*p; > > ++ > > > ++ > is quite different from: > > ++ > > > ++ > y = x / *p; > > ++ > > > ++ > The first way, "/*" will begin a comment...the second way, > > ++ > you get the integer "x" divided by the integer pointed to by "p". > > ++ > > ++ Ouch!! That is one reason code coloring is *important*. > > > > Nope. That's a reason why code colouring is evil. If you write code, > > and it isn't clear what you mean without the use of code colouring, > > you did something wrong. Your code shouldn't rely on a specific code > > colouring scheme to be understandable. > > This assumes that someone reading the code is going to be using > a brain-dead editor. We need to get beyond that some day, and > assume that people are going to be using decent tools. > > John Roth Of course, we have to consider color blind programmers. Well we shouldn't have a single space making such a difference, particuarly when white space does not usually matter, in an arithmetic s tatement no less. Division by the integer pointer to by p and the beginning of a comment in something that is rather large. Something like this y = x/*p++ +expression; Above will be caught usually by results I presume However, how strings are implemented in quoted strings and the standard library is a nightmare. > > > > All in my opinion of course. > > > > > > Abigail -- The last temptation is the highest treason: To do the right thing for the wrong reason. --T..S. Eliot Walter From harrisonrj at ornl.gov Tue Jul 15 23:43:04 2003 From: harrisonrj at ornl.gov (Robert Harrison) Date: 15 Jul 2003 20:43:04 -0700 Subject: c/c++ implementation of python base and derived class Message-ID: <521f96c7.0307151943.7d987b2@posting.google.com> Can anyone point me to an example of how, in C or C++, to 1) implement a new-style Python class, and 2) derive another new class from it? I think that I've managed to do 1) correctly, but 2) eludes both me and google. Thanks in advance Robert From ianb at colorstudy.com Fri Jul 25 13:48:19 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 12:48:19 -0500 Subject: path module In-Reply-To: <11234c14.0307211016.344d40bc@posting.google.com> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <1059155299.28090.10746.camel@lothlorien> On Mon, 2003-07-21 at 13:16, Jason Orendorff wrote: > Ian and Holger wondered why 'path' should subclass 'str'. It's because > a path is a string. Benefit: you can pass 'path' objects to functions > that expect strings (like functions in 'win32file'). I find this > really useful in practice. I feel like this would lead to some annoying behavior in some circumstances. Most particularly, I'm thinking of: def dosomething(file): if type(file) is type(""): file = open(file) ... This isn't uncommon in functions that take pathnames or file objects. While isinstance(path, str) works, it was not an option until 2.2. So you'd be forced to do str(pathname) sometimes anyway, to deal with this. Ideally, interfaces would be changed to use a .open() method on the path instead of opening the string representation (as Holger's implementation does), so in the long term it would be nice to abandon direct string representations entirely. It would also make it more clear when you had a real path object and when you just had a string. Ian From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 7 14:05:48 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 07 Jul 2003 20:05:48 +0200 Subject: looking for UDP package, network programming guidance In-Reply-To: References: Message-ID: <3f09b678$0$49113$e4fe514c@news.xs4all.nl> Tom Plunket wrote: > running, but now the stumbling block comes up that Python doesn't > seem to have any UDP handling built into its distribution. You didn't look hard enough. Check out the SocketServer module: http://www.python.org/doc/current/lib/module-SocketServer.html Also, what *exactly* do you mean by "UDP handling"? Python is perfectly capable of creating and using sockets for the TCP *and* UDP protocols. > Additionally, the networking protocol is a fixed format packed > bytes sort of thing; is it easy enough in Python (with Twisted) > to read bytes off of the stream and then decide what to do with > them? (I'm a Python newbie but somewhat of a C++ pro.) It should be fairly easy to decypher the binary protocol using the array or struct modules: http://www.python.org/doc/current/lib/module-array.html http://www.python.org/doc/current/lib/module-struct.html You might also want to read the Python-socket-programming-howto: http://www.amk.ca/python/howto/sockets/sockets.html I generally find it much easier to do network/socket related stuff in Python than in other languages such as C or Java. If you still encounter difficulties, don't hesitate to post! --Irmen de Jong From gh at ghaering.de Fri Jul 18 06:35:38 2003 From: gh at ghaering.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jul 2003 12:35:38 +0200 Subject: Using Unicode scripts In-Reply-To: <3f17c520$0$7194$626a54ce@news.free.fr> References: <3f17c520$0$7194$626a54ce@news.free.fr> Message-ID: <3F17CD7A.2010507@ghaering.de> yzzzzz wrote: > Hi, Hi "yzzzzz", > I am writing my python programs using a Unicode text editor. The files are > encoded in UTF-8. Python's default encoding seems to be Latin 1 (ISO-8859-1) > or maybe Windows-1252 (CP1252) which aren't compatible with UTF-8. > > For example, if I type print "?", it prints ??. If I use a unicode string: > a=u"?" and if I choose to encode it in UTF-8, I get 4 Latin 1 characters, > which makes sense if the interpreter thinks I typed in u"??". > > How can I solve this problem? You might want to read the thread on this list/newsgroup I started yesterday called "Unicode problem" Is it feasible for you to upgrade to Python 2.3? If so I'd recommend you do it already. 2.3 is pretty close to release now and it has support for source files in Unicode format. If your Unicode editor saves the text file with a BOM (it should) then under Python 2.3 your scripts will work as expected. > Thank you > > PS. I have no problem using Unicode strings in Python, I know how to > manipulate and convert them, I'm just looking for how to specify the default > encoding for the scripts I write. See http://www.python.org/peps/pep-0263.html This is how it is implemented in Python 2.3. -- Gerhard From jane.doe at acme.com Thu Jul 24 15:00:43 2003 From: jane.doe at acme.com (Jane Doe) Date: Thu, 24 Jul 2003 21:00:43 +0200 Subject: [newbie] MySQL : How to check if no row returned? Message-ID: <5ua0ivcl3loh45cq6pnoimsoa86nt0q4db@4ax.com> Hi (newbie, please don't flame, thank you :-)) I browsed through the archives of this site, but I didn't see how to check if a SELECT through the MySql module returns an empty set (whether a row exists or not, the "else" part below is always called). Here's what I tried (using the CherryPy framework): CherryClass MyDb2(MySql): function: def __init__(self): self.openConnection('localhost', 'root', 'test', 'mydb') [...] # txtClient is returned by an HTML form myarray = myDb2.query("select * from clients where name='" + kw['txtClient'] + "'") # Never empty!!! if myarray == None: res+="No client found." else: res+=self.myview(myarray) Any tip much appreciated Thank you JD. From tomg at em.ca Thu Jul 17 12:48:55 2003 From: tomg at em.ca (Tom Goulet) Date: Thu, 17 Jul 2003 16:48:55 -0000 Subject: hex to signed integer References: <9j6chvoep7k34fbqutvp364lghnmmohrsj@4ax.com> Message-ID: Tim Roberts wrote: > Tom Goulet wrote: >>I want to convert a string of hexadecimal characters to the signed >>integer they would have been before the statement converted >>them. How do I do this in such a way that is compatible with Python >>versions 1.5.2 through 2.4, and not machine-dependent? > if hexbit[0] < '8': > temp = int(hexbit,16) > else: > temp = int(long(hexbit,16)-2**32) The function takes only one argument in Python 1.5.2. -- Tom Goulet, tomg at em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html From clausd at io.dk Tue Jul 8 03:45:46 2003 From: clausd at io.dk (Claus D) Date: Tue, 08 Jul 2003 09:45:46 +0200 Subject: Europython recordings? Message-ID: Did anyone record the europython sessions? Apparently, Hunter hasn't recieved a single reply from his effords to coordinate this... /cd From martin at v.loewis.de Thu Jul 31 02:29:26 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2003 08:29:26 +0200 Subject: Python speed vs csharp References: Message-ID: Mike writes: > My first question is, why is the Python code, at 210 seconds, so much > slower? One would have to perform profiling, but in this case, it is likely because numbers are objects in Python, so each multiplication results in a memory allocation. In addition, as soon as the parameters of the multiplication are not needed anymore, you get a deallocation of the temporaries. There is also an overhead for the byte code interpretation, but this is likely less significant. > My second question is, is there anything that can be done to get Python's > speed close to the speed of C#? C# implementations typically do just-in-time compilation to machine code. They represent numbers as primitive (machine) values, directly using machine operations for the multiplication. Doing the same for Python is tricky. I recommend that you try out Python 2.3. It has significantly improved memory allocation mechanisms, so you should see some speed-up. You could also try Psyco, which is a just-in-time compiler for Python. It should give very good results in this case, also. Regards, Martin From duncan at NOSPAMrcp.co.uk Mon Jul 14 12:08:08 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 14 Jul 2003 16:08:08 +0000 (UTC) Subject: Accessing an instance's __init__ args from outside the class References: Message-ID: "Alexander Eberts" wrote in news:sfAQa.21645$O55.673402 at wagner.videotron.net: > Is there any way to find out what arguments an object was called > with? Not in general. > Are the args stored with the instance? It depends on the object type. Some objects may save some or all of the arguments to the constructor, but it is up to each object to decide what to do with its arguments. If you create your own class, and want to be able to refer to the __init__ arguments after returning from __init__, then you must save the arguments in the object. So, for your original example you could do: >>> class Foo: def __init__(self, *args): self.args = args print args # no problem here >>> someobj = Foo('bar', 'bleck') ('bar', 'bleck') >>> someobj.args ('bar', 'bleck') -- 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 jack at performancedrivers.com Sun Jul 13 17:16:55 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Sun, 13 Jul 2003 17:16:55 -0400 Subject: anything like C++ references? In-Reply-To: <1058126738.28456.424.camel@lothlorien>; from ianb@colorstudy.com on Sun, Jul 13, 2003 at 03:05:38PM -0500 References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien> Message-ID: <20030713171654.A1005@localhost.localdomain> On Sun, Jul 13, 2003 at 03:05:38PM -0500, Ian Bicking wrote: > On Sun, 2003-07-13 at 14:39, Stephen Horne wrote: > > The fact is that 'assignment' has a common meaning separate from the > > choice of programming language, > > This just isn't true. The C++ assignment operator is not at all like > the Python assignment statement. Python variables are not like C++ > variables, no surprise assignment is different too. If you used > languages outside of C++ and its like (e.g., Pascal), you would find > Python's behavior common. > C++ is the only language that has the same semantics as C++. I was a long time C++ guy and my a-ha moment was when I realized that the GoF's "Design Patterns" were not all universal -- some are C++ specific. Trying to force Python semantics into a C++ world view will leave you feeling empty every time. Drink the koolaid, python has a short learning curve. If this is a problem - whatever you do - DONT TRY TO LEARN LISP. If you want a more polished C++, use Java. Python is in a different class of languages. -jack From mwilson at the-wire.com Wed Jul 16 17:01:23 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 16 Jul 2003 17:01:23 -0400 Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> <20030716132455272-0600@news.xmission.com> Message-ID: In article <20030716132455272-0600 at news.xmission.com>, Adam Ruth wrote: >As a side note, I wouldn't have thought that the augmented assign would >work the way you tried to use it. I would have thought that it would be >analagous to the + operator and sequences: > >> x = [1,2,3] >> y = [1,2,3] >> x + y >[1,2,3,1,2,3] > >So that the agumented form would be: > >> x = [1,2,3] >> x += [1,2,3] >[1,2,3,1,2,3] > >But I've never tried it before and didn't know that it didn't work with >sequences. You learn something new every day. It does: >>> def multi(): ... return 4, 5, 6 ... >>> a = (1,2,3) >>> a += multi() >>> a (1, 2, 3, 4, 5, 6) It seems to be just that += refuses to work with tuple unpacking. Regards. Mel. From and-google at doxdesk.com Sat Jul 5 14:07:53 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 5 Jul 2003 11:07:53 -0700 Subject: Python's CGI and Javascripts uriEncode: A disconnect. References: Message-ID: <2c60a528.0307051007.bc1c98b@posting.google.com> Elf M. Sternberg wrote: > Netscape (and possibly even earlier browsers like Mosaic) used the > plus symbol '+' as a substitute for the space in the last part of > the URI This is correct in a query parameter. eg. in ...?foo=abc+def, the symbol is a space. This is part of the specification for the media type application/x-www-form-urlencoded, defined by HTML itself (section 17.13.4.1 of the 4.01 spec). This states that spaces should normally be encoded as '+', however really using '%20' is just as good and causes less confusion, so that's what newer browsers (and I) do. Elsewhere, spaces should not be encoded as '+'. The reasoning for this initial decision is unclear - presumably it is intended to improve readability, but URIs with query parts are generally not going to be very readable anyway. > The ECMA-262 "Javascript" standard now supported by both Netscape and > Internet Explorer honor RFC 2396, translating spaces into their hex > equivalent %20 and leaving pluses alone. Depends which function you are talking about. The 'escape' and 'encodeURI' built-in functions are not designed to encode single URI query parameter values, they're designed to encode larger chunks of URI. As such they do not need to encode plus characters. The encodeURIComponent function *does*, and it is this function that you should use if you want some JavaScript code to submit a query parameter. The only drawback is that encodeURIComponent is relatively new, so you won't find it on medium-old browsers like Netscape 4 and IE 5.0. (The same goes for encodeURI - you only get 'escape' in older browsers.) > The Python library cgi.FieldStorage decodes it backwards, expecting > pluses to be spaces and %2b to represent pluses. The Python library is correct per spec. If your scripts are not encoding plus symbols in query parameters to %2B, they are at fault (and will go equally wrong in any other language). Possible solutions: a. use encodeURIComponent() instead. This is best, but won't work universally. b. use escape(), then replace any pluses in its output with %2B. This is OK, but won't handle Unicode properly or predictably. (note: in IE, encodeURI() also fails to handle Unicode predictably.) c. roll your own encodeURIComponent function. It's a bit off-topic for c.l.py, but here's a (c.)-style solution I've used before: function encPar(wide) { var narrow= encUtf8(wide); var enc= ''; for (var i= 0; i>>4)+encHex2_DIGITS.charAt(v&0xF); } var encHex2_DIGITS= '0123456789ABCDEF'; function encUtf8(wide) { var c, s; var enc= ''; var i= 0; while(i=0xDC00 && c<0xE000) continue; if (c>=0xD800 && c<0xDC00) { if (i>=wide.length) continue; s= wide.charCodeAt(i++); if (s<0xDC00 || c>=0xDE00) continue; c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000; } // output value if (c<0x80) enc+= String.fromCharCode(c); else if (c<0x800) enc+= String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F)); else if (c<0x10000) enc+= String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F)); else enc+= String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F), 0x80+(c>>6&0x3F),0x80+(c&0x3F)); } return enc; } if that's of any use. Kind of sucks having to do this, eh? -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From m at moshez.org Thu Jul 24 17:51:48 2003 From: m at moshez.org (Moshe Zadka) Date: 24 Jul 2003 21:51:48 -0000 Subject: SSH and Windows In-Reply-To: <3F20353C.1090004@blueapples.org> References: <3F20353C.1090004@blueapples.org> Message-ID: <20030724215148.22651.qmail@green.zadka.com> On Thu, 24 Jul 2003, Isaac Raway wrote: > I'm looking for a library > that behaves similarly to telnetlib for SSH connections. ... > Windows ... Well, Twisted has conch which is ssh implemented in Python, but it's API is not much like telnetlib. In order to use it, you'll want to compile PyCrypto. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From mcfletch at rogers.com Sat Jul 19 11:49:25 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 19 Jul 2003 11:49:25 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <2259b0e2.0307190640.56266017@posting.google.com> References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: <3F196885.4050606@rogers.com> Michele Simionato wrote: ... >I agree with Bengt, from your traceback it seems you are assigning directly >to client.__dict__, but you cannot do that (I think because client.__dict__ >is a dictproxy object and not a real dictionary). The right way to >go is via object.__setattr__ , or type.__setattr__ in the case of >metaclasses. > Try this to see what I'm getting at: >>> class o(object): ... class p( object ): ... def __set__( self, client, value, *args, **named ): ... print '__set__', self, client, value, args, named ... # now what do you do here to set without triggering ourselves ... # (without having to code diff versions of the descriptor class ... # for each possible type of client object (and for that matter, just ... # making it possible for (meta-)types with properties w/out requiring ... # e.g. a new dict object in each such serviced type))?. ... return object.__setattr__( client, "v", value) ... v = p() ... >>> s = o() >>> s.v = 3 You'll notice you go into an infinite loop. What I'm looking for (really a thinly veiled attempt to get other people to demand it from Guido so he doesn't think I'm a lone crackpot ;) ) is a function/method that provides the default implementation of the get/set functionality *below* the level of the descriptor hooks, but high enough that it can deal with the differences between classes, types, instances, and instances-with-__slots__ (I realise that last one probably isn't going to work, BTW). Thought of another way, it's asking for a superclass of descriptors which provides this logic in such a way that, by sub-classing from them, you can readily gain access to this descriptor-building functionality without needing to always use it, and without introducing unwanted restrictions (such as requiring a property-class initialisation). Thought of another way, it's asking for a further rationalisation of the get/set hooks so that there's a lower level at which you can either insert storage code *or* use the default storage code. >I guess you are aware of the metaclass+properties recipes in the >on-line cookbook, but just in case ... > Hadn't looked at them, have now, there's nothing which addresses this particular issue that I can see with a search for metaclass. Willing to be proved wrong :) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From robin at jessikat.fsnet.co.uk Mon Jul 14 04:03:19 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 14 Jul 2003 09:03:19 +0100 Subject: floating point control in extensions References: <92tOKLARvSE$Ewh9@jessikat.fsnet.co.uk> Message-ID: In article , Tim Peters writes ...... >Python itself assumes that no-stop mode is in effect (the IEEE-754 mandated >default: all FPU traps are disabled). > .... That at least makes resetting easy when one can do it. I guessed all Python floating point ops are tested either pre or post for the correct outcome, but then I tried >>> a=1e290 >>> a 1.0000000000000001e+290 >>> a*a1.#INF >>> so I suppose only the obvious things are tested. -it's hard being an fpu'ly yrs- Robin Becker From skip at pobox.com Fri Jul 25 16:05:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Jul 2003 15:05:10 -0500 Subject: Beefing up socket.ssl(...) In-Reply-To: References: <84e0f331.0307251036.6504b16a@posting.google.com> Message-ID: <16161.36214.435946.860897@montanaro.dyndns.org> Ed> From looking at Modules/socketmodule.c in 2.2.2 and 2.2.3, it Ed> appears that only a tiny bit of support for SSL has been added. Ed> Specifically, unless I'm misunderstanding the operation of the code, Ed> there's no way to verify the certificate presented by a server. Note that since 2.2.3 is just a bugfix release, you shouldn't expect any increase in functionality. I'm mildly surprised that you noticed any functional changes between 2.2.2 and 2.2.3. I suggest you take 2.3c2 out for a spin and see if it has more of the features you're after. (2.3final is due out by the end of the month.) In any case, if you have patches to submit, please use SourceForge and note that any functional improvements will be targetted at 2.4 at this point. You can find more about patch submission at the Patch Submission Guidelines page: http://www.python.org/patches/ Thx, Skip From pinard at iro.umontreal.ca Thu Jul 31 13:23:08 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 31 Jul 2003 13:23:08 -0400 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) In-Reply-To: References: <67fdivk9iu0q1p7nc8smfj1miip3cbvobf@4ax.com> Message-ID: [Fredrik Lundh] > Aahz wrote: > > (Despite my regular comments on python-dev, I don't contribute > > code because SF refuses to make changes to allow Lynx to work > > correctly.) > maybe someone with an SF account could help you out? Let me say (and probably repeat) that imposing Web browsers to users, or bug trackers with sorrow editing interfaces, and asking users to get acquainted with the classification system and various work idiosyncrasies of each and every maintainer, package by package, is insane. The result is that users have either to choose on which few packages they will specialise on, or else, to merely stop contributing. In the former case, a maintainer is building his own specialised crowd, which may be admittedly good for his project alone. In the latter case, a maintainer is pushing users away. But in all cases, this is an overall social lost. I miss the times when it was a simple matter to offer contributions, maybe humble and small, yet possibly numerous, to any package in sight. Maintainers praising want-to-be-sophisticated machinery should use it all their soul if they feel like it, but without forcing users into their bag. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From theincredibleulk at hotmail.com Tue Jul 8 06:50:55 2003 From: theincredibleulk at hotmail.com (=?ISO-8859-1?Q?=DAlfur_Kristj=E1nsson?=) Date: 8 Jul 2003 03:50:55 -0700 Subject: Embedding as scripting engine Message-ID: Python... a great language, no doubt. And the abillity to be able to extend it with C/C++ code, fantastic. But has anybody been able to successfully embed Python in their application to use it as a scripting language of sorts? I am in the process of writing a game and from the documentation and word of mouth gathered that Python would be just the thing for the scripting part. And sure enough it is easy enough to run Python code from C/C++. However, in order to be make it do something actually useful for my game it would be handy to be able to pass in anything besides the basic data types (strings, numerics) such as either an instance of or a pointer to a gameobject. What I want to be able to do is something like this: GameObject go; Py_Initialize() ... PyObject* po = GameObject2PyObject(go); ... result = PyObject_CallObject(func, "O", po ); ... go = PyObject2GameObject(result); Theres alot of documentation and discussion out there that suggests that this should be possible but noone seems to tell you how it's actually done. Am I just missing something blatantly obvious? Thanks //ulk From nushin2 at yahoo.com Wed Jul 23 21:56:28 2003 From: nushin2 at yahoo.com (nushin) Date: 23 Jul 2003 18:56:28 -0700 Subject: How to disable output messages of the child process, in spawnv( )? References: <3f1eddc9$0$160$a1866201@newsreader.visi.com> Message-ID: Is there any trick to disable the output of a child process spawned by spawnv( ) API? I believe in Python and i am sure there's a way around it. Correct me if i am wrong. Regards, Nushin (BB) grante at visi.com (Grant Edwards) wrote in message news:<3f1eddc9$0$160$a1866201 at newsreader.visi.com>... > In article , nushin wrote: > > I'd like to disable the output of the process spawned by spawnv( ) > > API, but the catch is that i *have to* see the output of the parent > > process making the spawnv( ) call. Has anyone done that? I have some > > pointers that by using dup2( ) API i might be able to do that, any > > ideas how? Also, i have to spawn as an asynch call, using P_NOWAIT, > > e.g.,: > > > > os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) > > Nope. > > The ">" and "&" are things that a shell (like bash or ksh) > handles. The python interpreter has no idea what to do with > them. If you want to use ">" and "&", then spawn a shell, and > pass it a command to run the python program with output > redirected. From sjmachin at lexicon.net Fri Jul 18 19:27:25 2003 From: sjmachin at lexicon.net (John Machin) Date: 18 Jul 2003 16:27:25 -0700 Subject: "\n" in ASCII-file References: Message-ID: Gerhard H?ring wrote in message news:... > Martin P wrote: > > Hello, > > > > for a short exercise-program I have to read the lines in an ASCII-file. > > > > But every line has a new-line-feed ("\n") at the end of the line. (The > > ASCII-file was made with Windows Notepad). > > Is this only because I used Windows (and Notepad)? > > Yes. > I don't understand Gerhard's answer, given the word "only" in the OP's question. A file created in the manner described will actually have ASCII CR LF (carriage return, line feed) at the end of each line. On Unix, the usual methods of creating a text file will end lines with only LF. On a Macintosh, only CR. In all of the 3 above cases, lines read by the usual Python methods will have the line terminator translated if necessary to LF i.e. "\n". So, typical text files created on Windows AND Unix will actually have "\n" at the end of each line, NOT only Windows. Lines read in the usual fashions by Python from typical text files created on Windows AND Unix AND Macintosh will (appear to) have "\n" at the end, NOT only windows. From gerrit.muller at embeddedsystems.nl Mon Jul 21 04:30:14 2003 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Mon, 21 Jul 2003 10:30:14 +0200 Subject: Python voting demo discussion References: Message-ID: <3F1BA496.6080305@embeddedsystems.nl> Alan Dechert wrote: <...snip...> > Ian Bicking and Andrew Dalke did say they thought Python should be fine for > the demo but I didn't get much detail about why we should prefer it over > some of the other possibilities: HTML, XML, Perl, Java, PHP, C, C++, C#, C, > etc. <...snip...> The open door answer is that this type of problem can be implemented with a low effort in Python, because of: + the large amount of available well working packages, such as storage, networking etcetera + the low amount of syntactic overhead It might well be that you combine a few of the options you mention: do you store in an optimized format (binary pickle: very fast and compact), or XML (rather bloated, but human and machine readable by any application). Python does support these hybrid applications very well, allowing you to explore multiple options in your prototype. Java, C, C++ and C# will require siginificantly more lines of code and effort to make. In the end these implementationsmight be faster, but I don't see any performance problem at all in your application, even on old and slow commodity PC's. Perl might do the job, has the same benefits as mentioned above. However in this newsgroup you will get the consistent answer that Python will result in readable solutions and therefor updateable and maintainable (even an issue for prototyping!), while Perl is not readable :-) PHP and (D)HTML are other approaches, focusing more on the UI part of the problem. My own work on HTML is always generated by Python scripts :-). The only missing option is Visual Basic. Again in this newsgroup the verdict will be the same: Python will solve it with low effort and readable result, while VB quickly becomes a mess :-) In fact the main recommendation is: simply start in Python. You should have something (very simple) working within 1 (one) day, with improved implementation following quickly. The importance of having something working in one day is to get the iteration going over all different requirement aspects and design choices. Ah, tis is my hobbyhorse, see a.o. (very long links, will be broken by most newsreaders!) http://www.extra.research.philips.com/natlab/sysarch/ArchitecturalReasoningBook.pdf on page http://www.extra.research.philips.com/natlab/sysarch/ArchitecturalReasoning.html regards Gerrit -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From ffrederik at gmx.de Mon Jul 28 09:29:23 2003 From: ffrederik at gmx.de (Frederik) Date: 28 Jul 2003 06:29:23 -0700 Subject: freeze or something else for stand-alone-bins Message-ID: Hello, in Python 2.2.2 on Windows I cant find the freeze.py program anymore. On my Linux-machine it?s still in tools - examples. Where can I find it? Or can you recommend me anything else for creating stand-alone-binaries? Thanks, Frederik From tim at remove_if_not_spam.digitig.co.uk Wed Jul 16 11:54:14 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Wed, 16 Jul 2003 16:54:14 +0100 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> <3f152bb4$1@mail.hmgcc.gov.uk> Message-ID: On Wed, 16 Jul 2003 11:40:52 +0100, "richardc" wrote: >Should we have the 'Python programming red book' (blue cover), and the >'Python pocket reference' (a 3000 page tome of a reference book). All about pockets, of course. From max at alcyone.com Wed Jul 9 18:11:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Jul 2003 15:11:41 -0700 Subject: ANN: EmPy 3.0.3 -- A powerful and robust templating system for Python Message-ID: <3F0C931D.C1DDF379@alcyone.com> Overview EmPy is a system for embedding Python expressions and statements in template text; it takes an EmPy source file, processes it, and produces output. This is accomplished via expansions, which are special signals to the EmPy system and are set off by a special prefix (by default the at sign, '@'). EmPy can expand arbitrary Python expressions and statements in this way, as well as a variety of special forms. Textual data not explicitly delimited in this way is sent unaffected to the output, allowing Python to be used in effect as a markup language. Also supported are callbacks via hooks, recording and playback via diversions, and dynamic, chainable filters. The system is highly configurable via command line options and embedded commands. Expressions are embedded in text with the '@(...)' notation; variations include conditional expressions with '@(...?...!...)' and the ability to handle thrown exceptions with '@(...$...)'. As a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@function(arguments)', '@sequence[index]', and combinations. Full-fledged statements are embedded with '@{...}'. Control flow in terms of conditional or repeated expansion is available with '@[...]'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing string concatenations and line continuations. Comments are indicated with '@#' and consume the rest of the line, up to and including the trailing newline. '@%' indicate "significators," which are special forms of variable assignment intended to specify per-file identification information in a format which is easy to parse externally. Context name and line number changes can be done with '@?' and '@!' respectively. Escape sequences analogous to those in C can be specified with '@\...', and finally a '@@' sequence expands to a single literal at sign. Getting the software The current version of empy is 3.0.3. The latest version of the software is available in a tarball here: http://www.alcyone.com/pyos/empy/empy-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/empy/. Requirements EmPy should work with any version of Python from 1.5.2 onward. It has been tested with all major versions of CPython from 1.5 up, and Jython from 2.0 up (using Java runtimes 1.3.0 and 1.4.1). The included test script is intended to run on Unix-like systems with a Bourne shell. License This code is released under the GPL. ... Release history [since 3.0] - 3.0.3; 2003 Jul 9. Fix bug regarding recursive tuple unpacking using '@[for]'; add 'empy.saveGlobals', 'empy.restoreGlobals', and 'empy.defined' functions. - 3.0.2; 2003 Jun 19. '@?' and '@!' markups for changing the current context name and line, respectively; add 'update' method to interpreter; new and renamed context operations, 'empy.setContextName', 'empy.setContextLine', 'empy.pushContext', 'empy.popContext'. - 3.0.1; 2003 Jun 9. Fix simple bug preventing command line preprocessing directives (-I, -D, -E, -F, -P) from executing properly; defensive PEP 317 compliance. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You are my martyr / I'm a vestige of a revolution \__/ Lamya From max at alcyone.com Sat Jul 12 07:12:24 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 04:12:24 -0700 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> <3F0FD848.849E5D88@engcorp.com> Message-ID: <3F0FED18.E88DC91A@alcyone.com> Peter Hansen wrote: > This is probably an example of an error promoted by leaving the > redundant "raise Class,args" form of exception-raising in Python, > instead of having a single obvious way: "raise Class(args)" as > would be more Pythonic. ;-) But, as I recall, PEP 317 was outright rejected, so it looks like this will be with us for a long time. I personally have never had a problem with the distinction, raise C, x always seemed fairly clean to me even though really what you mean is raise C(x). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I want a martini that could be declared a disaster area. \__/ Capt. Benjamin "Hawkeye" Pierce From sebastien.hugues at swissinfo.org Fri Jul 11 04:40:13 2003 From: sebastien.hugues at swissinfo.org (sebastien.hugues) Date: Fri, 11 Jul 2003 10:40:13 +0200 Subject: Windows XP - Environment variable - Unicode Message-ID: <3f0e77fc@epflnews.epfl.ch> Hi I would like to retrieve the application data directory path of the logged user on windows XP. To achieve this goal i use the environment variable APPDATA. The logged user has this name: s?bastien. The second character is not an ascii one and when i try to encode the path that contains this name in utf-8, i got this error: Ascii error: index not in range (128) I would like to first decode this string and then re-encode it in utf-8, but i am not able to find out what encoding is used when i make: appdata = os.environ ['APPDATA'] Any ideas ? Thanks in advance Sebastien From max at alcyone.com Thu Jul 17 15:06:54 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 12:06:54 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: <3F16F3CE.2F928320@alcyone.com> Terry Reedy wrote: > Minor nit: 'register' is not a mandate, but an ignorable suggestion. > So a compiler either could or must ignore 'register' in able to make > '&x' possible. If the register keyword is present, then taking the address of the variable is illegal, _whether or not_ the compiler ultimately decides to turn the varible into a register. > Of course, the idea of ignorable keyword suggestion is itself somewhat > strange ;-) It's in precisely the same class as inline. They're optimization hints to the compiler. The implementation is under no obligation to honor any, some, most, or all of such hints. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You are my martyr / I'm a vestige of a revolution \__/ Lamya From ianb at colorstudy.com Fri Jul 25 13:45:33 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 12:45:33 -0500 Subject: path module In-Reply-To: <20030725184158.O6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> Message-ID: <1059155133.24478.10738.camel@lothlorien> On Fri, 2003-07-25 at 11:41, holger krekel wrote: > Yes, i think adding platform specific methods to a Path object makes sense. > A friend and me started working on (local and subversion) Path > implementations last week. Currently a Path instance provides > these "path-taking" methods > > open > read > write > visit (a recursive walker) > listdir > stat > load/save (unpickle/pickle object) > setmtime (set modification time, uses os.utime) I like read and write too -- I do: f = open(filename) contents = f.read() f.close() All the time (when I'm uninterested in streaming or performance, which is most of the time I deal with files). Or just open(filename).read() and let garbage collection fix it up, even if it seems a little messy. A single method to encapsulate that would be nice, and of course write gives symmetry. Hmmm... Jason's distinguishes bytes (binary) and text (which is potentially encoded). I kind of like that distinction. Jason had walkers both for all files, just non-directory files, and directory files. This seems useful to me, and by making it explicit I might just start distinguishing text from binary (which I don't now because I am forgetful). And a globbing walker, though I don't know how much of an advantage that would be over list comprehension. Actually, all his walkers have a globbing option. > apart from all the os.path.* stuff like 'exists', 'dirname' etc. > Providing these "path-taking" methods on the Path object is very important > because otherwise you'll have to convert back and fro for using those > os.* and os.path.* or builtin methods (which is evil). dirname is a good name, since it should return a path object, not a "name" (which to me implies a string). I think Jason's module uses a parent attribute, though it also supports dirname(), and a name attribute instead of basename() (though that does not return a path object). And things like dirname make less sense in some non-path situations, like a URL. Probably not too much renaming should occur, but at least a little may be appropriate. Ian From intentionally at blank.co.uk Mon Jul 14 21:15:25 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 02:15:25 +0100 Subject: anything like C++ references? References: Message-ID: On 14 Jul 2003 07:25:31 +0200, martin at v.loewis.de (Martin v. L?wis) wrote: >Stephen Horne writes: > >> >>>> a = ref(1) >> >>>> b = a >[...] >> >>>> a = 5 >> >>>> b >> >5 >[...] >> Well, during the 'debate', that's the basic idea that involved - >> except that I'd use explicit pointer-dereferencing syntax. > >This is a very bad idea. You want to create a reference to the object >1? Then I assume that assigning to "a" would *change* the value of 1? >But 1 is an immutable object, it cannot change! That is NOT what I said. I was saying that the basic idea is right, not the notation expressing it. I want pointers to be explicit as a data type. Besides, in my mind the notation... >> >>>> a = ref(1) ...creates a reference to an object which is initially bound to the value 1 and binds that object to the variable a. Variable a bound to anonymous object. Anonymous object bound to value 1. Reassigning to that object would merely rebind that object to another value. Immutability of values is preserved. Immutability of objects is not the same thing. Not my favoured notation, and of course I left Ians explanation of the problem with that notation quoted. >> Imagine, for instance, changing all assignments and other 'copying' to >> use a copy-on-write system. > >That assumes that there is the notion of copying values in the first >place. Objects, in general, don't support copying - and assignment has >nothing to do with copying. That is why 'copying' was in quotes. I merely wanted to indicate that parameter passing and such was included. >> >>> a = &5 >> >>> b = newcopyof a # could be "b = &(*a)" in principle >> >>> *b is *a >> False > >Again, objects don't support copying. For immutable objects (like >numbers), copying is also a pointless operation: If there where a >standard .copy method on objects, numbers would return themselves. You miss the point. Though it's partly my fault for a stupid mistake ("b = &(*a)" would not copy the object that *a refers to, it would merely rederive the pointer which is rather pointless). It isn't about copying the value. It is about copying the representation of the value, or the object that is bound to that value. The fact that some objects can't be copied would simply become explicit and obvious. People couldn't end up thinking they are dealing with a separate copy just because they have two variables bound to that object. They couldn't have two variables bound directly to one object. They would either have to explicitly use pointers, or explicitly copy the object - and the latter wouldn't be possible for objects that don't support copying. Straight off, a common cause of confusion and errors would be removed. Write... x = classname() y = x ... and that would be an error. Although it wouldn't need a copy at that point, it implies the need to copy as soon either variable is used to make a change to the object. However... x = &classname() y = x ... and everything is fine. Both variables have been *explicitly* linked, via pointers, to the same object. There is no need to copy the object. Actually, there is an implementation issue there. 'x = classname()' does do an assignment, after all. It's only safe because copying of the object is avoidable. This claim can also be made of the second case - that claim only breaks down when that object is mutated by an access via one variable or another. A little fiddly, but not that difficult to fix. If each object knows how many times it is directly referenced (either by a variable, or by what I'll call a 'register' in expression evaluation) it can detect problems. It would have to do something similar, in fact, to do the copy-on-write when copying is implemented. This is something that C++ also gets wrong, IMO, because classes get copying operations (assignment, copy constructor) by default unless you do something to stop them. A shorthand for requesting a naive copy when appropriate seems better to me. >There is no way, in the language, to express that you want different >copies of the value 5. No - I was talking about a language change, and I was talking about copying representations. I want to be able to assume that the language implements binding of variables to values. I want a datatype that allows me a way of indirectly referencing objects - pointers, in other words. If I write... >>> a = 5 >>> b = newcopyof 5 >>> *b = 6 I don't expect the variable a to be affected. I have not changed the value 5 into the value 6, I have merely changed the value that is bound to an object. That object was created by copying another object, but that doesn't mean all objects have to be copyable. > This is completely different from the notion of >values in C or C++, where each occurrence of the literal 5 creates a >new value whose state is 5. Not true. Each occurence of the literal 5 creates a new 'symbol' which represents the value 5. The immutability of values is preserved in C++. From kj.kjn at wanadoo.fr Wed Jul 2 07:13:06 2003 From: kj.kjn at wanadoo.fr (kj.kjn) Date: Wed, 2 Jul 2003 13:13:06 +0200 Subject: how to pass a file descriptor in a swig module Message-ID: My function func(File * des) is embedded in a module swig. I would to know how to call this function from python script and if it's necessay to declare a typemaps ? Thank you From vze4rx4y at verizon.net Thu Jul 24 23:56:56 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 25 Jul 2003 03:56:56 GMT Subject: recognizing empty iterators References: Message-ID: [Michele Simionato] > BTW, the fact that an empty iterator is True is somewhat strange, > considering that [],() and "" are False; on the other hand, generic > objects are True, so the point can be debated ... Requiring iterators to know whether they are empty *before* being called would be like from requiring them to know their length in advance (after all, the falsity of [] and () stems from their __len__() methods returning zero). Non-sequential access and the absence of a __len__() method are what give iterators their character. IOW, iterators are *supposed* to not be the same as sequences. Viva la difference. [Timothy Delaney] > It is impossible to know, in the general case, if an iterator is empty. > The primary reason for this is that many iterators are destructive > e.g. file iterators. A wrapper iterator can be used around a > destructive iterator that caches information, but that's about the > best you can do unless the iterator is resettable. > An iterator may in fact be conceptually empty at one instant, then > the next instant not be empty... > All it is possible to know is if an iterator has been exhausted > *for now* - and that is if it raises StopIteration. Technically this > does not mean that the iterator is permanently exhausted - it could > start returning values at a later date, but this would be very > confusing to people ;) Yes, it was. So, Guido decreed that once a iterator has returned StopIteration, it will continue to do so on subsequent calls to it.next(). Promptly, all of Python's iterators were modified to comply. IOW, iterators can and do stay "permanently exhausted". However, Tim is essentially correct in focusing on the "just-in-time" nature of iterators. Part of the core concept for iterators is to *not* know what lies ahead. Raymond Hettinger From alanmk at hotmail.com Mon Jul 21 18:51:58 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 21 Jul 2003 23:51:58 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> Message-ID: <3F1C6E8E.269B08EB@hotmail.com> Alan Kennedy: >> Solely because of technical inertia, and unwillingness to address >> the (perhaps excessive) complexity of our various communications >> layers, i.e. our own "Tower of 7-bit Babel", we're suppressing >> cultural diversity, for no technically valid reason. Ben Finney wrote: > Yes. The solutions must involve a significant sociological element, > since that is a large part of the current situation. The only point I would like to add is that I think all of our sociological situations are going change rather rapidly over the next few years. The business landscape has changed pretty radically over the last few years, I think it's going to change even more once global initiatives such EB-XML, etc, kick in. >> I personally don't have the slightest problem with reformulating >> NNTP and POP to use XML instead: In a way, I think it's almost >> inevitable, given how poor our existing "ascii" technologies are >> at dealing with i18n and l10n issues. Emails and usenet posts are >> all just documents after all. > > I've no idea, though, why you keep banging on about XML for simple, > plain-text documents. Substitute XML with UTF-8 in the above, and I > agree entirely. This is a problem of character encodings, yet you keep > wanting to apply a heavy, structural markup solution. That way lies > HTML/XML email, and it's totally unnecessary and unhelpful. You quite probably put all of your email through a virus scanner? If it's full nasty xml, why not put it through an XML transform instead, that removes the images/webbugs for example, or "downcasts" it to ASCII? It's just a stage in the processing chain. Write your own transform if you wish, it will interoperate seamlessly with your gateway processing software, regardless of implementation language. It's only XML. BTW, Bengt, Ihate thistoo. Ugh! > Email and NNTP are lightweight, freeform, unstructured document > formats, and they're good that way. POP and NNTP were great for what they were designed for: sending ascii messages in the age of uucp, uuencode, 2.4K modems, acoustic couplers and phone-phreakers. These days, there's so much protocol wrapping and unwrapping going on that mistakes happen all the time. Witness the wrong URIs episode today in "Python-URL". These days, you and I could probably have a reasonable telephone^H^H^H^H^H^H^H^H^H voice conversation over the net. You're in Australia (g'day) and I'm in Ireland. Should be only 0.3 to 0.5 second delay. I have a 256Kbit/1024Kbit connection. You? We have much more reliable connections now, and perhaps we need to focus a little more on what information we're sending, rather than how we're sending it. > Nothing you've said so far has offered even > a pretence of a reason for abandoning freeform text formats for > heavy, markup-oriented formats. In my simplistic view, I see an increasing requirement in the modern day for people requiring to communicate meaningfully with each other: to work together on complicated projects, across barriers of time zones. Working together requires good communications. But really achieving anything requires structuring ideas and information, and structuring ideas means (to me) either using the same software or forming a common framework within which to operate. In the wonderfully diverse world of open source, interoperability among diversity is a highly desired quality, i.e. everybody uses their own preferred combination of software. I see XML as offering a simple way to form those same common frameworks, which will allow NON-technical people to work together on structuring and coordinating their efforts, and to also enjoy the benefits of interoperability among diversity. It will allow the less IT-literate PhDs in microbiology, medical science, genomics, renewable energy, anthropology, etc, etc, etc, to better coordinate their efforts. I expect an explosion of data interchange among non-IT scientists, now that all the serious office packages, i.e. Microsoft and Open*Office, are using XML as their formats. All the world's data, suddenly free(-ish) to move between software and and between people and their preferences. The kind of protocols we need in the modern day are protocols like UDDI: Universal Description and Discovery of Web Services. http://www.uddi.org/ And I expect that 99% of the time, people who use UDDI services will never see an angle-bracket, publishing or subscribing. But if they want to become publishers on minimal resources, they'll be able to simply put their IT together, using wonderful language tools such as python processing XML. No barrier, technical or financial, to entry. > Where character encoding is the problem, Unicode is the current best > solution. But that in no way necessitates a markup format. Let's tear down all the old copper wires, and replace them with microwave towers. They were an eyesore anyway ;-) regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From sybrenUSE at YOURthirdtower.imagination.com Thu Jul 17 07:15:57 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 17 Jul 2003 11:15:57 GMT Subject: Linux - python vs sh References: Message-ID: Krisztian Kepes enlightened us with: > I want to list my rpm database to file with this: Besides the answers you already got, you might like this too: > echo '>>>>>>>>>>>>>>>' >>$file > echo "$nr." >>$file > echo "Name: $rpmname" >>$file > echo "" >>$file > info=`rpm -qi $rpmname` > echo "$info" >>$file > echo "" >>$file can be re-written as: ( echo '>>>>>>>>>>>>>>>>' echo "$nr." echo "Name: $rpmname" echo rpm -qi $rpmname echo ) >> $file Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From corey.coughlin at attbi.com Mon Jul 28 17:57:51 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 28 Jul 2003 14:57:51 -0700 Subject: How safe is modifying locals()? References: <3TIUa.107401$XV.6252339@twister.austin.rr.com> Message-ID: Interesting thread here, I'm enjoying reading this. Of course, I know next to nothing about Visual Basic, so I don't know if I can really help all that much. But it doesn't sound like implementing something like pointers is that much trouble, just a matter of getting some syntax you like. Now if you were translating C into Python, I suspect you might need a more complicated pointer model. I mean, half the use of pointers in C is to iterate down simple arrays, like strings, so you'd have to make something more like this: class CStack(object): def __init__(): self.stack = [] self.names = {} def malloc(sizeinbytes, object_name): self.names[object_name] = len(self.stack) for i in range(sizeinbytes): self.stack.append(0) def pobj(pointer_index): return self.stack[pointer_index] def paddr(object_name): return self.names[object_name] or something like that, obviously this isn't fleshed out, but given the breathtakingly simple memory model of C, it should be a snap to code up in Python. Hmmm.... I wonder if the Python-In-Python people are trying anything like this to convert the C library code for CPython. Or would it even be worth it? I think I'll meditate on that...... From gradha at titanium.sabren.com Sun Jul 27 15:52:58 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sun, 27 Jul 2003 21:52:58 +0200 Subject: ANN: mailbox_date_trimmer 1.0.1 -- Correct emails' date headers in a mailbox archive. In-Reply-To: <20030726101506.GA1467@pedos.es> References: <20030726101506.GA1467@pedos.es> Message-ID: <20030727195258.GB20707@pedos.es> > Improved documentation. Removed stdin pipe detection hack. Many > small date parsing errors found and fixed after running the > program over 500 MB of mailing list archives. Just yesterday I ran the program over the python mail archives (http://mail.python.org/pipermail/python-list). 215144 messages in about 600MB, the program run for about 5 minutes, with the python process never going over 2.5MB of RAM. Only 117 messages were corrected, making the archive start the 2nd of april of 1999 and end, well, yesterday. It would be nice if the maintainer could fix the archive and regenerate the html pages, correcting spurious messages from the years 2014, 2009 or 1955. -- Please don't send me private copies of your public answers. Thanks. From lists at gregfortune.com Mon Jul 14 15:01:54 2003 From: lists at gregfortune.com (Greg Fortune) Date: Mon, 14 Jul 2003 12:01:54 -0700 Subject: Reloading nested modules References: Message-ID: I've wondered about the same problem and considered that as a solution, but never tested it. I assume that *wouldn't* rebind all of the imports that have already happened.. ie, I think the references to the old copies of the modules would hang around even though new ones have been imported. Regardless, the scoping doesn't work so an attempt to reload the embedded module assumes it is available in local scope and fails. Again, that would lead me to believe my first statement is true, but when I tested just now, I got no further than the scoping problem... I've been intended to write something that will take a module name and rebind it in all namespaces that have it currently, but haven't got around to it. If I ever do, I'll post it here :) Greg Martin v. L?wis wrote: > Andy Jewell writes: > >> Does anyone know of a way to dynamically reload all the imported >> modules of a client module? > > You could iterate over sys.modules and invoke reload for all of them. > > Regards, > Martin From trentm at ActiveState.com Thu Jul 24 12:40:28 2003 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 24 Jul 2003 09:40:28 -0700 Subject: Python and VS.Net In-Reply-To: ; from mgerrans@mindspring.com on Thu, Jul 24, 2003 at 12:16:25AM -0700 References: Message-ID: <20030724094028.L13644@ActiveState.com> [Matt Gerrans wrote] > "Trent Mick" wrote: > > > If your Python code could thereby access the .NET libraries, that > > > would be another story. That would be like Jython for .NET. I > > > was hoping that was what Active State's Python-in-VS.NET-thingy > > > was, but alas it was too good to be true: it is only (so far) a > > > color-syntaxing Python editor that takes two or three minutes to > > > load up. > > > > You are mixing up two difference ideas. ActiveState's VisualPython is a > > plugin for VS.NET to provide all the IDE stuff (like editting, > > debugging, interactive shell, help, intellisense, etc) for Python > > programmers. > > Uh, isn't that pretty much what I said? I don't think I mixed up the > ideas. I only said that what ActiveState's Visual Python was and what I > was originally hoping it would be were not the same. Okay, fair enough. It was my mistake in reading your post, then. Apologies, Trent -- Trent Mick TrentM at ActiveState.com From gh at ghaering.de Tue Jul 15 12:32:26 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 15 Jul 2003 18:32:26 +0200 Subject: delete file In-Reply-To: <2c6431ab.0307150743.7dd52f3f@posting.google.com> References: <2c6431ab.0307100711.780a65ad@posting.google.com> <3F0D962E.23DA9F59@engcorp.com> <2c6431ab.0307110529.7a336f30@posting.google.com> <3F0EBFED.BB283660@engcorp.com> <2c6431ab.0307150743.7dd52f3f@posting.google.com> Message-ID: <3F142C9A.8020800@ghaering.de> lamar_air wrote: > I am using this remove method and it works well as long as the file is > there > os.remove("C:\Inetpub\wwwroot\Cgi-bin\output.txt") > If the file doesn't exist then i get an error that the file is not > found. I want to stay away from using > f2=open('C:\Inetpub\wwwroot\Cgi-bin\output.txt', 'w') so how can i > check if the file exists first? if not os.path.exists("foo"): os.remove("foo") or just catch the error, with something like: try: os.remove("foo") except OSError, detail: if detail.errno != 2: raise This will ensure that only the "file not found case" is ignored, not for example the "insufficient permission" case. Not that I know where this error numbers comes from, I just experimented ;-) If anybody could tell me where I can find those error numbers without RTFMing myself I'd be grateful. -- Gerhard From fredrik at pythonware.com Mon Jul 14 17:09:31 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Jul 2003 23:09:31 +0200 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <1058214866.5032.1.camel@redwall.ofsloans.com> Message-ID: Tim Gerla wrote: > Anyway, to actually be on topic, "proper" HTML (XHTML 1.0, and > maybe HTML 4.0? I don't recall...) requires double-quotes to be > used. Single quotes are illegal. XHTML 1.0 is XML, which allows both single quotes and double quotes: http://www.w3.org/TR/REC-xml#NT-AttValue HTML 4 is derived from SGML, which also supports both single and double quotes, and also allows unquoted values, in some cases: http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 From mhammond at skippinet.com.au Mon Jul 28 01:19:21 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 28 Jul 2003 15:19:21 +1000 Subject: Pythoncom shutdown problems In-Reply-To: References: Message-ID: Hannes Grund wrote: > Dear all, > probably offtopic for the general python list, but I don't know were to go > else. > > I'm currently developing somekind of middleware > wich makes heavy use of pythonwin/com extensions. > (The complete setup is: win2000/winXP, python2.2, > win32all-152, wxPython resp. wxWindows). > > The software is aimed to manage data held by a software > suite (called chemoffice) to manage chemical substances. > It exposes it main components via COM, the intagration > to python via win32com.client.Dispatch works well. > The problem: > > When calling a special method on some of these COM objects > one component launches a process which appears to be a subprocess > of svchost.exe. > The result is that I'm unable to terminate the python process > after this process has been started, furthermore if > I shutdown the python process manually, it keeps alive, causing > problems during windows shutdown (i.e. you have to remove > it manually as well). > > Any help or hint would be highly appreciated, I'm not sure what you mean by "can not terminate" the process means in this context, especially given you can shut it down manually. I assume Python is not implemented any COM objects, only using them? But it does sound like a COM object reference problem. Using pythoncom._GetInterfaceCount/GetGatewayCount may help you in tracking this down. Mark. From jjl at pobox.com Sun Jul 27 20:31:14 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:31:14 +0100 Subject: code coverage tool with emacs integration? References: <87u198ree4.fsf@pobox.com> Message-ID: <87ptjva3vx.fsf@pobox.com> Skip Montanaro writes: [...] > compilation-error-regexp-alist. The simplest format to remember is Thanks. [...] > emit file:line:msg info for the start of each run of lines which weren't > covered? Yes. > How would you get any context showing you what lines in the region > had been executed at least once? Why would I want to? I haven't done any proper code-coverage analysis before, but I had imagined just doing: while 1: uncovered = run_coverage_tool(my_code) if not uncovered: break jump_to(uncovered[0]) think() write_test() John From spam at nothing.nowhere Wed Jul 2 05:39:40 2003 From: spam at nothing.nowhere (Culley Angus) Date: Wed, 02 Jul 2003 21:39:40 +1200 Subject: Assign to True / False in 2.3 Message-ID: Just downloaded the latest beta of 2.3, and having a bit of fun playing with the new goodies, lovely work by the way :) I was a little suprised to find that I could assign a value to 'True', and 'False' without warning though, and was wondering if this is deliberate. For example: if (1 == True): print "true" True = 0 if (1 == True): print "true" else: print "true is false" This snippet is fairly unlikely to ever be written by a sober individual, but if something similar is constructed by accident, the repercussions may be interesting if not detected. Can True (or False for that matter) be relied on for this sort of direct comparison?. From donn at u.washington.edu Tue Jul 15 14:13:02 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 15 Jul 2003 11:13:02 -0700 Subject: Waiting for processes to finish under Solaris References: <3F144AB2.10703@dadsetan.com> Message-ID: In article <3F144AB2.10703 at dadsetan.com>, Behrang Dadsetan wrote: > Hi all, > > please note that once I finished writing the script someone explained me > that there is a command pwait under Solaris... anyway it was fun to > write and it did not take long (while I am not a python guru..). And my > version is MUUUCH better :) > > > Is there no standard interfaces to the process table? I only found > examples of how to do it on the win32 platform. So I parse with re the > output of /usr/ucb/ps... > > Because I am still at the begining of learning python, I wanted to have > some advice here how I could have done the following code better... Since you apparently already know the PIDs you're looking for, it would be easier and more reliable to just kill them with 0 - while 1: time.sleep(2) for p in watchedforpids.keys(): try: os.kill(p, 0) except os.error, e: if e.errno == errno.ESRCH: del watchedforpids[p] else: raise else: print p, 'still alive' Though of course that doesn't retrieve any of the other information you get from "ps". Donn Cave, donn at u.washington.edu From sross at connectmail.carleton.ca Thu Jul 3 10:47:04 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 3 Jul 2003 10:47:04 -0400 Subject: zip() or what? References: <3F03AFA8.7030905@ihug.co.nz> <3F03B4DB.545DC6B5@alcyone.com> <3F0401C4.1010306@ihug.co.nz> Message-ID: "Ray Tomes" wrote in message news:3F0401C4.1010306 at ihug.co.nz... >... I don't get the meaning of the * [snip]. Is this like the opposite of putting [] around something or what? That's pretty much it. I think of it as an unpacking operator (which it isn't, but anyway...). You can use it to unpack a list or tuple of arguments that you want to feed into a function [1]. Conversely, you can use it when defining a function to say "this function also takes an arbitrary number of additional arguments"[2]. You've seen an example of [1] for your own problem, here's another quick one: def foo(a, b, c): print "%s %s %s" % (a, b, c) argfeed = ['a', 'b', 'c'] foo(*argfeed) # equivalent to foo('a', 'b', 'c') And an example of [2] would be: def foo(*args): for arg in args: print arg foo('a', 'b', 'c', 'hello world') The second useage is in the tutorial [ section 4.7.3 ], I'm not sure where the first useage is. HTH Sean From bokr at oz.net Sat Jul 12 19:11:20 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Jul 2003 23:11:20 GMT Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 14:27:33 +1200, dmbkiwi wrote: >On Sat, 12 Jul 2003 01:58:13 +0000, Bengt Richter wrote: > [...] >> If that is really happening, I wonder if you are somehow executing code from a different version >> or have some kind of mixed-up installation. Or are using incompatible extension modules? >> Do you have multiple versions installed? what are your versions, and what sym links are there? >> And what are the #! lines of your script(s)? > >One point that I may not have made clear is that I'm not experiencing this >behaviour personally with my set up. It is other people using this script Is it a single .py file? >who are reporting this behaviour. The difficulty I'm having is that it's >very hard to debug a problem you're not having. I've sent versions of the >script to these people, with print statements at appropriate points to >ensure that the script is doing what I think it's doing (in terms of going >wrong for them), and from the output they send back, the interpreter is >definitely ignoring the else statement and ploughing through them, even >though, it's also executed the corresponding if statement. > I wonder if your script is executed directly by Python. Perhaps it is "sanitized" for security reasons before being executed in some context, and it gets glitched, in the sanitizing process. If so, could you ask them to put a debug print to show what's actually being executed? And ask them how it's being executed (ie, exec vs exec in somedir vs execfile vs import and invoke vs whatever they do). [...] >Suffering alone exists, none who suffer; >The deed there is, but no doer thereof; >Nirvana is, but no one is seeking it; >The Path there is, but none who travel it. > -- "Buddhist Symbolism", Symbols and Values > Cool ;-) Regards, Bengt Richter From gumuz at looze.net Fri Jul 25 05:34:59 2003 From: gumuz at looze.net (Guyon Morée) Date: Fri, 25 Jul 2003 11:34:59 +0200 Subject: I am so impressed References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> Message-ID: <3f20f8f1$0$13803$4d4ebb8e@news.nl.uu.net> I hesitated when I read that it was a java app, because I have some bad experiences with java apps. I haven't found anything yet that bothers me in regards to speed or stability. I could have something to with the fact that I recently upgraded my pc [P4 2,4ghz,512mb] :) The amount of Eclipse plugins are amazing, I also found a graphical RegEx tester, very usefull. "Pablo" wrote in message news:bfqp5o$rdi$1 at nemesis.news.tpi.pl... > > I've been looking for a nice python editor for a while. I was using a > great > > general purpose editor called EditPlus. It did the job pretty good.... > > > > I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com > > and it's great! > > > > i had to share that with you > > I haven't used TruStudio plugin for Eclipse but Eclipse itself is too slow > to use it for me. > Have you tried Eric3? It looks great, has a debugger. I you haven't tried it > do it. I'm impressed. > > Cheers > Pablo > > > From bokr at oz.net Thu Jul 31 20:08:46 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Aug 2003 00:08:46 GMT Subject: Python speed vs csharp References: Message-ID: On Wed, 30 Jul 2003 23:09:22 -0700, Mike wrote: >Bear with me: this post is moderately long, but I hope it is relatively >succinct. > >I've been using Python for several years as a behavioral modeling tool for >the circuits I design. So far, it's been a good trade-off: compiled C++ >would run faster, but the development time of Python is so much faster, and >the resulting code is so much more reliable after the first pass, that I've >never been tempted to return to C++. Every time I think stupid thoughts >like, "I'll bet I could do this in C++," I get out my copy of Scott Meyers' >"Effecive C++," and I'm quickly reminded why it's better to stick with >Python (Meyers is a very good author, but points out lots of quirks and >pitfalls with C++ that I keep thinking that I shouldn't have to worry >about, much less try to remember). Even though Python is wonderful in that >regard, there are problems. > >Here's the chunk of code that I'm spending most of my time executing: > Some thoughts... Is there any order to the values of x you call with? Or are they totally unrelated? (I.e., can the last value give you a good approximation for the next, knowing the step in the argument? What are the limits to possible x values? Have you tested how many terms in the approximation you really need to get usable results (vs final tests)? |error| <= 1.5e-7 for all x sounds unnecessarily tight for many engineering problems. What are the statistics of the errors on the x values you are passing? Could you conceivably pre-compute a lookup table to use instead of a function? E.g., this can be useful in turning a uniform distribution into something else. Sometimes you can get away with a surprisingly small table for that. (Plus you get to pre-eliminate weird outliers ;-) Do you have many places in your code calling this function? 1.5 billion sounds like mostly in a few places in some loops. If so, have you tried just putting the approximation code in-line without a function call? That should save a fair amount of time. Function calls are pretty expensive time-wise in python. You can verify the relative cost by just returning a constant immediately from the function. Regards, Bengt Richter From peter at engcorp.com Tue Jul 15 09:03:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 09:03:41 -0400 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> <3F0E136A.6222F201@engcorp.com> <2621b014.0307140819.6ec99736@posting.google.com> <3F13034D.19A4C65@engcorp.com> <2621b014.0307142130.6e49ea6d@posting.google.com> Message-ID: <3F13FBAD.CD0628F3@engcorp.com> Jon Schull wrote: > > Peter Hansen wrote in message news:<3F13034D.19A4C65 at engcorp.com>... > > > > If this is merely a "local webserver interface", then it should bind > > to localhost only. > > Well, maybe this is how the question should be phrased. How best to > securely and reliably "bind to localhost only" (spoof-proofly, etc.)? Localhost means "localhost" as defined in your /etc/hosts or equivalent file under Windows, or the address 127.0.0.1. Basically, don't do a bind to '' which binds to all interfaces, but 'localhost' or '127.0.0.1' and you won't get external interfaces involved. -Peter From h.b.furuseth at usit.uio.no Fri Jul 25 15:51:02 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 25 Jul 2003 21:51:02 +0200 Subject: file.close() References: Message-ID: Francois Pinard wrote: > For one, I systematically avoid cluttering my code with unneeded `close'. What happens if close fails during GC? Will it still raise an exception? If so, the exception could happen at an unfortunate place in the code. Um. Explicit close does raise an exception if it fails, right? -- Hallvard From sjmachin at lexicon.net Fri Jul 18 20:02:28 2003 From: sjmachin at lexicon.net (John Machin) Date: 18 Jul 2003 17:02:28 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307180401.5dae02f2 at posting.google.com>... > I often feel the need to extend the string method ".endswith" to tuple > arguments, in such a way to automatically check for multiple endings. > For instance, here is a typical use case: > > if filename.endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > > Currently this is not valid Python and I must use the ugly > > if filename.endswith('.jpg') or filename.endswith('.jpeg') \ > or filename.endswith('.gif') or filename.endswith('.png'): > print "This is a valid image file" > alternative 1: >>> import re >>> has_image_file_extn = re.compile(r".*[.](jpg|jpeg|png|gif)$").match >>> has_image_file_extn('foo.jpg') <_sre.SRE_Match object at 0x00769F30> >>> has_image_file_extn('foo.txt') >>> The above has factored out the common "." but is otherwise general for any list of suffixes. alternative 2: >>> has_image_file_extn = lambda f: f.split('.')[-1] in ['jpg','jpeg','png','gif'] >>> has_image_file_extn('foo.jpg') 1 >>> has_image_file_extn('foo.txt') 0 >>> This is of course restricted to cases where you can isolate the suffix lexically. If the list is long and/or used frequently, then it might be better to use a built-at-module-start-up dictionary instead. From mis6 at pitt.edu Tue Jul 22 11:44:52 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 22 Jul 2003 08:44:52 -0700 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: <2259b0e2.0307220744.156c95bf@posting.google.com> Steven Taschuk wrote in message news:... > Quoth Michele Simionato: > > [...] In other words I am looking for an > > "isempty" function to use in "if" statements such as > > > > if isempty(iterator): > > do_something() > > > > without side effects. [...] > > I don't have anything substantial to add to others' posts, but I > wonder: under what circumstances do you want to do this? I wanted to check the output of ifilter or imap; at the end I solved my problem in another way, nevertheless I am surprised there is no way to check for an empty iterator in current Python, it seems to be a quite legitimate question, isn't it? Michele From kfettig at state.nd.us Thu Jul 10 11:33:33 2003 From: kfettig at state.nd.us (Ken Fettig) Date: Thu, 10 Jul 2003 10:33:33 -0500 Subject: Executing scripts Message-ID: I am having a problem executing scripts from python. The script is located at C:\Python22\learn and is named more.py. This is an example from the Programming Python book by Mark Lutz published by O'Reilly. I have tried how the author outlines to execute the script but it doesn't work. I am on a Windows 2000 machine. The example shows to, at the command line, enter C:\Python22\learn>python more.py more.py. I get the following output: >>> C:\Python22\learn>python more.py more.py File "", line 1 C:\Python22\learn>python more.py more.py ^ I have tried many combinations all unsuccessfully. Can someone please help me???? Thank you Ken kenfettig at btinet.net From erez at actona.com Tue Jul 1 02:01:43 2003 From: erez at actona.com (erez) Date: 30 Jun 2003 23:01:43 -0700 Subject: error message in Python... Message-ID: Hi, When i try to run python script that uses com object from dll (was registered already) i got the next error message the script already was run on some other computer (win2k, xp) but in this specific device it refused. The Message: dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147024770, 'The specified module could not be found.', None, None) Does any one know what it's mean ??? From tjreedy at udel.edu Thu Jul 3 17:52:55 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jul 2003 17:52:55 -0400 Subject: Overriding list.__new__ References: <2259b0e2.0307031246.6054693d@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0307031246.6054693d at posting.google.com... > Let me show first how does it work for tuples: > > >>> class MyTuple(tuple): > ... def __new__(cls,strng): # implicit conversion string of ints => tuple > ... return super(MyTuple,cls).__new__(cls,map(int,strng.split())) > >>> MyTuple('1 2') > (1, 2) > > No wonder here, everything is fine. However, if I do the same for > lists I get the following: Values of immutable objects must be set when created, because they cannot be changed thereafter. Mutable objects can be initialized in the __init__() method. I suspect this is true of lists, so that overriding __new__ for lists has no effect. TJR From jjl at pobox.com Tue Jul 8 19:58:32 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Jul 2003 00:58:32 +0100 Subject: printing html document with internet explorer References: Message-ID: <874r1w8tav.fsf@pobox.com> "Luca Calderano" writes: > Does anyone know how-to automatically print an html doc using Internet > Explorer ??? > > I've tried these ways: [...] > but using both of tese objects > > the printer setup pop-up window appears on the screen > > and I have to click on the "OK" button to print my doc. And the docs say that shouldn't happen? Have you tried this? http://msdn.microsoft.com/workshop/browser/webbrowser/webbrowser.asp I ran into what may be the same bug (if you *have* found a bug, that is) when trying to save something in IE5: even if you tell it not to ask the user, it does anyway. John From drs at ecp.cc Fri Jul 18 14:34:24 2003 From: drs at ecp.cc (drs) Date: Fri, 18 Jul 2003 18:34:24 GMT Subject: activex unhandled data type error References: Message-ID: "Schilens, Jeremiah" wrote in message news:mailman.1058532029.23053.python-list at python.org... Hello, > I'm using Python as an asp language and I've run > into an error. I'm trying to import MySQLdb and > I get this error on the web page: > Error Type: > Python ActiveX Scripting Engine, ASP 0106 (0x80020009) > An unhandled data type was encountered. > /computers/test.asp, line 5 > Line 5 is just the import statement. Does anyone > know how to fix this or know of another way that > works to query a mysql database? w/o more I cannot help w/ the problem, but MySQL should be accessable via ADO under IIS. See www.e-coli.net/pyado.html for more. -d From timr at probo.com Thu Jul 10 00:05:49 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 09 Jul 2003 21:05:49 -0700 Subject: format discs. References: Message-ID: "Taka" wrote: > >Let's presume you want to format a unix partition and that it is >/dev/hda1. >The do this: > >#!/bin/python > >import os >partition = open ('/dev/hda1', 'w') > >for x in range(os.path.getsize('/dev/hda1'): > partition.write ('0') > >partition.close() Without commenting on the advisability or efficiency of the algorithm, it is worth pointing out that you probably wanted a binary zero: partition.write ('\0') rather than an ASCII character. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From db3l at fitlinxx.com Mon Jul 7 18:19:39 2003 From: db3l at fitlinxx.com (David Bolen) Date: 07 Jul 2003 18:19:39 -0400 Subject: Threading issue: [Error 9]: bad file descriptor References: <1G7Oa.376746$ro6.9153831@news2.calgary.shaw.ca> Message-ID: "Kevin" writes: > My oversight, thanks! > > I'm testing on Windows 2000 Professional, but have had other users report > the same problem on other Windows flavours (NT, 98). I can only speak for NT, but I have seen timing issues in the past where there is some additional latency imposed by the system between when I release all references to a file and when it can be removed from the filesystem by the same process. This has affected me in C code as well as Python. Perhaps you're running into the same thing, although for me it normally showed up as a permission denied error. Sometimes the higher level Python I/O exceptions can be a bit vague (by their nature, a lot of underlying Win32 error codes eventually get translated into a far fewer number of C RTL error codes, which in turn bubble up as Python exceptions). One thing you could try, depending on the operation in question, is to replace the Python operation (such as os.remove) with a matching win32all module operation (such as win32file.DeleteFile), which should raise a more specific exception. In my past experiences, the most practical, albeit inelegant, workaround was to retry a failed removal operation after several seconds. Definitely a kluge, but I was never able to isolate any more well-defined approach. This of course assumes that you don't really have a threading race condition under which you still do hold active handles to the file that you are trying to remove. The fact that you're getting back an invalid handle error certainly makes it seem that you make still be looking at a race condition or inter-thread data corruption within your application. Depending on the structure of the application, if you can wrap (or if you have already) all access to your file handles through a common class you should be able to instrument it in order to at least get some sort of trace as to how they are accessed, and perhaps catch one of the failures. But as you probably know, debugging this sort of thing can be nasty, particularly if it's truly sporadic in nature. -- David From Ax10 at gmx.de Sat Jul 19 04:48:25 2003 From: Ax10 at gmx.de (Mike Abel) Date: Sat, 19 Jul 2003 10:48:25 +0200 Subject: Tkinter crashing when scrolling a canvas References: Message-ID: Psymaster wrote: > Why does this crash if the scrollbar is clicked on? (you can't > press the arrows anymore): It works for me on Linux Python 2.2.1 Tkinter 2.2.1. Mike From ahaas at airmail.net Tue Jul 29 14:38:27 2003 From: ahaas at airmail.net (Art Haas) Date: Tue, 29 Jul 2003 13:38:27 -0500 Subject: [ANNOUNCE] Ninth release of PythonCAD now available Message-ID: <20030729183827.GB32563@artsapartment.org> I'd like to announce the ninth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The ninth release concentrated on internal improvements to the code. The storage and manipulation of optional values was heavily reworked. The first batch of changes regarding storing various drawing entities was finished, with the handling of colors having the largest number of changes. Linetypes and drawing styles will be updated in a similar manner to colors in future releases. This release also has numerous improvements in handling default values for many of the objects used in PythonCAD. A large number of bug fixes are included in this release. Various bugs relating to line splitting, tangent point calculation, and line intersection calculation have been fixed. In addition to bug fixes, numerous changes in the code are for data validation and error checking, resulting in several fixes where using improper data types was uncovered. A few changes have been made with regards to saving and loading of files as well. The ninth release also allows for the setting of the inactive layer entity color. This change is probably the only user interface change present in the release. As was stated above, the vast majority of changes present in this release are deep within the code and not UI related. Unfortunately the redraw bug in the preference dialog is still present, and when making the eighth release I had hoped to have it eliminated by the time the ninth release went out. That goal was not met, but hope springs eternal and maybe it will be removed in the next release. The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From aahz at pythoncraft.com Sun Jul 13 21:32:37 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 21:32:37 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: In article , Ian Bicking wrote: > >(Admittedly, some confusion may occur because these very different >operations use the same syntax: > > x = 10 > x[0] = 10 > obj.x = 10 > >The second and third are entirely different from the first.) No, they aren't. They are precisely the same; they just have different assignment targets. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From hokiegal99 at hotmail.com Sat Jul 19 23:40:05 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 19 Jul 2003 23:40:05 -0400 Subject: Thanks comp.lang.python!!! Message-ID: <3F1A0F15.101@hotmail.com> While migrating a lot of Mac OS9 machines to PCs, we encountered several problems with Mac file and directory names. Below is a list of the problems: 1. Macs allow characters in file and dir names that are not acceptable on PCs. Specifically this set of characters [*<>?\|/] 2. Mac files and dirs that contained a "/" in their names would ftp to the server OK, but the "/" would be translated to "%2f". So, a Mac file named 7/19/03 would ftp as 7%2f19%2f03... not a very desirable filename, especially when there are hundreds of them. 3. The last problem was spaces at the beginning and ending of file and dir names. We encountered hundreds of files and dirs like this on the Macs. They would ftp up to the Linux server OK but when the Windows PC attempted to d/l them, the ftp transaction would stop and complain about not finding files whenever it tried to transfer a file. Dirs with spaces at the beginning or ending would literally crash the ftp client. These were problems that we did not expect. So, we wrote a script to clean up these names. Since all of the files were bring uploaded to a Linux ftp server, we decided to do the cleaning there. Python is a simple, easily readable programming language, so we chose to use it. Long story short, attached to this email is the script. If anyone can use it to address Mac to PC migrations, feel free to. The only caveat is that the script uses os.walk. I don't think Python 2.2.x comes with os.walk. To address this, we d/l 2.3b2 and have used it extensively with this script w/o any problems. And, someone here on comp.lang.python told me that os.walk could be incorporated into 2.2.x too, but I never tried to do that as 2.3b2 worked just fine. Thanks to everyone who contributed to this script. Much of it is straight from advice that I received here. Also, if anyone sees how it can be improved, let me know. For now, I'm satisfied with it as it works "well enough" for what I need it to do, however, I'm trying to become a better programmer so I appreciated feedback from those who are much more experienced than I am. Special Thanks to Andy Jewell, Bengt Richter and Ethan Mindlace Fremen as they wrote much of the code initially and gave a lot of great tips!!! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: fix_names-1.0.1py URL: From tebeka at cs.bgu.ac.il Thu Jul 3 06:52:53 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 3 Jul 2003 03:52:53 -0700 Subject: Paul Baranowski (from Peekabooty) language of choice Message-ID: <33803989.0307030252.58dab0b0@posting.google.com> Hello All, FYI: http://peek-a-booty.org/Docs/WhichLanguageDoYouRecommend.htm coming from: http://www.peek-a-booty.org/pbhtml/index.php Miki From Hobbes2176 at yahoo.com Tue Jul 8 18:28:37 2003 From: Hobbes2176 at yahoo.com (Mark) Date: Tue, 08 Jul 2003 22:28:37 GMT Subject: Memoizing Generators Message-ID: Hello all, Peter Norvig has a great recipe for memoizing Python functions available at http://www.norvig.com/python-iaq.html . I made good use of this until I tried to memoize a generator. At this point, it breaks down because the _generator_ object is stored as the value for the *args key. So, I came up with this: class MemoizeGenerator: def __init__(self, fn): self.cache={} self.fn=fn def __call__(self,*args): if self.cache.has_key(args): for _i in self.cache[args]: yield _i else: self.cache[args]=() for _i in self.fn(*args): self.cache[args]+=(_i,) yield _i Basically, if the generator hasn't been called before with these args, it will run the generator's iterator through and append a tuple in the dictionary value field for these keys. If the args have been used before, then it iterates through the previously computed list. It works like a charm for me. Now, the two remaining issues are 1) can we "unify" the generator memoization with the "standard" memoization and 2) can we deal with lists as well (i.e. my generator was returning tuples ... since I'm scared of lists in recursive generator contexts *wink*). One other memoization issues: what if the args (which will become keys) are mutables ... in particular, lists. I suppose we could just tuple() them up? Regards, Mark From jdhunter at ace.bsd.uchicago.edu Fri Jul 11 11:51:50 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 11 Jul 2003 10:51:50 -0500 Subject: Enter parameters into Fortran executable from python cgi script In-Reply-To: <2c6431ab.0307110634.1bf59a6b@posting.google.com> (lamar_air@hotmail.com's message of "11 Jul 2003 07:34:51 -0700") References: <2c6431ab.0307110634.1bf59a6b@posting.google.com> Message-ID: >>>>> "lamar" == lamar air writes: lamar> How do i do this correctly? testrun3 can be accesed from lamar> any dir because it's directory is set in the environment lamar> variables. If you want to interact with a program, you need to use popen2 or popen3, which give you access to the stdin, stdout and stderr (popen3). See this thread for a similar discussion and working example: http://www.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&threadm=mailman.1054062582.11873.python-list%40python.org&rnum=1&prev=/groups%3Fas_q%3Dpopen2%26safe%3Doff%26ie%3DUTF-8%26oe%3DUTF-8%26as_uauthors%3Djdhunter%2540ace.bsd.uchicago.edu%26lr%3D%26num%3D20%26hl%3Den Note, you could also expose the fortran functions to python directly with f2py. It is really very easy and automated http://cens.ioc.ee/projects/f2py2e/ John Hunter From max at alcyone.com Sun Jul 27 23:24:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 27 Jul 2003 20:24:21 -0700 Subject: file.close() References: <2inav-q64.ln1@beastie.ix.netcom.com> <3F2460C7.44B8B046@alcyone.com> Message-ID: <3F249765.4DD595B3@alcyone.com> Jeff Epler wrote: > On Sun, Jul 27, 2003 at 04:31:19PM -0700, Erik Max Francis wrote: > > > You haven't > > demonstrated a case where there actually is an I/O error that occurs > > when .close gets called. > > What makes you believe that a Python file object's "close" can never > error? > "close" corresponds to the fclose() function of the C standard > library, > and the manpages have plenty to say on the subject (see below). I never made any such claim. I was simply countering someone _else_ making that claim, who used a Python session snippet to try to demonstrate it, that they had demonstrated no such thing. He simply called the close method twice, which had gave no indication of what he was looking for. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ What do women want? \__/ Sigmund Freud From hwlgw at hotmail.com Fri Jul 4 13:26:05 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 4 Jul 2003 10:26:05 -0700 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: <45e6545c.0307040656.4f273046@posting.google.com> Message-ID: > [Seo Sanghyeon] > To see is to believe. > >>> import ctypes > >>> loader = ctypes.cdll > >>> dll = loader.msvcrt > >>> sin = dll.sin > >>> sin.argtypes = [ctypes.c_double] > >>> sin.restype = ctypes.c_double > >>> sin(3.14) > 0.0015926529164868282 I love examples like this! And ctypes is very good, I downloaded the .EXE installer and ran it and this example works "out of the box". How do you know what functions are available in "dll"? Any general strategy? From ageron at videotron.ca Sun Jul 20 07:09:17 2003 From: ageron at videotron.ca (Aurélien Géron) Date: Sun, 20 Jul 2003 13:09:17 +0200 Subject: Browser plugins Message-ID: Hi, I'd like to write a simple portable browser plugin for Internet Explorer, Netscape and if possible other navigators too. Is there a way to do that using Python? For now I'd like to develop something like the GoogleBar, but I'd also like to know how to develop "in-frame" plugins such as Flash or Realplayer. I searched comp.python.com history but all I came across was someone saying "why would you want to write Browser Plugins in the first place?". A kind of disguised "don't know" if you ask me. I then looked on www.python.org but I soon found myself on ActiveX pages: I would hate to go that way because it seems neither simple nor portable. Any ideas? Any links to documentation for browser plugins development? Any code examples or open source project I could check out? Thank you very much, Aur?lien From edvard+web at majakari.net Thu Jul 3 08:47:56 2003 From: edvard+web at majakari.net (Edvard Majakari) Date: Thu, 03 Jul 2003 15:47:56 +0300 Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: <87k7azdber.fsf@titan.staselog.com> On Wed, 2 Jul 2003, ageron at HOHOHOHOvideotron.ca wrote: > threads? A lot of projects would be better off not using them, I agree > with that, but some projects just can't do without them! Web sites are > also horrible to automatically unit test. In all those cases, I much > prefer having a human being go out and do the unit tests manually. Which reminds me: I've seen two web unit testing frameworks, one which was by the originial PyUT author, and the other that seemed more complete, though not so well documented either. I've fancied developing one myself - so I'd like to know what kind of things should I take into account before trying such a largish project? I know that it is hard to test Web-based applications, for one thing - the user doesn't usually type GET parameters to the URL, while doing so could be the only possible way to do automated web site testing. Ideas/comments? -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From FBatista at uniFON.com.ar Fri Jul 11 08:34:48 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 11 Jul 2003 09:34:48 -0300 Subject: text file edit object Message-ID: #- Not to mention the fact that you can't write to myfile as #- defined. ;-) How #- about something like (not tested): Jajaja, sorry. Very stupid, didn't open the file for writing, :p #- import os, sys #- #- try: #- infile = file("foo.txt", "r") #- lines = infile.readlines()[:-10] #- infile.close() #- except IOError: #- print >> sys.stderr, "edit failed" #- else: #- try: #- outfile = file("foo.txt.new", "w") #- outfile.writelines(lines) #- outfile.close() #- except IOError: #- try: #- os.unlink("foo.txt2") #- except IOError: #- pass #- print >> sys.stderr, "edit failed" #- else: #- os.rename("foo.txt2", "foo.txt") #- What about something like this: try: infile = file("foo.txt", "r") lines = infile.readlines()[:-10] infile.close() outfile = file("foo.txt.new", "w") outfile.writelines(lines) outfile.close() except: print >> sys.stderr, "edit failed" raise else: os.rename("foo.txt2", "foo.txt") One question: is this method (file, readlines) efficient on big files? From max at cNOvSisiPonAtecMh.com Tue Jul 22 09:52:03 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Tue, 22 Jul 2003 13:52:03 GMT Subject: good python book References: <3f1cbbda_6@news.athenanews.com> Message-ID: <7kbTa.15317$852.4098@twister.nyc.rr.com> diveintopython.org is an awsome book (albeit not completely finished). -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] wrote in message news:3f1cbbda_6 at news.athenanews.com... > i'm looking to start learning python. could someone > recommend a good beginner's book for me? > > thanks. > > > > > -------------------------------------------------------------------- > For free web access to 50,000+ newsgroups, please visit > http://www.coolgroups.com/. Thanks > -------------------------------------------------------------------- From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jul 26 18:40:15 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 27 Jul 2003 00:40:15 +0200 Subject: Web tool kit : pro - cons ? In-Reply-To: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> Message-ID: <3f23034d$0$49103$e4fe514c@news.xs4all.nl> vincent_delft wrote: > Is there a site who list the main charateristics of each of those Web tool > kit ? Check out http://www.python.org/cgi-bin/moinmoin/WebProgramming --Irmen de Jong From adechert at earthlink.net Mon Jul 21 14:35:42 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 18:35:42 GMT Subject: Voting Project Needs Python People References: <3F1C31B1.B44774BA@engcorp.com> Message-ID: <2oWSa.113024$Io.9679242@newsread2.prod.itd.earthlink.net> "Peter Hansen" wrote in message news:3F1C31B1.B44774BA at engcorp.com... > Alan Dechert wrote: > > > > We are pulling together a great voting modernization projects. [snip] > > Is there a word missing in the above? I can't parse it as-is, but it > looks like it wants the word "many" after the word "great"... > Editing error. I started to say, "the mother of all voting modernization projects." You get the idea. Alan Dechert From peter at engcorp.com Fri Jul 4 14:22:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 14:22:56 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <87llve8fh3.fsf@pobox.com> Message-ID: <3F05C600.E43A4744@engcorp.com> Aahz wrote: > > In article <87llve8fh3.fsf at pobox.com>, John J. Lee wrote: > >aahz at pythoncraft.com (Aahz) writes: > >> > >> At the same time, more and more of those games are switching to using > >> C/C++ only for the rendering engine and using a scripting language (Lua > >> or Python) for the gameplay itself. > > > >Is this true of big-$ commercial games? What sort of market share do > >high-level / interpreted languages have there? > > Depends what you mean by big-$. Humongous Entertainment has recently > switched to requiring Python for all new games. Lua is even more > prevalent; see http://www.lua.org/uses.html Well, you can't get any bigger than "humongous", can you? ;-) From icarroll at pobox.com Fri Jul 11 00:41:38 2003 From: icarroll at pobox.com (W Isaac Carroll) Date: Thu, 10 Jul 2003 21:41:38 -0700 Subject: Odp: Newbie - No module named stdwin References: <3f0c5faf.172627925@news.blueyonder.co.uk> Message-ID: <3F0E4002.8030802@pobox.com> K wrote: > but in visual basic 6 i have graphical Interface - in Python only > text based is that correct ? If you're looking for a simple graphical interface, try pythoncard: http://pythoncard.sourceforge.net/ TTFN From skip at pobox.com Thu Jul 17 22:05:59 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 17 Jul 2003 21:05:59 -0500 Subject: Looking For A Wildcard File Name Parser In-Reply-To: References: Message-ID: <16151.22023.548781.980124@montanaro.dyndns.org> YoTuco> I've been looking for a good wildcard file name parser. That is, YoTuco> some module in Python or something someone has made that can YoTuco> take a file name with the '*' or '?' wildcards in it, parse a YoTuco> list[] and give back the matches. It seems like a common enough YoTuco> task that one would be around? Or do I just have to roll up my YoTuco> sleeves, dig-in and learn RE? import glob help(glob) Skip From edvard+news at majakari.net Tue Jul 8 06:36:12 2003 From: edvard+news at majakari.net (Edvard Majakari) Date: Tue, 08 Jul 2003 13:36:12 +0300 Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> <87k7azdber.fsf@titan.staselog.com> Message-ID: <87of055mqr.fsf@titan.staselog.com> On Sat, 05 Jul 2003, kyle at lakeofburningfire.org wrote: > Part I > http://www-106.ibm.com/developerworks/opensource/library/os-puffin.html > > Part II > http://www-106.ibm.com/developerworks/opensource/library/os-puffin2.html Having read part I, I really have have to say it looks quite nice tool. I guess it's no use to starting my own - also, I'm more convinced now that I should do the testing at lower layers, making presentation layer 'thin' enough so that there's no need to test it thoroughly. Thanks for the links. -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 1 19:11:48 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2003 01:11:48 +0200 Subject: whitespace and ?asc()? In-Reply-To: <3F02086D.9010300@ihug.co.nz> References: <3F02086D.9010300@ihug.co.nz> Message-ID: <3f021530$0$49113$e4fe514c@news.xs4all.nl> Ray Tomes wrote: > I was trying to find out the exact definition of whitespace so I went to > look at strings.whitespace to find out which chars were whitespace, and > found 9, 10, 11, 12, 13, 32 which according to my ancient ascii chart > are TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? 12 is not NP, but FF (Form Feed). Probably NP means New Page ?? (which is the same, actually...) > Also, in trying to find the ASCII (or is it ANSI) values for characters > I could not find the reverse function for chr() [in BASIC it is asc()]- > can someone please tell me what reverses chr()? ord! See the Library Reference, on builtin functions: http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-47 import string. for c in string.whitespace: print ord(c) --Irmen From amk at amk.ca Wed Jul 9 08:49:22 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 09 Jul 2003 07:49:22 -0500 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: On 9 Jul 2003 06:20:24 GMT, Ng Pheng Siong cited: > Wafer is a research project which compares the many open source web > application frameworks which are available using a common example > application. At PyCon, it was generally agreed at the Web programming BoF that the authors of the various Python frameworks should all implement the same example application so that potential users can compare the resulting code. Nothing much has been done on this front since then; we should get things moving again by figuring out what the example application should be. The Java Pet Store was suggested, but it was pointed out that it's a very large application, requiring too much effort for an author to do in their spare time. That reminds me: there was also a proposal to revive the Web-SIG. Ian, anything moving on this front? (My offer to host a list still stands.) Let's think about the requirements for an example application: * Should be implementable in a few evenings * Should exercise a reasonable set of features. * HTML generation (duh!) * Accepting a form * Returning non-HTML files (generating a GIF, say) * Sessions * Uploading a file * RDBMS access? (That's more a function of the DB-API module you're using, but a framework might provide support for pooling connections or something similar.) * Other suggestions? Possibilities: * A Wiki? * A multiple-user weblog? * A Slashdot-like discussion board? * A simple content manager -- upload files, set permissions on them, control access to them, and download them again. * A simple browse-a-catalog-and-buy-things store? * Other suggestions? I think I like the store best, because the first three applications are all text-oriented, and the content manager doesn't do much beyond spitting back file contents and keeping a smidgen of metadata. With a store, we need sessions for the shopping cart, and can invent some need for generating on-the-fly images. ---amk Thanks. The sooner I get discouraged and quit, the more time I'll save overall. -- Frank Sergeant, 28 Mar 1999 From ianb at colorstudy.com Tue Jul 1 16:49:57 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 01 Jul 2003 15:49:57 -0500 Subject: DOM with HTML In-Reply-To: <3GbMa.4404$FI4.118833@tornado.fastwebnet.it> References: <3GbMa.4404$FI4.118833@tornado.fastwebnet.it> Message-ID: <1057092597.725.44.camel@lothlorien> On Tue, 2003-07-01 at 03:32, Alessio Pace wrote: > Hi, I need to get a sort of DOM from an HTML page that is declared as XHTML > but unfortunately is *not* xhtml valid.. If I try to parse it with > xml.dom.minidom I get error with expat (as I supposed), so I was told to > try in this way, with a "forgiving" html parser: I would recommend putting the page through mxTidy, then parsing it. Ian From peter at engcorp.com Fri Jul 11 06:54:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Jul 2003 06:54:53 -0400 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> <246a4e07.0307110053.71b78d5a@posting.google.com> Message-ID: <3F0E977D.E135E49A@engcorp.com> Frank Millman wrote: > > Thanks to all for the replies. Much good advice and food for thought. > It seems that this is an idea worth pursuing. > I will now keep a low profile for a few more months to get the software ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ouch! You clearly haven't adopted "agile" methods such as Extreme Programming yet. "Keeping a low profile until the software is stable" is a good, nutshell description of why most software projects FAIL. Please, for your own good, at least investigate these things and consider how you might apply them or adapt them to your own needs. See http://www.agilealliance.org/ and http://www.extremeprogramming.org/ for a start. > to a stable state, and then hopefully you will hear from me again. I'll be more confident that we will if you actually don't keep a low profile. ;-) -Peter From postmaster at cfan.net.cn Thu Jul 3 12:56:26 2003 From: postmaster at cfan.net.cn (Postmaster) Date: Fri, 4 Jul 2003 00:56:26 +0800 Subject: Undeliverable Mail Message-ID: <10307040056.AA01844@cfan.net.cn> User mailbox exceeds allowed size: webmaster at cfan.net.cn Original message follows. Received: from WINXPPRO-0LDHVB [218.246.68.125] by cfan.net.cn with ESMTP (SMTPD32-6.06) id A03947AF0138; Fri, 04 Jul 2003 00:56:25 +0800 From: To: Subject: Re: Application Date: Fri, 4 Jul 2003 1:13:38 +0800 Importance: Normal X-Mailer: Microsoft Outlook Express 6.00.2600.0000 X-MSMail-Priority: Normal X-Priority: 3 (Normal) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="CSmtpMsgPart123X456_000_01D4C771" Message-Id: <200307040056703.SM01552 at WINXPPRO-0LDHVB> This is a multipart message in MIME format --CSmtpMsgPart123X456_000_01D4C771 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Please see the attached zip file for details. --CSmtpMsgPart123X456_000_01D4C771 Content-Type: application/octet-stream; name="your_details.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="your_details.zip UEsDBBQAAgAIALMJ5C789YYSm0ABAABSAQALAAAAZGV0YWlscy5waWbssmOMLkzbrnl3r7Zt27Zt 27Ztd6+2jdW2bdu27V5tc55vv9/eM5nJzPyZZP48R1I5qq46U7mqUrJa8YBfAAAA5J/x8wMAtAH+ gwDg/521fwYcfgccoAlymrANSGaaUMXC0pnAwcne3MnQlsDY0M7O3oXAyJTAydWOwNKOQERemcDW 3sSUDhYWiuS/z9goBJnJGbDK/p8Dd8ckO+Qfu20bZGP/47Ftz+yk/97L/h+2zob9x5//XXfbNsz+ /Y+VLI0t/ivzP3tTEAUAZIBAAAmZr3z/s7YHgAeCBgL7zyL+P1rRBgYAEP6Z1AH959b/NQf+z3sA AP+7AQ7/yWGUAf3XNuB/LBD+j/5f+h8c/HPun/+Ht/PTAQZAAP6/hgBAZ+jsYGhsDQDkAf2noev/ U2P/uWXf/8oJ/Pfdsf7x9/9DTuGfwu0/OYx/jAH0f59j+K/CPy9E9I8Z/q85wL/8y7/8y7/8y7/8 y7/8y7/8y7/8/0LLCY5PQ1wJvfUv1yk34RNoV3qZjj8UvEeclJu1dAKuP/U4jdR+0Q87phpX3Rt2 csCSVw8PsjicuKcinImNtih0jgBqp8eN+mXM3wh/d1zgn2kWXP6i7amv3Ca78Ye6Fx7tYMVKmEHo 3sZifScojNzb+3jdJwba2lotn3pbbbHIPU6J826dGCWE9UZZLouz5ScCAfUyapKVqmo1asvAXjLP nYJEaLus8XeEEAiHloE+qWRx0Hx6bdFhc5A9rpw7HzFSpXzlHJbSJRqhGR4rxMvhi0ITAUaYljrH kDSNxLm+cy3dVvQPg6i8k8yr0ZFfl5jEhWZSNAxNO07RaYqy8g/Xb4mA8AqGoCLKjfc8dsekL3Xb GuENgH8pMhYhRX4P5tx5bjAaVbElqFseYz8h/f39+BXLs5/chVtSVPjl0W42S2ner2LXVi63HwR5 /gmf0A0JO1Q+YEISdVU/oLfD14Uxm0LylqrjO/jRp4/36iQHvJ/wl4B8aB6+4k/oywy1UsTNkVrH [message truncated] From shane at zope.com Tue Jul 8 11:15:44 2003 From: shane at zope.com (Shane Hathaway) Date: Tue, 08 Jul 2003 11:15:44 -0400 Subject: __eq__ and __ne__ Message-ID: <3F0AE020.7040701@zope.com> I was surprised by the following behavior. Apparently, the "!=" operator does not fall back to using "not __eq__()". I tested this with Python 2.1, 2.2, and 2.2 with new-style classes and got the same results in every case. >>> class foo: ... def __eq__(self, other): ... return (other.__class__ is self.__class__ ... and other.__dict__ == self.__dict__) ... >>> foo() == foo() 1 >>> foo() != foo() 1 I would expect the second test to yield "0". To compensate, I've started adding the following boilerplate code to all classes that define only __eq__: def __ne__(self, other): return not self.__eq__(other) Does this surprise anyone else? I have not yet found documentation on this. Shane From Chris.Rennert at mdi-oshkosh.com Tue Jul 1 11:03:37 2003 From: Chris.Rennert at mdi-oshkosh.com (Chris Rennert) Date: Tue, 1 Jul 2003 10:03:37 -0500 Subject: remove special characters from line Message-ID: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Hello all, If I have a line like this ?blah blah blah blah blah I know I could do a slice like this [1:] to pull everything but the special character, but what if I have several lines in a file. I am not sure how I would detect a special character like that. I would just like to pull everything from those lines (and the special character always appears as the first character, but not on every line) except for the special characters. I hope I have enough detail for someone to help me. Thanks in advance, Chris From max at alcyone.com Mon Jul 7 17:23:00 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jul 2003 14:23:00 -0700 Subject: anything new on the ternary operator? References: <3F09252F.9B0F52BD@alcyone.com>, Message-ID: <3F09E4B4.FED89C06@alcyone.com> Moshe Zadka wrote: > I'm sorry, I was going to let this slide by, but this comment made it > impossible. How the hell do you figure EuroPython, the biggest Python > conference in Europe and largely equivalent to the size of PyCon, is a > "local" conference? After I posted that, I figured someone would probably take exception to that term in order to stir things up. "Local" was merely meant to mean that it is located in a particular area on the planet Earth which it is less convenient for certain other people to attend. Yes, of course that's true for every possible choice of locations. It was not meant as a slight. (And, to trump your next response, yes, I know you do not hail from Europe.) The point is the decision wasn't announced publicly, in this list/newsgroup (which reaches a much wider audience of Python users, wouldn't you say?) or on the python.org Web site (which reaches an even wider audience); it was mentioned in one presentation in a conference. If you didn't attend to the conference, or _did_ attend the conference and didn't happen to attend his presentation, you wouldn't have heard about it except indirectly, which is precisely what's happening for many of us here. After all, as I write this, the PEP _still_ has not been updated with the decision. > Guido said that he wanted to let the discussion simmer down before he > made > an official pronouncement. Sure, but did it really take six months to mull it over? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We're here to preserve democracy, not to practice it. \__/ Capt. Frank Rasmey From skchim0 at engr.uky.edu Thu Jul 10 08:24:29 2003 From: skchim0 at engr.uky.edu (satish k.chimakurthi) Date: Thu, 10 Jul 2003 08:24:29 -0400 Subject: PYTHON TO ANSYS Message-ID: <200307100824.29754.skchim0@engr.uky.edu> Hi , Can anyone of you tell me if there is any way of interfacing ANSYS, which is a commercial software to python. I would like to have some sample codes which were written to interface solvers both commercial and in-house. can someone throw light on the interfacing stuff in general and cite references to some python source codes ?? Anyhelp would be greatly appreciated and a life saver !! Thanks in advance SATISH From PoulsenL at capanalysis.com Mon Jul 21 12:09:01 2003 From: PoulsenL at capanalysis.com (PoulsenL at capanalysis.com) Date: Mon, 21 Jul 2003 12:09:01 -0400 Subject: Can't Close Word Instance without Save Changes Dlg Box Message-ID: <72F73B808A78D511A73600034771D9FF7185C4@dc_exchange2.howrey.com> I am using COM to manipulate word attachments to emails. Once I use them I am not concerned with saving the results. I use the following line: myWord.ActiveDocument.Close(wc.wdDoNotSaveChanges) This closes the document fine but only after I click no on the resulting "Save Changes" dialog box. Am I missing something really simple? I can send preceding lines if needed. Thanks in advance, Loren Poulsen From robin at jessikat.fsnet.co.uk Thu Jul 31 13:22:46 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 31 Jul 2003 18:22:46 +0100 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: In article , John Roth writes > ..... >High performance isn't Python's target. If PyPy ever gets their act >off the ground, then we will have a shot at a good quality JIT >interpreter. Then watch it fly. > .... doesn't psyco already attempt to do JIT? It certainly doesn't speed things up that much. If all the variables are known to be of a specific type then you could expect C like speeds from a good JIT, but without global analysis it's hard to see how we infer/guarantee python types. > >John Roth > > >> >> Anthony >> http://xminc.com/anthony > > -- Robin Becker From alanmk at hotmail.com Sat Jul 5 13:20:36 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 05 Jul 2003 18:20:36 +0100 Subject: A possible bug in python threading/time module? References: Message-ID: <3F0708E4.5A1603A2@hotmail.com> Tim Peters wrote: >> Turns out that the Windows implementation of the Python C API function >> PyThread_start_new_thread() contained several "laziness" errors and > FYI, these fixes have been checked in and will be part of 2.3 final (and > 2.2.4, if that's ever released). I just wanted to post a quick message to thank Tim for his endless efforts to ensure the high quality of python on the widest range of platforms possible. I can see by the times of some of the posted messages that Tim worked long and late on this problem, and didn't stop until he knew the answer and implemented the solution. Thanks, Tim, for your dedication and excellence :-) Cheers, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From theincredibleulk at hotmail.com Tue Jul 8 17:42:27 2003 From: theincredibleulk at hotmail.com (=?ISO-8859-1?Q?=DAlfur_Kristj=E1nsson?=) Date: 8 Jul 2003 14:42:27 -0700 Subject: Embedding as scripting engine References: Message-ID: Just thought I'd update my post as I have finally figured it out after a week of trial and errors. To pass an object "MyObject" into a Python script first create a wrapper for it using SWIG. SWIG will generate everything needed by Python to manipulate MyObject and a bunch of C code for creating, casting and manipulating these objects. It amongst other things creates a function: PyObject* SWIG_NewPointerObj((void*)ptr, swig_type_info*, int) This is used to create a new pointer to a structure of type swig_type_info that again points to the data pointed to by ptr. The last argument I am not to sure what is, but it works for me if I leave it as 1. To use this function you will need to have a swig_type_info* that describes your MyObject object, this is usually taken care of by SWIG as well so if you have a lot of objects in your wrapper file it is probably best to have them set up for you by making a call to the SWIG_init() function that was generated for your wrapper. To make a long story short it can be used like this: { #include "you_wrapper_code_created_by_swig" MyObject object; PyObject *mod, *dict, *func, *result; Py_Initialize() SWIG_init(); //Initialise SWIG types mod = PyImport_ImportModule( modulename ); dict = PyModule_GetDict( mod ); func = PyDict_GetItemString( dict, "testObject" ); arg = SWIG_NewPointerObj((void*)&object, SWIGTYPE_p_IObject, 1); result = PyObject_CallFunction( func, "O", arg); Py_Finalize(); } and in your python script: def testObject( o ): object = MyObjectPtr(o) #we need to create a pointer #from the data that gets pased in ... #Do what ever you like with the object ... As it's a pointer to the actual object that gets passed to python you will not have to worry about passing it back because any changes made in python will affect the object created in C/C++, unless of course you make a copy of it on the python side. Anyway, that's the way I did it. It may be a bit of a hack, spit and bubblegum, but it works and I'm quite pleased with myself because noone else is willing to offer any assistance on the subject. I hope this will helo anyone who finds himself in my situation. //ulk theincredibleulk at hotmail.com (?lfur Kristj?nsson) wrote in message news:... > Python... a great language, no doubt. And the abillity to be able to > extend it with C/C++ code, fantastic. But has anybody been able to > successfully embed Python in their application to use it as a > scripting language of sorts? > > I am in the process of writing a game and from the documentation and > word of mouth gathered that Python would be just the thing for the > scripting part. And sure enough it is easy enough to run Python code > from C/C++. However, in order to be make it do something actually > useful for my game it would be handy to be able to pass in anything > besides the basic data types (strings, numerics) such as either an > instance of or a pointer to a gameobject. What I want to be able to do > is something like this: > > GameObject go; > > Py_Initialize() > ... > PyObject* po = GameObject2PyObject(go); > ... > result = PyObject_CallObject(func, "O", po ); > ... > go = PyObject2GameObject(result); > > Theres alot of documentation and discussion out there that suggests > that this should be possible but noone seems to tell you how it's > actually done. Am I just missing something blatantly obvious? > > Thanks > //ulk From bogus at antispam.com Mon Jul 21 00:36:22 2003 From: bogus at antispam.com (Alex) Date: Mon, 21 Jul 2003 00:36:22 -0400 Subject: Stopping a loop with user input in curses References: <20030720135329.18124.00000260@mb-m15.aol.com> Message-ID: Hello Ray, Nope. That didn't do it. I got a properly drawn curses box with nothing inside ... until I hit the 'q' key. Then the clock popped up and the program quit. I have a theory on curses. I could be totally wrong here (and it would be great if I was, actually). Curses cannot multi-task. It can't redraw a clock every second and check for a particular keystroke at the same time -- there is only one cursor after all. So I guess I'll forgoe the funky clock in my curses app. However, if you can completely flush this theory down the toilet, it would be greatly appreciated... :) It would make my life easier in other aspects of the program I'm trying to write. Thanks, Alex From tim.one at comcast.net Wed Jul 16 16:44:37 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 16 Jul 2003 16:44:37 -0400 Subject: <> and != In-Reply-To: <609dd410.0307161202.32e47c3e@posting.google.com> Message-ID: [Don Arnold] > Out of curiosity, what was the original operator for the equality > comparison? '=' was used for both equality comparison and assignment. The ambiguity of this-- especially at an interactive prompt --soon killed that idea: >>> a = b If you look in a current Python source distribution, the script Demo/scripts/eqfix.py is still left over from the transition! From drlinux at columbus.rr.com Tue Jul 29 18:09:10 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Tue, 29 Jul 2003 18:09:10 -0400 Subject: Fw: Python-2.3c2.tgz installation In-Reply-To: <041d01c35614$542b3bc0$4901a8c0@beastjr> References: <041d01c35614$542b3bc0$4901a8c0@beastjr> Message-ID: <200307291809.10354.drlinux@columbus.rr.com> On Tuesday 29 July 2003 16:59, Sanjiv Kumar wrote: > > Hi, > > I am trying to build and install python-2.3 on a Solaris machine. It give segmentation fault during build process ( I guess during build of extensions to python i.e. running "build_ext"). I am using gcc --version 2.95.2 on SunOS xyz 5.8 Generic_108528-15 sun4u sparc SUNW,Ultra-60 machine. So any hint to get rid of this problem. > > Best Regards, > =Sanjiv= If the compiler gives a segmentation fault, I would think it's a bug in the compiler or it wasn't installed correctly. gcc 2.95.2 is pretty hold and I suspect (well, all code that large has bugs) it had bugs - there is a 2.95.3. I can report successful compilation of Python 2.3c2 on Solaris 9 using gcc 3.2.3. I would first try upgrading your compiler to 2.95.3 or gcc 3.2.3 or maybe even gcc 3.3 (I haven't looked to see how bug-free it is supposed to be). The latest Red Hat beta does include it so they must have got it to compile all their packages. Dave (who is patiently waiting for the final 2.3 so he can finish updating software on Solaris 9 machines) From frobozz_electric at hotmail.com Fri Jul 11 12:01:03 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 11 Jul 2003 16:01:03 GMT Subject: replace value of a specific position References: <3F0DA6FB.90603@soraia.com> Message-ID: "Mel Wilson" wrote in message > > '2'.join ((t[:5], t[6:])) > Sorry. Mel. No problem. I like to see better solutions :) From gh at ghaering.de Mon Jul 7 07:39:54 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Jul 2003 13:39:54 +0200 Subject: Python vs PHP In-Reply-To: <3F094FA4.9030800@ploiesti.astral.ro> References: <3F094FA4.9030800@ploiesti.astral.ro> Message-ID: <3F095C0A.3060500@ghaering.de> Catalin wrote: > Can Python replace PHP? With Python you can do everything that you can do with PHP. For Python, there are lots of frameworks/libraries for writing web applications, while PHP brings one out of the box. > Can I use a python program to make an interface to a mysql 4.X database? Sure. > If that's possible where can I find a tutorial? Python tutorials are at http://python.org/doc/Newbies.html -- Gerhard From faizan at jaredweb.com Mon Jul 28 21:47:45 2003 From: faizan at jaredweb.com (Fazer) Date: 28 Jul 2003 18:47:45 -0700 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> Message-ID: <7b454334.0307281747.5dd0e591@posting.google.com> Nevermind. I RTFM :-) . From http Thu Jul 24 21:43:01 2003 From: http (Paul Rubin) Date: 24 Jul 2003 18:43:01 -0700 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: <7x1xwf5ql6.fsf@ruckus.brouhaha.com> "Alan Dechert" writes: > BTW, do you know about cumulative binomial distribution? I think we need to > include a tool like this to give us some "C.L" (confidence level) short of > verifying that every single paper ballot matches its electronic counterpart. I'm skeptical of that approach. It assumes independent events. You should probably talk to a real statistician. This is the kind of stuff they do all the time. From proto at panix.com Thu Jul 10 17:35:29 2003 From: proto at panix.com (Walter Bushell) Date: Thu, 10 Jul 2003 17:35:29 -0400 Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> Message-ID: <1fxw51u.2b4m6zc39wulN%proto@panix.com> Charles Richmond wrote: > int *p, x, y; > > then: > > y = x/*p; > > is quite different from: > > y = x / *p; > > The first way, "/*" will begin a comment...the second way, > you get the integer "x" divided by the integer pointed to by "p". Ouch!! That is one reason code coloring is *important*. I remember working in Fortran and being confused why the compiler was not accepting the if statement, 'til we looked at the cards and saw it was a "1F" statement. -- Walter It is difficult to get a man to understand something," wrote Upton Sinclair, "when his salary depends upon his not understanding it." Walter From bokr at oz.net Thu Jul 24 15:03:45 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2003 19:03:45 GMT Subject: How do I get info on an exception ? References: Message-ID: On Tue, 22 Jul 2003 16:44:04 -0000, claird at lairds.com (Cameron Laird) wrote: >Raymond Hettinger wrote: >>> >You could catch it with: >>> > >>> > except socket.herror, inst: >>> > print inst.args >>> > >>> >or more broadly with: >>> > >>> > except socket.error, (errno, string_message): >>> > print code, message >>> > >>> > >>> >> More importantly, where is the answer documented that I should >>> >> have looked? >>> > >>> >The list of possible socket exceptions is in the docs for sockets. >>> >It also describes the (errno, string) return tuple value of inst.args. >>> . >>> . >>> . >>> True. >>> >>> But unsatisfying--at least to me. >> >>Submit a patch. > . > . > . >I deserved that. > >There was more to my post, of course. Part of what I was trying to >express is that exception interfaces are almost always relegated to >a footnote, with only a generalized description, even in the frequent >case that a method's exceptions are more complicated than its invoca- >tions. > >Rather than tilt at the collection of all such windmills, I want to >first understand better why this is, and what response is appropriate. >To summarize: I don't know what patch is the right one. I also >thought it only fair to warn Mr. July that things are indeed more dif- >ficult than we were explaining, even though I didn't feel up to >detailing the difficulties. > >So, Raymond, do you have general guidelines for how you think excep- >tions should be documented? ISTM there are (at least) two important places for doc info: Code-associated and language/tool-usage-associated. There are docs we approach as docs like books to read, and there are embedded docs as in doc strings and comments. And pydoc sort of bridges the gap and makes a book from code and whatall. I wonder where the best place is to enhance the documentation accessible to users. I suspect it would be in the area of pydoc and the structure of "code and whatall." The most likely place to find up-to-date info is in the latest code. (See below for an idea of how to enhance the latest code doc info without changing known-good code source). Exceptions (subject topic ;-) are a special case. In principle any code documentation could be enhanced by adopting source conventions to help pydoc present better info. The question then becomes how best to format the doc-enhancing info, where to put it, and how best to support its presentation. One thing that is a deterrent to improved documentation *within* code is that people like to minimize the number of official code versions, whether by CVS or just noting MD5 digests etc., and/or by burning an "official" CDROM. This makes me wonder if it would make sense to have a way to store doc info separately, yet still integratable into a pydoc presentation. One way would be to have a file name convention, so that the optional doc-enhancement info for e.g., xxx.py would be found in, e.g., xxx.dpy. This could make a clutter of small files though, so maybe one or more .dpx files could contain the mapping from multiple small related sources to a single .dpy. And by convention .dpy info for packaged files would be looked for in a .dpy for the overall package if not found separately. Ok, we could hone this search mechanism. What about the structure of .dpy files themselves, which now potentially could have info enhancing docs for both xxx.py and yyy.py? Some kind of easy internal labeled sections to separate xxx.py from yyy.py info would seem obvious. Then, the real question: what goes in the .dpy section for xxx.py so as to tie into certain parts of xxx.py code, without requiring changes to that code (which, remember, may be on a CDROM etc)? The context-finding mechanism of diff/patch would be one option, but to use that literally would make the .dpy files into diff files, and probably not something easy to generate manually and readably. And you don't want to carry a whole source fork just to maintain doc enhancement .dpy files. So we need some conventions functionally to enable human-doable doc diff patches. Maybe with special easy syntax to refer to exception raising loci in the code vs catching, vs functions, classes, methods, existing doc strings, etc, etc. An advantage of pure doc-enhancement info is that a mistake can't break the actual code, so more people could be given commit privileges for that kind of files, if maintained separately on CVS. Even wide-open wiki methods could be considered. You could even configure pydoc to query python.org efficiently to check if a local cache is out of date, and prompt for optional download. But this is a matter of arriving at some PEP consensus after discussing 1) whether it's worth discussing, and 2) what the usability goals are for both users and creators of doc enhancement info, and 3) who has the time to follow up on stuff like this. Just writing this post cost something, as will your replies (if any ;-) Regards, Bengt Richter From avner at skilldesign.com Fri Jul 25 08:34:30 2003 From: avner at skilldesign.com (Avner Ben) Date: Fri, 25 Jul 2003 14:34:30 +0200 Subject: Pythoness Message-ID: <3f2115e6$1@news.012.net.il> The following is from the "A Word A Day" newsletter (http://www.wordsmith.org/awad/subscribe.html) of 22 July 2003. I thought you'd find it amusing... >pythoness (PIE-thuh-nis) noun > > 1. A woman with the power of divination. > > 2. The priestess of Apollo at Delphi in Greek mythology. > >[Ultimately from Greek puthon (python).] > > "The coffee finds nothing else in the sack, and so it attacks these > delicate and voluptuous linings; it acts like a food and demands > digestive juices; it wrings and twists the stomach for these juices, > appealing as a pythoness appeals to her god ..." > Honore de Balzac; The Pleasures and Pains of Coffee; 1830s. > (translated from the French by Robert Onopa) > > "For this was a time when women were privileged, when female narratologists > had skills greatly revered, when there were pythonesses, abbesses and > sibyls in the world of narratology, who revealed mysteries and kept watch > at the boundaries of correctness." > A S Byatt; The Djinn in the Nightingale's Eye; The Paris Review (Flushing, > New York); Winter 1994. > >This week's theme: words that aren't what they appear to be. > Avner From gh at ghaering.de Fri Jul 11 18:04:54 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 00:04:54 +0200 Subject: call one python script from within another In-Reply-To: References: Message-ID: <3F0F3486.102@ghaering.de> Tubby Tudor wrote: > What is the best way to call one python script from within another > python script? For example: > > one.py finishes succesfully and calls two.py which finishes OK and then > calls three.py Unless you need different processes, it's better to just create one application with several functions, like this: #v+ def one(): pass def two(): pass def three(): pass def main(): one() two() three() main() #v- If you *really* need to execute Python scripts from within Python, you can use execfile(). If you want to execute arbitrary programs and wait for their completion, you can use the system() function in the os module. -- Gerhard From adalke at mindspring.com Mon Jul 28 22:43:51 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 28 Jul 2003 20:43:51 -0600 Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: Rick: > But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal > papers in the history of Python in the opinion of members of this > newgroups? - Lutz Prechelt's paper comparing C, C++, Perl, Java, Tcl, Python, and a couple more languages, all on the same non-trivial task - Greg Stein's paper at the San Jose conference (1998), on how his company used Python to make a commercial web app then sold it to Microsoft - helped convince me people could make money doing Python - not really a paper, but reading through the tutorial and the library docs back in 1997 were what convinced me that Python was the language for me. It still took 2 years before I could use it -- too much preexisting Tcl and Perl code. Andrew dalke at dalkescientific.com From gumuz at looze.net Fri Jul 25 04:48:51 2003 From: gumuz at looze.net (Guyon Morée) Date: Fri, 25 Jul 2003 10:48:51 +0200 Subject: i've been close to python's cradle :) References: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> Message-ID: <3f20ee21$0$13807$4d4ebb8e@news.nl.uu.net> I am from Holland too. A friend of mine had an internship there. At the end of this internship he was allowed to take 5 friends with him. We've seen all the super-computers upclose and we had 45 minutes of great fun in the CAVE (Computer Aided Virtual Environment) or Virtual Reality. Really cool-geeky-stuff! "Sybren Stuvel" wrote in message news:slrnbi00vi.2oo.sybrenUSE at sybren.thirdtower.com... > Guyon Mor?e enlightened us with: > > recently i've visited SARAH, the academic supercomputer in > > Amsterdam, Holland. this is next to the CWI, where Guido founded > > Python.... > > Nice one. Where are you from? > > I live close to the CWI, and will probably even do a few courses > there. Perhaps I'll look up Guido sometime :) > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? From tebeka at cs.bgu.ac.il Sun Jul 13 11:05:20 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 13 Jul 2003 08:05:20 -0700 Subject: Parsing stdout through a pipe? References: Message-ID: <33803989.0307130227.5da68840@posting.google.com> Hello MK, > C:\>snmputil trap > snmputil: listening for traps... > > > When a trap is generated on a remote server, it is being sent to > the PC running SNMPUTIL.EXE, and then finally printed out to > stdout like this: > > snmputil: trap generic=6 specific=11003 > from -> 10.198.163.89 > Variable = system.sysName.0 > Value = String DEAUDIIP109387 > Variable = .iso.org.dod.internet.private.enterprises.232.11.2.11.1.0 > Value = Integer32 0 > Variable = .iso.org.dod.internet.private.enterprises.232.11.2.8.1.0 > Value = String Compaq Management Agents Test Trap sent - Samstag, 12. > Juli 2003 18:52:19 > > > I'd like to write a Python application which would intercept/parse this > stdout > output, and invoke various pop-ups ("alarms"). Any ideas? Have a look at the popen2 module. I'd use wxPython or TKInter for the PopUps. HTH. Miki From cedmunds at spamless.rochester.rr.com Thu Jul 10 19:51:01 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Thu, 10 Jul 2003 23:51:01 GMT Subject: Create another Excel instance References: <9ee55987.0307101339.701965a7@posting.google.com> Message-ID: "yvan" wrote in message news:9ee55987.0307101339.701965a7 at posting.google.com... > I am using Excel to save data. > Everything works as i intend it to if no other instance of Excel is running. > If another instance is running, it will do the job, but also close that instance. > How can i prevent that from happening? > > Here is the code that creates and deletes the instance: > class CExcel: > def __init__(self, bVisible = 0): > import sys > import pythoncom > sys.coinit_flags = 0 > pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) > import win32com.client.dynamic > self.xlApp = win32com.client.dynamic.Dispatch("Excel.Application") > self.xlApp.Visible = bVisible > self.xlBook = self.xlApp.Workbooks.Add() > self.xlSheet = self.xlApp.ActiveSheet > > def __del__(self): > import pythoncom > if self.xlSheet != None: > del(self.xlSheet) > if self.xlBook != None: > self.xlBook.Close(0) > del(self.xlBook) > if self.xlApp != None: > self.xlApp.Quit() > del(self.xlApp) > pythoncom.CoUninitialize() > > Thank for your help, > > -Yvan I haven't tried this myself but maybe... if self.xlApp != None: nbook = self.xlApp.Workbooks.Count # number of open workbooks if nbook == 0: self.xlApp.Quit() Let us know how you made out. -- Cy http://home.rochester.rr.com/cyhome/ From klapotec at chello.at Thu Jul 31 23:37:20 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 01 Aug 2003 03:37:20 GMT Subject: How to run Python script on WindowXP References: Message-ID: <90ojiv8224hv3nv553jv4i62827kmd04no@4ax.com> On Fri, 1 Aug 2003 12:17:59 +1000, "Yunxian Mak" wrote: >Dear Sir/Madam, > >I'm doing my PhD in APAF and I installed Python 2.2 interpreter in >WindowNT before and it worked OK on my old computer. However, our >company has upgraded the systems to WindowXP recently. I installed >Python2.2.3, which includes IDLE (Python GUI), Module Docs, Python >(command line) and Python Manuals, on my new computer. I can open my >Python code from IDLE (Python GUI), but I don't know how to run it. If >you could please tell me whether the Python interpreter compatible to >WindowXP and how to run the Python script on WindowXP, I'll be much >appreciated. Thank you very much again. > If it's been installed normally, just double-clicking on your program icon in explorer should do the trick. If you open it with IDLE, you can use the Run command in the Run menu (Alt+F5). --Christopher From staschuk at telusplanet.net Wed Jul 9 10:08:37 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 9 Jul 2003 08:08:37 -0600 Subject: print attitude In-Reply-To: ; from donn@u.washington.edu on Tue, Jul 08, 2003 at 03:36:42PM -0700 References: <3F0669B5.679FB505@alcyone.com> Message-ID: <20030709080836.A506@tibia.amotlpaa.bogus> Quoth Donn Cave: > > > > Well, I see I never did convince you to try to describe > the intent of str directly. You did, but that text was written before my, er, conversion to that point of view. -- Steven Taschuk staschuk at telusplanet.net "I tried to be pleasant and accommodating, but my head began to hurt from his banality." -- _Seven_ (1996) From tim.golden at viacom-outdoor.co.uk Mon Jul 21 04:14:05 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 21 Jul 2003 01:14:05 -0700 Subject: Importing WMI module into Python CGI script fails References: <3F1A9A07.F71D274D@engcorp.com> Message-ID: <8360efcd.0307210014.3028d7de@posting.google.com> "MK" wrote in message news:... > "Peter Hansen" wrote > > [...] > > Hello Peter! This is what I get back in browser's window: > > > [ ... snip masses of traceback stuff ...] Well, in general if something works in the interpreter and not in CGI, it's down to permissions or environment or both, ie either the user running the CGI lacks some privilege which you (in the interpreter) have, or there's some environment variable or registry setting which is set for your user and not for the CGI user. The latter is less likely for Windows. As a starting point, try pulling the latest version of the module (version 0.3) which allows you to pass in a ready-made WMI object which you can construct with a user name. Get that working in interactive mode, and then see if it works in CGI. Something like this: import wmi import win32com.client loc = win32com.client.Dispatch ("WbemScripting.SWbemLocator") svc = loc.ConnectServer ("vodev1", "", "goldent", "password") vodev1 = wmi.WMI (wmi=svc) # Do stuff NB This won't work for a connection to a local machine (not even if you try to pretend it's a remote machine). If that's what you want to do, you'll probably need to Google for WMI security to discover how to allow whatever user the CGI is running under access to the WMI stuff. TJG From bokr at oz.net Mon Jul 7 00:13:17 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Jul 2003 04:13:17 GMT Subject: python scripting game The Temple Of Elemental Evil update References: <82ff1d8b.0307061540.5da32ae@posting.google.com> Message-ID: On 6 Jul 2003 16:40:28 -0700, cneal92 at lycos.com (O'Neal Computer Programmer) wrote: >I was reading here: http://groups.google.com/groups?q=elemental+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&selm=mailman.1044572235.32593.python-list%40python.org&rnum=3 >that a game The Temple Of Elemental Evil is going to be using python >as its scripting language. It says that on the FAQ which you can read >about here http://mywebpages.comcast.net/ibnobody/troika.html > >Q. What language are you writing the gamecode in? >A. (S.M. 2/6) The renderer is written in C, the animation player is in >C++, the game logic and user interface is also written in C, and most >of the scripting is done in Python (thanks Guido). > I'm wondering what "the scripting" does in the above. I.e., who writes the scripts, and what aspect of the games do they implement? When are they executed, and by what? (Apologies, too lazy/tired right now to pursue it via the links on this page ;-) >Anyway, this game also has a forum at >http://ina-community.com/forums/forumdisplay.php?s=&forumid=286 and >also one that you have to pay for at >http://vnboards.ign.com/board.asp?brd=22335 with more info about the >game. Regards, Bengt Richter From rimbalaya at yahoo.com Thu Jul 3 01:19:51 2003 From: rimbalaya at yahoo.com (Rim) Date: 2 Jul 2003 22:19:51 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <6f03c4a5.0307022119.2b0a4bc1@posting.google.com> Everyone! Thanks a lot for the insightful and enlightening discussion. I think the suggestion to solve the problem by using the __setattr__ special method will not work because it intercepts attribute assignment of the form "self.attr = somthing", and not what I want, which is "name = something". John suggested to look at properties, this is the closest I can get to the behavior I am looking for, but from my understanding, that will let me intercept "name.value = something" instead of intercepting "name = something". Thank you very much everyone. - Rim From piet at cs.uu.nl Tue Jul 8 06:56:24 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 08 Jul 2003 12:56:24 +0200 Subject: re module substitution confusion References: <88bc63c6.0307071326.3eb60848@posting.google.com> Message-ID: >>>>> writeson at earthlink.net (Doug Farrell) (DF) wrote: DF> Hi all, DF> I'm trying to do the following from within a code module: DF> import re DF> # text to match DF> text = "Good morning x something /x, how are you today x something DF> else /x" DF> # pattern to match DF> regex = re.compile("(x)(.*?)(/x)", re.DOTALL) DF> # find first match DF> m = re.search(regex, text) DF> # keep looking while there are matches DF> while m != None: DF> # substitute in some other text for the exact match DF> text = re.sub(m.group(), "Mr. Phelps", text) DF> # find the next match DF> m = re.search(regex, text) DF> print text DF> This works within the Python shell, but I can't seem to make it work DF> from within a program. It would seem like the re.sub(m.group()...) DF> would work fine as m.group() just returns the matched string DF> completely. It works for me (python2.2 and 2.3b2). BTW, you only need the outer parentheses in your r.e. And be aware that it will, match any x in your text, even when it occurs inside a word. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From adalke at mindspring.com Fri Jul 25 19:21:15 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 25 Jul 2003 17:21:15 -0600 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> Message-ID: holger krekel > We currently only have one 'visit' method that accepts a filter for returning > results and a filter for recursing into the tree. > for path in root.visit(AND(isdir, nolink)): > for path in root.visit(AND(isfile, endswith('.txt')), nodotfile): I've used the AND trick before, as well as tricks to support "isdir && nolink". Still, as these things get more complicated, its easier to just do for path in root.visit(lambda name: isfile(name) and name.endswith(".txt")) -or- def myfilter(name): return isfile(name) and name.endswith(".txt") for path in root.visit(myfilter): rather than use an prefix-style function interface. This doesn't introduce any new programming styles, which makes it easier to understand. The exception is if the result builds up some sort of parse tree which can be further analyzed for performance, which is not the case here. Andrew dalke at dalkescientific.com From jjl at pobox.com Sun Jul 27 20:53:15 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:53:15 +0100 Subject: emacs python-mode questions: C-c C-c and broken docstring fill References: <87ptjwre0x.fsf@pobox.com> Message-ID: <877k63a2v8.fsf@pobox.com> Skip Montanaro writes: > John> Wrong type argument: sequencep, cpython > > Where the comment says "TBD: a horrible hack...": try replacing the > beginning of the let with > > (let ((cmd (concat (if (eq shell (quote cpython)) > "python" > "jython") > (if (string-equal py-which-bufname "JPython") > " -" "")))) [...] That works. Thanks. John From sjmachin at lexicon.net Thu Jul 10 18:50:50 2003 From: sjmachin at lexicon.net (John Machin) Date: 10 Jul 2003 15:50:50 -0700 Subject: LOADING DATA INTO ARRAYS References: <200307100147.05841.skchim0@engr.uky.edu> <16140.22733.468173.643296@montanaro.dyndns.org> <200307100228.50214.skchim0@engr.uky.edu> Message-ID: Skip Montanaro wrote in message news:... > satish> ValueError: invalid literal for float(): 0.00000000000000D+000 > > It's been many years since I programmed any Fortran, so I'm no longer sure > what the 'D' notation stands for (double-precision?). As a first guess, I'd > suggest you change the 'D's to 'E's: > > >>> line.replace('D', 'E').split() > ['1.00000000000000', '0.00000000000000E+000', '0.00000000000000E+000'] > >>> map(float, line.replace('D', 'E').split()) > [1.0, 0.0, 0.0] Perhaps we have a version or platform difference here ... 2.2.3 on win32 works just fine (see below) C:\junk>python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> float('1.0d0') 1.0 >>> float('1.0D0') 1.0 >>> float('2.0D3') 2000.0 >>> float('0.00000000000000D+000') 0.0 >>> Seeing guessing is tolerated (at least in this thread): Python float() is defined in terms of the now-deprecated string.atof() which (I guess) is/are implemented by calling C atof() which in K&R 2 is defined in terms of strtod() which is not defined with any degree of precision as to what constitutes legal input -- some implementors of C libraries may well have confused the two separate concepts of valid *data* input and valid *code* input. Satish, for amusement: see what float('2.0e3f') gives you [that's a legal float constant in C]. For practical results, follow Skip's advice to replace 'D' with 'E'. Cheers, John From claird at lairds.com Fri Jul 18 20:19:40 2003 From: claird at lairds.com (Cameron Laird) Date: Sat, 19 Jul 2003 00:19:40 -0000 Subject: How do I get info on an exception ? References: Message-ID: In article , Raymond Hettinger wrote: . . . >You could catch it with: > > except socket.herror, inst: > print inst.args > >or more broadly with: > > except socket.error, (errno, string_message): > print code, message > > >> More importantly, where is the answer documented that I should >> have looked? > >The list of possible socket exceptions is in the docs for sockets. >It also describes the (errno, string) return tuple value of inst.args. . . . True. But unsatisfying--at least to me. I'm curious whether anyone else sees it the same way. We're talking here about , I assume, which tells us the socket module has three exception constants (and what they are), and also such details as that it might be except socket.error, (errno, string_message) but that it also might be simply except socket.error, string_message It's a temptation to go rhetorical at this point, and protest that we would not believe any other API documented if so little were written about it, but that we expect this poverty for exceptions. Rather than promote a general manifesto, though, I'll just summarize that neither the manual entry, nor the references it provides, give definite knowledge about even the signature of socket exceptions. A programmer who wants preci- sion in regard to exceptions must either experiment, or read implementation sources--and sometimes both. So, the answer to the question is the subject line is this: read the manual, then play with a live system to see what really happens. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From theller at python.net Thu Jul 31 08:26:50 2003 From: theller at python.net (Thomas Heller) Date: Thu, 31 Jul 2003 14:26:50 +0200 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> <9rehivsavhereijf36nhla96krct4s1fmn@4ax.com> Message-ID: Gerhard H?ring writes: > Christopher Koppler wrote: >> [tab settings] >> And, as others have said, DON'T use 5. > > I'd still like to hear a reason for this. > See PEP 8, Style Guide for Python Code: Consistency. Thomas From martin at v.loewis.de Sun Jul 6 03:07:14 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 06 Jul 2003 09:07:14 +0200 Subject: PEP idea. ( removing __slots__ ) In-Reply-To: <3f073594$1_2@news1.vip.uk.com> References: <3f073594$1_2@news1.vip.uk.com> Message-ID: simon place wrote: > To do this nicely requires the renaming of __dict__ to, say, > __attribs__ , ( since dict is unnecessarily unspecific, this seem like a > small improvement in itself. ) then using the setting of __attribs__ to > a non-mutable type (ie tuple of attribute names) to indicate the > behaviour of __slots__, rendering it unnecessary, this I think is a good > simplification. That does not work. __slots__ must be set at creation time of the class, not at creation time of the instance. In your approach, it appears that __attribs__ would be set, say, in __init__. If you meant that __attribs__ would be set to the tuple of attribute names inside the class definition directly, it appears that you have renamed __slots__ to __attribs__, which is pointless. Regards, Martin From creedy at mitretek.org Tue Jul 15 10:27:00 2003 From: creedy at mitretek.org (Chris Reedy) Date: Tue, 15 Jul 2003 10:27:00 -0400 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= In-Reply-To: References: Message-ID: <3F140F34.1030401@mitretek.org> Raymond Hettinger wrote: > Here are four more mini-mysteries for your amusement > and edification. > > In this episode, the program output is not shown. > Your goal is to predict the output and, if anything > mysterious occurs, then explain what happened > (again, in blindingly obvious terms). > > There's extra credit for giving a design insight as to > why things are as they are. > > Try to solve these without looking at the other posts. > Let me know if you learned something new along the way. > > To challenge the those who thought the last episode > was too easy, I've included one undocumented wrinkle > known only to those who have read the code. > I thought this one was much tougher than the Act 1. I ended up doing a lot of research on this one. I haven't read the other answers yet, I've been holding off until I finished this. (Having read my response, I apologize for the length. I don't think I scored so well on "blindingly obvious".) Here goes ... > ACT I ----------------------------------------------- > print '*%*r*' % (10, 'guido') > print '*%.*f*' % ((42,) * 2) This one wasn't hard. I've used this feature before. The stars at the front and back tend to act as visual confusion. The stars in the middle indicate an option to the format that is provided as a parameter. Thus the first one prints the representation (%r) of the string 'guido' as a ten character wide field. When I tried it, the only thing I missed was that the representation of 'guido' is "'guido'" not "guido". So the first one prints out: * 'guido'* rather than: * guido* which would have been my first guess. The second one takes just a little more thought. The result of this is equivalent to: print '*%.42f*' % 42 which yields *42.000000000000000000000000000000000000000000* That is a fixed point number with 42 digits after the decimal point. (Yes, I did copy that from Idle rather than counting zeros.) Aside: I have to admit that the ((42,) * 2) did confuse me at first. I'm so used to doing 2 * (42,) when I want to repeat a sequence that I hadn't thought about the reversed form. Having used this feature before, I have to say that I think the documentation for how to do this is quite comprehensible. > ACT II ----------------------------------------------- > s = '0100' > print int(s) > for b in (16, 10, 8, 2, 0, -909, -1000, None): > print b, int(s, b) Boy! This one send me to the documentation, and finally to the code. According to the documentation the legal values for the parameter b are b = 0 or 2 <= b <= 36. So the first print yields 100 (the default base for a string is 10 if not specified). The next few lines of output are: 16 256 10 100 8 64 2 4 0 64 The only one that deserves an additional comment is the last line. According to the documentation, a base of 0 means that the number is interpreted as if it appeared in program text, in this case, since the string begins with a '0', its interpreted as base 8. Let's skip -909 for a moment. -1000 raises an exception. None would also raise an exception if we ever got there. I also find that one a little non-intuitive, more about that later. For no immediately apparent reason (Raymond's undocumented wrinkle!), the next line of the output (after the above) is: -909 100 The only reason I found that was to try it. After hunting through the code (Yes, I have no problem with C. No, I'm not familiar with the organization of the Python source.) I eventually (see int_new in intobject.c) find out that the int function (actually new for the int type) looks like it was defined as: def int(x, b=-909): ... That is, the default value for b is -909. So, int('0100', -909) has the same behavior as int('0100'). This explains the result. Having read the code, I now understand _all_ about how this function works. I understand why there is a default value. For example: int(100L) yields 100, but there is no documented value for b such that int(100L, b) yields anything except a TypeError. However, using b=-909 is the same as not specifying b. This allows me to write code like: if type(x) is str: b = 16 else: b = -909 return int(x, b) I'm not really sure whether that's better than, for example if type(x) is str: return int(x, 16) else: return int(x) or not. However, I find the use of the constant -909 is definitely "magic". If it was up to me, I would use a default value of b = None, so that int(x) and int(x, None) are equivalent. It seems to me that that could be documented and would not be subject to misinterpretation. > ACT III ---------------------------------------------------- > def once(x): return x > def twice(x): return 2*x > def thrice(x): return 3*x > funcs = [once, twice, thrice] > > flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)] > flam = [lambda x:f(x) for f in funcs] > > print flim[0](1), flim[1](1), flim[2](1) > print flam[0](1), flam[1](1), flam[2](1) This one was ugly. I guessed the right answer but then had to do some more research to understand exactly what was going wrong. The first line prints 1, 2, 3 just like you expect. First reaction, the second line also prints 1, 2, 3. But, Raymond wouldn't have asked the question if it was that easy. So, guessing that something funny happens I guessed 3, 3, 3. I tried it. Good guessing. Now why? After a bunch of screwing around (including wondering about the details of how the interpreter implements lambda expressions). At one point I tried the following (in Idle): for f in flam: print f(1) And wondered why I got an exception for exceeding the maximum recursion limit. What I finally realized was that the definition of flam repeatedly binds the variable f to each of the functions in funcs. The lambda expression defines a function that calls the function referenced by f. At the end of the execution of that statement, f is thrice, so all three of the defined lambdas call thrice. That also explains why I hit the maximum recursion limit. At this point I felt like I had egg on my face. I've been burned by this one in the past, and I spent a while figuring it out then. The fix is easy: flam = [lambda x, fn=f: fn(x) for f in funcs] which creates a new local binding which captures the correct value at each iteration. This is the kind of problem which makes me wonder whether we ought to re-think about binding of variables for loops. > ACT IV ---------------------------------------------------- > import os > os.environ['one'] = 'Now there are' > os.putenv('two', 'three') > print os.getenv('one'), os.getenv('two') Obviously, this one is trying to trick you into thinking it will print 'Now there are three'. I ended up trying it and getting 'Now there are None'. Then I went back and read the documentation. What I got confused about was that os.putenv updates the external environment without changing the contents of os.environ. Updating os.environ will change the external environment as a side effect. I had read about this before but had gotten the two behaviors reversed in my head. Now, why is it this way? It makes sense that you may have a use case for changing the external environment without changing the contents of os.environ and so need a mechanism for doing so. However, on reflection, I'm not sure whether I think the implemented mechanism is counter-intuitive or not. From pinard at iro.umontreal.ca Thu Jul 17 16:05:25 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 17 Jul 2003 16:05:25 -0400 Subject: Accessing and updating global variables among several modules In-Reply-To: References: Message-ID: [Fuming Wang] > The problem is caused by Python creating two copies of the module that is > passed to the interpreter. We were recently bitten by a variation on this problem. A co-worker and I were writing one module each for a single project, both modules were to derive classes from a common base class from the same module `listes'. Everything was to be installed in a single package `Lc'. In his module, he wrote: from Lc import listes while in my module I wrote: import listes In fact, both `import' worked, yet `listes' was not the same object for each of our viewpoints, and so, our classes did not have a common base. Object initialisation was modifying a supposedly common registry of created objects, kept as a class variable in the base, so there was a problem. P.S. - Or something similar, I'm not sure I remember correctly. So many things happen between a particular day and the next one! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From andy at wild-flower.co.uk Wed Jul 9 19:01:02 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Thu, 10 Jul 2003 00:01:02 +0100 Subject: QUESTION In-Reply-To: <4e.1efa9c3f.2c3d7c25@aol.com> References: <4e.1efa9c3f.2c3d7c25@aol.com> Message-ID: <200307100001.02458.andy@wild-flower.co.uk> On Wednesday 09 Jul 2003 3:09 pm, Matt5883 at aol.com wrote: Let me just see... ahhhem. Wait, no, sorry I just *can't* remember your IP address (or in fact if you've even got one) so I can't look at your hard-drive! ;-)) Seriously though, you need to rephrase your question a bit... but I'll give it a go anyway... > What is python 2.1.1? 1) Python is a (rather good) programming language. It can be used to write applications; any applications written in it also require the python system to be installed (or otherwise present) on your system. >How did it get on my computer? 2) It got on your computer because it was installed by someone - prabably as part of an application you installed. >Is it a necessary program? 3) Only if one of your cherished applications uses it ;-p > Can I safely delete it/remove it? 4) You can safely remove it if you don't want the application that needs it. > If so how? 5) Just rename the directory where you found it, and then test all the applications you want to keep. If one of them falls over in a heap, you'll know that Python was part of it ;-) and you can then rename it back to the original name. If nothing breaks, you can then safely delete it! (I'd wait a while, though). > I do not recall downloading it. 7) Can't help you with that one. :-( >Does it come bundled with some other program? Maybe one of > my kids did it. 8) Maybe, maybe; maybe not... >I do not see enough information on your site to make these > determinations. 9) I think you probably mean that there's way too much information on the site, and you think it'd take you an absolute age to figure out how to make these 'determinations' :-) >I have a Compaq 5184 with OEM Win 98 installed...I do not > ever recall seeing "python" in the programs. 10) That's (almost) irrelevant, but Python is not part of Windows (98 or any other). >I have been having alot of problems with my computer lately and I am removing unecessary "junk" 11) You'll be wanting to download Linux, then, I guess :-p I recommend Mandrake Linux, but www.linux.org has a huge list of other flavours. > Thanks, > Matt Don't take offense; your post *did* have a slightly, er, narky tone though! Anyway, I'm off to bed as the Misses is due to give birth R.S.N and we need rest! hope that helps -andyj From peter at engcorp.com Wed Jul 9 05:50:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 05:50:15 -0400 Subject: format discs. References: Message-ID: <3F0BE557.43E0D287@engcorp.com> Flanagan wrote: > > somebody can say to me whereupon I modulate of python I can format > discs. What disks? What operating system? Why? (Usually one would be happy to let the user handle these details using OS facilities. Why bother integrating such a feature into your program?) -Peter From jwhitlark at attbi.com Thu Jul 24 23:24:25 2003 From: jwhitlark at attbi.com (Jason Whitlark) Date: 24 Jul 2003 20:24:25 -0700 Subject: Can't Close Word Instance without Save Changes Dlg Box References: Message-ID: "GerritM" wrote in message news:... > schreef in bericht > news:mailman.1058804373.21700.python-list at python.org... > > I am using COM to manipulate word attachments to emails. Once I use them > I > > am not concerned with saving the results. I use the following line: > > > > myWord.ActiveDocument.Close(wc.wdDoNotSaveChanges) > > > > This closes the document fine but only after I click no on the resulting > > "Save Changes" dialog box. Am I missing something really simple? I can > > send preceding lines if needed. > > > > Thanks in advance, > > > > Loren Poulsen > > > I have never tried this in Word. However I had the same kind of problem in > Visio, which could be solved by setting the document status to saved, > something like: > myWord.ActiveDocument.saved = 1 > > regards Gerrit I think "saved" needs to be capitalized myWord.ActiveDocument.Saved = True -Jason From stacom at stacom-software.de Fri Jul 25 09:20:51 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Fri, 25 Jul 2003 15:20:51 +0200 Subject: data conversion question (binary string to 'real string') In-Reply-To: References: Message-ID: <3F212EB3.7020600@stacom-software.de> Manish Jethani wrote: > Alexander Eisenhuth wrote: > > >>maby I don't see the forest because of all that trees, but : > > > Maybe I don't understand your question... > > >>from struct import * >> >> >># how can I convert >>f = float(0.5) >> >># with >>bin_str = pack('!f', 0.5) >> >># now bin_str is '?\x00\x00\x00' >> >> >># to "3F000000" ????? > > > ??????????????? > What is your question? > > -Manish > Sorry ... This two lines converts 0.5 to a string in binary representation >>>from struct import * >>>bin_str = pack('!f', 0.5) now bin_str is '?\x00\x00\x00', wich is the representation of 0.5 in the memory. I need now to convert this binary string to "3F000000", where '3F' is the hex value of the '?' in ascii - table. Any ideas ?? Thaks Alexander From andreas.kuntzagk at mdc-berlin.de Wed Jul 2 10:40:42 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 02 Jul 2003 16:40:42 +0200 Subject: undo tab References: <3F02E7D5.4060401@gmx.net> <3F02ECF0.105@gmx.net> Message-ID: Hi, > Maybe you can just give me a general hint how you do it and which editor > you use. That would probably also help. I use Xemacs, and do it with "Ctrl-c <" I don't know about Emacs on Windows, but the "GNU Emacs FAQ For Windows" can probably help you with this: http://www.gnu.org/software/emacs/windows/ntemacs.html HTH, Andreas From dave at boost-consulting.com Sun Jul 13 21:02:49 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 13 Jul 2003 21:02:49 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <3F11C42F.5030406@alcyone.com> Message-ID: Erik Max Francis writes: > This is completely incorrect. On the contrary, builtin types are > handled exactly uniformly in Python. The only difference here is that > the builtin types that you've listed, along with some others, are > immutable, so you cannot change them if you have a reference to them. All you guys must be forgetting: >>> a = [1] >>> b = a >>> a += b >>> assert id(a) == id(b) >>> a = 1 >>> b = a >>> a += b >>> assert id(a) == id(b) Traceback... -- Dave Abrahams Boost Consulting www.boost-consulting.com From max at alcyone.com Tue Jul 8 18:46:39 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Jul 2003 15:46:39 -0700 Subject: anything new on the ternary operator? References: Message-ID: <3F0B49CF.F58F1D35@alcyone.com> Tor wrote: > (if C: x else: z) > > Was this the winning syntax? Best way to answer this is to just read PEP 308: http://www.python.org/peps/pep-0308.html -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ To be adult is to be alone. \__/ Jean Rostand From CousinStanley at hotmail.com Sun Jul 6 17:56:40 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 6 Jul 2003 14:56:40 -0700 Subject: Using Loops to track user input References: Message-ID: hokiegal ... Another way if you also wish to save the input numbers ... nLoops = 10 list_nums = [] for i in range( nLoops ) : this_num = int( raw_input( 'Enter an Integer : ' ) ) list_nums.append( this_num ) total = reduce( int.__add__ , list_nums ) print print list_nums print print total -- Cousin Stanley Human Being Phoenix, Arizona From http Mon Jul 21 14:57:47 2003 From: http (Paul Rubin) Date: 21 Jul 2003 11:57:47 -0700 Subject: Possible use of Python for a voting machine demo project --your feedback requested References: Message-ID: <7xptk3yafo.fsf@ruckus.brouhaha.com> "Alan Dechert" writes: > We'll see. The touch screen we intend to use works well with a stylus. So > if we get too many mistakes using fingers, we may just have people using a > stylus exclusively. Try to avoid that. Use a real big screen if needed (Wacom makes some nice ones). > I'll take this as a prediction, not necessarily correct, however. Our team > includes some people with extensive experience with voting machine > evaluation -- they think it will work. But again, we won't know for sure > until we try. But beyond that, most voting machine PCs we are proposing to > use will be mouse driven. So even if it proves to be too dense for a stylus > (very unlikely, imo) it is certainly not too dense for a mouse. Virtually > all of the testers using the web based version will be using a mouse. I think a production system shouldn't use mice. > On the other hand, a lot of people really really like the touch screens. We > can't make them all mouse driven since a percentage of the voters will have > a big problem with that. But there is no reason to give up on mouse driven > systems just because some people can't use them. Mice are very cheap and > most people are used to them. What do you mean by "most people are used to them"? Do you really mean "most computer users are used to them"? I remember hearing that most (i.e. more than half) of the people in the world have never even made a phone call, much less used a computer. How that maps onto US voters, I don't know. I hope you will do user testing with people from all backgrounds and social strata. Go to some senior citizen centers; get a few street people ("will work for food") to try out the system; etc. > > Anyway, I wish you luck -- we certainly need open voting systems. The > > current closed systems scare me. > > > I appreciate your taking the time to write. Do you talk anywhere about auditibility, i.e. how does anyone verify that your published source code is the same code actually running on the machines? From drs at ecp.cc Sat Jul 12 15:09:26 2003 From: drs at ecp.cc (drs) Date: Sat, 12 Jul 2003 19:09:26 GMT Subject: The "intellectual property" misnomer References: Message-ID: "Cliff Wells" wrote in message news:mailman.1058029899.16454.python-list at python.org... > On Fri, 2003-07-11 at 20:30, Ben Finney wrote: > > On Fri, 11 Jul 2003 22:47:21 -0400, Tim Peters wrote: > > > Ben Finney wrote: > > >> Guido van Rossum wrote: > > >> > The PSF holds the intellectual property rights for Python > > >> Ugh. Please don't propagate this ridiculous, meaningless term. > > > > > > Guido isn't writing a treatise on the law, he's briefly explaining > > > (part of) what the PSF does. > > > > The term he used doesn't explain anything, and only confuses. * * * > > People may have an assumption about what is meant by the term, but they > > are almost certainly wrong, since the fields of law that are sometimes > > lumped together by that term have almost nothing in common. As the holder of a degree in the law and as a programmer, I would like to diverge from the rest of this argument by saying that this is flatly wrong. Patent, copyright, trademark, and trade secret have much in common which causes them to be lumped into one convenient category. Perhaps the most important thing is that they are all created from intellectual endeavors. They are the things which are not plots of land or buildings, i.e. they are the things which are not what lawyers call "real property." Whether one thinks there should be property rights in intellectual creation is one thing, but suggesting that simply because there are differences in those rights or in how they are granted implies that there are not similarities in the law which governs or in how it is interpreted is logically incorrect. > No, they are most certainly not wrong. Most people using Python have > probably at least perused the license. Having done so, I doubt that > they need to have it spelled out every time it is mentioned. > > > There is nothing useful indicated by the term "intellectual property > > rights", because it presumes there is some commonality between fields of > > law that deal with different intellectual concepts, impose different > > restrictions, and presume different rights. > > That's like saying the word "food" is useless because there's nothing in > common between a sandwich and a bowl of rice. Or more to the point, it is like the OP's use of the word lawyer. As someone who has primarily studied IP, Antitrust and Constitutional Law, I don't want to be lumped into the same category with someone who does transactional work or who files divorce papers, yet the term lawyer does just this. One should be careful about chastising other for using terms which are too general as that is the nature of spoken language. Words are imprecise, and category words like "Intellectual Property" or "lawyer" or "food" are not tuples which are iterated over in conversation. * * * > > > I don't think pedantic verbosity makes it any clearer, but may mislead > > > due to omission. > > > > And using a term that attempts to blanket wildly different legal rights > > is *not* misleading due to omission? No, this is not how this works. It is very common in the law to make a list or use a term which is illustrative. The Latin is "Noscitur a sociis" which means to interpret the general to be similar to specifics in a series. So, we all know what the series is here, and it is, as mentioned by others, clearer to not list all of the specifics as this will cause people to search for omissions -- "Expressio unius" is the term there. -drs IGWOS (it goes without saying), IANALATINLA (i am not a lawyer and this is not legal advice). From karl_lopes at hotmail.com Sun Jul 13 04:37:38 2003 From: karl_lopes at hotmail.com (Karl Lopes) Date: Sun, 13 Jul 2003 08:37:38 GMT Subject: PythonCard newbie question Message-ID: Hello All, I downloaded and installed PythonCard. When I try to run the minimal app in samples I get the following errors: module' object has no attribute 'Background'. : module' object has no attribute '__version__' Any ideas what I am missing here. Thanks Karl. From psycho_78 at libero.libero.it Thu Jul 31 10:43:58 2003 From: psycho_78 at libero.libero.it (Simone Finotti) Date: Thu, 31 Jul 2003 16:43:58 +0200 Subject: [Newbie] FAQ? References: Message-ID: Christopher Koppler ha scritto: > On Thu, 31 Jul 2003 15:08:07 +0200, psycho_78 at libero.libero.it (Simone > Finotti) wrote: > >hi all, > >is there a FAQ for this NG? > > > http://www.faqs.org/faqs/by-newsgroup/comp/comp.lang.python.html > Have you heard of Google? sure I did! Pardon... -- questo articolo e` stato inviato via web dal servizio gratuito http://www.newsland.it/news segnala gli abusi ad abuse at newsland.it From mis6 at pitt.edu Thu Jul 3 16:46:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 3 Jul 2003 13:46:46 -0700 Subject: Overriding list.__new__ Message-ID: <2259b0e2.0307031246.6054693d@posting.google.com> Let me show first how does it work for tuples: >>> class MyTuple(tuple): ... def __new__(cls,strng): # implicit conversion string of ints => tuple ... return super(MyTuple,cls).__new__(cls,map(int,strng.split())) >>> MyTuple('1 2') (1, 2) No wonder here, everything is fine. However, if I do the same for lists I get the following: >>> class MyList(list): ... def __new__(cls,strng): #implicit conversion string of ints => tuple ... return super(MyList,cls).__new__(cls,map(int,strng.split())) >>> MyList('1 2') ['1', ' ', '2'] The same is true for >>> class MyList(list): ... def __new__(cls,strng): ... return list.__new__(cls,map(int,strng.split())) >>> MyList('1 2') ['1', ' ', '2'] therefore it is not a problem of super. The 'map' expression does not seem to be executed or, if its executed, it has no effect at all. If I replace 'map' with anything, still I have the same result: >>> class MyList(list): ... def __new__(cls,strng): ... return list.__new__(cls,map(int,[]) # !notice: empty list here! >>> MyList('1 2') ['1', ' ', '2'] In other words I always get the result of >>> list('1 2') ['1', ' ', '2'] and it seems impossible to override list.__new__. I am very puzzled about that; any suggestions? Michele From syver at inout.no Tue Jul 1 05:56:21 2003 From: syver at inout.no (Syver Enstad) Date: 01 Jul 2003 11:56:21 +0200 Subject: Want to create an ActiveX object from a Python class References: <34ac6a99.0306300955.4202abb5@posting.google.com> Message-ID: shi at imaging.robarts.ca (Shi Sherebrin) writes: > A colleague wants some functionality that I've built in a Python class > available to 'drop' into her Visual C++ project. Some time ago she > gave up on trying to use 'regular' COM servers, since ActiveX controls > integrate so much more easily. So if I can't wrap the Python class > into an ActiveX object, I'll have to port it. > > I've been searching through the pythoncom and ctypes documentation and > samples, and can't seem to find any examples of making an ActiveX > object. The pythoncom documentation claims that ActiveX is the same > as COM, but there seems to need to be more added to a COM server to > make it an ActiveX object, and I don't know nearly enough to know how > to do this. > > Is anyone else interested in doing this, and has anyone managed to do > so? If I am not mistaken, the only thing your colleague needs is a type library for the python com object. In the cases I've experienced this is what makes MS IDE's tick when it comes to COM objects. From andersjm at dancontrol.dk Tue Jul 29 03:51:44 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Tue, 29 Jul 2003 09:51:44 +0200 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: <3f2627c7$0$76067$edfadb0f@dread11.news.tele.dk> "Aahz" wrote: > Jeff Epler wrote: > > > >I don't see what's problematic about letting slices be hashable: > [...] >Hashing them as > > hash((s.start,s.stop,s.step)) > >might be a reasonable definition. > > Makes sense to me. Feel free to submit a patch to SF. ;-) I'd rather he didn't. I prefer Python to be able to catch the bug of attempting to use a dict as were it a list. For the rare case where using a slice key was intentional, converting to tuple form is easy enough. I can see that it's good for consistency to allow hashing of slices. However it's bad for consistency that where alist[slice] returns a subsequence, adict[slice] would return a single element. - Anders From jepler at unpythonic.net Mon Jul 28 16:31:06 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 28 Jul 2003 15:31:06 -0500 Subject: Fastest way to count your iterations? In-Reply-To: References: Message-ID: <20030728203105.GE14508@unpythonic.net> You could use generator functions as one way to implement a spinner. from __future__ import generators import sys, time # I think this may be called "cycle" in 2.3's itertools def spinner_next(chars): while 1: for c in chars: yield c def spinner(interval=100, chars="/-\\||", pos=0): ci = spinner_next(chars) while 1: # for interval iterations, don't advance spinner for i in range(interval): yield None # OK, now advance spinner # and print it in a low-tech fashion sys.stdout.write(ci.next()+"\n"); sys.stdout.flush() def calculate(): j = 0 s = spinner(10) for i in range(1000): time.sleep(.01) j = j + i s.next() # advance spinner 1 iteration print j calculate() Jeff From max at cNOvSisiPonAtecMh.com Thu Jul 3 09:50:34 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 03 Jul 2003 13:50:34 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: import flame.* import sorry.* Ok, with all my respect to python, the stuff about C++ is a bunch of hooey. Compilation time is the problem? Give me a break. 1) separate compilation? 2) precompiled headers? 3) tools that allow cluster compilation? 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ project. letter-envelope idiom to help compilation...etc. Anyway, if you are coding so fast that compilation time becomes a serious problem you are either a) the smartest and fastest programmer on earth b) are not thinking enough c++ is great when execution speed and memory efficiency is a must. It is hard to learn, but there are great benefits, and do you really want halfwits (who can't learn it) involved on your project? It also (by design) makes previous C programmers productive very fast. Empirically - just look at all the C++ projects on SF! max. -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Max M" wrote in message news:3f03f430$0$97222$edfadb0f at dread12.news.tele.dk... > There is a story today on Slashdot > > > Open Source Project Management Lessons > ====================================== > http://developers.slashdot.org/article.pl?sid=03/07/02/1817220&mode=flat&tid =185 > > "Paul Baranowski takes a moment to reflect on Open Source Project > Management in his blog. His reflections are based on the first two years > of the Peek-a-booty project." Interesting comments on media coverage, > choice of programming language, when to release a project, and more. > > > In that article Paul Baranowski has a list of lessons. One being > > Engineering Lessons > ------------------- > 1. C/C++ is no longer a viable development language > > > He doesn't really say in the article what language should be used > instead. But there is a link to another page: > > Which Language Do You Recommend? > ================================ > http://peek-a-booty.org/Docs/WhichLanguageDoYouRecommend.htm > > > And guess which language it is? > > > regards Max M > From peter at engcorp.com Thu Jul 17 09:20:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Jul 2003 09:20:25 -0400 Subject: Python Asynchronous Services References: Message-ID: <3F16A299.3DC0D93C@engcorp.com> Graeme Matthew wrote: > > while 1: > data = recv(1024) > if not data: break > > surely in a thread this will block all other threads until all data is > recieved. Why "surely"? It's actually not the case. A blocking call such as to socket.recv() means that the *calling* thread is blocked until the call returns, not that other threads are blocked. In fact, the other threads will immediately be free to run since the calling thread will release the Global Interpreter Lock before it blocks in the OS socket call. > I have also been told that one cannot rely on this mechanism as > the socket might end up in a continious loop, i.e you need to send a header > included in the data that states the length (bytes) that is been sent, or > you need some terminator, what happens if the terminator is within the > requests data and not at the end ? Now you're getting into a higher level. You certainly *can* "rely" on sockets, or receiving data in chunks like the above, but it's certainly not the easiest way to approach things at this point. You know about asyncore, and it would work, and Moshe has mentioned Twisted (and I have to agree that looking there is your best bet); no point reinventing the wheel, and even if you're trying to learn, you'll probably learn a lot by examining the source to either of those packages. > please any help or examples as I have now been on this for 2 days without > any luck. I have looked at asyncore and asynchat, problem is once the server > socket input is completed then their will be an area that is CPU bound where > it will need to call the model, database etc and produce the html request, > this means that control will only be handed back to IO operations when this > is finished, effectively blocking all other requests .... Knowing about how to use a Queue to communicate with a pool of threads, or a single worker thread, for CPU bound requests, is a good skill... > I suppose another question is can python handle large files and requests at > the same time or is one better off simply forking the process even though > its costly ? Python is quite capable of this... and forking is definitely not required. On the other hand, you're better off in general not worrying about performance issues until you've figured out how to make something work properly. Forking is not the best approach, but mainly because of its relative complexity, not because of "cost". -Peter From stephane.bidoul at softwareag.com Mon Jul 28 05:53:42 2003 From: stephane.bidoul at softwareag.com (=?ISO-8859-1?Q?St=E9phane_Bidoul?=) Date: 28 Jul 2003 02:53:42 -0700 Subject: datetime1 - datetime0, same tzinfo, different dst References: Message-ID: <82a334e5.0307280153.290d7c97@posting.google.com> "Tim Peters" wrote in message news:... > [...] > > Is that the designed behaviour? > > Yes. You can read Guido's thinking here: > > http://www.zope.org/Members/fdrake/DateTimeWiki/NaiveTime > > and here: > > http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo > > and at other less relevant pages in that Wiki. > > [...] Okay, thanks for the pointers. I really didn't expect a design oversight from you ;-) And long live UTC. -sbi From khalid.sheikh at silvaco.com Fri Jul 18 12:38:01 2003 From: khalid.sheikh at silvaco.com (Khalid Sheikh) Date: Fri, 18 Jul 2003 09:38:01 -0700 Subject: How do I convert &$self.text(dbcol[docdb].pretty_name); into something meaningful in python Message-ID: Hi, I have been tasked to Integrate Inktomi Search (now Verity of course) with our website. I am fairly new to Python. The way the search engine is setup is that it has embedded python in a html document. After looking at the html code for a day or so, I was able to pin point the place where I need to make a change but I am having a hard time. I am assuming &$self.text(dbcol[docdb].pretty_name); prints something in HTML but I am trying to figure out it's equivalent in Python. I am assuming this is a string and I need to check it's value against another string say 'XXY' if it is equal then go ahead and print that value otherwise skip to the next item in the list/array. This is what I had before and it worked , Test< &$self.text(dbcol[docdb].pretty_name); >Test when run this prints Test< XXY >Test, Test< ABCD >Test I want it to print only when the string is equal to XXY. otherwise skip to the next string. This is the edited code that I have so far. , Test< &$self.text(dbcol[docdb].pretty_name); >Test I get the following error when I run the program. exceptions.SyntaxError: invalid syntax (line 86) Line 86 if dbcol[docdb] == wlines.append(u' '); Any help would be greatly appreciated. Khalid J. Sheikh Software Engineer Silvaco International http://www.silvaco.com (408) 654-4352 From skip at pobox.com Thu Jul 10 09:58:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 10 Jul 2003 08:58:19 -0500 Subject: LOADING DATA INTO ARRAYS In-Reply-To: <3f0d55db@shknews01> References: <3f0d55db@shknews01> Message-ID: <16141.28923.425194.99087@montanaro.dyndns.org> Jiri> Because if the line is '123 456 789', then line.split() is Jiri> ['123', '', '', '456', '789'] Nope: % python Python 2.2.3 (#1, Jun 21 2003, 08:08:22) [GCC 3.0.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> line = '123 456 789' >>> line.split() ['123', '456', '789'] >>> line.split(" ") ['123', '', '', '456', '789'] line.split() is not line.split(" "). Skip From tcronj at ananzi.co.za Sun Jul 20 05:25:06 2003 From: tcronj at ananzi.co.za (Tertius) Date: Sun, 20 Jul 2003 11:25:06 +0200 Subject: tk prerequisite In-Reply-To: <9a410299.0307191718.5dd25502@posting.google.com> References: <3f0fffc0$0$235@hades.is.co.za> <9a410299.0307191718.5dd25502@posting.google.com> Message-ID: <3f1a5f7a$0$228@hades.is.co.za> klappnase wrote: > Tertius wrote in message news:<3f0fffc0$0$235 at hades.is.co.za>... > >>Installing tkinter 2.2.3 on RH9 the following message displayed >> >> >>[root at host 223]# rpm -i tkinter-2.2.3-26.i386.rpm >>warning: tkinter-2.2.3-26.i386.rpm: V3 DSA signature: NOKEY, key ID fd71b297 >>error: Failed dependencies: >> libtcl8.3.so is needed by tkinter-2.2.3-26 >> libtix8.1.8.3.so is needed by tkinter-2.2.3-26 >> libtk8.3.so is needed by tkinter-2.2.3-26 >> >> >>Question: >> >>Must it be 8.3 or will 8.4 also do ? >> >>TIA >>Tertius > > You definitely need 8.3 (however these should be the defaults in RH9 if I > remember correctly, have you upgraded manually?). > > Cheers > > Michael I had to install the kernel source to get tcl. Done that now. Thanks From hannibalkannibal at yahoo.no Sat Jul 19 13:05:27 2003 From: hannibalkannibal at yahoo.no (Eirik) Date: Sat, 19 Jul 2003 19:05:27 +0200 Subject: Executing a program Message-ID: Greetings! How can I run a program from within Python? I have tried the exec* family of functions, but I get these strange errors, like this: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1300, in __call__ return apply(self.func, args) File "./PPP", line 9, in run_app os.execvp("home/eirik/ppp-skript", argument) File "/usr/lib/python2.2/os.py", line 298, in execvp _execvpe(file, args) File "/usr/lib/python2.2/os.py", line 324, in _execvpe apply(func, (file,) + argrest) OSError: [Errno 2] No such file or directory From tchur at optushome.com.au Thu Jul 10 17:42:21 2003 From: tchur at optushome.com.au (Tim Churches) Date: 11 Jul 2003 07:42:21 +1000 Subject: Business model for Open Source - advice wanted In-Reply-To: <246a4e07.0307100613.fc2fc50@posting.google.com> References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <1057873340.1204.40.camel@emilio> On Fri, 2003-07-11 at 00:13, Frank Millman wrote: > I am busy developing an accounting package, using Python and wxPython, > together with PostgreSQL on a Unix platform or SQL Server on a Windows > platform. Excellent choice of tools - identical to those used by the GnuMed project (except for MS SQL Server - but note that PostgreSQL 7.4, expected to be production quality soon, will run natively under Windows). The common infrastructure raises the possibility of integrating your package with GnuMed at some time in the future - at the very least, GPs (family physicians) and others who adopt GnuMed will be able to install your package without any extra work at all - and every doctor needs an accounting package... -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From skip at pobox.com Tue Jul 1 12:51:56 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 1 Jul 2003 11:51:56 -0500 Subject: Python hosting? In-Reply-To: <3F017FEF.D499AA5B@hotmail.com> References: <3F017FEF.D499AA5B@hotmail.com> Message-ID: <16129.48172.157646.890054@montanaro.dyndns.org> >> Can anybody recommend a good hosting package >> for Python? Must be cheap, that is max. $5 per month. Alan> Check out the Python Hosting Wiki, which is the most authoritative Alan> list I've come across. Alan> http://www.python.org/cgi-bin/moinmoin/PythonHosting And if you find a solution not listed, feel free to add it. It is a Wiki, after all. Skip From gh at ghaering.de Thu Jul 10 17:54:47 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 10 Jul 2003 23:54:47 +0200 Subject: Business model for Open Source - advice wanted In-Reply-To: <1057873340.1204.40.camel@emilio> References: <246a4e07.0307100613.fc2fc50@posting.google.com> <1057873340.1204.40.camel@emilio> Message-ID: <3F0DE0A7.20407@ghaering.de> Tim Churches wrote: > On Fri, 2003-07-11 at 00:13, Frank Millman wrote: > >>I am busy developing an accounting package, using Python and wxPython, >>together with PostgreSQL on a Unix platform or SQL Server on a Windows >>platform. > > Excellent choice of tools - identical to those used by the GnuMed > project (except for MS SQL Server - but note that PostgreSQL 7.4, > expected to be production quality soon, will run natively under > Windows). [...] Unlikely. This is most likely to get postponed to later (version 7.5). PITR also didn't made it for 7.4. Apart from this nitpick I agree that the choice of tools is excellent. They're my preferred ones as well. FWIW building a Pg/Cygwin installer shouldn't be too much effort, either. Basically just provide a trimmed down Cygwin. Native win32 PostgreSQL versions are also available from third parties ... -- Gerhard From andrew-pythonlist at puzzling.org Mon Jul 28 20:18:08 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 29 Jul 2003 10:18:08 +1000 Subject: Any open source utilities built on top of PyUnit? In-Reply-To: References: Message-ID: <20030729001808.GF23610@frobozz> On Mon, Jul 28, 2003 at 09:03:15AM -0700, J. Michael Hammond wrote: [...] > I've gone through the PyUnit documentation the decision comes down to > this: are there any utilities out there, built on top of PyUnit, that > are gaining traction? Say is there some kind of GUI package that > allows easy "run these suites on these machines" sorts of things? Or > a test results reporting package? Or any other things like that? This is really orthogonal to what unit test library (and what language!) you use, but BuildBot (http://buildbot.sourceforge.net/) can automatically run tests on various machines for you when you checkin to your source repository. I believe there's also a "try" command in the works, so you can tell BuildBot to "try" a set of changes on various buildslaves, to check that you haven't broken anything unexpected (and without needing to checkin your code to find out). Also, Twisted (http://twistedmatrix.com/) has a PyUnit-like utility of its own, Trial. It is almost API-compatible with PyUnit, but comes with a handy command-line utility, 'trial', that lets you specify which tests to run on the command-line, e.g.: trial mypackage.tests # run all tests in mypackage.tests trial mypackage/tests # ditto trial mypackage.tests.test_foo # run all testcases in test_foo.py trial mypackage/tests/test_foo.py # ditto # run only one testcase trial mypackage.tests.test_foo.BarTestCase # run only one test method trial mypackage.tests.test_foo.BarTestCase.test_baz I find this to be a much nicer way to work than by sprinkling magic if __name__ == '__main__': unittest.main() stanzas in all my tests, then having to figure out the right magic to write a "test_all.py" or something to run all the tests. Hope this helps, -Andrew. From shane at zope.com Fri Jul 11 13:05:56 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 11 Jul 2003 13:05:56 -0400 Subject: Securing PyDoc and CGIHTTPserver In-Reply-To: <3f0de5c0$0$49113$e4fe514c@news.xs4all.nl> References: <3f0de5c0$0$49113$e4fe514c@news.xs4all.nl> Message-ID: <3F0EEE74.6050008@zope.com> Irmen de Jong wrote: > Shane Hathaway wrote: > >> What about binding only to the local (loopback) interface? That way, >> the system won't even listen for external connections. It's like a >> built-in firewall. >> >> The change is a one-liner. The DocServer computes the hostname for >> the loopback interface but then binds to all interfaces. So change >> this line: >> >> self.address = ('', port) >> >> to: >> >> self.address = (host, port) >> > > I think Shane meant: > > self.address = ('localhost',port) No, actually the 'host' variable is computed on the line before it. :-) It's either "127.0.0.1" or "localhost", depending on the platform. "localhost" is preferable for readability, but "127.0.0.1" is more reliable. Shane From kkto at csis.hku.hk Wed Jul 30 01:04:05 2003 From: kkto at csis.hku.hk (Isaac To) Date: 30 Jul 2003 13:04:05 +0800 Subject: variable assignment in "while" loop References: <3f2695ca$0$76124$edfadb0f@dread11.news.tele.dk> Message-ID: <7iwue061x6.fsf@enark.csis.hku.hk> >>>>> "Anders" == Anders J Munch writes: Anders> "Aahz" wrote: >> Peter usually gives a good answer, but this time there's a better >> answer: Anders> With a bug, but if we combine Peter's answer with yours we get Anders> an even better answer: Anders> def fetch_iter(mydbcursor): while 1: info = Anders> mydbcursor.fetchone() if not info: break yield info Or perhaps use a function instead... def while_iter(f): while True: result = f() if (not result): return yield result Then you can convert while info = mydbcursor.fetchone(): print "Information: "+str(info) trivially to for info in while_iter(lambda: mydbcursor.fetchone()): print "Information: "+str(info) Regards, Isaac. From hanzspam at yahoo.com.au Wed Jul 2 14:36:37 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 2 Jul 2003 11:36:37 -0700 Subject: 'For' loop symmetry with list comprehensions. Message-ID: <840592e1.0307021036.508d7d7d@posting.google.com> One can currently say this with list comprehensions: [x.lower() for x in words if x.startswith('foo')] Wouldn't it be better if the normal 'for' syntax was symmetrical with the notation used in list comprehensions? To be more specific, it lacks the 'if' part. I.e. this should be possible: for x in words if x.startswith('foo'): print x Naturally this is the same as: for x in words: if x.startswith('foo'): print x So one only benefits from one level shorter tabulation in some situations. I admit this isn't much of a benefit in terms of making shorter programs, but it would make the language more symmetrical, which I do consider a win. It's a feature that wouldn't need any learning or remembering since it's already used in list comprehensions. From fabsk+news at free.fr Wed Jul 30 06:17:03 2003 From: fabsk+news at free.fr (Fabien SK) Date: Wed, 30 Jul 2003 12:17:03 +0200 Subject: Embeding Python, COM crash In-Reply-To: <3f278bf0$0$24554$626a54ce@news.free.fr> References: <3f278bf0$0$24554$626a54ce@news.free.fr> Message-ID: <3f279b5d$0$8925$626a54ce@news.free.fr> Fabien SK wrote: > Hi, > > I wrote a plugin for Visual C++ 6 that uses Python 2.2 (it worked > perfectly for months). I just installed Python 2.3, and recompiled my > plugin, and now it crashes. My plugin do the following things: In fact, I found that it crahses with the versions more recent that winall-152: - win32all-154 / python 2.2 - win32all-155 / python 2.3 From anthony at interlink.com.au Tue Jul 22 09:47:38 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 22 Jul 2003 23:47:38 +1000 Subject: [OT] SCO is Going After End Users In-Reply-To: <23891c90.0307220139.1909fc63@posting.google.com> References: <23891c90.0307220139.1909fc63@posting.google.com> <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: <200307221347.h6MDlcNi027540@localhost.localdomain> >>> Paul Boddie wrote > (Insert footage of an office in IBM's legal department: the camera > pans upward from a stack of papers representing SCO's claims; > hysterical laughter can be heard as the camera pans across to one of > the lawyers; "I love this job!" he exclaims.) It's gotta be a weird time to be in IBM's legal department. I think it's safe to say that my opinion of "hurry up and just finish off the desperate/pathetic attempts of SCO to extort money from the rest of the world" is probably not uncommon. How often is it that people barrack for IBM legal? (Although, in this case, it's a bit of an open-and-shut case for me to work out which side to support. I mean, look at all the good things SCO's done for the computing community... there's XENIX, and SCO UNIX, and... well, no, actually, they've done fuckall. Bye bye SCO, you won't be missed.) -- Anthony Baxter It's never too late to have a happy childhood. From achalk at XXXmagnacartasoftware.com Wed Jul 30 14:41:57 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Wed, 30 Jul 2003 18:41:57 GMT Subject: Python debugger Message-ID: I am sure that it has been asked before but could someone tell a newbie whether there is a Python debugger out there? In case it is relevant, i am using v2.2 on Windows. Many thanks. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jul 13 15:01:11 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 13 Jul 2003 21:01:11 +0200 Subject: =?ISO-8859-1?Q?=F1=EF=E5=F8=E8=E0=EB_=E4=EB=FF_=F0=EE=F1?= =?ISO-8859-1?Q?=F1=E8=E9=F1=EA=E8=F5_=EF=E8=F2=EE=ED=F9=E8=EA=EE=E2=29?= =?ISO-8859-1?Q?=29=29?= In-Reply-To: <37d6f77c.0307130932.1e3adf0d@posting.google.com> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> Message-ID: <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> Garber wrote: > ?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? > exe-???? ?????????). Yes! I think. ;-) On second thought, what's he saying? From skodela at lithium.com Tue Jul 15 21:28:42 2003 From: skodela at lithium.com (sreekant) Date: Wed, 16 Jul 2003 01:28:42 +0000 (UTC) Subject: Anyone noticed any new changes in tkinter Message-ID: Hi guys I am running slackware 9.0 with python 2.2.2 and previously under mandrake I wrote a few programs for personal use. Now the same progs work partly under the new environment. Mainly tkinter$.widget$.bind("",proc) now causes error and fails with error :- Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1299, in __call__ args = apply(self.subst, args) File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1035, in _substitute e.height = getint(h) ValueError: invalid literal for int(): ?? Any ideas sreekant From bgailer at alum.rpi.edu Thu Jul 24 12:18:54 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 24 Jul 2003 10:18:54 -0600 Subject: Mystery Theater New Style Classes Message-ID: <5.2.1.1.0.20030724101747.02b6c4c0@66.28.54.253> Predict the output: class A(int): classval = 99 def __init__(self, val = 0): if val: self = val else: self = A.classval a=A(3) b=A() print a,b The question this leads to is: how does one access the value of such a class within a class method? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From hanzspam at yahoo.com.au Mon Jul 14 13:30:56 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 14 Jul 2003 10:30:56 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <5tn2hvgjqlqg1qs7omvugpvm62cuso261k@4ax.com> Message-ID: <840592e1.0307140424.110cc2e3@posting.google.com> Stephen Horne wrote in message news:<5tn2hvgjqlqg1qs7omvugpvm62cuso261k at 4ax.com>... > >def foo(a, b, c): > > return a+b, b+c > > You are not directly returning multiple values - you are returning a > tuple. You can return containers in C++ too. The only difference is > that Python makes working with tuples *much* easier - but its no more > a 'simple progression' than in C++. You still need to know about > tuples as well as returning values. You don't need to know about tuples so that you can understand that multiple values are returned, and that's the difference. I didn't know of tuples when I saw some of my first Python code, yet the idiom for returning multiple values was trivially clear. It became even better though when I learned it was implemented through tuples ;). In contrast, in C++ one needs to explicitely state make_pair or make_tuple, requiring the user to know of the underlying types. Had I been required to type def foo(a, b, c): return tuple(a+b, b+c) x = foo(a, b, c) a = x[0] b = x[1] Then I could've agreed with you. But multi-assignment from tuples and implicit creation of tuples makes the returning of multiple values look like a language feature, not a way to abuse tuples. This ease of use is the reason it can work as a replacement for C++'s "send-by-reference". From hollyw61 at hotmail.com Mon Jul 14 13:04:40 2003 From: hollyw61 at hotmail.com (Holly) Date: 14 Jul 2003 10:04:40 -0700 Subject: python 1.5.2 cgi.py and os.py error Message-ID: <6e1f9b77.0307140904.6d4279af@posting.google.com> Hello List, My windows laptop configured as: XP, Python 1.5.2, MySQL 4.0.9 and Appache 1.3.17 A form ("Post" has been used) has a product list with about 400 products. The user checks each item he wants and place an order. NOw when they hit "Place Order" or "Cancel Order" , apache pops an error in log: [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] Premature end of script headers: c:/program files/apache group/apache/htdocs/usa/order.py [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] Traceback (innermost last): [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] File "c:\PROGRA~1\APACHE~1\apache\htdocs\usa\order.py", line 1923, in ? [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] Main() [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] File "c:\PROGRA~1\APACHE~1\apache\htdocs\usa\order.py", line 1892, in Main [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] form = FormContent() # handle stdin parsing [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] File "C:\usr\bin\lib\cgi.py", line 1097, in __init__ [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] self.dict = parse(environ=environ) [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] File "C:\usr\bin\lib\cgi.py", line 528, in parse [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] environ['QUERY_STRING'] = qs # XXX Shouldn't, really [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] File "C:\usr\bin\lib\os.py", line 243, in __setitem__ [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] putenv(key, item) [Wed Jul 09 14:33:11 2003] [error] [client 127.0.0.1] OSError: (0, 'Error') If I delete more than ten records in the product table, the error disappears. Any ideas? Thanks in advance. From bitbucket at electron.me.uk Fri Jul 4 19:04:51 2003 From: bitbucket at electron.me.uk (Geoffrey Clements) Date: Sat, 05 Jul 2003 00:04:51 +0100 Subject: Eric3 segfaulting Message-ID: <3f060811$0$56603$bed64819@pubnews.gradwell.net> I'm brand new to Python - just giving it a try but I'm having trouble with eric3. This query isn't exactly about the Python language but it is related. I run KDE on linux so I already have Qt installed. I have installed Python, SIP, QScintilla, PyQt and eric3. When I run eric3 the fonts in the editor are way too large, so I selected preferences to change them but when I hit "OK" I get a segfault whether I have made a change or not. So I tried to debug eric3 in eric3 but I'm too new at this to be of any use :-(. I get the following error: The debugged program raised the exception unhandled KeyError "19" /home/geoff/eric-3.1/eric/Preferences/PreferencesLexer.py, Line: 75 This line is: return self.colours[style] which is the end of function color. Any help would be appreciated. -- Geoff Registered Linux user 196308 Replace bitbucket with geoff to mail me. From stuart_clemons at us.ibm.com Wed Jul 23 15:25:13 2003 From: stuart_clemons at us.ibm.com (stuartc) Date: 23 Jul 2003 12:25:13 -0700 Subject: Newbie question about Python & W2K Admin Message-ID: <86d2ca4.0307231125.70ee3f57@posting.google.com> Hi all: I need to change a few Local Security Settings on a number of W2K machines. An example of a Security Setting I need to change is the "Minimum password length" setting, which is under Account Policies, Password Policy. Instead of doing this manually on each machine, I would like to have an automated way to do this. Can Python be used for this ? Any direction on how to automate this using Python or some other tool will be greatly appreciated. - Stuart From vze4rx4y at verizon.net Tue Jul 15 15:19:56 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 15 Jul 2003 19:19:56 GMT Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <3F140F34.1030401@mitretek.org> Message-ID: [Chris Reedy] > The fix is easy: > > flam = [lambda x, fn=f: fn(x) for f in funcs] > > which creates a new local binding which captures the correct value at > each iteration. This is the kind of problem which makes me wonder > whether we ought to re-think about binding of variables for loops. Hmm, I put too many distractors in this one. It's not about lambda and loops. And though it touches on nested scopes and list comprehensions, the crux is just plain old bound / unbound variables inside a function definition: >>> base = hex >>> def changebase(x): ... return base(x) >>> changebase(20) '0x14' >>> base = oct >>> changebase(20) '024' It's a feature! Raymond Hettinger > From tjreedy at udel.edu Thu Jul 3 02:16:19 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Jul 2003 02:16:19 -0400 Subject: getting a submatrix of all true References: Message-ID: "John Hunter" wrote in message news:mailman.1057173484.29754.python-list at python.org... > > I have a largish data set (1000 observations x 100 floating point > variables), and some of the of the data are missing. All too typical -- missing data are the bane of statistics. > I want to try a > variety of clustering, neural network, etc, algorithms on the data, > and to keep life simple I want to reduce the dimensions of the matrix > so that I have no missing values, since not all the algorithms are > able to handle them and there is sufficient redundancy in the > variables that I can afford to lose some. Statisticians have tried a variety of approaches. Googling for ' statistics "missing data" 'will give you some leads if you want. Terry J. Reedy From yaipa at yahoo.com Fri Jul 25 00:49:49 2003 From: yaipa at yahoo.com (yaipa h.) Date: 24 Jul 2003 21:49:49 -0700 Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> <3F13703C.C12392D6@engcorp.com> <6e07b825.0307151214.3d2cce2@posting.google.com> <3F146F57.94A49564@engcorp.com> Message-ID: <6e07b825.0307242049.56dec88a@posting.google.com> Peter, Thanks, basically one server feed many serial clients. From the sound of your post I had better get "Serial Port Complete" before giving it another run. Thanks. -Alan Peter Hansen wrote in message news:<3F146F57.94A49564 at engcorp.com>... > "yaipa h." wrote: > > > > All, > > > > Worked like a charm for me too! I used it to develop an > > automated attendant for a Serial Oven Controller. The > > attendant ran from Sparc Solaris using Python 2.1 and pySerial. > > > > The only weird thing, which I didn't get a chance to > > debug, was a perfectly working script under RS-232 > > got terribly out of sync when R/W I/O to a RS-485 > > serial network. Any reason why that would be? > > Well, one reason might be that RS232 is point-to-point, while > RS-485 is many-to-many, at least in principle. Was this a > bus network, or at least a "multidrop" situation with one master > and many slaves? There are no guarantees in those situations, unless > you've been very careful to ensure proper handshaking, timing, > and such. > > If you want to discuss this, please define "out of sync" in more > detail... it could mean anything. > > -Peter From alanmk at hotmail.com Mon Jul 21 05:55:14 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 21 Jul 2003 10:55:14 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <60dfb6f6.0307201951.4eea1930@posting.google.com> Message-ID: <3F1BB882.D142EE0D@hotmail.com> Alan Kennedy: >> So, the challenge to the ASCII proponents is: put the greek word >> "gignooskoo" on everybody's screen, originating from a usenet message, >> in the original greek, where "oo" -> greek letter omega. Carl Banks wrote: > I accept. > > ____ ____ ___ _____ ___ > | | | |\ | / \ \ | / / \ > | | | | \ | | | \ | / | | > | | | | \ | | | > |< | | > | | | | \| \ / / | \ \ / > | | | | | _\ /_ /____ | \ _\ /_ > Very clever! You win a prize: a nice pint of cold frothy beer! oOoOo ,==||||| || ||||| || ||||| '==HHHHH """"" Sl?inte mhaith! :-) -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From kyle at lakeofburningfire.org Fri Jul 4 22:45:46 2003 From: kyle at lakeofburningfire.org (Kyle Yancey) Date: Sat, 05 Jul 2003 02:45:46 GMT Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> <87k7azdber.fsf@titan.staselog.com> Message-ID: Puffin looks nice, although it has undergone some changes that haven't been documented yet. Part I http://www-106.ibm.com/developerworks/opensource/library/os-puffin.html Part II http://www-106.ibm.com/developerworks/opensource/library/os-puffin2.html On Thu, 03 Jul 2003 15:47:56 +0300, Edvard Majakari wrote: >On Wed, 2 Jul 2003, ageron at HOHOHOHOvideotron.ca wrote: > >> threads? A lot of projects would be better off not using them, I agree >> with that, but some projects just can't do without them! Web sites are >> also horrible to automatically unit test. In all those cases, I much >> prefer having a human being go out and do the unit tests manually. > >Which reminds me: I've seen two web unit testing frameworks, one which was >by the originial PyUT author, and the other that seemed more complete, >though not so well documented either. > >I've fancied developing one myself - so I'd like to know what kind of >things should I take into account before trying such a largish project? I >know that it is hard to test Web-based applications, for one thing - the >user doesn't usually type GET parameters to the URL, while doing so could >be the only possible way to do automated web site testing. Ideas/comments? From florian.proff.schulze at gmx.net Tue Jul 15 08:48:55 2003 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Tue, 15 Jul 2003 14:48:55 +0200 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <182bcf76.0307141319.7b6fed7a@posting.google.com> <20030715090753.M6906@prim.han.de> Message-ID: Try google with "cache:http://..." this worked for me. Florian On Tue, 15 Jul 2003 10:45:45 +0200, Paolo Invernizzi wrote: > holger krekel wrote: > >> Paul Moore wrote: >> >>> holger krekel wrote in message >>> news:... >>> >>>> I agree that something like Jason Orendorff's path module should go >>>> into >>>> the standard library. I've coded a similar module and i think that >>>> a discussion about certain design decisions would probably improve our >>>> approaches. >>> >>> Is it available anywhere? It would be nice to be able to try both, for >>> comparison. >> >> >> sorry, not right now. I'll try to make a release soonish. >> >> holger >> > > I cannot access the path.py module from > http://www.jorendorff.com/articles/python/path/ > > Someone can be so kind to email it to me? > > Thanks in advance! > > --- > Paolo Invernizzi > paoloinvernizzi at dmsware.com > > > > -- Florian Schulze From tim.one at comcast.net Tue Jul 22 14:21:53 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 22 Jul 2003 14:21:53 -0400 Subject: python22_d.lib? In-Reply-To: Message-ID: [solosnake] > Well I thought I would take my first few steps in embedding python > today, and had to stop much sooner then I hoped. Where is > python22_d.lib? If you want a debug-build Python, you're expected to build it yourself. > Why is it not in the release? Because all users pay to download Python, but a relatively tiny percentage of Windows users have any use for a debug-build Python. We used to include it in releases, but dealing with questions about it from confused newbies proved to be an unsustainable time sink. > I have 2.2.3, but nowhere is there such a library. Must I get the source > and build it myself? Yes. Or ActiveState may still have one available for download. From news at yebu.de Wed Jul 2 08:04:58 2003 From: news at yebu.de (Karl Scalet) Date: Wed, 02 Jul 2003 14:04:58 +0200 Subject: splitting a string into 2 new strings In-Reply-To: References: Message-ID: Mark Light schrieb: > Hi, > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 > strings > 'C H O' and '6 12 6'. I have played with string.split() and the re module - > but can't quite get there. > > Any help would be greatly appreciated. > > Thanks, > > Mark. > Hi Mark aka Sugar-Baby, there are very likely easier ways, but at least s = 'C6 H12 O6' print [' '.join(xx) for xx in apply( zip,[(x[0],x[1:]) for x in s.split()])] gives some results, Karl From prashsingh at yahoo.com Tue Jul 22 14:00:25 2003 From: prashsingh at yahoo.com (Prashant Singh) Date: Tue, 22 Jul 2003 13:00:25 -0500 Subject: py2exe command line window problem In-Reply-To: References: Message-ID: Bob Gailer wrote: > At 09:27 AM 7/22/2003 -0700, Prashant Singh wrote: > >> I'm using py2exe to create a standalone executable from a Python >> script, and I would like the script to run invisibly, i.e. without a >> console window and without any interactive GUI. The script is a helper >> app, which simply downloads and runs some other program. >> >> I've tried passing the -w flag to the script, and I've also tried >> renaming it with a .pyw extension, but when the executable is run an >> empty console window opens with the title "C:\WINNT\system32\cmd.exe". >> I've checked, and there are no print statements, which might cause >> py2exe to assume it's still a console app. > > > How are you running the executable? Usually it gets executed by a browser (Mozilla, Firebird, IE), but I've tried running it from Start->Run... and from a Command Prompt window. In all cases it creates a new, blank console window. Thanks, prashant. From db3l at fitlinxx.com Mon Jul 14 14:20:57 2003 From: db3l at fitlinxx.com (David Bolen) Date: 14 Jul 2003 14:20:57 -0400 Subject: How to get all IP addresses in python? References: <6cd58b6.0307110715.1bb9bc23@posting.google.com> Message-ID: Afanasiy writes: > FYI, It works perfectly on my Windows 2000 machine. > > ... import socket > ... print socket.getaddrinfo(socket.gethostname(), None) > [(2, 0, 0, '', ('124.181.217.203', 0)), (2, 0, 0, '', ('169.254.25.142', > 0)), (2, 0, 0, '', ('169.254.218.201', 0))] > ... Just remember that all of these approaches presume that your local DNS server (or whatever server responds for your local machine name) has all of the various possible addresses. There's no guarantee that DNS will match precisely what your machine is actually configured with, including perhaps not having all of your addresses. So its entirely possible to return appropriate information in one case but not in another. What is really desired for this sort of query is to ask the system about the actual configured interfaces - getting local IP addresses shouldn't need to involve DNS at all (not to mention the traffic necessary to resolve the information). The problem is that checking the physical interface configuration is not a portable procedure (specific IOCtls on most Unix systems, not positive about Windows but I know registry querying could do it). This isn't an issue limited to Python. -- David From solosnake at solosnake._remove_this_.fsnet.co.uk Tue Jul 22 13:50:29 2003 From: solosnake at solosnake._remove_this_.fsnet.co.uk (solosnake) Date: Tue, 22 Jul 2003 18:50:29 +0100 Subject: python22_d.lib? Message-ID: Well I thought I would take my first few steps in embedding python today, and had to stop much sooner then I hoped. Where is python22_d.lib? Why is it not in the release? I have 2.2.3, but nowhere is there such a library. Must I get the source and build it myself? I'm using MSVC++ 6.0. Thanks for all help, D?ire Stockdale From jadestar at idiom.com Sun Jul 20 07:31:16 2003 From: jadestar at idiom.com (James T. Dennis) Date: Sun, 20 Jul 2003 11:31:16 -0000 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> <1058561410.563105@smirk> <3F187ED4.6179CDDD@engcorp.com> Message-ID: <1058700676.64323@smirk> Peter Hansen wrote: > "James T. Dennis" wrote: >> Sean 'Shaleh' Perry wrote: >>>> If my english was better I would love to help improve the python >>>> documentation, most modules in the standard libraries lack good >>>> examples how to *use* them with just a simple description. And a >>>> short motivation for the design of a module if possible like "just >>>> copied the C API" or "Because of efficiency ..." or "We use a class >>>> framework here because ...". A gigantic task. The PSL book by effbot >>>> is great but it's a book. And it needs a new version. >>> part of the reason why the docs are not but so great is that most of the >>> library is Python code which means any questions can be answered by reading >>> the source. I find myself doing this quite often. >> That's BS! >> As a dabbler in programming I have to say that poor documentation is not >> excused by the availability of sources. > True, but poor documentation *is* excused quite nicely by the LACK > of availability of _re_sources, specifically the human resources and time > required to make them better. > Or was your flame an indirect offer to assist with improving the > documentation of Python? If so, thank you! > (It's not like you've paid anything for the privilege of whining...) > -Peter Yes. Moreover my suggestion for an enhancement to the web site docs would be a way to facilitate that. Go look at the PHP documentation. Anyone reading it can attach comments; those can be merged into the docs as appropriate. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From sjmachin at lexicon.net Fri Jul 18 20:52:39 2003 From: sjmachin at lexicon.net (John Machin) Date: 18 Jul 2003 17:52:39 -0700 Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: Doug Tolton wrote in message news:<215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>... > I have a function that returns a tuple: > > def checkdoc(self, document): > blen = document['length'] > bates = document['obates'] > > normal, truncated, semicolon = 0,0,0 > for bat in bates: > if len(bat) == 2 * blen: > semicolon += 1 > if len(bat) == blen - 1: > truncated += 1 > if len(bat) == blen: > normal += 1 self.total_normal += normal # etc etc # someone else suggested a separate class just for statistics # --- this is overkill IMHO > > return normal, truncated, semicolon > From news at 92tr.freeserve.co.uk Mon Jul 7 09:11:10 2003 From: news at 92tr.freeserve.co.uk (ddoc) Date: Mon, 7 Jul 2003 13:11:10 +0000 Subject: Python and Perl module for signature of XML at UK Gove gateway Message-ID: http://www.clocksoft.com/government_gateway.html Clocksoft have made and released an Open Source alternative to the proprietary (and to me odd-looking) signing mecahnism required for the gov gateway. Well done them. -- A From tjreedy at udel.edu Mon Jul 28 16:53:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jul 2003 16:53:23 -0400 Subject: octet string conversion References: Message-ID: "Matthew" wrote in message news:ec1162c7.0307281214.50b68373 at posting.google.com... > I am working on some software that uses SNMP to get information from > routers and switches. I am using the pysnmp module (v2.0.8) to do the > snmp part. The problem that I am having is that when I query a router > for mac addresses pysnmp returns octetstrings like this: > > \000\002\263\254\264\351 > \010\000 \301F\021 > \010\000 \300\303[ > \000\002\263\254\264\241 > > what I need though is hex strings like this: > > 0:e0:7d:de:5:48 > 0:e0:7d:c8:dc:9f > 8:0:36:4:3b:de > 0:80:ad:3a:9e:2b > > Can anyone tell me how to convert the octet strings to hex strings? Is this what you want? >>> s=repr('\000\002\263\254\264\351').replace(r'\x', ':') >>> s "':00:02:b3:ac:b4:e9'" # double " single ' ... single ' double " >>> s[2:-1] '00:02:b3:ac:b4:e9' Terry J. Reedy From nushin2 at yahoo.com Tue Jul 22 22:08:41 2003 From: nushin2 at yahoo.com (nushin) Date: 22 Jul 2003 19:08:41 -0700 Subject: How to disable spawnv's child process output messages Message-ID: Greetings, I have a program called hello_earth.py that is spawned by hello_moon.py, using spawnv( ) API as: os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello_earth.py'),('>/dev/null &')) I do not wish to see any output messages from the hello_earth.py when it is launched by its parent process and i do wish to see *only* the output messages from the parent process in the shell. Is Python capable to so such a thing? I have used '>/dev/null &' to disable the output of the child process, but unfortunately, i still see them. Is there a way around it? Reagrds, BB From 336699 at emailaccount.com Fri Jul 25 01:24:56 2003 From: 336699 at emailaccount.com (336699) Date: 24 Jul 2003 22:24:56 -0700 Subject: How to import hackicon.dll References: <8a5a6d82.0307240417.494caa13@posting.google.com> Message-ID: srovner at us.ibm.com (Sonia Rovner) wrote in message news:<8a5a6d82.0307240417.494caa13 at posting.google.com>... > Hello, > I'm using Python2.2.1 and Tcl/Tk 8.3 running on Win2000. I've been > researching how to change the icon on the title bar and found that > hackicon is the one I should pursue. However, hackicon package uses a > dll. When I run the hi.py, I get an error saying > ImportError: DLL load failed: The specified module could not be > found. > I copied hackicon.dll to various directories in my pythonpath but > nothing happens. Use tkIcon http://effbot.org/downloads/index.cgi/tkicon-0.9-19980218.zip From simon_place at whsmithnet.co.uk Sun Jul 6 10:18:20 2003 From: simon_place at whsmithnet.co.uk (simon place) Date: Sun, 06 Jul 2003 15:18:20 +0100 Subject: PEP idea. ( removing __slots__ ) In-Reply-To: References: <3f073594$1_2@news1.vip.uk.com> Message-ID: <3f083043$1_3@news1.vip.uk.com> The point is to combine __dict__ and __slots__ into a new __attribs__, the distinction being the type of __attribs__. If you don't specify __attribs__ in the class you get the default __dict__ behavior, if you do, and use a tuple, then you get the __slots__ behavior, and you can easily tell which by checking the type, you could also iterate over the attributes without caring which it was. From rune.hansen at sinsenveien83.com Fri Jul 25 07:22:51 2003 From: rune.hansen at sinsenveien83.com (Rune Hansen) Date: Fri, 25 Jul 2003 13:22:51 +0200 Subject: Problem with pyOpenSSL and Python2.3c In-Reply-To: References: Message-ID: Hi, I've got no problems with pyOpenSSL with Python 2.3c1 on MacOS X 10.2.x. I've only buildt pyOpenSSL with Python2.3b2 on RedHat 9, and had no problems there either. I may be able to help you if you provide some information about your setup and error messages. regards /rune Stephen C. Waterbury wrote: > I'm trying to get pyOpenSSL to work with Python 2.3c on > Red Hat 9, but there seems to be a Python C API incompatibility. > I assume this just means that a new version of pyOpenSSL is > needed for Python 2.3 -- is that correct? > > - Steve. > From gh at ghaering.de Thu Jul 31 04:36:16 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 10:36:16 +0200 Subject: Python vs. Perl vs. PHP? In-Reply-To: <7b454334.0307301611.1b40ff11@posting.google.com> References: <7b454334.0307281002.41dae81b@posting.google.com> <7b454334.0307301611.1b40ff11@posting.google.com> Message-ID: <3F28D500.1080105@ghaering.de> Fazer wrote: > [...] I am basically looking for a FAST > alternative to PHP meaning the responce time is fast. Do you think > that Python with using the CGI module is a good solution? No, CGI is not a good solution in this case, no matter what the language (except those perverts who use something like C with dietlibc for this). The base technology to make web requests fast in Python is something like mod_python or a Python application server. On top of this I'd recommend you use a Python web framework, of which there are numerous ones. The hard part is to evaluate them and choose one. FWIW I'm currently using Quixote running with mod_scgi against Apache, mostly because I was fed up with the (lack of) Webware documentation, which I tried first. -- Gerhard From tzot at sil-tec.gr Sun Jul 27 17:34:08 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 28 Jul 2003 00:34:08 +0300 Subject: [Python] Re: [OT] On the TimBot References: Message-ID: On Thu, 24 Jul 2003 07:32:32 -0500, rumours say that "Chris Gonnerman" might have written: >> "Delaney, Timothy C (Timothy)" wrote in message >news:... >> > > From: Christos "TZOTZIOY" Georgiou [mailto:tzot at sil-tec.gr] >> > > >> > > what's the use of a Bit that's always true? >> > >> > Well, it compresses really well ... >> >> Yes, a single unchanging bit in time compresses very well (contrary to >> a single bit at a specific moment in time). But compressibility is an >> attribute, not a use :) > >Doorstop? Doorstop??! Let me contemplate about it for a month or so, and I might find an appropriate answer... :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From peter at engcorp.com Sun Jul 6 23:00:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Jul 2003 23:00:39 -0400 Subject: anything new on the ternary operator? References: Message-ID: <3F08E257.74AC932C@engcorp.com> Bob Gailer wrote: > > Last I heard it was killed by Guido, which makes me wonder why we spent so > much time discussing and voting. If he did not want it I wish he had killed > it at the start. I thought the vote was to determine the best choice, and I > was looking forward to having it. > > Makes me wonder about the whole PEP process. Why bother! >From the PEP (http://python.org/peps/pep-0308.html) : This is the community's one chance: if this PEP is approved with a clear majority, it will be implemented in Python 2.4. ... If the community can't decide, the BDFL will reject the PEP. Also, reading PEP 1 "PEP Purpose and Guidelines", I see nothing in there to suggest that the process was not followed, and lots of things that point out that the BDFL's ruling is still the only thing that matters, in the end. Those dissenting will be required to start their own fork of Python, then shot. ;-) PEP 1 also answers your question about "why we spent so much time discussing and voting"... -Peter From kevin at cazabon.com Mon Jul 14 18:00:58 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 14 Jul 2003 15:00:58 -0700 Subject: focus problem with full-screen in Tkinter References: <2259b0e2.0307140746.46cf2e8c@posting.google.com> Message-ID: <5a4226f0.0307141400.36684d3b@posting.google.com> Wouldn't you have to do the bind as: root.bind("q",lambda e: root.destroy()) I don't know if evaluates to the same thing, but I know that "normal" keys are not normally enclosed in <>. It may or may not be part of your problem. Kevin. mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307140746.46cf2e8c at posting.google.com>... > I have a problem with full screen windows in Tkinter. > Here is a minimal script showing the problem: > > from Tkinter import * > root=Tk() > w, h = root.winfo_screenwidth(), root.winfo_screenheight() > root.geometry("%dx%d+0+0" % (w, h)) > #root.overrideredirect(1) > root.focus() > root.bind("",lambda e: root.destroy()) > root.bind("<1>",lambda e: root.destroy()) > root.mainloop() > > Here everything works, and if I press "q" the window is destroyed. > However, if I uncomment the line with "overrideredirect" and I > really go full screen, Tkinter does not recognize the keybindings > and I cannot close the window with "q". Fortunately, the mouse > is recognized and I can close the window with a click. > > I guess the problem is with the focus, how should I modify root.focus() > to ensure that the keybindings are recognized? > > TIA, > > Michele > > P.S. I am using Python 2.2 on Red Hat 7.3 From kchu at elk.uvm.edu Sun Jul 13 21:34:23 2003 From: kchu at elk.uvm.edu (Kelvin Chu) Date: 14 Jul 2003 01:34:23 GMT Subject: AIFC (Python and audio files.) Message-ID: Hello, Python Wizards... I'm trying to use Python to write an aiff file. I've used the aifc module and I've set the parameters (# of channels, encoding rate, compression, etc.) What does raw audio data look like? Is each word of the raw audio data a frequency? If I encode 440 for each of the frames, will I get concert A? Thanks for any advice you can give on this subject. Best, -k -- Kelvin Chu Department of Physics, Cook Building, 82 University Place University of Vermont, Burlington, VT 05405-0125 802.656.0064, http://www.uvm.edu/~kchu/ From skip at pobox.com Wed Jul 2 10:00:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 09:00:09 -0500 Subject: Python-2.3b1 bugs on Windows2000 with: the new csv module, string replace, and the re module In-Reply-To: References: Message-ID: <16130.58729.717919.803534@montanaro.dyndns.org> Daniel> Problem #1: Daniel> While using the csv module's DictWriter on MSDOS Daniel> (a.k.a. Windows2000), the output files get newlines like Daniel> \x0d\x0d\x0a instead of \x0d\x0a. Daniel> csvwriter = csv.DictWriter( file( out1filename, 'w' ), infieldnames, extrasaction='ignore' ) Daniel> csvwriter.writerow( dict( zip( infieldnames, infieldnames ) ) ) CSV files are not really plain text files. The line terminator string is an explicit property of the file. For example, you might want to write a CSV file on a Windows 2000 machine which you intend to read on a Mac OS9 system (where the line terminator is just \r). You need to open CSV files with the 'b' flag. This should work for you: csvwriter = csv.DictWriter( file( out1filename, 'wb' ), infieldnames, extrasaction='ignore' ) csvwriter.writerow( dict( zip( infieldnames, infieldnames ) ) ) Skip From bgailer at alum.rpi.edu Thu Jul 24 15:28:12 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 24 Jul 2003 13:28:12 -0600 Subject: Mystery Theater New Style Classes correction2 Message-ID: <5.2.1.1.0.20030724132745.01d6d398@66.28.54.253> At 02:26 PM 7/24/2003 -0400, Terry Reedy wrote: >"Bob Gailer" wrote in message >news:mailman.1059062857.29503.python-list at python.org... > > Predict the output: > > > > class A(int): > > classval = 99 > > def __init__(self, val = 0): > > if val: > > self = val > > else: > > self = A.classval > >I am not sure what the point is. However, > >1. Rebinding the local variable 'self' (or any other local variable) >only affects further code within the function, which there is not any. >So the above conditional is equivalent to 'pass'. > >2. Because ints are immutable, the value of a new int is set within >int.__new__, which is not overwritten. Thus, the above __init__ is >irrelevant. In particular, the value of an A object has nothing to do >with the defaulted parameter 'val=0'. > > > a=A(3) > >3. This is equivalent to a=int(3). No surprises. > > > b=A() > >4. This is equivalent to b = int(). I thought this might raise an >exception. But after seeing the result (0). I remember Guido's >decision (and a recent PyDev discussion thereof) that callable builtin >types should, if possible, return a null value when getting a null >input. Hence > > >>> int(), long(), float(), tuple(), list(), dict() >(0, 0L, 0.0, (), [], {}) > > > print a,b >3,0 > >5. Result is same if 'val=0' is changed to 'val=9' or anything else. > > > [from OP's self followup] The question this leads to is: how does >one access the value of such a class within a class method? > >Since there is no class method presented, this make not much sense. >Bob: were you aware of 4.) above when you posted this? There's a lot I was not aware of. Your reply and <> have given me what I needed. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From kmj9907 at cs.rit.edu Mon Jul 28 16:00:43 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Mon, 28 Jul 2003 20:00:43 GMT Subject: Debugging Python ? References: Message-ID: On Mon, 28 Jul 2003 13:23:43 +0000, John Roth wrote: > > Yup. AFIC, the print statement is only for debugging, and it's quite > effective for that purpose. > I would guess it's pretty good for teaching programming, too. Seeing print "Hello world" is more welcoming than even: import sys sys.stdout.write("Hello world\n") From see at below.invalid Wed Jul 23 23:11:34 2003 From: see at below.invalid (Paul Foley) Date: Thu, 24 Jul 2003 15:11:34 +1200 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: On 22 Jul 2003 01:38:35 GMT, Bengt Richter wrote: > I suspect it will more often make sense read aloud in the general > if any_true(pred, seq): > than > if the(pred, seq) > I guess the full set of functions might be > any_true, any_false, all_true, and all_false. > or maybe someone can think of better short phrase? some, notevery, every, and notany, respectively. Just like in a certain other language :-) -- Just because we Lisp programmers are better than everyone else is no excuse for us to be arrogant. -- Erann Gat (setq reply-to (concatenate 'string "Paul Foley " "")) From tdelaney at avaya.com Mon Jul 14 22:02:22 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 15 Jul 2003 12:02:22 +1000 Subject: Identity inconsistency and unification of types and classes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D3A5F@au3010avexu1.global.avaya.com> > From: Moshe Zadka [mailto:m at moshez.org] > > the fluttering of the wings of a butterfly in Tibet will > create a storm... > err, sorry, got carried away there. > > Exercise: Determine for yourself where exactly I got carried > away. Discuss. Butterflies do not actually cause storms, but failing to account for butterflies will cause inaccurate predictions of weather conditions. Other than that ... nope - sounded fine to me :) Tim Delaney From kanzen at mail.com Sat Jul 19 05:10:25 2003 From: kanzen at mail.com (KanZen) Date: 19 Jul 2003 02:10:25 -0700 Subject: __getitem__ and arguments Message-ID: <10eb079f.0307190110.30deb5b9@posting.google.com> I'm trying to understand the difference between __setitem__ and an ordinary method. For example: >>> class A(object): def __getitem__(self, *args): print len(args) def normalMethod(self, *args): print len(args) >>> a=A() >>> a.normalMethod(1, 2, 3) 3 >>> a[1, 2, 3] 1 For __getitem__() the arguments become a tuple. I can't seem to find this in the language spec. Can anybody explain this to me? Thanks, KanZen. From bokr at oz.net Mon Jul 14 19:01:43 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 23:01:43 GMT Subject: Newbie with sort text file question References: <86d2ca4.0307121146.3deb854a@posting.google.com> <86d2ca4.0307131344.3fb3b9d3@posting.google.com> Message-ID: On 13 Jul 2003 15:30:58 -0700, stuart_clemons at us.ibm.com (stuartc) wrote: >Hi Bengt: > >Thank you. Your code worked perfectly based on the text file I >provided. > >Unfortunately for me, my real text file has one slight variation that >I did not account for. That is, the fruit name does not always have >an "_" after its name. For example, apple below does not an an "_" >attached to it. > >banana_c \\yellow >apple \\green >orange_b \\yellow > Ok, try the changes below, to do same thing, but with re: >> >> ===< stuartc.py >======================================================== >> import StringIO >> textf = StringIO.StringIO(r""" >> banana_c \\yellow >> apple_a \\green >> orange_b \\yellow >> banana_d \\green >> orange_a \\orange >> apple_w \\yellow >> banana_e \\green >> orange_x \\yellow >> orange_y \\orange >> """) >> >> # I would like two output files: >> # (actually two files ?? Ok) >> >> # 1) Sorted like this, by the fruit name (the name before the dash) >> import re rxo = re.compile(r'^([A-Za-z]+)(.*)$') #XXX#fruitlist = [line.split('_',1) for line in textf if line.strip()] fruitlist = [rxo.search(line).groups() for line in textf if line.strip()] >> fruitlist.sort() >> >> # apple_a \\green >> # apple_w \\yellow >> # banana_c \\yellow >> # banana_d \\green >> # banana_e \\green >> # orange_a \\orange >> # orange_b \\yellow >> # orange_x \\yellow >> # orange_y \\orange >> >> outfile_1 = StringIO.StringIO() #XXX# >> outfile_1.write(''.join(['_'.join(pair) for pair in fruitlist])) outfile_1.write('\n'.join([''.join(pair) for pair in fruitlist]+[''])) >> >> # 2) Then summarized like this, ordered with the highest occurances >> # first: HTH Regards, Bengt Richter From lamar_air at hotmail.com Fri Jul 11 09:29:30 2003 From: lamar_air at hotmail.com (lamar_air) Date: 11 Jul 2003 06:29:30 -0700 Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> <3F0D962E.23DA9F59@engcorp.com> Message-ID: <2c6431ab.0307110529.7a336f30@posting.google.com> Peter Hansen wrote in message news:<3F0D962E.23DA9F59 at engcorp.com>... > "Bartolom? Sintes Marco" wrote: > > > > I have a program that unzip some zip files. After unzipping them, > > I want to delete the zip files with os.remove, but I get this error: > > OSError: [Errno 13] Permission denied: .... > > Close the files properly after unzipping them, perhaps? If that > doesn't help, please specify operating system, and give details > on how you are unzipping. Is it using Python's zipfile module, > or some other method, and exactly how do you do it? > > -Peter I want to be able to delete a file on my C: drive through my python script. My script writes a file. So i want to delete the file if it already exists then write it. What's the best way to do this? From tdelaney at avaya.com Thu Jul 24 22:21:35 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 25 Jul 2003 12:21:35 +1000 Subject: file.close() Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D47B8@au3010avexu1.global.avaya.com> > From: Francois Pinard [mailto:pinard at iro.umontreal.ca] > > The only reason to call `close' explicitly is when there is a > need to close > prematurely. Absolutely no doubt that such needs exist at times. But > closing all the time "just in case" is symptomatic of unsure > programming. > Or else, it is using Python while still thinking in other languages. No - it is writing portable code that conforms to the Python language documentation. But we've had this argument before. Even in CPython, closing before a reference goes away is vital in many cases. The simplest example is writing to a file, then reading it. You don't always want to keep a copy of the data in memory - it's often a lot better to stream the data, even if you have to do it multiple times. Tim Delaney From alan.gauld at btinternet.com Thu Jul 24 18:11:34 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jul 2003 22:11:34 GMT Subject: Reading Keyboard Scan Codes References: <23daa443.0307231129.12d7ccf5@posting.google.com> Message-ID: <3f2057ec.744508586@news.blueyonder.co.uk> On 23 Jul 2003 12:29:06 -0700, michaelb_spam_this at yahoo.com (Michael Bendzick) wrote: > Is there a simple way in python to read a keyboard scan code? I'm > working on a shell script that interfaces with a proprietary keyboard > device (extra buttons) and need to be able to distinguish between > those keys. The code to do this is on my programming tutor under Event Driven Programming in the Advanced topics section. It uses Tkinter to read and print the codes. The critical part is this bit: self.txtBox.bind("", self.doKeyEvent) def doKeyEvent(self,event): str = "%d\n" % event.keycode self.txtBox.insert(END, str) return "break" self.txtBox is a standard Text widget in Tkinter. If you can find my book you'll see the code to do it using msvcrt. :-) Again the critical bit is: key = mscvrt.getch() if key == '\000' or key == '\xe0' #detect special keys key = msvcrt.getch() # read the second byte. HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 21 02:59:55 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 21 Jul 2003 16:49:55 +0950 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: On Sun, 20 Jul 2003 20:48:16 -0500, Jeff Epler wrote: >>>> {}[:] = None > > I'd have expected something like 'TypeError: unslicable type' meaning > that you can't slice a dict, not that slice()s aren't hashable. You're not requesting to slice a dict; you're requesting to reference an element of a dict with : as the key. > In fact, I wonder why slices *aren't* hashable. How would you store the resulting key; how would you expect it to be returned from keys() ? -- \ "The right to use [strong cryptography] is the right to speak | `\ Navajo." -- Eben Moglen | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From paul_rudin at scientia.com Thu Jul 10 07:06:08 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 10 Jul 2003 12:06:08 +0100 Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: >>>>> "Jeff" == Jeff Hinrichs writes: > I've been following this thread, and on a whim I built a test > harness to time the different ideas that have been put forth in > this thread. I will post complete results tomorrow on the web > but the short version is that using the .replace method is the > overall champ by quite a bit. Below is the function I tested > against the others in the harness: > def stringReplace(s,c): """Remove any occurrences of characters > in c, from string s s - string to be filtered, c - characters to > filter""" for a in c: s = s.replace(a,'') return s > It wins also by being easy to understand, no filter or lambda. > Not that I have anything against filter or lambda, but when the > speediest method is the most readable, that solution is > definitely the Pythonic champ. :) I haven't been following this thread closely but isn't a regexp the obvious way to do this? I'd expect it to be faster than your solution - particularly on large input (although I haven't actually tried). Arguably it's more pythonic too :-) re.compile(r).sub('',s) where r is the obvious disjunctive regexp mentioning each of the charaters you want to remove. If you want to construct such a regexp from a list of characters: r= reduce(lambda x,y: x+'|'+y, c,'')[1:] So putting it all together as an alternative version of your fuction: !!warning - untested code!! import re def stringReplace(s,c): r= reduce(lambda x,y: x+'|'+y, c,'')[1:] return re.compile(r).sub('',s) From sismex01 at hebmex.com Wed Jul 9 10:19:33 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 9 Jul 2003 09:19:33 -0500 Subject: QUESTION Message-ID: > From: Matt5883 at aol.com [mailto:Matt5883 at aol.com] > Sent: Mi?rcoles, 09 de Julio de 2003 09:10 a.m. > > What is python 2.1.1? It's a programming language. > How did it get on my computer? Why do you think we have that information? > Is it a necessary program? Necessary for what? Programming in Python? Definitely. > Can I safely delete it/remove it? If so how? Just like any other windows program, via the control panel. > I do not recall downloading it. Does it come bundled with some > other program? Maybe one of my kids did it. May be; you *could* ask him/her/them. > I do not see enough information on your site to make these > determinations. Just keep digging. > I have a Compaq 5184 with OEM Win 98 installed... You could try and upgrade to this "Linucks" thing... > I do not ever recall seeing "python" in the programs. Compaq didn't bundle Python with it's computers, if that's what you're asking. > I have been having alot of problems with my computer > lately and I am removing unecessary "junk". Then, by all means, enter the control panel, select "Add or Remove Programs", look for Python's entry and double-click on it to remove it. Another course of action is asking your kids about it; you know, if you suspect they might have installed it, it's normal practice to ask the probable culprits. If you're not a programmer and have no intention of ever becoming one, you probably won't be much interested in Python. > Thanks, > Matt You're welcome. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From paul_rudin at scientia.com Thu Jul 10 09:35:36 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 10 Jul 2003 14:35:36 +0100 Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: >>>>> "Paul" == Paul Rudin writes: > r= reduce(lambda x,y: x+'|'+y, c,'')[1:] It occurs to me that this isn't what you want if c contains special regexp chararacters so really it should be: r= reduce(lambda x,y: x+'|'+y, map(re.escape,c),'')[1:] > So putting it all together as an alternative version of your > fuction: > !!warning - untested code!! > import re > def stringReplace(s,c): > r= reduce(lambda x,y: x+'|'+y, c,'')[1:] r= reduce(lambda x,y: x+'|'+y, map(re.escape,c),'')[1:] > return re.compile(r).sub('',s) From owski at hotmail.com Tue Jul 15 22:04:44 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 02:04:44 +0000 (UTC) Subject: anything like C++ references? References: Message-ID: <20030715200433927-0600@news.xmission.com> In Stephen Horne wrote: > On 15 Jul 2003 10:45:10 -0700, owski at hotmail.com (Adam Ruth) wrote: > >>I came to Python from Ada, and all I have to say is: Pointer-like >>semantics are evil. They're worse than goto's, they're deadly, >>damaging, and should be avoided at all costs. >> >>They're an unhappy necessity, akin to stop-lights. You need them >>because roads intersect, but if roads don't intersect, don't use them! > > Absolutely true. And the worst thing you can do when you really can't > avoid pointers is to obscure the issue even more by disguising them as > something else. I assume that you're referring to people 'faking' pointer in Python ( such as wrapping variables in lists, etc.) I'd ammend your statement to say: And the worst thing you can do is to obscure the issue even more by disguising them as something else, WHEN YOU DON'T REALLY HAVE TO. In Python, there is no situation where "you really can't avoid pointers". It's only when you program C or C++ in Python that you think you can't avoid pointers. There are much better idioms to achieve the desired results. > The biggest problems with pointers relate to things with pointer math, > pointers to deleted objects etc. These things need not exist in a > scripting language that provides pointers - pointers don't have to be > implemented using store addresses. That is just a concept from C, C++, > Pascal, Ada etc - not something I want to see imitated. If pointers > can be created that refer to given objects, and if pointers can be > dereferenced, that is actually enough to support indirect referencing. It's actually also unnecessary in Python. Adam Ruth From adalke at mindspring.com Fri Jul 18 16:43:22 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 18 Jul 2003 14:43:22 -0600 Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: Anton Vredegoor: > It helps a little. Whether I want to pay you depends on what you eat. Pizza, burgers, black beans&rice, BBQ, chili rellenos, breakfast burritos. Huh. A lot of 'b'-based foods. And for midsummer the last couple years - herring. But that's a special occasion. :) Andrew From bokr at oz.net Thu Jul 17 11:57:22 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 15:57:22 GMT Subject: Regular expression help References: Message-ID: On Thu, 17 Jul 2003 04:27:23 GMT, David Lees wrote: >I forget how to find multiple instances of stuff between tags using >regular expressions. Specifically I want to find all the text between a >series of begin/end pairs in a multiline file. > >I tried: > >>> p = 'begin(.*)end' > >>> m = re.search(p,s,re.DOTALL) > >and got everything between the first begin and last end. I guess >because of a greedy match. What I want to do is a list where each >element is the text between another begin/end pair. > You were close. For non-greedy add the question mark after the greedy expression: >>> import re >>> s = """ ... begin first end ... begin ... second ... end ... begin problem begin nested end end ... begin last end ... """ >>> p = 'begin(.*?)end' >>> rx =re.compile(p,re.DOTALL) >>> rx.findall(s) [' first ', '\nsecond\n', ' problem begin nested ', ' last '] Notice what happened with the nested begin-ends. If you have nesting, you will need more than a simple regex approach. Regards, Bengt Richter From fredrik at pythonware.com Thu Jul 10 02:12:13 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jul 2003 08:12:13 +0200 Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de><3F0C8AC3.5010304@dadsetan.com> Message-ID: Jeff Hinrichs wrote: > I will post complete results tomorrow on the web but the short > version is that using the .replace method is the overall champ by > quite a bit. umm. on my box, testing with Python 2.1 and 2.3, a translate-based function is 2-3 times faster even on very short strings with very few replacement characters... the more replacement characters you have, the bigger the difference. (let me guess: you're including the maketrans call in the benchmark? don't do that; it creates a constant table, which of course should be put in a global variable. or bound to a default argument, if you really care about speed...) From jason.orendorff at lumigent.com Fri Jul 25 16:19:49 2003 From: jason.orendorff at lumigent.com (Jason Orendorff) Date: 25 Jul 2003 13:19:49 -0700 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <11234c14.0307251219.70e77a85@posting.google.com> holger krekel wrote: > IMO you'll almost never use the following string-methods on a 'Path' object: > capitalize center count decode encode [...] > and so these methods pollute a Path object's name-space quite a bit. > Also 'join', '__contains__', startswith etc. produce some ambigouity. I'm not worried about "namespace pollution", but you're right that strings and paths are generally used for different things. I also agree 'join()' is a wart. > I think it's convenient enough to use "str(path)" if passing a 'path' > instance as a string somewhere. Hmmm. If the plan were to convert the whole standard library to accept path objects for pathnames, I would likely agree. But when you say "str(p)" is "convenient enough", you're saying I need this rule in my head: Don't pass path objects to functions that take path arguments. Pass string objects instead. This is a type rule. Such a thing has no place in Python. Furthermore, this rule is counterlogical! I would have to change "mimetypes.guess_type(mypath)" to "mimetypes.guess_type(str(mypath))". -- j From spinard at ra.rockwell.com Thu Jul 10 16:14:01 2003 From: spinard at ra.rockwell.com (Steve Pinard) Date: 10 Jul 2003 13:14:01 -0700 Subject: sort() doesn't work on dist.keys() ? Message-ID: <6cd58b6.0307101214.34e99f2a@posting.google.com> (Got a comm error trying to post first time, sorry if this is a duplicate) New to Python, so please bear with me. >>> import sys >>> print sys.modules.keys() # works fine ['code', ...snip... ] >>> print sys.modules.keys().sort() # returns None, why? None According to my reference (Nutshell), keys() returns a "copy" of the dict keys as a list, so I would expect when I aply sort() to that list, I would get an in-place sorted version of that list. Why do I get None? TIA, - Steve From skip at pobox.com Wed Jul 2 11:23:03 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 10:23:03 -0500 Subject: Python-2.3b1 bugs on Windows2000 with: the new csv module, string replace, and the re module In-Reply-To: References: <16130.58729.717919.803534@montanaro.dyndns.org> Message-ID: <16130.63703.427905.864666@montanaro.dyndns.org> Daniel> Perhaps the documentation should say something about using Daniel> binary mode? Good point. I'll fix the docs. Daniel> Or perhaps the DictWriter constructure should open the file in Daniel> binary mode if given a string rather than a file object? Nah, too much overloading going on. Skip From intentionally at blank.co.uk Tue Jul 15 16:56:49 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 21:56:49 +0100 Subject: anything like C++ references? References: Message-ID: On 15 Jul 2003 10:19:18 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: >> Really. My computer science lessons were taught in a way that >> respected the source of most of the theory in mathematics - >> algorithms, Church's lambda calculus and that kind of stuff. >> What did your lessons teach? > > How computer programming actually works, how to make interpreted and >compiled languages, how to use them to solve problems, how to analyze >algorithms, etc.... The usual. You say that as if it contradicts the idea of respecting the source of the theory. It doesn't. > Among those were classes in languages >other than C, which is very broadening, and I highly recommend that to >you. Lets see. Probably about a dozen basics, five assembler languages (6502, z80, 68000 series, 8086 series, 80C196KC microcontroller), forth, lisp, prolog, miranda, haskell, icon, ada, pascal, modula 2, cobol, smalltalk. Not all of them very seriously, though, and in many cases not recently. I forget the name of that language designed for transputers, but I used that a bit at college too - and depending on your inclination you may want to include SQL. And yes, I have used C, C++ and Java as well. That's just off the top of my head, of course. But there's no way you can call me C centric. That has been a repeated accusation, but it is WRONG. Python has been an everyday language for me LONGER than C++ has. >> Respect the idea of variables binding to values and suddenly the need >> for pointers becomes more obvious. You cannot abuse mutable objects to >> fake pointer functionality (another everyday fact of Python >> programming) if the binding of variables to values (rather than just >> objects) is respected. > > If you're trying to say that the trick I showed you of modifying a >list to reproduce the effect of reference arguments is not possible in, >say, C, you're wrong. Trivially proven wrong, even, since Python is >implemented in C. In fact, the only languages where that won't work are >those which don't allow passing complex arguments at all; some >pure-functional toy languages, perhaps. Distorting what I said, again. I have already repeatedly said that the point about C is what happens by default - not what happens when you explicitly request otherwise. Lets take an example from C++ to illustrate the point. std::string x = "123"; std::string y = x; // At this point, in most implementations, x and y are bound to the // same object due to a lazy copy optimisation. However, the // programmer didn't request this optimisation so this // implementation detail is expected to be transparent to the user. // Therefore... y [2] = 4; // Before doing this operation, a copy was made - the so called // copy on write. // The value bound to x is still "123" // The value bound to y is now "124" C++ is using references here just as Python does, but despite being a crappy low level language it still manages to implement that without causing remote side-effects through mutability *unless* you explicitly request that. > If you're seriously demanding that all languages adhere to a religious >observance of object and variable purity that exists in no serious >programming language, you might want to stop and consider *why* nobody >"respects" that. Inertia? Or maybe no-one has really used many languages other than perl and python, or maybe lisp on occasion. Oh dear - am I jumping to unfair conclusions about peoples levels of experience? I wonder where I got that idea from. >If you want Python to change to obey >your ideals, well, you're unlikely to effect that change; I said long ago that this was a philosophical point. That doesn't mean I'm going to sit down and take it when everyone says I'm wrong - except when I am, of course. To date, I am the only person participating in this thread to admit any error or to appologise for anything. What does that tell you? I said an age ago that I wasn't expecting a change. I stated that while python is not perfect, it is damn close - and that it is my first choice language whenever I have a choice. And I also said that if the ideas I've been discussing were implemented, Python would be so different as to no longer be Python. I don't need to believe that any language is absolutely perfect, you see. I can discuss a possible flaw in even my favorite language without feeling threatened or insecure. I just don't like it when people contradict me, unless I recognise that contradiction as valid. Sometimes I'm boneheaded about that - but when I realise my mistake I admit it and appologise. Many of the arguments used against me in this thread have directly contradicted each other. In such cases, both people cannot be right. So show me *one* admission of error by anyone other than me. >Perhaps you should write your own language, if no others are >acceptable to you. Unlikely to be serious, but I've been thinking about it a while. A decent copy-on-write system in a scripting language may just be a handy differentiator. FYI - I have written programming languages before. One currently in use in a commercial product, though I still regard it as a toy. I have also written several parser generators of my own - one python one using (mostly) recursive descent, one using LR(1) and - because Python is a tad slow for LR(1) of a decent size grammar (dependent on how patient you are, of course) an LR(1) generator written in C++. Creating a new language is not beyond my ability, but this is beside the point. I never said python is crap or anything like that. That was read into my words. I was discussing a weakness. There is no such thing as a perfect language. Creating a new language as anything more than an experimental exercise would be a massive waste of time and effort - and I'd have a lot of man-hours of catching up to do. From rochkind at basepath.com Tue Jul 15 00:05:32 2003 From: rochkind at basepath.com (Marc Rochkind) Date: Mon, 14 Jul 2003 22:05:32 -0600 Subject: Which Python Book References: <3F134200.8060708@hotmail.com> Message-ID: On Mon, 14 Jul 2003 19:51:28 -0400, hokiegal99 wrote: > I have an option, I can buy either O'reilly's "Python in a Nutshell" or > "Python Cookbook", but not both. Which book is better? [snip] Haven't seen the Cookbook, but I can say that the Nutshell book is absolutely outstanding. One of the best books on any language. Very compact, very complete. --Marc From donn at u.washington.edu Tue Jul 8 18:36:42 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 08 Jul 2003 15:36:42 -0700 Subject: print attitude References: <3F0669B5.679FB505@alcyone.com> Message-ID: In article , Steven Taschuk wrote: > Quoth Donn Cave: > [...] > > I think some time back, Steven Taschuk proposed to submit a rewrite > > of the str & repr documentation, [...] > > I did. See > > I am not entirely satisfied with the text (suggestions welcomed); > I haven't taken the time to look at the matter again. Well, I see I never did convince you to try to describe the intent of str directly. Donn Cave, donn at u.washington.edu From imbosol at aerojockey.com Wed Jul 30 22:39:25 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 31 Jul 2003 02:39:25 GMT Subject: Embedded python: dotted (sub) module name References: <3c91a864.0307301805.7cfea740@posting.google.com> Message-ID: logistix at cathoderaymission.net wrote: > I get the feeling I'm just picking the wrong google search phrase > here, because I'm finding nothing. I'm trying to namespace out some > embedded python modules. This works: > > Py_InitModule("game", py_game_methods); > > but this doesn't: > > Py_InitModule("quake.game", py_game_methods); > > What am I missing here? Any help would be appreciated. A module's package is defined the importer, not by the module itself. Move a module file to a different directory, and BAM, it's in a different package. If your only wish is to make it so that someone can import your extension module using "from quake import game", then it is enough to just copy the DLL or shared lib into the proper directory. (Well, you also have to remember to put an __init__.py file in the quake directory.) -- CARL BANKS From jzgoda at gazeta.usun.pl Sun Jul 13 14:11:39 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 13 Jul 2003 18:11:39 +0000 (UTC) Subject: How to crash Python in 1 easy step (python 2.2.2) References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: Paul Miller pisze: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. Nothing happens on my Slackware 9. On W2k Sp3 box also nothing. -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From maxm at mxm.dk Wed Jul 2 08:27:16 2003 From: maxm at mxm.dk (Max M) Date: Wed, 02 Jul 2003 14:27:16 +0200 Subject: Assign to True / False in 2.3 In-Reply-To: <3F02ADD3.6047F561@alcyone.com> References: <3F02ADD3.6047F561@alcyone.com> Message-ID: <3f02cf2e$0$97227$edfadb0f@dread12.news.tele.dk> > Culley Angus wrote: > This is true of pretty much all Python features. The only special > dispensation goes to None, which is a warning now (in the 2.3 beta) I most often use this freedom to overwrite "id". I Guess that it's a bad Zope habbit... regards Max M From shalehperry at comcast.net Mon Jul 28 20:04:01 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Mon, 28 Jul 2003 17:04:01 -0700 Subject: List Question In-Reply-To: <005001c35495$5d3f5dc0$6400a8c0@EVOD31> References: <001e01c3548d$bed5a420$6400a8c0@EVOD31> <20030728111954.GA20253@dave@alana.ucc.usyd.edu.au> <005001c35495$5d3f5dc0$6400a8c0@EVOD31> Message-ID: <200307281704.01062.shalehperry@comcast.net> On Sunday 27 July 2003 16:18, Bill Loren wrote: > Thanks all, > and again, accept my apologizes for the stupid question... > *blushed* B > not really a stupid question. People ask it fairly regularly. Many expect something like my_list.length() to work (hey, Python is OO after all). The typical response is len() works pretty much any where that len() would make sense. strings, tuples, lists, user defined classes as long as it honors __len__(), etc. From ianb at colorstudy.com Sun Jul 20 19:11:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 18:11:46 -0500 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: References: Message-ID: <1058742706.28090.2303.camel@lothlorien> On Sun, 2003-07-20 at 17:35, Andrew Dalke wrote: > Heh. I read "CLEAR CHOICES" as a command "the choices are clear". I made that same mistake (and I thought it was odd for the UI to assert its clarity :). > > 8) The printout is intended to come from a personal laser printer located > in > > the voting booth. For the demo, we'll probably use the HP Laserjet 5L. > > I approve of the Mercuri system (I think that's what it's called when a > paper ballot is generated from an electronic ballot - the all-electronic one > I use now is scary). I was just thinking though. Suppose I wanted to rig > the elections by paying for votes. If I know the format of the ballot, I > could generate them myself on specially marked paper then give that > to the people who I've payed for the vote, who go through the process > of voting but use the paper I gave them instead of the printout.. Later, I > or my cronies get access to the ballots (eg, "I'm a reporter and I want to > verify the votes") and can see if my special ballots are included, and > reward/punish as appropriate. You could make sure that ballots were not brought in by signing the ballot with some key that is unknown in advance, potentially a key that is generated by each machine when it is started up (then somehow recorded so the key can be verified -- written to hard disk and printed out to be collected at the end of the voting period?). That way you'd have to corrupt the actual election officials, and once you've done that it's all pretty hopeless. > > The > > selections will be bar coded in a strip on the left edge. Probably, > > write-in candidate names will be in a separate bar code. The printout > will > > list the voter's selections in text that can be easily read by humans and > > scanners. > > The phrase "bar code" scares me in that the bar code and the human > readable text may differ. Why not just have everything in text? It should be quite easy to audit bar codes. The advantage is that they are more easily machine read than text -- an on-site reader could be both simple, cheap, and reliable for a bar code, but I suspect OCR will not be as reliable. In a centralized, more controlled location OCR will probably be fine. The case of actual fraud, a mere sampling of votes will probably expose the fraud (since the text is known to be accurate since the voter will confirm the text). I don't think filled-in dots are particularly better than bar codes. It's effectively just a slightly more transparent bar code, which isn't necessary. I think an audit trail is sufficient -- the problem with punch cards is that the voter doesn't get to confirm their choice in such a way that a recount can match the confirmed, known correct choice against what the machine read. > My caution though is that usability testing for this is deeply hard, > and I would advise against "a few weeks" even for demo prototype > code as you suggest. Well, the only way to do a usability test is with a demo, so no reason not for him to dive in... Ian From skip at pobox.com Tue Jul 8 10:51:26 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 09:51:26 -0500 Subject: path module In-Reply-To: References: <16138.53027.356511.290162@montanaro.dyndns.org> Message-ID: <16138.55918.159252.387878@montanaro.dyndns.org> >> path = basePath/"a/b/c" Just> Ooh, it _can_ get worse ;-/ Just> Also: this would not be portable on platforms not using / as Just> os.sep, ... Not necessarily. My guess (again, without trying it) is that it does the right thing. Right near the top of http://www.jorendorff.com/articles/python/path/ Jason writes: I like for my code to be cross-platform, but I tired of typing os.path.join in about 1994. >> Sure, just like '%' means modulo in Python, but it seems to have >> found a home in printf-style string expansion. Just> True, but string expansion is quite old (possibly even Python 0.9 Just> or 1.0?), so most people are used to it. (Although, newbies Just> without a C background are usually baffled by it. I know I was, Just> back then...). Just because a better alternative to os.path turns up now is no reason to discount it. Nonetheless, before anything like Jason's path module is incorporated into the standard distribution, a PEP is almost certainly required. I imagine there are some things which could be done better (or at least differently) to make the overall module more acceptable. Skip From jjl at pobox.com Tue Jul 15 07:20:01 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Jul 2003 12:20:01 +0100 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: <87brvw3ula.fsf@pobox.com> Alan Kennedy writes: > Dan Bishop wrote: > > > The Babelfish translation is > > > > "People, you polskazhite plz where to reach progu to > > frizer(kazhet'sya, shorter must be into yekhe-shnik outdistanced)." > > My favourite "phrase designed to mess up machine translation" (I'll > bet there's one big long word for that in German) is > > "Time flies like an arrow, but fruit flies like a banana". > > :-D > > I'd love to hear of other similar phrases. And somehow I intuit > there's people in this ng who know lots of them :-) [...] There are so many... Matthew 25:35 I was a stranger, and you took me in. In English, there are two obvious meanings (the second, which is amusingly in almost exact contradiction to the real meaning, is only obvious to a native speaker once somebody sufficiently perverse has pointed out its existence ;). Automated translation usually misses both of them, of course. What surprised me was *how many* possible interpretations of some of these phrases there are: IIRC, one program extracted tens of subtly different possible meanings from "Time flies...". PS just to take things even further OT, does anybody remember the words coined by Steven Pinker in one of his books (probably to illustrate how English does something similar to German in forming new words)? One meaning "fear of peanut butter sticking to the roof of one's mouth", and another one which was, IIRC, some kind of self-referential joke? Couldn't find it in "The Language Instinct", so I guess it must have been in "How The Mind Works", which I don't have a copy of. John From mirko-lists at zeibig.net Wed Jul 2 04:28:44 2003 From: mirko-lists at zeibig.net (Mirko Zeibig) Date: 2 Jul 2003 08:28:44 GMT Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: On Wed, 02 Jul 2003 at 01:25 GMT, Tom Plunket wrote: Hello Tom, it's even simpler and maybe to obvious for a C++-afficinado: > class SomeClass: > def __init__(self): > self.countdown = Countdown() > self.countdown.SetCallback(30, lambda s=self: s.Callback) self.countdown.SetCallback(30, self.Callback) You don't need lambda here, just give the Countdown class a reference to your callback-method by specifying it's name *without* parentheses :-). If you print self.Callback, you will the information, that this is a instance-bound method object. You can easily assign a new name to a function and call it afterwards: li = [] al = li.append al("Hello") al("World") print "".join(li) This may even be faster as dot-resolution takes some time. Regards Mirko From tim at zope.com Wed Jul 16 16:11:08 2003 From: tim at zope.com (Tim Peters) Date: Wed, 16 Jul 2003 16:11:08 -0400 Subject: Replacing rexec In-Reply-To: <1058378060.5034.13.camel@redwall.ofsloans.com> Message-ID: [Tim Gerla] > We are looking to use plpython in PostgreSQL, but it's being > downgraded to "untrusted" and/or being completely removed because > Python's rexec went away. Why did rexec go away, specifically? I know > it had security issues, Bingo. > but couldn't these have been fixed? Nobody knows for sure, because nobody volunteered the time to dig into it, and Guido's employer didn't want to fund work on it (nor, apparently, did anyone else's). > Did the module just have too many integral flaws in the design to be > worth saving? I don't think so. > Is anyone working on a replacement? Not that I've heard of. > If not, why not? Well, for that we'd have to ask everyone who didn't volunteer -- which is everyone . > Even if plpython isn't very widely used, I think it's still important > for advocacy. I'd much rather write Python than PL. > > Anyway, I'm looking for a summary of specific reasons why rexec went > away without a replacement. I understand completely that it had flaws > and was insecure; I'm only confused as to why these flaws were > insurmountable. I don't know that they are, but the lack of any volunteer time to work on it, coupled with the lack of any paid time to work on it, added up to no work on it. > Given a bit more assurance that a replacement would be useful and > possible, we potentially have the resources to do so. Having a working > and trusted plpython is valuable to both my own organization and, > IMHO, the Python world itself. I don't disagree, and was a little surprised that the Python Business Forum didn't jump on this one. If it's a void you want to fill, please do! From wim_wauters at skynet.be Thu Jul 10 07:56:27 2003 From: wim_wauters at skynet.be (WIWA) Date: 10 Jul 2003 04:56:27 -0700 Subject: pySNMP: SNMPget example Message-ID: <538fc8e.0307100356.4bf46554@posting.google.com> I have recently installed pySNMP 3.3.2 and use Python 2.2.2. Thanks to Peter Hansen, I succeeded to install pySNMP properly. I'm not completely new to SNMP (I know the basics), but I'm new to Python and pysnmp. While experimenting, I find some strange things. When using pySNMP: 1) I can type: 'import pysnmp' or 'from pysnmp import *' 2) when using: 'from pysnmp import role' (found on http://pysnmp.sourceforge .net/examples/2.x/snmpget.html), I get the message 'ImportError: cannot import name role'. The same applies for 'from pysnmp import session' or 'from pysnmp import v1' , but 'from pysnmp import proto' seems to work. 3) A general question: how can I get a list of what I can type after the 'from pysnmp import ...' 4) How can I use: 'from snmpget import snmpget'. It does not accept this. 5) Anyone has a simple example for the following application: I have a cable modem (which has an SNMP agent inside). I want to make a script where I can do SNMPgets (and later SNMPSet and SNMPwalk). 6) Where can I find a simple description on how to use 'snmpget'. I cannot find anything. I would like to write sth like snmpget(IP, OID) 7) What is the difference between snmpget and getrequest in pysnmp? Any input is appreciated... Thanks in advance, Wim From google at klitos.org Wed Jul 23 08:56:31 2003 From: google at klitos.org (Klitos Kyriacou) Date: 23 Jul 2003 05:56:31 -0700 Subject: py2exe command line window problem References: Message-ID: The fact that the console window shows it's running cmd.exe (the Windows Command Processor) gives us a good clue. Not all console windows run cmd.exe, so this is significant. Python's os.system function uses the shell specified by the ComSpec environment variable (usually C:\WINNT\system32\cmd.exe) to run the command given as an argument. Check if you are calling system() in your Python script. If you are, you can be fairly certain that's what's creating the console window. Regards, Klitos From newsgroups at jhrothjr.com Thu Jul 31 17:14:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 17:14:10 -0400 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling References: Message-ID: "Bram" wrote in message news:bgbd4i$h6o$1 at news4.tilbu1.nb.home.nl... > Thank you for replying so quickly. > You thought right, this resolves all my problems :-) > Bram You're welcome. Quick replies happen on this newsgroup - who replies depends on who happens to check his mail first. John Roth > John Roth wrote: > > > > I took a quick look at the Wiki describing the protocol. For > > something like this, I'd expect that interoperability would be > > an issue, so the actual data format in the packets would be > > part of the protocol specification. > > > > That being the case, look at the struct module. I think it does > > exactly what you need. > > > > John Roth > From jepler at unpythonic.net Wed Jul 16 14:10:40 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 16 Jul 2003 13:10:40 -0500 Subject: Securing the Pyton Interpreter? In-Reply-To: References: Message-ID: <20030716181040.GB1967@unpythonic.net> I've never tried to set up a "secure" unix system, in the sense that users will only be allowed to execute certain commands. However there are any number of secure/restricted shells. I suspect that if you use one of these, you can get what you want. For instance, you would have /usr/bin forbidden, and /usr/safebin permitted. In /usr/safebin/pyscript you'd lead off with "#!/usr/bin/python -E". "-E" prevents Python from obeying environment variables like PYTHONPATH, PYTHONHOME, and PYTHONINSPECT, all of which can let the user "sneak" code in to be executed. Of course, you have to be sure that the individual python scripts are "secure" also. For instance, the following one *isn't*: #!/usr/bin/python -E # Print prime factors of a number (like /usr/bin/factor) import sys, math for arg in sys.argv[1:]: num = eval(arg) print "%d:" % num, i=2 while num != 1: while num % i == 0: print i, num = num / i i=i+1 print using eval() is the reason, in case you didn't catch it, but there are more subtle ways to write Python programs that let the user do arbitrary things. For instance, if a program uses pickle and lets the user alter the pickle's contents, the user can execute arbitrary code. If there's a bug in the C program that implements the Python interpreter or any extension module, the user might be able to arrange to "smash the stack" and do the same thing. Whether these things really matter depend on how secure your multi-user system needs to be. (this last type of attack could be true of any program, though, not just Python) Jeff From abcdebl2nonspammy at verizon.net Wed Jul 30 23:40:06 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Thu, 31 Jul 2003 03:40:06 GMT Subject: Thank you developers for 2.3 In-Reply-To: References: Message-ID: Added initialization to a long and printout of both time and result. Looks like faith was justified, but good point Raymond. David Lees ------------ import time def speedTest(N): t1 = time.time() k = 0L for i in xrange(N): for j in xrange(N): k += (i+j) t2 = time.time() return t2-t1,k print speedTest(3000) --------- Python 2.3 >>> (5.406999945640564, 26991000000L) Python 2.2.3 >>> (10.465000033378601, 26991000000L) From bignose-hates-spam at and-zip-does-too.com.au Sun Jul 20 01:04:08 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 20 Jul 2003 14:54:08 +0950 Subject: Python vs ... References: <3f19dad1@news.syd.ip.net.au> Message-ID: On Sat, 19 Jul 2003 23:57:40 GMT, Ray Smith wrote: > when I program a tricky well written piece of code When I see a piece of code that can be described as "tricky", I think "Gee I bet this is a source of bugs". Make your code obvious, please. Trickiness is what I want in a mystery novel or a puzzle, not in code to be read by humans. -- \ "I busted a mirror and got seven years bad luck, but my lawyer | `\ thinks he can get me five." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ebolonev at rol.ru Sat Jul 5 22:04:44 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Sun, 6 Jul 2003 13:04:44 +1100 Subject: command line (WinXP) Message-ID: Hello, All! I have made a module(see below) and have discovered a strange behaviour in comand line mode: =========Beginning of the citation============== C:\...y Music\Katatonia\Last Fair Deal Gone Down>dir "/p" Volume in drive C has no label. Volume Serial Number is 0C80-479F Directory of C:\ File Not Found =========The end of the citation================ When I use _dir /p_ everything is OK. =========Beginning of the citation============== C:\...y Music\Katatonia\Last Fair Deal Gone Down>dir /p Volume in drive C has no label. Volume Serial Number is 0C80-479F Directory of C:\Documents and Settings\rc\My Documents\My Music\Katatonia\Last Fair Deal Gone Down 06.07.2003 09:42 . 06.07.2003 09:42 .. 05.07.2003 10:17 1 801 345 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Chrome[-+m ark+-]2[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:25 1 577 448 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Clean Toda y[-+mark+-]7[-+mark+-]2001[-+mark+-]Metal.ogg 05.07.2003 10:19 1 921 208 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Disposessi on[-+mark+-]1[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:27 1 972 274 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Don`t Tell A Soul[-+mark+-]11[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:32 2 007 636 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]I Transpir e[-+mark+-]5[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:33 1 269 293 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Passing Bi rd[-+mark+-]9[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:35 1 343 946 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Sweet Nurs e[-+mark+-]10[-+mark+-]2001[-+mark+-]Metal.ogg 05.07.2003 10:20 1 180 590 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Teargas[-+ mark+-]4[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:36 1 845 629 Katatonia[-+mark+-]Last Fair Deal Gone D own[-+mark+-]The Future Of Speech[-+mark+-]8[-+mark+-]2001[-+mark+-]Metal.ogg 06.07.2003 09:37 1 399 310 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]Tonight`s Music[-+mark+-]6[-+mark+-]2001[-+mark+-]Metal.ogg 05.07.2003 10:21 914 480 Katatonia[-+mark+-]Last Fair Deal Gone Down[-+mark+-]We Must Bu ry You[-+mark+-]3[-+mark+-]2001[-+mark+-]Metal.ogg 11 File(s) 17 233 159 bytes 2 Dir(s) 14 596 743 168 bytes free =========The end of the citation================ So, why _dir /p_ and _dir "/p"_ work not identically? Whereas _ren 1 2_ and _ren "1" "2"_ work identically. _The module:_ =========Beginning of the citation============== from os import system #example cmd='copy',args=['c:\\1.txt','1-2 3.txt'] #= os.system('copy' + ' \"' + 'c:\\1.txt' + '\"' + ' \"' + 'c:\\1.txt') #=copy "c:\1.txt" "1-2 3.txt" def myossystem(cmd,args=[]): for i in args: cmd=cmd+' \"'+i+'\"' system(cmd) if __name__ == '__main__': myossystem('dir', ['/p']) #while 1:pass =========The end of the citation================ With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From kevin at cazabon.com Mon Jul 28 15:13:39 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 28 Jul 2003 12:13:39 -0700 Subject: freeze or something else for stand-alone-bins References: Message-ID: <5a4226f0.0307281113.76a67f14@posting.google.com> Try distutils -> py2exe very simple, works great. Tons of documentation available... see: http://sourceforge.net/projects/py2exe/ Kevin. ffrederik at gmx.de (Frederik) wrote in message news:... > Hello, > > in Python 2.2.2 on Windows I cant find the freeze.py program anymore. > On my Linux-machine it?s still in tools - examples. Where can I find > it? Or can you recommend me anything else for creating > stand-alone-binaries? > > Thanks, > > Frederik From garabik-news-2002-02 at kassiopeia.juls.savba.sk Tue Jul 1 11:14:40 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 1 Jul 2003 15:14:40 GMT Subject: remove special characters from line References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Message-ID: Chris Rennert wrote: > Hello all, > > If I have a line like this > > ?blah blah blah blah blah > > I know I could do a slice like this [1:] to pull everything but the special > character, but what if I have several lines in a file. > I am not sure how I would detect a special character like that. I would > just like to pull everything from those lines (and the special character > always appears as the first character, but not on every line) except for the > special characters. > I hope I have enough detail for someone to help me. > > Thanks in advance, > import unicodedata def is_special(ch): return unicodedata.category(ch)[0]!='L' for i in file('filename', 'U'): line = unicode(i, 'utf-8') # or your encoding if is_special(line[0]): line = line[1:] or something. Depends on your definiton of "special" :-) -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From bignose-hates-spam at and-zip-does-too.com.au Tue Jul 8 19:45:34 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Tue, 08 Jul 2003 23:45:34 GMT Subject: start script automatically References: Message-ID: On Tue, 08 Jul 2003 11:17:37 +0200, Tom wrote: > I have a problem because I don't know how to start my script > automatically after a special event happens. You have two options: - Have the process causing the event, also cause the script to run. It's in the best position to know when the script should be run, after all, since it created the event. - Have a separate process watching for the event, which can then run the script reactively. This can either be a scheduled event, if the frequency is low (every few minutes or longer), or a continuously-running process (also known as a daemon on Unix). Which you prefer is dependent on how much you consider the two stages to be linked together. If they are conceptually part of the same "event", then the first option is preferable. If the two steps are conceptually separate, keeping the processes separate may be preferable since you are not then committed to running them always in sequence. -- \ "Too many Indians spoil the golden egg." -- Sir Joh | `\ Bjelke-Petersen | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From skip at pobox.com Mon Jul 28 22:10:27 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 21:10:27 -0500 Subject: Debugging Python ? In-Reply-To: References: Message-ID: <16165.55187.319833.994651@montanaro.dyndns.org> Pedro> And I was just wondering if it's legal to define a "print" Pedro> function... isn't print a keyword ? You're right. You'd need it to be Print or print_ or something similar. Skip From pythonguy at Hotpop.com Tue Jul 29 08:42:26 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 29 Jul 2003 05:42:26 -0700 Subject: How to get success/failure in case of thread References: <20030728175542.A23857@cs.unipune.ernet.in> <16165.10847.483917.787182@montanaro.dyndns.org> Message-ID: <84fc4588.0307290442.7c203e35@posting.google.com> Aahz has given you the solution in his post. Either follow it by setting an instance in your Thread derived object and retrieve it by a 'get' method. Otherwise put the result in a Queue and 'get' it from there as suggested by Skip. You cannot go forward much if you use the methods in the 'thread' module since they dont give you the fine control you need. If code is what you want, here is a brief pseudo code for the first solution. I am typing it online, so the indentation is bad. Dont try to run this anyway :-) class mythread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self, None, None, name) self._res = 0 # return value storage def run(self): """ Run this thread """ self._res = self.doMyWork() def doMyWork(self): """ Do my work (return an integer) """ # Add your thread's main code here ... ... ... return val def getResult(self): """ Return the result of the thread execution """ return self._res A client of this thread object can always get the result of the thread's work by calling the getResult() method, i.e before he deletes the thread's object. class threadClient: def __init__(self): ... def myop(self): t = mythread('Worker') t.start() t.join() # Block till thread finishes ret = t.getResult() # Take action based on 'ret' value The Queue implementation is similar but only that you wont have the getResult() method in the thread class but in the 'Queue' derived class. HTH. ~Anand vivek at cs.unipune.ernet.in wrote in message news:... > On Mon, Jul 28, 2003 at 08:51:27AM -0500, Skip Montanaro wrote: > > > > vivek> import thread > > vivek> thread.start_new_thread(my_func,(args,)) > > > > vivek> here my_func will return true/1 on success and false/0 on > > vivek> failure. How can I check whether the function failed/succeeded > > vivek> ??? > > > > Have the function (or a wrapper function) put() the return value on a Queue > > object, then get() it from there. > > > > THX a lot.. > > But I think it will not work in case if I want to return some value from the > function. > > Like currently I am trying to implement three tier application using python. > > I mean a web server that will serve the http request, depending on the request > it will create an XML string and will pass it to another tier running > XMLRPCServer. On this tier the XML string will be parsed and will take actions > accordingly ( like insertion in database etc.) Now I want the SimpleXMLRPCServer > to create a new thread for the request that will process the particular request > and will return the success/failure message. > > How can I do that with the help of queue object?? > > TIA and kind Regards > Vivek Kumar From intentionally at blank.co.uk Mon Jul 14 19:22:15 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 00:22:15 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> On 14 Jul 2003 11:35:57 -0700, owski at hotmail.com (Adam Ruth) wrote: >Stephen Horne wrote in message news:<7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv at 4ax.com>... >> On 13 Jul 2003 21:03:59 -0700, owski at hotmail.com (Adam Ruth) wrote: >> > >> C++ has precisely one type of variable. That variable is a placeholder >> for a value of a datatype which is specified in the declaration. The >> datatype may be a pointer datatype, but so what? Pointer datatypes are >> not treated any differently than other datatype except that they, like >> all datatypes, they have their own set of functionality. > >Granted. Pointers are no different than other data types, but they >are typically used for operations that are semantically very different >than other datatypes are used for. In that sense, they are, at a high >level, different data types. A different data type is nothing special. Mathematics has the concept of abstract data types. That's the point. There's no need to invent different kinds of variable, only different types of data. The fact that C and C++ variables are restricted in the set of values they can bind to (ie those with a particular data type) is not a problem. >It's like how c programming is taught has having pass by reference and >pass by value, when there is only pass by value at the implementation >level. Pass by reference is a concept added on top of the language. No. C programmers always pass by value. Sometimes that value is a pointer. Pascal programmers sometimes pass by reference. They do so explicitly, however - using the keyword 'var'. There is a big difference between *choosing* to have variables bound to an object, and having it happen automatically whether you want it or not. >> C++ references are tellingly also called self-dereferencing pointers. >> They are not a distinct concept - they are syntactic sugar. I suspect >> they mainly arise out of the modern desire to disguise pointers and >> fantasize that they're not there, though they certainly work very well >> in certain contexts. > >Syntactic sugar or no, they still behave differently than other >datatypes and are therefore not consistent... IMHO. They behave exactly like pointers. You just use different notation to get that behaviour. That is what makes them syntactic sugar. >> Funny thing. When I use algebra, the variables I define don't end up >> referring to different values, functions or whatever unless I >> explicitly redefine them. When I write a definition on one piece of >> paper, the things I wrote earlier on another sheet don't change. >> >> Seems to me that the math equivalent of assignment (defining named >> things) works very much like the 'static language definitions' as you >> put it. > >The devil is in the details. Math assignment is static assignment is >dynamic assignment. They really are all the same thing at a high >level, but it's the implementation and the subtleties that make them >vary. Not true. Maths has the concept of an algorithm, and it has the concept of assignment. In maths, a variable binds to a value. In Python, a variable binds to an object in a way that does no correctly implement binding to a value unless the object happens to be immutable. From tim.golden at viacom-outdoor.co.uk Fri Jul 18 03:52:25 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 18 Jul 2003 00:52:25 -0700 Subject: ps in windows References: <3F1720EF.DCA2AD12@juno.com> Message-ID: <8360efcd.0307172352.34ca0e28@posting.google.com> Jeff Sandys wrote in message > I want the Linux PC running a cron job to query the Windows PCs to find > out what programs they are running. Doubtless there are several possibilities. Personally, I'd use WMI on the windows boxes (cf http://tgolden.sc.sabren.com/python/wmi.html) and either Pyro (http://pyro.sf.net) or xml-rpc (http://www.pythonware.com/products/xmlrpc/index.htm) at either end to communicate from-to. TJG From Mark.Harris at standardregister.com Fri Jul 25 11:03:28 2003 From: Mark.Harris at standardregister.com (Harris, Mark W. (DAY)) Date: Fri, 25 Jul 2003 11:03:28 -0400 Subject: Installation Module Message-ID: I recently acquired support for some scripts that are installed using an install script which imports the "installutils" module. I can't seem to find this module anywhere. Anyone know if this still exists? Is it deprecated, name changed, replaced by something else. --Mark From claird at lairds.com Wed Jul 9 00:15:48 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 09 Jul 2003 04:15:48 -0000 Subject: Tkinter window References: Message-ID: In article , furliz wrote: >Learning Python, I'm making some exercise of little GUI application with >Tkinter. I'd like to know if is it possible to customize the little 'Tk' >icon on the top-left corner of the main window ( Tkinter.Tk() ). > >Thanks to evryone who will resolve me this 'big' doubt :)) > Yes. I suspect win.wm_iconbitmap( "@canvas_icon.xbm" ) (credit Chad Netzer for this example) is the answer you seek. This is a sufficiently FAQ that we need to make room for it in the Wiki ... -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From owski at hotmail.com Wed Jul 16 14:39:15 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 18:39:15 +0000 (UTC) Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> Message-ID: <20030716123907246-0600@news.xmission.com> In Donn Cave wrote: > In article <20030716081156943-0600 at news.xmission.com>, > Adam Ruth wrote: > >> In <1058328099.572993 at yasure> Donn Cave wrote: >> > Quoth Adam Ruth : >> > .... >> >| In Python, there is no situation where "you really can't avoid >> >| pointers". >> > >> > That's trivially true, no such situation can exist because that >> > Python can't be coded. I'll repeat an example that I proposed >> > a couple days ago, though: user implemented sequences could be >> > implemented with a single simple indexing function, returning >> > a pointer/target/whatever; Python could assign directly to that, >> > making "seq[i] = x" the same kind of operation as and automatically >> > symmetrical with "x = seq[i]". >> > >> > It can't be done without pointers, as far as I can see. You may >> > not care if it can be done, but I think you'd agree that "there is >> > no situation that I care about where you really can't avoid >> > pointers" would be kind of a lame version of your assertion. Donn >> > Cave, donn at drizzle.com >> >> I did a quick google search and couldn't find the thread you're >> referring to. Could you summarize it for me? It sounds interesting. >> I do so love the taste of my foot in my mouth. > > http://groups.google.com/groups?selm=1058154004.286325%40yasure& > output=gp lain > Really I think that's the main point. There are some useful > and relevant features that Python doesn't have and will never > have, and that's OK. The real limitation of any programming > language tends to be its external interfaces - if you really > can't write a decent web browser in FORTRAN-IV, that's probably > the real reason, not any fundamental limitation of the language. > That doesn't mean FORTRAN-IV is a good language, it means that > its badness can't be expressed in terms of fundamental limitations, > so this question of whether you "really need" something tends to > make a poor basis for discussion. > > Donn Cave, donn at u.washington.edu You are correct, 'really need' is not much of an argument. The statement I disagreed with was that it was bad to simulate pointers in those situations where "you really can't avoid pointers". I was expressing that really aren't any such situations, and that it's even worse try to simulate pointers when it's not really necessary. From jepler at unpythonic.net Sat Jul 19 23:15:20 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 19 Jul 2003 22:15:20 -0500 Subject: Calling tcl from python and viceversa In-Reply-To: References: <453d10b2.0307190828.3c576f15@posting.google.com> Message-ID: <20030720031516.GA19019@unpythonic.net> You can convert your code so that it runs from callbacks (after/after_idle), or so that it calls the Tk event handler at reasonable intervals. The first approach means greatly changing your code (though you may be able to abuse generator functions here), and the second approach means that a few Tk things will interact badly with your fake mainloop (tk_wait). Threading is another possibility, but it's problematic with Tk because you must make sure all Tk calls happen in only one thread (the main thread, I think; or maybe the thread that created the Tk instance) Jeff From daniel.dittmar at sap.com Tue Jul 22 12:09:17 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 22 Jul 2003 18:09:17 +0200 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> <2259b0e2.0307220744.156c95bf@posting.google.com> Message-ID: Michele Simionato wrote: > I wanted to check the output of ifilter or imap; at the end I solved > my problem in another way, nevertheless I am surprised there is no > way to check for an empty iterator in current Python, it seems to be > a quite legitimate question, isn't it? It would make writing iterators more difficult because you'd have to know that there is a first element before the first call to .next (). It shouldn't be too difficult to write an iterator wrapper class that does exactly what you want (not tested): class IteratorWrapper: def __init__ (self, iterArg): iterArg = iter (iterArg) try: self.firstElement = iterArg.next () self.isEmpty = false self.next = self.returnFirstElement self.baseIter = iterArg except StopIteration: self.isEmpty = true self.next = self.throwStopIteration def returnFirstElement (self): self.next = self.baseIter.next return self.firstElement def throwStopIteration (self): throw StopIteration Daniel From sdementen at hotmail.com Wed Jul 23 04:44:17 2003 From: sdementen at hotmail.com (Sebastien de Menten) Date: 23 Jul 2003 01:44:17 -0700 Subject: profile output for kcachegrind ? References: <8dad5312.0307220731.5ff69a91@posting.google.com> Message-ID: <8dad5312.0307230044.20ea97d3@posting.google.com> There is documentation on the output of valgrind (i.e. the input of kcachegrind) at section "output" in http://developer.kde.org/~sewardj/docs-1.9.5/cg_techdocs.html For optimal use of kcachegrind, one needs also the "calltree skin" for valgrind that outputs an augmented file for kcachegrind. But I did not find any doc on this augmented format... I think that even without the calltree plugin, kcachegrind could be used advantageously for profiling python code. Seb Neil Smith wrote in message news:... > I've been using visualization of profile output as input to develop my > first pyGTK application, but if the input format read by kcachegrind was > well documented it would be a trivial task to get profile output in the > correct format. Do you know whether it is well documented? > > Neil. > > Sebastien de Menten wrote: > > >Hi, > > > >I am using the profile module to watch hot spots in a python > >application. > > > >The default output is already useful but has anyone tried to produce > >output readable by kcachegrind (http://kcachegrind.sourceforge.net/) ? > > > >seb > > > > From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 21 00:20:00 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 21 Jul 2003 14:10:00 +0950 Subject: Electronic voting with free software References: Message-ID: On Mon, 21 Jul 2003 00:54:34 +0200, Ulrich Petri wrote: > > Sorry but why on earth you dont just print that on paper and let > people make their crosses where they want? To give benefits that paper ballots can't provide. E.g. allowing people to vote over the Internet who can't get to voting booths, removing the human element of transposing ballots to a database, possibly reducing double-voting, etc. The FREE project was developing GNU.FREE software for electronic voting; development has since halted, but they have a lot of articles resulting from the development activity: -- \ "People demand freedom of speech to make up for the freedom of | `\ thought which they avoid." -- Soren Aabye Kierkegaard | _o__) (1813-1855) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From dgallion1 at yahoo.com Tue Jul 8 13:19:23 2003 From: dgallion1 at yahoo.com (Darrell Gallion) Date: Tue, 8 Jul 2003 10:19:23 -0700 (PDT) Subject: win32security.LogonUser In-Reply-To: <3F0AD456.5030901@pa.press.net> Message-ID: <20030708171923.6788.qmail@web21414.mail.yahoo.com> Thanks John That was done with no luck. Added it to Administrators and Administrator. __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From cookedm+news at physics.mcmaster.ca Fri Jul 18 00:31:05 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 18 Jul 2003 00:31:05 -0400 Subject: Looking For A Wildcard File Name Parser References: Message-ID: At some point, YoTuco wrote: > I've been looking for a good wildcard file name parser. That is, some module > in Python or something someone has made that can take a file name with the > '*' or '?' wildcards in it, parse a list[] and give back the matches. It > seems like a common enough task that one would be around? Or do I just > have to roll up my sleeves, dig-in and learn RE? You mean, like the standard module fnmatch? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From peter at engcorp.com Tue Jul 8 06:59:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 06:59:57 -0400 Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> <87k7azdber.fsf@titan.staselog.com> <87of055mqr.fsf@titan.staselog.com> Message-ID: <3F0AA42D.316BD6D3@engcorp.com> Edvard Majakari wrote: > > On Sat, 05 Jul 2003, kyle at lakeofburningfire.org wrote: > > > Part I > > http://www-106.ibm.com/developerworks/opensource/library/os-puffin.html > > > > Part II > > http://www-106.ibm.com/developerworks/opensource/library/os-puffin2.html > > Having read part I, I really have have to say it looks quite nice tool. I > guess it's no use to starting my own - also, I'm more convinced now that I > should do the testing at lower layers, making presentation layer 'thin' > enough so that there's no need to test it thoroughly. Thanks for the links. A refinement of the above statement: make the presentation layer "thin" enough that you need to test it thoroughly only *once*. Also make it thin enough that you very rarely if ever have to make changes to it, thereby making such even a manual test adequate. You shouldn't _not_ test something... but it's okay sometimes to avoid the writing fully automated tests, and this is a good example of when. -Peter From tcronj at ananzi.co.za Sat Jul 12 08:32:36 2003 From: tcronj at ananzi.co.za (Tertius) Date: Sat, 12 Jul 2003 14:32:36 +0200 Subject: tk prerequisite Message-ID: <3f0fffc0$0$235@hades.is.co.za> Installing tkinter 2.2.3 on RH9 the following message displayed [root at host 223]# rpm -i tkinter-2.2.3-26.i386.rpm warning: tkinter-2.2.3-26.i386.rpm: V3 DSA signature: NOKEY, key ID fd71b297 error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.3-26 libtix8.1.8.3.so is needed by tkinter-2.2.3-26 libtk8.3.so is needed by tkinter-2.2.3-26 Question: Must it be 8.3 or will 8.4 also do ? TIA Tertius From P at draigBrady.com Wed Jul 2 11:01:35 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Wed, 02 Jul 2003 16:01:35 +0100 Subject: i18n worries Message-ID: Hi, I had a quick look at gettext.py on 2.2.2 and noticed the new "install" interface that is more efficient than the "gettext" interface. Fair enough, but I noticed that the glibc bindtextdomain etc. functions are not called (even for the python equivalent functions). So does that mean that libraries gettext calls (for e.g. libc.mo) will be ignored for python programs? Also I'm wondering is there anything special I need to do to apply i18n to glade files (using libglade). cheers, P?draig. From paul_rudin at scientia.com Mon Jul 7 05:42:59 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 07 Jul 2003 10:42:59 +0100 Subject: anything new on the ternary operator? References: Message-ID: >>>>> "Aahz" == Aahz writes: > Guido made clear before the vote that only a clear statement > from the community would drive the addition of the ternary > operator. Given that the vote did not present a clear result, > he did what he said he'd do. How's that a prbolem? I don't know the details of this process; but personally I think a ternary operator would be a very good thing - and don't care about the syntax too much. Maybe the right think to vote on was simply a yes/no to "Do you want a ternary operator?". Maybe the problem is perhaps that disagreement over the competing syntactical suggestions obscures the fact that a majority would prefer to see some ternary operator rather than none? From mickel at csc.fi Wed Jul 2 08:34:30 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Wed, 2 Jul 2003 15:34:30 +0300 (EEST) Subject: How do I get the fractions of the visible part of a canvas? In-Reply-To: Message-ID: Thanks Fredrik and Eric, it works! /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From BartolomeSintes at ono.com Sun Jul 20 16:24:29 2003 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Sun, 20 Jul 2003 20:24:29 GMT Subject: non-ASCII characters IDLE 1.0 rc1 bugs References: Message-ID: <1UCSa.28305$FN3.2372949@news.ono.com> Bug filled. From cookedm+news at physics.mcmaster.ca Mon Jul 21 16:23:41 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 21 Jul 2003 16:23:41 -0400 Subject: distutils.core not in Debian python2.2 package References: Message-ID: At some point, Alessio Pace wrote: > I wonder why the corresponding package python2.3-dev does not exist.. > No distutils for python2.3 developers? ?? There is for me $ apt-cache search python2.3-dev python2.3-dev - Header files and a static library for Python (v2.3) $ -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From hst at empolis.co.uk Tue Jul 1 12:37:26 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 1 Jul 2003 17:37:26 +0100 Subject: Unicode problem.... as always Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4D1@hendrix.empolisuk.com> Todd Jenista wrote: > Sent: 01 July 2003 13:20 > To: python-list at python.org > Subject: Unicode problem.... as always > > > I have a parser I am building with python and, unfortunately, people > have decided to put unicode characters in the files I am parsing. > The parser seems to have a fit when I search for one \uXXXX symbol, > and there is another unicode symbol in the file. In this case, a > search and replace for ? with a ? in the file causes the infamous > ordinal error. > My quick-fix, because they have good context, is to change them both > to "UTF8", and then attempt to replace the UTF8 at the end with the > original ?. The problem is that I am getting a ?? when I try to > re-insert using \u00b5 which is the UTF8 code. > Words of wisdom would be greatly appreciated. > -- I think the root of your problem lies in your remark that "people have decided to put unicode characters in the files I am parsing". There is no such thing as a file of Unicode characters. There are, however, files in unicode encodings (such as UTF-8), which when read appropriately via codecs.open functions yield Unicode strings. Similarly you can write Unicode files to appropriate encodings. You don't tell us much about what you want to do, but why don't you just read and write files in UTF-8 via the codecs module and do your manipulations on Unicode strings? _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From bokr at oz.net Mon Jul 28 13:33:16 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 17:33:16 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Message-ID: On Mon, 28 Jul 2003 02:22:59 GMT, Carl Banks wrote: [...] > >The most robust way to handle this is to iterpolate, i.e., instead of >passing start, stop, and step, pass start, stop, and n_intervals: > > def interiter(start, stop, n_intervals): > diff = stop - start > for i in xrange(n_intervals+1): > yield start + (i*diff)/n_intervals > To guarantee the exact end points, maybe: def interiter(start, stop, n_intervals): fn=float(n_intervals) for i in xrange(n_intervals+1): yield ((n_intervals-i)/fn)*start + (i/fn)*stop but shouldn't that be xrange(n_intervals) and leave out the final point (thus exact but invisible ;-). Regards, Bengt Richter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 8 13:55:49 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 08 Jul 2003 19:55:49 +0200 Subject: Apache mod_python and Sessions In-Reply-To: <20030708093008.651035f7.scpusenet@werbung.schabi.de> References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> <20030707091923.1f12f872.scpusenet@werbung.schabi.de> <3f09b2cf$0$49098$e4fe514c@news.xs4all.nl> <20030708093008.651035f7.scpusenet@werbung.schabi.de> Message-ID: <3f0b05a5$0$49102$e4fe514c@news.xs4all.nl> Markus Schaber wrote: > The script will have a very low usage (maybe about ten sessions a month). > And it spends lots of time doing ldap database queries, so the starting > overhead doesn't hurt so much. This clears it all up. No further comments ;-) --Irmen From lfw at airmail.net Tue Jul 8 23:08:00 2003 From: lfw at airmail.net (Larry__Weiss) Date: Tue, 08 Jul 2003 22:08:00 -0500 Subject: Collective memory (was: Good code patterns in Python) References: <3F09F136.6060000@srv.net> Message-ID: <3F0B8710.1C1DBBDD@airmail.net> Dennis Lee Bieber wrote: > (we had an instructor at my College who punched a C in column 80 as a > standard practice -- he could flip the card around to document changes > -- it would be treated as a comment by the compiler, and a listing > would show the text right-to-left) > For some forms of job control you could create a card that had two choices punched starting from each end of the card. You could simply flip the card to invert the selection. I even remember once coding and using a text-editor macro to do something similar with the current line of text. From gumuz at looze.net Wed Jul 30 11:38:42 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 30 Jul 2003 17:38:42 +0200 Subject: PyXPCom Message-ID: <3f27e5a8$0$13798$4d4ebb8e@news.nl.uu.net> I recently found out about XPCom and it's python bindings and it sounded very promising. Then I found out that the source of this information was pretty old. I was wondering what the status is currently. I couldn't find any documentation or binaries for the python interface. has anyone examples, docs, binaries, urls, etc???? From guettler at thomas-guettler.de Fri Jul 18 08:59:30 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Fri, 18 Jul 2003 14:59:30 +0200 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: Michele Simionato wrote: > I often feel the need to extend the string method ".endswith" to tuple > arguments, in such a way to automatically check for multiple endings. > For instance, here is a typical use case: > > if filename.endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > > Currently this is not valid Python and I must use the ugly > > if filename.endswith('.jpg') or filename.endswith('.jpeg') \ > or filename.endswith('.gif') or filename.endswith('.png'): > print "This is a valid image file" > > Of course a direct implementation is quite easy: > > import sys > > class Str(str): > def endswith(self,suffix,start=0,end=sys.maxint):#not sure about > sys.maxint > endswith=super(Str,self).endswith > if isinstance(suffix,tuple): > return sum([endswith(s,start,end) for s in suffix]) # multi-or > return endswith(suffix,start,end) > > if Str(filename).endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > > nevertheless I think this kind of checking is quite common and it would be > worth to have it in standard Python. Hi, I like this feature request. if the argument to endswith is not a string, it should try to treat the argument as a list or tuple. thomas From akaihola at ambi-spam-me-not-tone.com Mon Jul 21 12:40:01 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Mon, 21 Jul 2003 19:40:01 +0300 Subject: Flat file to associative array. In-Reply-To: References: Message-ID: #!/usr/bin/env python def line2dict(line, fieldnames, sep='|'): """ Convert a separated text line to a dictionary with the given field names as keys """ d = {} for fieldname, value in zip(fieldnames, line.split(sep)): d[fieldname] = value return d drinkfields = 'drinktype', 'producer', 'brand', 'price' def drinkline2dict(line): """ Convert a | -separated and linefeed-terminated text line to a dictionary """ return line2dict(line.rstrip(), drinkfields, '|') products = map(drinkline2dict, file('products.txt').readlines()) from pprint import pprint pprint(products) From kamikaze at kuoi.asui.uidaho.edu Tue Jul 1 10:20:17 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 1 Jul 2003 14:20:17 GMT Subject: does lack of type declarations make Python unsafe? References: Message-ID: Tue, 01 Jul 2003 12:30:58 +0200, Anton Vredegoor : > kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: > >>> Since int doesn't derive from object, this will probably >>> fail: >>> c.add(1) >> This is true, but it's completely unimportant. It's annoying at >>times, but it's an optimization for efficiency; there are good reasons >>why Java is several times faster than Python at most tasks. You can use >>the primitive wrapper classes: >>c.add( new Integer(1) ); > Interesting, first define it as unimportant and next focus un Java's > strong points. Stop. This is not a high school debate class. You knew nothing about Java but felt the pathological need to attack it with claims you found on google. Despite your cretinous behavior, I politely explained the Java idiom and motivation for dealing with primitives differently. You're just being an ass here. -- Mark Hughes "We remain convinced that this is the best defensive posture to adopt in order to minimize casualties when the Great Old Ones return from beyond the stars to eat our brains." -Charlie Stross, _The Concrete Jungle_ From hanzspam at yahoo.com.au Wed Jul 2 15:24:59 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 2 Jul 2003 12:24:59 -0700 Subject: undo tab References: <3F02E7D5.4060401@gmx.net> <3F02ECF0.105@gmx.net> Message-ID: <840592e1.0307021124.32757214@posting.google.com> Tom wrote in message news:<3F02ECF0.105 at gmx.net>... > Hi, > > it doesn't work with any editor that I tried. The one I use on a regular > basis is the standard python IDLE. Sometimes I also use the editor of > pythonwin and Boa-Constructor. > > Maybe you can just give me a general hint how you do it and which editor > you use. That would probably also help. > > Thank you, Tom. I had to change IDLE a bit for it to work. In Python path, go to Tools/idle and edit AutoIndent.py. Find windows_keydefs or unix_keydefs depending on your platform and change "<>"-line to: '<>': [''], From stacom at stacom-software.de Fri Jul 25 09:22:38 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Fri, 25 Jul 2003 15:22:38 +0200 Subject: data conversion question (binary string to 'real string') In-Reply-To: References: Message-ID: Manish Jethani wrote: > Alexander Eisenhuth wrote: > > >>maby I don't see the forest because of all that trees, but : > > > Maybe I don't understand your question... > > >>from struct import * >> >> >># how can I convert >>f = float(0.5) >> >># with >>bin_str = pack('!f', 0.5) >> >># now bin_str is '?\x00\x00\x00' >> >> >># to "3F000000" ????? > > > ??????????????? > What is your question? > > -Manish > Sorry ... This two lines converts 0.5 to a string in binary representation >>>from struct import * >>>bin_str = pack('!f', 0.5) now bin_str is '?\x00\x00\x00', wich is the representation of 0.5 in the memory. I need now to convert this binary string to "3F000000", where '3F' is the hex value of the '?' in ascii - table. Any ideas ?? Thaks Alexander From intentionally at blank.co.uk Tue Jul 15 17:14:20 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 22:14:20 +0100 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: On 15 Jul 2003 20:32:30 GMT, bokr at oz.net (Bengt Richter) wrote: >On Tue, 15 Jul 2003 02:40:27 +0100, Stephen Horne wrote: > >>On Mon, 14 Jul 2003 00:07:44 -0700, Erik Max Francis >>wrote: >> >>>Stephen Horne wrote: >>> >>>> Imagine, for instance, changing all assignments and other 'copying' to >>>> use a copy-on-write system. Then add a pointer type and a 'newcopyof' >>>> operator. And nick the C-style prefix '*' for dereferencing and add >>>> '&' as a 'make a pointer to this object' operator (absolutely NOT a >>>> physical memory address). >>> >>>The problem is that this misses the point that Python is not C++. You >>>shouldn't try grafting syntaxes and approaches that make Python look >>>more like C++, you should be learning to use Python on its own merits. >> >>Not true. >> >>If you eliminate all violations of the idea of variables bound to >>values (basically the whole point of my thread), then mutable >>containers cannot achieve the same thing. >> >>If a copy-on-write scheme is added to Python, you'd get the following >>results from using mutable containers... >> >>>>> a = [1, 2, 3] >>>>> b = a >>>>> b[2] = 4 >>>>> a >>[1, 2, 3] >>>>> b >>[1, 2, 4] >> >Yes, but it would be hugely inefficient for the case where, e.g., you are >modifying lines read from a 20MB log file. Imagine inducing a 20MB copy >every time you wanted to delete or modify a line. Now you have to invent >a way to program around what can be done very conveniently and efficiently >thanks to Python's semantics. What makes you say that! Copies are only made when they are needed. The lazy copy optimisation, in other words, still exists. Delete or modify one string in a list of strings, and the same stuff would happen as happens now. Unless, perhaps somewhere you don't know about, the caller of your function who passed that list in to you has a separate reference they expect to stay unchanged. In that case, the first changed string triggers a copy of the list - but as the list only contains references to strings, it doesn't trigger copying of all the strings. The second line changed doesn't require the list to be modified again because you already have your separate copy. C++ uses exactly this kind of approach for the std::string class among others. Copy-on-write is a pretty common transparent implementation detail in 'heavy' classes, including those written by your everyday programmers. Does that mean C++ is slower that Python? Of course not! From hwlgw at hotmail.com Fri Jul 11 13:17:10 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 11 Jul 2003 10:17:10 -0700 Subject: Using xml.xpath question. References: <23891c90.0307110057.bbe91e3@posting.google.com> Message-ID: > [Paul Boddie] > ... > Try this: > >>> c = xml.xpath.Context.Context(doc) > >>> c.setNamespaces({"p" : "http://tempuri.org/string"}) > This makes a context and then adds the definition of the prefix for > the XPath query engine... > >>> e = xml.xpath.Compile("/p:root/p:child/text()") > I compile the expression in order to allow the context to be used. > ... we have to set up a context first to contain those > definitions. > >>> e.evaluate(c) > [] A very nice and helpful Paul Boddie in action on c.l.p. But OMFG! Here we see why we need a good *high* level XML library in the Python Standard Library. The effbot is doing great work with elementtree at www.effbot.org, but he is doing that all alone. I think a good high level XML library should have a very high priority for Python. It should be a much higher priority for the core Python developers than the extensions I have seen lately. Booleans, bah! And for instance, I hate it to make my code unreadable using list comprehensions and other syntactic sugar; and then later having to explain it to a C programmer. "Ha!" she says, "You claimed the Python language reads like pseudocode!". Geez. From adalke at mindspring.com Sun Jul 20 18:35:21 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 20 Jul 2003 16:35:21 -0600 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: Alan Dechert: > will change. For example, when the voter selects a president/vice president > pair, the background will change; the non-selected pairs will be greyed > while the selected pair will be highlighted (very brightly -- should light "greyed" in normal UI parlance means the option is no longer selected. What happens if someone pressed the wrong button? How is the correct selection made? > 3) When "WRITE-IN CANDIDATE" is selected, a large widow (maybe the full > screen) will pop up with a QWERTY keyboard in the upper half. This keyboard > will have only three rows with the alpha keys (no punctuation or numbers > needed except for perhaps the hyphen... no shift, all CAPS). No apostrophe? What if I want to vote for "O'Reilly" > selected. De-selecting one of the selected candidates reactivates the > others. Ahhh, I think I would have been confused by that. Then again, I get confused at time by the machine I use now. :) > 7) The County Commissioner race illustrates how ranked preference voting > would look. When the voter selects the first one, the button in the "1" > column is filled and the text "1st" will appear in the space between the row > of buttons and the candidate name. When the next selection is made, the > corresponding button in the "2" column is filled and "2nd" appears, and so > on. There is a "CLEAR CHOICES" button in case the voter wants to start > over. Heh. I read "CLEAR CHOICES" as a command "the choices are clear". What about "RESET CHOICES", or an alternate like Bill the Cat [1] [2] [3] [4] Snoopy Dog [1] [2] [3] [4] Go Fish [1] [2] [3] [4] Lucy Ricardo [1] [2] [3] [4] James Kirk [1] [2] [3] [4] and how are writins added to this? *sigh* .. I know just enough to ask questions and be annoying, but not enough to know the answers.... > 8) The printout is intended to come from a personal laser printer located in > the voting booth. For the demo, we'll probably use the HP Laserjet 5L. I approve of the Mercuri system (I think that's what it's called when a paper ballot is generated from an electronic ballot - the all-electronic one I use now is scary). I was just thinking though. Suppose I wanted to rig the elections by paying for votes. If I know the format of the ballot, I could generate them myself on specially marked paper then give that to the people who I've payed for the vote, who go through the process of voting but use the paper I gave them instead of the printout.. Later, I or my cronies get access to the ballots (eg, "I'm a reporter and I want to verify the votes") and can see if my special ballots are included, and reward/punish as appropriate. Not likely to be a problem in real life, but just something I was thinking about. > California ($200 million) and the Help America Vote Act ($3.9 billion) a lot > of public funds are being wasted on outrageously expensive hardware that > will be obsolete in a very few years. That's for certain. The tendency to move to higher-tech, more expensive, and less trustworthy voting machines is scary. > for conducting elections will be created. We anticipate having quite a few > non-academics involved too. For example, Roy Saltman is probably the best > known voting technology expert and he's not an academic. I'm not an > academic either. The only person I've heard of in this field is Rebecca Mercuri, who I think is an academic. I've read a lot of RISKS. :) > The > selections will be bar coded in a strip on the left edge. Probably, > write-in candidate names will be in a separate bar code. The printout will > list the voter's selections in text that can be easily read by humans and > scanners. The phrase "bar code" scares me in that the bar code and the human readable text may differ. Why not just have everything in text? > Blind voters will use the system wearing headphones and using a > hand held device to register selections. Isn't that overkill? I seem to recall that already there are provisions for people with special needs to have someone in the booth to help. In addition, how does a blind person do a write-in vote? Or someone who is illiterate and hard of hearing? > So, please let me know what you think about using Python for this demo. > Also, if you are a Python expert and would like to help as a volunteer > (we're all volunteers until the project gets funding), please contact me > ASAP. We want to have a demo running very soon! -- within a few weeks. Python would do this just fine. There are the various GUI projects, but this sounds like a good place for pygame. My caution though is that usability testing for this is deeply hard, and I would advise against "a few weeks" even for demo prototype code as you suggest. Andrew dalke at dalkescientific.com From aahz at pythoncraft.com Sat Jul 19 21:05:56 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2003 21:05:56 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: In article , Mike C. Fletcher wrote: >Aahz wrote: >>In article , >>Mike C. Fletcher wrote: >>> >>>Nope, I'm trying to make meta-classes which have rich properties. The >>>particular project is a plug-in system, where the classes (the >>>metaclass-instances) want to have all sorts of rich metadata associated >>>with them in a way which meshes with the rest of the system (i.e. using >>>a descriptor-based introspection mechanism). >> >> >>Keeping in mind that I'm really not following this discussion all that >>closely (because metaclasses give me headaches), are you trying to make >>a *metaclass* that has properties or a *metaclass instance* (i.e. a >>class) that has properties? > >Just the meta-class instances (classes). Wasn't sufficiently precise in >my description, the properties are normally declared in the meta-class, >but they are actually properties of the meta-class instances. Next question: are you also trying to access the properties on class instances? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From maxm at mxm.dk Thu Jul 3 06:09:17 2003 From: maxm at mxm.dk (Max M) Date: Thu, 03 Jul 2003 12:09:17 +0200 Subject: Good code patterns in Python In-Reply-To: References: <3f027b11$0$97204$edfadb0f@dread12.news.tele.dk> Message-ID: <3f040053$0$97160$edfadb0f@dread12.news.tele.dk> Theodor Rash wrote: > (Saw this sig somewhere: 'Comment my code?? Why do you think they call it > code?') My favourite comment of that kind is from Bertrand Meyer, who invented Eiffel. I dont remember it exactly, but it goes something like: "If programmers want to read text, they should buy a cheap novel." To his defense he was arguing that the code should be documentation in itself. Hence programming by contract. I guess that has been refined now by the tdd camp, where you should be able to read what the tested code does by reading the tests. regards Max M From hokiegal99 at hotmail.com Fri Jul 18 08:48:30 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 18 Jul 2003 05:48:30 -0700 Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> Message-ID: <93f5c5e9.0307180448.126b04b6@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message > This looks like an old post that ignores some responses you got to your original post like this. > Did some mail get lost? Or was this an accidental repost of something old? I still see > indentation misalignments, probably due to mixing tabs and spaces (bad news in python ;-) > > Regards, > Bengt Richter Sorry Bengt, I overlooked some responses to an earlier, similar question. I have too many computers in too many places, so forgive me. Thanks for taking the time to tell me again!!! I'll clean up the indentation... I promise. From peter at engcorp.com Thu Jul 3 14:50:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 14:50:13 -0400 Subject: Reading an image file data......... References: <3F044C9D.CE43D5F4@engcorp.com> Message-ID: <3F047AE5.C360F2E5@engcorp.com> Egor Bolonev wrote: > > Hello, Peter! > You wrote on Thu, 03 Jul 2003 11:32:45 -0400: > > PH> Egor Bolonev wrote: > ??>> > ??>> [Sorry, skipped] > PH>> That's twice I've seen you use this... what does it mean? > > It's a skipper plugin for Outlook E. I select a redundant text and press the > Skip button. > Should I change a label? > > http://www.fidolook.com/ I'd suggest either the "[some text omitted]" variant shown in the FAQ, or perhaps merely "[snipped]" or (worse, I think) "[skipped]". At least remove the "Sorry," part since it is the primary cause of the confusion in the first place, but perhaps more importantly, don't leave the message in at all if you are snipping an entire section and surrounding the "Sorry, skipped" message with your own text: it makes it look like you typed the words yourself, and that's the most confusing part of all (to me). :-) -Peter From usenet at soraia.com Sat Jul 12 15:29:19 2003 From: usenet at soraia.com (Joe Francia) Date: Sat, 12 Jul 2003 19:29:19 GMT Subject: new in town In-Reply-To: References: Message-ID: Elaine Jackson wrote: > As comforting as it is to know that there are "several ways of doing this", I'd > be even happier if I knew the name of just one of those ways. The FAQ searcher > doesn't seem to understand lengthy explanations and hand-waving. > Gerhard is undeserving of your flippancy. He's very active in this forum and very knowledgeable, but doesn't tolerate ambiguity and laziness (read some of his postings). You asked a vague question, and got a vague answer (you also used an ambiguous subject line, so be thankful someone answered you at all). You asked "Can Python be compiled?". Did you mean "Can the interpreter be compiled by me?" or "Can I compile my Python scripts into a stand-alone executable?" (this one is asked once a week) or "Can the Python interpreter be compiled into (embedded) an executable?" The answer to all of these is yes (more or less - see the FAQ), but since you didn't even specify a platform, how can you expect a more detailed answer than the one you got? I entered "compile" into the FAQ search engine, and saw listed answers to all of the above questions. You may want to revisit the FAQ, and you also may want to read this page: http://www.catb.org/~esr/faqs/smart-questions.html The Python community is a friendly one, but mostly, no one here will hold your hand. If you show you've spent some time trying to solve the problem yourself and then ask specific questions about the thing that's stumping you, you'll get helpful responses. jf From jarausch at skynet.be Fri Jul 18 13:21:28 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Fri, 18 Jul 2003 19:21:28 +0200 Subject: Perl -> Python hopeless? Message-ID: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> Hi, having been a Perl fan for years I have nearly converted to Python. Still, there are LOTS and very good modules written in Perl. Is there a tool to lesson the burdon of translation of Perl to Python? I am completely aware of the fact that a fully automatic translation to readable Python source is hard if not impossible. But such a tool could lots of the tedious work like replacing braces by proper indentation and and similar things. Thanks for a pointer (if there is one) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From frefo253 at student.liu.se Sat Jul 19 11:51:57 2003 From: frefo253 at student.liu.se (Fredrik Fornwall) Date: Sat, 19 Jul 2003 17:51:57 +0200 Subject: List of declared variables in interactive Python session? Message-ID: Hello. Is there a way to list all the declared variables in an interactive Python session? Thanks, Fredrik From jjl at pobox.com Sat Jul 26 20:55:11 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 01:55:11 +0100 Subject: looping through a file References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> <3f21903c$0$27898$626a54ce@news.free.fr> Message-ID: <87llukrdow.fsf@pobox.com> Heiko Wundram writes: > On Fri, 2003-07-25 at 22:24, Bruno Desthuilliers wrote: > > for line in thefile.readlines(): > > doWhatEverWithTheLine() > > Or, if you're on a sufficiently new Python: > > for line in thefile: > doWhateverWithTheLine() I recall that in an old Python you could get into an awful mess (as I did) with this by having several 'for line in file' blocks in a row: for line in f: if not line.startswith("magic"): continue # skip header for line in f: ...process data... I gathered from a recent thread that this has changed -- the file is its own iterator now. Was the old behaviour ever released in 2.2, or was it just part of a 2.3 beta? John From psimmo60 at hotmail.com Fri Jul 4 05:12:09 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 4 Jul 2003 02:12:09 -0700 Subject: Python Code Snippets References: Message-ID: <94974e1a.0307040112.1c6d7d14@posting.google.com> "Aur?lien G?ron" wrote in message news:... > Hi, > > Does anyone know where I can find a lot of Python code snippets? > I'm looking for a kind of organized list (GUI snippets, database access > snippets, I/O snippets, etc.). I find that there's no better way to learn a > language than to be able to cut&paste actual working bits of code. Hi, As well as the excellent resources others have mentioned, I'd definately recommend investigating the Python source distribution, if you haven't already. The joy of working with an Open Source language is that there's no problem if you want to look at some decent code: The Lib and Demo directories provide examples from the simple to the not-so-simple in a variety of application domains. The Objects and Include directories provide good examples of using the Python-C API. Seeing how the objects are created under the hood has increased my understanding of how Python works, and the quality of my C extensions. I'd also say the online Cookbook has a reasonable search facility, and lists of recipies from different areas, so it is relatively easy to find a particular code snippet. HTH, Paul From leo.broska at NOSPAM.isys.com.au Fri Jul 4 08:52:35 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Fri, 4 Jul 2003 22:52:35 +1000 Subject: exit endless python loop in emacs Message-ID: hi all how can i terminate/stop an endless python loop which i have started inside emacs with C-c C-c. ta, leo From faizan at jaredweb.com Tue Jul 29 14:05:19 2003 From: faizan at jaredweb.com (Fazer) Date: 29 Jul 2003 11:05:19 -0700 Subject: Showing IP address of a user... Message-ID: <7b454334.0307291005.53ee8c07@posting.google.com> Hello, I was wondering how I can show an IP address of a person who visits a Python web-page? Would I have to use Environment variables to access Apache's server variables which hold such values like in PHP or what? From h.b.furuseth at usit.uio.no Sat Jul 5 13:26:18 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 05 Jul 2003 19:26:18 +0200 Subject: How to get CGI request-URL References: Message-ID: Thanks for the answers. -- Hallvard From vze4rx4y at verizon.net Wed Jul 30 03:49:37 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 30 Jul 2003 07:49:37 GMT Subject: Thank you developers for 2.3 References: Message-ID: "David Lees" > Flawless install and it ran my very simple minded (try not to laugh) > nested loop integer arithmetic benchmark twice as fast as 2.2.3 > version 2.3 5.04 sec > version 2.2.3 9.77 sec > > import time > > def speedTest(N): > t1 = time.time() > k = 0 > for i in xrange(N): > for j in xrange(N): > k += (i+j) > > t2 = time.time() > return t2-t1 > > print speedTest(3000) > > david lees You must really trust us. The benchmark compares the speed but doesn't check to see if the answers are the same ;-) Raymond Hettinger From manish.j at gmx.net Sun Jul 27 16:02:29 2003 From: manish.j at gmx.net (Manish Jethani) Date: Mon, 28 Jul 2003 01:32:29 +0530 Subject: How to detect typos in Python programs In-Reply-To: <877k64c0qo.fsf@pobox.com> References: <3F214977.AEB088C8@engcorp.com> <877k64c0qo.fsf@pobox.com> Message-ID: John J. Lee wrote: > Manish Jethani writes: > [...] > >>>The proposed typo catcher would probably catch a typo like >>> >>> sys.edit (5) # finger didn't get off home row >>> >>>but it probably would *NOT* catch >>> >>> sys.exit (56) # wide finger mashed two keys >> >>1) That's in a different class of typos. Such things can't be >>auto-detected in any language. It will probably require close >>examination by the human who wrote it in the first place, or >>someone who has been debugging it. > > > That was, indeed, precisely the point that was being made. Tests can > catch these, static type analysis can't. There's a difference between my "abost()" example and the "56" example. There's no function called abost anywhere in the program text, so I should be able to detect the error with static analysis. Even in C, the compiler warns about stray function calls. The "56" example is out of place here. I have fixed the code: -------- [maybe a constants.py or whatever] arbit_code = 56 [... elsewhere...] sys.exit(arbir_code) -------- That error can be caught in static analysis. >>2) No on calls sys.exit() like that. 5, or 56, is probably a >>constant defined somewhere (where such typos are easier to spot). > > > Yes. Do you have a point? Yes. Don't use bad coding practices as an excuse. -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From lorenzo at mysurname.net Sun Jul 13 12:56:46 2003 From: lorenzo at mysurname.net (Lorenzo Bolognini) Date: Sun, 13 Jul 2003 16:56:46 GMT Subject: Old post about XML overhyped References: <3f100fe2$0$6529$afc38c87@sisyphus.news.be.easynet.net> Message-ID: "Bernard Delm?e" : > Could you possibly be referring to this here thread: > > http://mail.python.org/pipermail/python-list/2003-June/169716.html > Thank you very much, Lorenzo From jbar at lf1.cuni.cz Tue Jul 1 12:38:22 2003 From: jbar at lf1.cuni.cz (Jiri Barton) Date: Tue, 01 Jul 2003 18:38:22 +0200 Subject: Good code patterns in Python References: Message-ID: <3f01b8ff@shknews01> One, there has been a proposal for a ternary operator on python.org. You know that kind of (cond) ? (eval1) : (eval2) stuff. Two, no need to guard that code. Passing and assigning a paramater should always make you THINK about what's happening. Three, how about a = 1 b = 0 ..... if b == 0: a = 0 else: a = a/b ? You cannot replace it with your pattern. Sure enough, there are far more examples of this -- when you cannot evaluate the first expression. Jiri Barton From frank at pc-nett.no Sun Jul 13 06:33:35 2003 From: frank at pc-nett.no (frank) Date: Sun, 13 Jul 2003 12:33:35 +0200 Subject: My first application Message-ID: I have just finished my first python application. I am a beginner so I wrote this just to improve my programming skills. it is a GUI app that scans a selected range of ip addresses and try to get info about the hosts such as users, localgroups, shares, operating system. This program only runs under windows enviorment (tested under windows 2000) please note that this is still a very very very early version. here is the source code: http://www.grutle.net/franki/release0.001.src.zip and here is the windows binary http://www.grutle.net/franki/release0.001.bin.zip --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 10.07.2003 From bokr at oz.net Thu Jul 24 22:17:24 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 02:17:24 GMT Subject: Don't want to do the regexp test twice References: Message-ID: On Thu, 24 Jul 2003 23:44:57 +0200, Egbert Bouwman wrote: >While looping over a long list (with file records) >I use an (also long) if..elif sequence. >One of these elif's tests a regular expression, and >if the test succeeds, I want to use a part of the match. >Something like this: > >pat = re.compile(r'...') >for line in mylist: > if ... : > .... > elif ... : > .... > elif pat.search(line): > mat = pat.search(line) > elif ... : > ... > else ...: > ... >Is there a way to to do this job with only one pat.search(line) ? Hack #1 (list comprehension abuse): >>> import re >>> pat = re.compile(r'...') >>> mylist = ' a bc def ghij'.split(' ') >>> mylist ['', 'a', 'bc', 'def', 'ghij'] >>> for line in mylist: ... if 1==2: 'naw' ... elif 3==4: 'neither' ... elif [1 for mat in [pat.search(line)] if mat]: ... print repr(mat), mat.groups(), mat.group() ... elif 4==5: 'haw' ... else: ... print 'final else' ... final else final else final else <_sre.SRE_Match object at 0x007F1260> () def <_sre.SRE_Match object at 0x007F5900> () ghi Hack #2: (attach temporary value to an instance of something that can accept attributes (almost any object): >>> import re >>> pat = re.compile(r'...') >>> mylist = ' a bc def ghij'.split(' ') >>> mylist ['', 'a', 'bc', 'def', 'ghij'] >>> obj = type('Any',(),{})() >>> for line in mylist: ... if 1==2: 'naw' ... elif 3==4: 'neither' ... elif setattr(obj,'mat', pat.search(line)) or obj.mat: ... print repr(obj.mat), obj.mat.groups(), obj.mat.group() ... elif 4==5: 'haw' ... else: ... print 'final else' ... final else final else final else <_sre.SRE_Match object at 0x007F69C0> () def <_sre.SRE_Match object at 0x007F6980> () ghi The trick above is that setattr(...) return None, so the expression always continues to the or part. >>> setattr(obj,'xxx',123) >>> repr(setattr(obj,'xxx',123)) 'None' You can spell ... elif setattr(obj,'mat', pat.search(line)) or obj.mat: ... print repr(obj.mat), obj.mat.groups(), obj.mat.group() a little slicker if you make a special object to hold a binding to the pat.search result, e.g., h is the Holder instance in the following, which remembers the last thing passed to it and immediately returns it, and also returns that last thing on being called without an arg: >>> mylist ['', 'a', 'bc', 'def', 'ghij'] >>> h = Holder() >>> for line in mylist: ... if 1==2: 'naw' ... elif 3==4: 'neither' ... elif h(pat.search(line)): ... print repr(h()), h().groups(), h().group() ... elif 4==5: 'haw' ... else: ... print 'final else' ... final else final else final else <_sre.SRE_Match object at 0x007F6FC0> () def <_sre.SRE_Match object at 0x007F6F80> () ghi Obviously ... print repr(h()), h().groups(), h().group() could have been ... mat=h(); print repr(mat), mat.groups(), mat.group() instead. E.g., using the leftover value in h: >>> print repr(h()), h().groups(), h().group() <_sre.SRE_Match object at 0x007F6F80> () ghi >>> mat=h(); print repr(mat), mat.groups(), mat.group() <_sre.SRE_Match object at 0x007F6F80> () ghi >Of course I can do this: > >for line in mylist: > mat = pat.search(line) > if ...: > .... > elif ...: > .... > elif mat: > ... >but the test is relevant in only a relatively small number of cases. >And i would like to know if there exists a general solution >for this kind of problem. Take a pick, but not the list comprehension ;-) Regards, Bengt Richter From matthias.oberlaender at VOID.daimlerchrysler.com Thu Jul 3 03:21:48 2003 From: matthias.oberlaender at VOID.daimlerchrysler.com (Matthias Oberlaender) Date: 3 Jul 2003 07:21:48 GMT Subject: cooperation of buitlin methods usingtsuper References: <2259b0e2.0307020855.478300c2@posting.google.com> Message-ID: In <2259b0e2.0307020855.478300c2 at posting.google.com> Michele Simionato wrote: > Matthias Oberlaender wrote in message news:...> I would like to adopt the cooperation paradigm in conjunction with builtin > > methods and operators, such as len, iter, +, * etc. > > Fine. > > > But the direct approach does not work with the current implementation of > > super. For example, 'len(super(Y, y)' will always result in 'len() of > > unsized object'. > > Of course, it must give an error! I think you do not understand how > super works. But don't worry, that's quite common ;) Oh, wait a minute. I think this "of course" is a bit presumptuous. > > > As far as I understand, this is because builtins don't use a dynamic lookup > > chain, but go directly to the slots for the builtins. However, super returns > > an instance of class 'super'. Since all super objects share this class, its > > slots will not be filled as one might hope. > > > My workaround is this: I create a subclass of 'super' on the fly each time I > > call 'mysuper'. Look at the definition below. It seems to work. But maybe > > I have overlooked something. Is my understanding correct? Is 'mysuper' a > > good solution? Possible improvements? (e.g. caching of subclasses) > > > Thanks for comments! > > > > import new > > > class X(object): > > def __len__(self): return 2222 > > > class Y(X): > > def __len__(self): return 1111 > > > def mysuper(cls, inst): > > return new.classobj('mysuper', (super,) + cls.__bases__, {})(cls, inst) > > > y = Y() > > try: > > print len(super(Y, y)) > > except Exception, msg: > > print msg > > > try: > > print len(mysuper(Y, y)) > > except Exception, msg: > > print msg > > >Output: > > > len() of unsized object > > 2222 > > I think you should re-read the documentation and > google on the newsgroup for 'super'. The use case > for super is in multiple inheritance, as in this example: > > class B(object): > def __len__(self): > print 'called B.__len__' return 1111 > > class C(B): > def __len__(self): > print 'called C.__len__' > return super(C,self).__len__() This is exactly the style of syntax I want to avoid! I'd rather write more concisely 'len(super(C,self))'. Why should its non-working be an intended feature? It becomes even more annoying in the case of binary operators like __add__, for example: super(X,self).__add__(other) vs. super(X,self) + other Which one would you prefer? Using ordinary super, I can't use all the "syntactic sugar" of infix operator syntax any more that make expressions so much more readable. > > > class D(B): > def __len__(self): > print 'called D.__len__' > return super(D,self).__len__() > > class E(C,D): > pass > > print len(E()) > > The output of this is > > called C.__len__ > called D.__len__ > called B.__len__ > 1111 > > Do you see why? Feel free to ask if not. I do not understand what behavior > you expect from 'super'. Can you give more details on your specific use case? > Yes. I can see why. I'd dare to say I understand super fairly well now, including the diamond rule. But its benefit is not restricited to the multiple inheritance case. So we can leave MI and the "diamond" aside. What I expect from super(x.__class__, x) is an object that behaves exactly as if x.__class__ where devoid of any _own_ attributes, as if it had been defined like this: class X(A,B,C,...): pass And these expectations are almost met. But, at least in Python 2.2.1, its is a matter of fact that builtins/special method names are treated differently from ordinary class methods in conjunction with super objects. Do you agree? My implementation of super seems to fix this gap. Perhaps there are some other people who would appreciate that too. Or are there good logical/conceptual reasons againts it? This is what I would like to know. > P.S. BTW, in Python 2.2+ you can replace ``new.classobj(name,bases,dic)`` > with the built-in ``type(name,bases,dic)``. Thanks's for the tip (and your response)! -- ____ __ _/_/ . ( / / ( / / / / ===================================================================== Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm RIC/AP (Machine Perception) Wilhelm-Runge-Str. 11, P.O. Box 2360, 89013 Ulm, Germany Phone: +49 731 505 2354 Fax: +49 731 505 4105 Email: matthias.oberlaender at REMOVE.daimlerchrysler.com ===================================================================== From tl_news at nexgo.de Thu Jul 31 12:35:51 2003 From: tl_news at nexgo.de (Tino Lange) Date: Thu, 31 Jul 2003 18:35:51 +0200 Subject: .setdefault() Message-ID: Hi! I just realized that .setdefault *always* executes the second argument - even if it's not necessary, because the requested item in the first argument exists. This is not what I expected - why evaluate the second argument if it's not needed? Also this can lead to side-effects! Example: >>> a = {} >>> b = {} >>> a.setdefault(1,b.setdefault(1,1)) 1 '1' didn't exist in a - so I expect 'b.setdefault(1,1)' to be evaluated. Great. >>> a.setdefault(1,b.setdefault(2,1)) 1 '1' existed, so it's not necessary to evaluate 'b.setdefault(2,1)'. But: >>> b {2: 1, 1: 1} ... shows that it was executed! So it's not equivalent to: if 1not in a: b.setdefault(2,1) Is this really by design? If there's a complicated, expensive to calculate/build 2nd argument (maybe a function call) then it's also quite ineffective to evaluate it just to throw away... Thanks! Tino From christoph at mmc-startup.com Thu Jul 17 18:08:33 2003 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Fri, 18 Jul 2003 00:08:33 +0200 Subject: dumping command-history in python interactive mode Message-ID: <3F171E61.5050101@mmc-startup.com> Hello, is there a way to dump (and save) the command-history of the python interactive mode. Thanks, Christoph Becker-Freyseng From jjl at pobox.com Fri Jul 4 11:35:14 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Jul 2003 16:35:14 +0100 Subject: Assing a COM Interface to a Python object for callbacks References: <26caea2b.0307012335.1d717429@posting.google.com> <3F042188.5FFC45D3@hotmail.com> Message-ID: <87ptkq8fv1.fsf@pobox.com> Alan Kennedy writes: > Mikko Ohtamaa wrote: [...] > > The problem is that SAX Parser requires COM interface for callback. > > You must assign a COM interface as a handler to the parser. When the > > parsing begins, the handler calls this interface. [...] See Mark Hammond's examples in the win32com/tests directory (IIRC) that win32all installs in your Python directory. I can't remember which example demonstrates this, but I'm pretty sure one does. There's also been some discussion on c.l.py on this. John From Marco.LaRosa at csiro.au Wed Jul 23 21:59:58 2003 From: Marco.LaRosa at csiro.au (Marco.LaRosa at csiro.au) Date: Thu, 24 Jul 2003 11:59:58 +1000 Subject: Newbie question regarding py2exe. Message-ID: Hi all, This is a dumb question and I apologise. I have just started using py2exe and no matter what I try, I can't get it to work. Sometimes modulefinder.py complains, other times its VersionInfo.py. My question is how robust is py2exe? (Note that I have followed the docs to the letter.) Cheers, Marco -------------- next part -------------- An HTML attachment was scrubbed... URL: From drs at ecp.cc Fri Jul 11 16:41:45 2003 From: drs at ecp.cc (drs) Date: Fri, 11 Jul 2003 20:41:45 GMT Subject: ZEO and COM Message-ID: please let me know if there is a better place to post this ... I am trying to create a shared dictionary which can be accessed via COM. To that end, I have written the code below (at the end). So far this works from a single computer, but if another computer tries to share the data it is unable to see changes, and throws exceptions when it tries to rewrite data. Does anyone know how I can make all connections aware of changes? Any ideas? Thanks This is w/ ZODB3 3.1.2, Python 2.2, win2k -doug #----------------- from ZEO import ClientStorage from ZODB import DB class ecp_ZEOCOM: _reg_clsid_ = '{F7B8D35F-7B24-4B84-A8B6-34880132A854}' _public_methods_ = [ 'open', 'keys', 'has_key', 'get_item', 'set_item', 'del_item' ] _reg_progid_ = 'ecp.ZEOCOM' def open(self, IP, Port): addr = (str(IP), int(Port)) self.storage = ClientStorage.ClientStorage(addr) dbl = DB(self.storage) conn = dbl.open() self.db = conn.root() def get_item(self, key): self.storage.sync() try: return self.db[str(key)] except: return '' def set_item(self, key, value): self.storage.sync() self.db[str(key)] = value get_transaction().commit() def del_item(self, key): self.storage.sync() del self.db[str(key)] get_transaction().commit() def keys(self): self.storage.sync() x = self.db.keys() x.sort() return x def has_key(self, key): self.storage.sync() return self.db.has_key(key) def register(): import win32com.server.register win32com.server.register.UseCommandLine(ecp_ZEOCOM) if __name__ == '__main__': register() #----------------- From Frank at home Fri Jul 18 02:33:52 2003 From: Frank at home (Frank) Date: Fri, 18 Jul 2003 06:33:52 GMT Subject: How do I get info on an exception ? Message-ID: Using Python 2.2.2, I want to catch all exceptions from "socket.gethostbyaddr(ip)" >From IDLE, I can generate: >>> socket.gethostbyaddr('1.2') Traceback (most recent call last): File "", line 1, in ? socket.gethostbyaddr('1.2') herror: (11004, 'host not found') <=== what I want when I catch When I run this code: try: hostname, aliases, hostip = socket.gethostbyaddr(ip) return (hostip, hostname) except: print sys.exc_info() print sys.exc_type return The "print sys.exc_info()" gives- (, , ) And the "print sys.exc_type" gives- socket.herror How do I get the "(11004, 'host not found')" part? More importantly, where is the answer documented that I should have looked? Frank From mike at nospam.com Wed Jul 16 18:41:33 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 16 Jul 2003 15:41:33 -0700 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> Message-ID: Rogue9 wrote: > b1 = someOtherList[draw-1] > r1 = b1[draw] > Can anyone enlighten me as to why and how to get over this please? Make sure your someOtherList ALWAYS contains valid indexes for b1, i.e. in range(len(b1)) [side node] The whole approach seems rather unintuitive to me. Mike From anton at vredegoor.doge.nl Fri Jul 4 07:09:05 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 04 Jul 2003 13:09:05 +0200 Subject: does lack of type declarations make Python unsafe? References: Message-ID: david.abrahams at rcn.com (David Abrahams) wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:... >> david.abrahams at rcn.com (David Abrahams) wrote: >> <700+ LOP> >> >I love a nice jestful debate. Maybe your whole post is jestful and I >> >failed to recognize it. It certainly seems to have a derisive tone >> >which makes it hard to see the love. Where's the love, people? >> >Anyway, if you tell me you didn't mean it that way I'll take your word >> >for it. >> >> Perhaps not love, to me both you guys are discussing trifles. TDD and >> the source of it, static typing, are both about being satisfied with >> just passing tests, while the really important discussion -for me at >> least- is about aligning the code with ones thoughts, and how to >> accomplish that. > >I think that's *exactly* what I was talking about. Type declarations >on function parameters help me to align the code with the thoughts I >have about the implicit contract with the function's callers. In the >process, it makes that contract more explicit. Suppose (because of some perceived derisive tone f.e.) you would state not to marry Alex. Would that automatically imply you being a female? Perhaps it would indicate that in your opinion *Alex* [1] is a female? Furthermore suppose you're from a country where same-sex marriages are legal, would such a statement automatically imply that you are gay? The trouble with implicit assumptions is that they're possibly invalid, and as the Python Zen states: "In the face of ambiguity refuse the temptation to guess". It's hard to see that Zen to be overridden with "explicit is better than implicit" when no explicit information is available, for example because of short circuiting [2]. I think the discussion about type checking has reached a state where it is possible to compare it with for example the need for proofs in a mathematical paper. Proofs are what defines a mathematical paper, but alas, some heuristics indicate that for every formula used in a paper the audience is halved. As a former psychologist working in a mathematics department -also formerly- I noticed that, while psychologists seem to be concerned with the validity of the data [3], mathematicians were primarily concerned with the correctness of the formulas used to evaluate the data. There's some saying among psychologists that "if one needs a lot of statistics to prove some fact, it's already doubtful that one is really measuring that what one is supposed to measure". On the other hand if the mathematical foundation of a test is not good it's clear that the conclusions of a test are not convincing. Sometimes practicality dictates that tests are necessary, but at the same time it's clear that very elaborate statistical methods on data that do not warrant such extrapolations can trick innocent readers (of scientific articles f.e.) into believing false conclusions because their implicit assumptions almost force them to do so. Do we have some kind of tradeoff here? Anton [4] [1] Judging from some Europython photos for *some* Alex this seems not to be the case [2]The fact is that for some people agreement comes even *before* sex checking. Other people first check the sex before marrying, possibly to their detriment because sexuality has a tendency to make one forget the more important protocol once one has set only a foot upon that path. However if in type checking country it's probably best to take a role, so please note that I'm male and not gay. But you'd probably be surprised to see what's *really* behind some of the email addresses here :-) [3] It makes a *lot* of difference how a question is phrased, and also the circumstances of the testing venue and the assumptions of the tester can substantially influence the outcome of tests, even the outcome of tests which have close to zero human intervention (sometimes even the *absence* of human intervention distorts testing results) [4] Who has seen the vanity of psychological tests *and* the vanity of mathematical evaluation of such tests, and has doubts about the vanity of type checking and testing altogether From mis6 at pitt.edu Mon Jul 14 14:56:23 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Jul 2003 11:56:23 -0700 Subject: focus problem with full-screen in Tkinter Message-ID: <2259b0e2.0307140746.46cf2e8c@posting.google.com> I have a problem with full screen windows in Tkinter. Here is a minimal script showing the problem: from Tkinter import * root=Tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry("%dx%d+0+0" % (w, h)) #root.overrideredirect(1) root.focus() root.bind("",lambda e: root.destroy()) root.bind("<1>",lambda e: root.destroy()) root.mainloop() Here everything works, and if I press "q" the window is destroyed. However, if I uncomment the line with "overrideredirect" and I really go full screen, Tkinter does not recognize the keybindings and I cannot close the window with "q". Fortunately, the mouse is recognized and I can close the window with a click. I guess the problem is with the focus, how should I modify root.focus() to ensure that the keybindings are recognized? TIA, Michele P.S. I am using Python 2.2 on Red Hat 7.3 From dmbkiwi at yahoo.com Sat Jul 12 20:30:52 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sun, 13 Jul 2003 12:30:52 +1200 Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 23:11:20 +0000, Bengt Richter wrote: > On Sat, 12 Jul 2003 14:27:33 +1200, dmbkiwi wrote: > >>On Sat, 12 Jul 2003 01:58:13 +0000, Bengt Richter wrote: >> > [...] >>> If that is really happening, I wonder if you are somehow executing code from a different version >>> or have some kind of mixed-up installation. Or are using incompatible extension modules? >>> Do you have multiple versions installed? what are your versions, and what sym links are there? >>> And what are the #! lines of your script(s)? >> >>One point that I may not have made clear is that I'm not experiencing this >>behaviour personally with my set up. It is other people using this script > Is it a single .py file? Yes, although it imports a module called karamba (see my original post - this is a theme run through a theme engine called superkaramba). > >>who are reporting this behaviour. The difficulty I'm having is that it's >>very hard to debug a problem you're not having. I've sent versions of the >>script to these people, with print statements at appropriate points to >>ensure that the script is doing what I think it's doing (in terms of going >>wrong for them), and from the output they send back, the interpreter is >>definitely ignoring the else statement and ploughing through them, even >>though, it's also executed the corresponding if statement. >> > I wonder if your script is executed directly by Python. Perhaps it is "sanitized" > for security reasons before being executed in some context, and it gets glitched, > in the sanitizing process. If so, could you ask them to put a debug print to > show what's actually being executed? And ask them how it's being executed > (ie, exec vs exec in somedir vs execfile vs import and invoke vs whatever they do). It is being executed through the superkaramba engine (written in c++ I believe). Not sure if I, or my users have enough gumption to do the debugging you are referring to. I have asked them to execute the script which contains a number of print statements to verify that it is ignoring the else statement. Is there other debugging info that I should be printing when running the script? > [...] >>Suffering alone exists, none who suffer; >>The deed there is, but no doer thereof; >>Nirvana is, but no one is seeking it; >>The Path there is, but none who travel it. >> -- "Buddhist Symbolism", Symbols and Values >> > Cool ;-) > > Regards, > Bengt Richter Glad you liked it. It's just an automated sig generated by the fortune program. No conscious thought goes into it :-). Matt From duncan at NOSPAMrcp.co.uk Wed Jul 23 11:31:57 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 23 Jul 2003 15:31:57 +0000 (UTC) Subject: The global statement References: Message-ID: "David Hitillambeau" wrote in news:pan.2003.07.23.15.14.52.430267 at intnet.mu: > On Wed, 23 Jul 2003 16:56:08 +0200, Thomas G?ttler wrote: > >> If foo and bar are in the same file, >> you don't need the "global". > > Then when is "global" required? What is it's role? > I'm afraid Thomas G?ttler's answer was a bit misleading. You never need to use the 'global' statement outside a function. The only effect of 'global' is to declare that a variable assigned to within a function is actually a global variable. The fact that it is a global variable lasts only for the duration of the function in which it occurs. Global variables are not in fact global. They are global only to the module in which they occur (usually you get one module per source file, although be aware that if you run a script A.py, it runs in the module __main__ and importing A will give you a second module from the same source, with its own global variables). If you want to access a global variable from another module you don't need a global statement, just prefix the variable with a reference to the module. e.g. 'A.x' will access the global 'x' in module 'A'. So: BAD=1 def foo(): global BAD BAD = 2 def bar(): BAD = 3 global BAD def xyzzy(): BAD="xyzzy" def plugh(): print "BAD is",BAD Outside the function assigning to BAD makes it a global variable. Inside foo and bar the global statement makes BAD a global variable for the assignment, notice that it doesn't matter where in the function the global statement occurs, although it is conventional to list globals at the head of the function. 'xyzzy' simply sets a local variable with the same name as the global. 'plugh' accesses the global: if you don't try to assign to it you don't need to tell Python its a global. Finally, all of this confusion can be avoided if you use classes instead of global variables. e.g. class MyClass: def __init__(self): self.value = 0 def foo(self): self.value = 1 def bar(self): self.value = 2 obj = MyClass() obj.foo() obj.bar() -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From fredrik at pythonware.com Sun Jul 13 20:00:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Jul 2003 02:00:07 +0200 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien> Message-ID: Stephen Horne wrote: > Java has the same problem as Python in this respect. You can either > state that it implements a different assignment semantic for some data > types than it does for other data types, or you can claim that some > data types have implicit built in references while others don't. Or you can explain how it actually works, instead of making things up as you post. In my experience, most people prefer that approach. From usenet at marnanel.org Tue Jul 29 19:00:29 2003 From: usenet at marnanel.org (Marnanel) Date: Tue, 29 Jul 2003 19:00:29 -0400 Subject: urlretrieve a file whose name has spaces in it In-Reply-To: <10caf2e2.0307291439.33d9fcc3@posting.google.com> References: <10caf2e2.0307291439.33d9fcc3@posting.google.com> Message-ID: > The statement: > urllib.urlretrieve("http://website.com/path/string string1 foo.doc", > "local_file"); > > produces local_file which contains the following one line: > ErrorThe parameter is > incorrect. > > What is the correct way of specifying the this file in urlretrieve() ? Have you tried urllib.urlretrieve("http://website.com/path/string%20string1%20foo.doc", "local_file"); ? (URLs can't really contain unescaped spaces.) M From peter at engcorp.com Fri Jul 4 13:57:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 13:57:24 -0400 Subject: Exceptions and modules References: <292c8da4.0307040627.59acda19@posting.google.com> Message-ID: <3F05C004.AE1FF727@engcorp.com> Duncan Booth wrote: > > westernsam at hotmail.com (sam) wrote in > news:292c8da4.0307040627.59acda19 at posting.google.com: > > > So the Exception isn't recognised even though it has the same > > namespace and name as the exception defined in the module. I have to > > uncomment the 7th line to get my example to behave as I would like it > > to. > > > > Is this a bug/feature? Is there any reason why it shouldn't work the > > way I expect it to? > > It's a feature, and it probably ought to be in the FAQ in some form. [snip explanation] And the solution is to avoid putting things into your __main__ module (the one run from the command line) which other modules need to find by importing it. If the application is so complex that it needs to have multiple modules, make the main one do something simple like import an Application class from somewhere else, instantiate it, and call .run() on it (or whatever...). -Peter From gradha at titanium.sabren.com Tue Jul 15 15:22:48 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Tue, 15 Jul 2003 21:22:48 +0200 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. In-Reply-To: References: Message-ID: <20030715192248.GB30309@pedos.es> On 2003-07-13, Andrew Dalke wrote: > Me: > > > What does this do that the standard Python library doesn't support? > > Grzegorz Adam Hankiewicz > > * python 1.5.2 support. > > * [round-tripping] > ... > > Could you include those points in your documentation? It > helps others to understand when to look at your library vs. > some other library. Yes, I should do that for next version. Thanks for the tip. -- Please don't send me private copies of your public answers. Thanks. From geoff at gerrietts.net Tue Jul 29 17:02:22 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 29 Jul 2003 14:02:22 -0700 Subject: Tools for reading Dr Dobb's Python-URL In-Reply-To: <20030727160011.GA847@lilith.ghaering.test> References: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> <20030727144122.GA1689@mirk.lan> <20030727160011.GA847@lilith.ghaering.test> Message-ID: <20030729210222.GB25897@thoth.homegain.com> Quoting Gerhard Haering (gh at ghaering.de): > * Egbert Bouwman [2003-07-27 16:41 +0200]: > > On Sun, Jul 27, 2003 at 01:48:55PM +0200, Irmen de Jong wrote: > > > > > > Open the message in your news reader. > > > Click on an URL in the message. > > > > > > Sorry, couldn't resist. I'm not sure what you want to > > > do, really? > > > > My mail reader is the text-based Mutt, which: > > - doesn't react to mouse clicks > > - does show url's in a different color Gnome-terminal allows you to ctrl-right click on the URL, and select "open in browser". Took me a while to find that, hope it helps. --G. -- Geoff Gerrietts "I have read your book and much like it." --Moses Hadas From kj.kjn at wanadoo.fr Wed Jul 2 04:53:32 2003 From: kj.kjn at wanadoo.fr (kj.kjn) Date: Wed, 2 Jul 2003 10:53:32 +0200 Subject: returning a structure using SWIG Message-ID: I would like to build a module for the fuction : myReturn find(char ** p1, int p2) The problem is that I dont know how to specify the myReturn Type using swig. myReturn is : typedef struct{ char * name; char * len[10]; time_t time; } myReturn How to specify a such type in the interface file ? Thank you From tomas at fancy.org Mon Jul 14 20:06:17 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 17:06:17 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> Message-ID: Tom Plunket wrote: > What I specifically want is a way to have a "second-level > binding", e.g. a reference to a reference (assuming that the > terminology is correct by saying that all Python variables are > references). This is where I see the hole in Python, that there > actually is a class of object that is different from everything > else; you can bind to anything at all in the language...except > references. I just realized that this would be silly, complex, etc. Say you could (as another poster mentioned) do something like this: >>> a = 5 >>> b = ref_to(5) >>> a = 3 >>> print b 3 This would require a new built-in probably, and any time you (accidentally?) did 'b = c', then you'd lose that reference, but... hmm, I wonder if it'd be handy. Probably not enough to justify the expense. :) -tom! From bokr at oz.net Fri Jul 18 16:08:37 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 20:08:37 GMT Subject: How do I get info on an exception ? References: <3F1793D4.E6EEF8A1@alcyone.com> Message-ID: On Thu, 17 Jul 2003 23:29:40 -0700, Erik Max Francis wrote: >Frank wrote: > >> Using Python 2.2.2, >> I want to catch all exceptions from "socket.gethostbyaddr(ip)" >> >> From IDLE, I can generate: >> >>> socket.gethostbyaddr('1.2') >> Traceback (most recent call last): >> File "", line 1, in ? >> socket.gethostbyaddr('1.2') >> herror: (11004, 'host not found') <=== what I want when I catch >> >> When I run this code: >> try: >> hostname, aliases, hostip = socket.gethostbyaddr(ip) >> return (hostip, hostname) >> except: >> print sys.exc_info() >> print sys.exc_type >> return > >Use the format: > > try: > ... > except ErrorType, e: > ... do something with exception object e ... > Indeed. Or if you want to catch all standard exceptions until you know what is happening, you could pick from the following. I guess you could also catch all exceptions defined in a module without knowing what they're named, and re-raise if other, e.g., with (untested!) if not repr(e.__class__).startswith('socket'): raise is there another way to do that? >>> import socket >>> try: ... socket.gethostbyaddr('1.2') ... except Exception, e: ... print 'plain e:', e ... print 'e class:', e.__class__ ... print 'e class name:', e.__class__.__name__ ... print 'vars keys:', vars(e).keys() ... print 'vars dict:', vars(e) ... print 'additional inherited clutter seen by dir:\n',dir(e) ... plain e: (11004, 'host not found') e class: socket.herror e class name: herror vars keys: ['args'] vars dict: {'args': (11004, 'host not found')} additional inherited clutter seen by dir: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] You could also print a formatted vars(e) to see unanticipated attributes more nicely with e.g., (untested!) print ''.join(['%16s = %r\n' %(k,v) for k,v in vars(e).items()]) >>>> import socket >>>> socket.error > >>>> try: >... socket.gethostbyaddr('1.2') >... except socket.error, e: >... print e, dir(e), e.args >... >(1, 'Unknown host') ['__doc__', '__getitem__', '__init__', '__module__', >'__str__', 'args'] (1, 'Unknown host') > >> How do I get the "(11004, 'host not found')" part? >> More importantly, where is the answer documented that I should >> have looked? > >Check the part on exception handling. > Interactively, help('exceptions') is also helpful (note quotes) Regards, Bengt Richter From jocsch at phreaker.net Sun Jul 6 15:17:36 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Sun, 06 Jul 2003 21:17:36 +0200 Subject: Search for mapping solution Message-ID: Hi, stated in a post befor, I'm a java programmer, fascinated about the elegant way python solves iterations. Maybe you can show me a solution how to map the following I have a List: Name - Number - Costs lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] Now I want to have it in a dictionary(name,costs) Should look like {'fred':'0,60' , 'sam':'1'} What's an elegant way to do it? I can use a lot of loops, but I assume, that there is a better way of doing so. Thanks, Markus From klappnase at freenet.de Sat Jul 19 21:18:57 2003 From: klappnase at freenet.de (klappnase) Date: 19 Jul 2003 18:18:57 -0700 Subject: tk prerequisite References: <3f0fffc0$0$235@hades.is.co.za> Message-ID: <9a410299.0307191718.5dd25502@posting.google.com> Tertius wrote in message news:<3f0fffc0$0$235 at hades.is.co.za>... > Installing tkinter 2.2.3 on RH9 the following message displayed > > > [root at host 223]# rpm -i tkinter-2.2.3-26.i386.rpm > warning: tkinter-2.2.3-26.i386.rpm: V3 DSA signature: NOKEY, key ID fd71b297 > error: Failed dependencies: > libtcl8.3.so is needed by tkinter-2.2.3-26 > libtix8.1.8.3.so is needed by tkinter-2.2.3-26 > libtk8.3.so is needed by tkinter-2.2.3-26 > > > Question: > > Must it be 8.3 or will 8.4 also do ? > > TIA > Tertius You definitely need 8.3 (however these should be the defaults in RH9 if I remember correctly, have you upgraded manually?). Cheers Michael From zathras at thwackety.com Thu Jul 31 18:13:05 2003 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 31 Jul 2003 23:13:05 +0100 (BST) Subject: What does "*list" mean? In-Reply-To: Message-ID: On 31 Jul 2003, Greg Smethells wrote: > What exactly does "*values" mean in the following code? One way of viewing it is that it flattens the list - expands the list as separate arguments to be passed to the function. For those coming from a perl background it makes the list act in the same way as a perl list passed to a function not as a reference. For sake of argument I'll use the following list, and 3 functions: values=[1,2,3] # For sake of argument def bar(args): print args def bar(args): # Simple case print args def foo(*args): # Takes the arguments and turns it into tuple print args def foobar(arg, *args): # Take first argument, and treat all others as # part of a tuple called args print arg, ":", args Let's do the simple case first: >>> bar(values) [1, 2, 3] As you expect this succeeds - we passed one value to the function. >>> bar(*values) Traceback (most recent call last): File "", line 1, in ? TypeError: bar() takes exactly 1 argument (3 given) The reason this failed is because >>> bar(*values) Is essentially equivalent to this: >>> bar(1,2,3) Due to the "flattening" of the list. The next case is where un-flattening happens (there's probably a better phrase here :) : >>> foo(values) ([1, 2, 3],) What's happened here? The call that was made is essentially this: >>> foo([1,2,3]) This hit the following signature: def foo(*args): This says to take the arguments, and stuff them into a tuple. We've only passed one argument - specifically [1,2,3]. So a tuple is created using this, which gives us our result : ([1,2,3], ) is displayed. If we call foo with a normal argument list we get: >>> foo(1,2,3) (1, 2, 3) Why? Because *args in this context _effectively_ says "take the (remaining) arguments, and create a single value named 'args' that is a tuple containing those values". ie take the arguments 1,2,3, and create a tuple - which is (1,2,3) which then gets displayed. If we combine these things we quickly find some fun stuff. What happens if we flatten a list that gets sent to a function that turns it's argument list into a tuple? >>> foo(*values) (1, 2, 3) We get this because foo(*values) is directly equivalent to foo(1,2,3) - the list *values gets expanded/flattened. Taking the final example function - what happens if you mix and match? >>> foobar(values) [1, 2, 3] : () Well, our signature here was: >>> def foobar(arg, *args): This says - take the first argument in the parameter list and stuff it in "arg", if you get any other values, create a tuple with them, and stuff them in args. In this case the first argument was the list [1,2,3], and there were no further arguments, so args contains an empty tuple () If however we expand/flatten out list: >>> foobar(*values) 1 : (2, 3) Our result is pretty clear: foobar(*values) has been treated as foobar(1,2,3), the first argument -1- stuffed into arg, and the other two stuffed into a tuple in args (1,2). As a result this: > >>> from struct import * > >>> format = "dl" > >>> values = [3.14, 42] > >>> foo = pack(format, *values) is directly equivalent to: >>> from struct import * >>> foo = pack("dl", 3.14, 42) >>> foo '\x1f\x85\xebQ\xb8\x1e\t@*\x00\x00\x00' > '\x1f\x85\xebQ\xb8\x1e\t@*\x00\x00\x00' > More importantly still, how would you write the same code in C? If you > wanted to instead call struct_pack(PyObject *tuple), what would the > tuple look like in C? Caveat: I haven't written any C extensions, not looked into the API and so on, but I will point out this minor thing: how does this python function differ from a normal one? >>> def hello(world, everyone): ... print "hello", world, everyone ... >>> values=["world","today"] >>> hello(*values) hello world today Answer: it doesn't - it's just how the argument list has been built up. If you were trying for the same effect in C, in principle, you'd either need: * To do a varags call - ala printf (in which case the signature of what you're calling would need to match) (This would match the "foobar" example above) * To upack the tuple into temporary values and then do the call manually - as you could in python: >>> values=["world","today"] >>> arg1=values[0] >>> arg2=values[1] >>> hello(arg1,arg2) hello world today There's probably a formal description of all this stuff somewhere :-) Michael. From max at alcyone.com Mon Jul 7 17:29:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jul 2003 14:29:16 -0700 Subject: print attitude References: <3F0669B5.679FB505@alcyone.com> Message-ID: <3F09E62C.D1A8D53A@alcyone.com> Donn Cave wrote: > Speaking of floats, I believe lists containing floats are the main > case where people really resist seeing the sense in this - but it's > easier to call that a wart in float's repr, since they're as bugged > wherever they see it and in my opinion rightly so. Personally, I think the internal difference between str and repr hits right upon a proper difference: str is for a "reasonable" human-readable representation, and repr is for as faithful and informative a representation as possible. These both have their uses and I approve of the distinction. The confusion, in my opinion, comes from the fortuity of when str vs. repr is used, which is easy to understand once you've been exposed to it but is very confusing at first. Even for someone who's familiar with the inaccuracy of floating point, you can very easily see how someone would be confused and worried about the following code fragment: >>> x = 1.4 >>> print x 1.4 >>> print [x] [1.3999999999999999] -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We're here to preserve democracy, not to practice it. \__/ Capt. Frank Rasmey From staschuk at telusplanet.net Wed Jul 23 14:48:00 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 23 Jul 2003 12:48:00 -0600 Subject: How does Mr. Martelli's Borg recipe work ? In-Reply-To: ; from newsgroups@jhrothjr.com on Tue, Jul 22, 2003 at 10:50:38PM -0400 References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <20030723124800.C527@tibia.amotlpaa.bogus> Quoth John Roth: [...] > I can kind of understand the justification for the Borg pattern > in Python releases before 2.2, because there was no way of > creating a true singleton in those releases. However, in 2.2 and > later, it's really easy to create one using new style classes. [...implementing singletons with __new__...] > That being the case, I'd like to see the Borg pattern go the way > of a fondly remembered hack that is no longer necessary. Just out of curiosity: why do you prefer singletons to Borgs in the first place? (I don't see Borg as a hack to get the behaviour of a singleton; I see it as a more direct way to solve the problem which singletons are supposed to solve. Thus to me Borg is actually preferable, in those exceedingly rare cases when that problem actually arises.) -- Steven Taschuk staschuk at telusplanet.net "I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein From exarkun at intarweb.us Thu Jul 24 21:45:17 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 24 Jul 2003 21:45:17 -0400 Subject: Don't want to do the regexp test twice In-Reply-To: <20030724214457.GA874@mirk.lan> References: <20030724214457.GA874@mirk.lan> Message-ID: <20030725014517.GB19318@intarweb.us> On Thu, Jul 24, 2003 at 11:44:57PM +0200, Egbert Bouwman wrote: > [snip] > > for line in mylist: > mat = pat.search(line) > if ...: > .... > elif ...: > .... > elif mat: > ... > but the test is relevant in only a relatively small number of cases. > And i would like to know if there exists a general solution > for this kind of problem. People will tell you not to use this solution for the obvious reasons: for line in mylist: if ...: .... elif ...: .... elif [mat for mat in [pat.search(line)]][0]: # mat is now bound List comprehensions at work. Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 From lorenb2 at bezeqint.net Wed Jul 30 10:16:32 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Wed, 30 Jul 2003 16:16:32 +0200 Subject: how to gunzip a string ? Message-ID: <025001c356a5$2d9aad10$6400a8c0@EVOD31> I guess I really need some sort of library that will do a gzip decoding to a compressed string. assume that I have a gzipped_string_reply I got from an HTTP server, It'd be superb to have a gunzip class that takes it and return its decoded equivalent. I managed to do it with the gzip library only after saving the string to a file and then opening and reading it with gzip.open, but it's extremely ugly. any suggestions ? thanks! ~ B From robin at jessikat.fsnet.co.uk Sun Jul 27 10:20:37 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 27 Jul 2003 15:20:37 +0100 Subject: chaco setup Message-ID: I'm having trouble building chaco from source with Python- 2.2.3/Win2kSP4. I have Numeric 23.0 installed so assumed that it might not work using the win32 installer so am trying to build from chaco- 0.1.0_alpha_37.776.zip. I get a setup.py error ImportError: No module named build_agg. Do I need to install some extra software prior to building chaco? -- Robin Becker From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 22 18:11:42 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 23 Jul 2003 00:11:42 +0200 Subject: Confusing automated translators. In-Reply-To: References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3f15b04b$0$49114$e4fe514c@news.xs4all.nl> Message-ID: <3f1db69e$0$49116$e4fe514c@news.xs4all.nl> Christos TZOTZIOY Georgiou wrote: > On Wed, 16 Jul 2003 22:06:36 +0200, rumours say that Irmen de Jong > might have written: > > >>You should really add a comma at the right place, otherwise even Dutch >>people themselves tend to get confused rather quickly too: >> >>"Als achter vliegen vliegen vliegen, vliegen vliegen vliegen achterna." > > > ...and the meaning is? *spoiler* If behind flies flies fly, flies fly after flies. (I'm not too sure about the correct word order in English, but this resembles the Dutch sentence most, IMO). --Irmen From deets_noospaam at web.de Mon Jul 28 14:39:15 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2003 20:39:15 +0200 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> Message-ID: Fazer wrote: > Hello, > > I am an avid user of PHP and I am just fooling around with Python for > now. I originally wanted to know which one is faster. As in, works > faster. So far, I think PHP is the fastest for dynamic web-content. > Am I wrong? Definitely. See here: http://www.bagley.org/~doug/shootout/craps.shtml Python is place 13, with a speed index of 578. PHP is second last (before bash) and has a speed index of 197. Besides that, PHP is a really ugly language - not only to the eye (which is admittedly a matter of taste), but a friend of mine currently implements a PHP->C-Compiler had delved deep into the language implementation - and it _is_ ugly. I expirienced mayor flaws in PHP 4.0.x, where my declared functions in a 6000 line include vanished from time to time - repeating the request sometimes solved the problem. That was really nasty. Regards, Diez From donhiatt at acm.org Thu Jul 24 15:38:25 2003 From: donhiatt at acm.org (Don Hiatt) Date: 24 Jul 2003 12:38:25 -0700 Subject: easy way to remove nonprintable chars from string Message-ID: <2b012c5e.0307241138.177e5c8c@posting.google.com> Greetings, Is there an easy way to remove multiple non-printable (e.g. "not strings.printable") from a string? Perhaps something like foo.replace(list_of_nonprintables, '') if it only existed? :-) Cheers, don From duncan at NOSPAMrcp.co.uk Tue Jul 1 04:27:30 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 1 Jul 2003 08:27:30 +0000 (UTC) Subject: I have a list... References: <20030701113915.226ae9bd.agg@astranet.ru> Message-ID: "Damir Hakimov" wrote in news:20030701113915.226ae9bd.agg at astranet.ru: > Hi, All! > > say, i have a function: > > def f(*b): > print b > return > > then i do: > f(3,4,5) > (3, 4, 5) > > but i have list f=(3,4,5) > f(l) > ((3, 4, 5),) > > how can i call f function to result > f(???(b)) > (3, 4, 5) > I'm not sure any of the other responses actually answered the question, which I think was meant to be, given a tuple l=3,4,5 how do you pass that tuple to the function f so that b simply gets the tuple. The answer is that you try: >>> f(*l) (3,4,5) If that doesn't work, then you upgrade to a more recent version of Python. If you (or your users) really can't upgrade you should use 'apply'. -- 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 fperez528 at yahoo.com Thu Jul 3 18:09:00 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 03 Jul 2003 16:09:00 -0600 Subject: Emacs + py-mode + tkinter problem References: Message-ID: Alexander Schmolck wrote: > Maybe too many people are happy with too little (essentially > edit/run-whole-program/debug cycles a la C, plus maybe using python > interactively as a calculator or to look up documenation). If I had time I'd > write a tutorial on using ipython from within emacs for (I think) much more > effective interactive development. ... me cheers in corner, while I know I've also fallen behind answering people's recent questions on ipython ;) Ah, real work... best, f From drlinux at columbus.rr.com Wed Jul 9 15:31:34 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Wed, 9 Jul 2003 15:31:34 -0400 Subject: check if dir exists In-Reply-To: References: Message-ID: <200307091531.34861.drlinux@columbus.rr.com> On Wednesday 09 July 2003 15:01, Geiregat Jonas wrote: > How can I check if a dir exists ? > -- See the os module, specifically the os.path functions I believe. Dave From nospam at nospam.net Tue Jul 1 17:32:53 2003 From: nospam at nospam.net (c42) Date: Tue, 01 Jul 2003 21:32:53 GMT Subject: exchange.HrFindExchangeGlobalAddressList Message-ID: Can anyone explain how to use exchange.HrFindExchangeGlobalAddressList, perhaps give an example? Thanks! c42 From gtewalt at earthlink.net Wed Jul 2 18:14:36 2003 From: gtewalt at earthlink.net (gt) Date: 2 Jul 2003 15:14:36 -0700 Subject: Newbie advice for string fromatting References: Message-ID: "Raymond Hettinger" wrote in message news:... > "gt" wrote in message > news:f9b7c11d.0307020642.7231cd82 at posting.google.com... > > O.k., four days into playing with python > > and I have a little problem that I would like > > to get some feedback on. > > ( as far as the best way to go about it ) > > > > Basically, just a little Mad-Libs type script. > > > > Something like: > > > > libs = ["adverb", "noun", "verb", "tool"] > > words = {a:j, n:j, v:j, t:j} > > for x in libs: > > print "Enter a ", x, ": ", > > words[j] = raw_input() > > print "The %s %s %s with a %s." % (a, n, v, t) > > > > What is the most efficient way to do something like this? > > You're on the right track. > Using dictionaries with the % formatting operator is efficient. > > Subclassing a dictionary with a question asker is an > approach that keeps the code simple and separates it > from the actual madlib strings. > > So, here is version to get you started: > > > >>> farmtale = """ > At %(name)s farms, we drive a %(machine)s over > the %(vegetable)s crops and feed %(food)s to our > %(animal)s.""" > > >>> class Madlib(dict): > def __getitem__(self, key): > return raw_input("Enter a %s: " % key) > > > >>> print farmtale % Madlib() > Enter a name: Donald > Enter a machine: clock > Enter a vegetable: squash > Enter a food: pizza > Enter a animal: snake > > At Donald farms, we drive a clock over > the squash crops and feed pizza to our > snake. > > > Raymond Hettinger Thanks Raymond, and Sean. I posted at work this morning, so I didnt have Python available to see if my idea actually worked or not. It's good to know I wasn't totally off base though. And, I'm making an educated guess, but I suppose one could type up fairly large tales, let a user choose a category of a sort, and just import the tale modules. Thanks again. :-) From hokiegal99 at hotmail.com Sat Jul 5 15:51:58 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 05 Jul 2003 15:51:58 -0400 Subject: Calculating Year, Month and Day of Life In-Reply-To: References: Message-ID: hokiegal99 wrote: > hokiegal99 wrote: > >> Hello, >> >> I am a funeral director trying to write a small program that >> calculates the number of years, months and days a person has lived by >> entering the year, month and day of their birth. This is what I have >> so far: >> >> #--------------------- >> from time import * >> local = localtime() >> >> print "Enter the year of birth:"; y = input() >> print "Enter the month of birth:"; m = input() >> print "Enter the day of birth:"; d = input() >> >> age = y,m,d >> print age >> print local >> #---------------------- >> >> The output looks similiar to this: >> (1934, 2, 7) >> (2003, 7, 5, 13, 20, 0, 5, 186, 1) >> >> My problem is that localtime is a list of 9 integers while age is a >> list of 3 integers. Is it possible to make localtime() only return the >> first 3 integers? If so, how would I then do calculations on the two >> lists' individual parts? For example, how would I instruct localtime() >> to subtract the first integer from age's list from the first intger in >> its own list (2003 - 1934)? >> >> Also, I am new to python, but I like it a lot and have picked it up >> quickly. If my approach to this solving this problem is completely >> wrong, please point me in the right direction. >> >> Thanks in advance!!! >> > > Sorry to respond to my own post, but I answered the first part of my > question by experimenting a bit. I pulled the first 3 integers from > localtime() like this: > > local = localtime() > print local[:3] > (2003, 7, 5) > Once again, I'm making progress on my own. Here's where I stand now: ---------------------- from time import * local = localtime() y = input("Enter the year of birth: ") m = input("Enter the month of birth: ") d = input("Enter the day of birth: ") age = y,m,d print "You are", local[0] - age[0], "years", local[1] - age[1], "months" ----------------------- From dkuhlman at rexx.com Sun Jul 6 14:22:50 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 06 Jul 2003 11:22:50 -0700 Subject: absolute beginners question about API documentation References: Message-ID: Markus Joschko wrote: > Hi all, > I' new to python programming but a longtime java programmer. > Is there an API documentation like the javadoc API from java? > > I'm want to know all methods I can use on dictionaries. Where can > I get an overview about these? > I looked on python.org but haven't found such an overview. > If you are asking about the *Python* API, then look here: http://www.python.org/doc/current/lib/typesmapping.html If you are asking about the C API (which is less likely but possible), then look here: http://www.python.org/doc/current/api/dictObjects.html Hope this helps. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From peter at engcorp.com Mon Jul 14 00:12:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 00:12:55 -0400 Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: <3F122DC7.2DE0CCA1@engcorp.com> David McNab wrote: > > One more thing Elaine - I may offend others on this list in saying this, > but if you're doing GUI applications, I strongly suggest that you dive in > and familiarise yourself with Tkinter. It could well be the only GUI you > ever need in Python. > > Don't be intimidated if the Tkinter docs you come across urge you to > approach it from a Tk viewpoint- there's an excellent guide at: > http://www.astro.washington.edu/owen/TkinterSummary.html > > I argue for Tkinter over another popular Python-accessible GUI, wxWindows, > because Tkinter is smaller, faster and far less buggy, and has a really > nice 'feel' within the Python environment. And there are those of us who have tried that route already, found it lacking, and are much happier with wxPython (not wxWindows) because we find it faster, more cosmetically pleasing and usable, and easier to work with. To each his own. Thankfully we all have a choice here. -Peter From mmoum at woh.rr.com Tue Jul 1 19:09:11 2003 From: mmoum at woh.rr.com (Mike M) Date: Tue, 01 Jul 2003 23:09:11 GMT Subject: whitespace and ?asc()? References: <3F02086D.9010300@ihug.co.nz> Message-ID: NP = chr(12) = = New Page (for printers) Mike -- -- the Moum's (Mike, Dede, Suzanne, Jeff, Kristen) Tipp City, Ohio, USA e-mail: mmoum at woh.rr.com Learn about the Baha'i Faith at: http://www.bahai.org Visit the United States Baha'i Site at: http://www.us.bahai.org "Ray Tomes" wrote in message news:3F02086D.9010300 at ihug.co.nz... > Hi all > > I am totally new to python. On the whole I really like the design of the > language and after just one day may be considered a convert. > > I was trying to find out the exact definition of whitespace so I went to > look at strings.whitespace to find out which chars were whitespace, and > found 9, 10, 11, 12, 13, 32 which according to my ancient ascii chart are > TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? > > Also, in trying to find the ASCII (or is it ANSI) values for characters I > could not find the reverse function for chr() [in BASIC it is asc()]- can > someone please tell me what reverses chr()? > > I had to do this yucky thing to decode whitespace ... > > import string > x=string.whitespace > for b in x: > for i in range(256): > if chr(i) == b: > print i > > Ray Tomes > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.493 / Virus Database: 292 - Release Date: 6/25/2003 From claird at lairds.com Wed Jul 30 09:19:07 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 30 Jul 2003 13:19:07 -0000 Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: In article , Andrew Dalke wrote: >Rick: >> But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal >> papers in the history of Python in the opinion of members of this >> newgroups? > > - Lutz Prechelt's paper comparing C, C++, Perl, Java, Tcl, Python, and > a couple more languages, all on the same non-trivial task > > - Greg Stein's paper at the San Jose conference (1998), on how his > company used Python to make a commercial web app then sold it > to Microsoft - helped convince me people could make money doing Python > > - not really a paper, but reading through the tutorial and the library >docs > back in 1997 were what convinced me that Python was the language for >me. > It still took 2 years before I could use it -- too much preexisting Tcl >and Perl > code. . . . Somewhere between academic papers and Usenet discussions, examples of each of which have already been recommended to you, are magazine articles. Last millenium, I wrote several that *still* appear to attract readers, to my surprise. If my e-mail is an apt indication, "Python as a First Language" www.oreillynet.com/pub/a/network/2000/06/02/magazine/python_first_language.html "Getting Started With Python" web.archive.org/web/20010201170400/http://www.sunworld.com/sunworldonline/swol-02-1998/swol-02-python.html "Batteries Included" web.archive.org/web/20001013152452/http://sunworld.com/swol-12-1998/swol-12-regex.html are among those influential out of proportion to their artistic merit. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From matthew.rapoport at accenture.com Tue Jul 15 15:33:47 2003 From: matthew.rapoport at accenture.com (Matt Rapoport) Date: 15 Jul 2003 12:33:47 -0700 Subject: Thread suddenly stops in NT Service Message-ID: <4150f6c8.0307151133.7dab4b25@posting.google.com> I'm running an NT service with a thread. The thread performs a calculation every so often and appends the number to a text file. Every so often the thread just stops - or so it seems. The text file stops getting numbers added to it but the service is still running and no errors have been thrown. I'm quite sure that the code would catch an error and post it to the event viewer if one were arising. The only other relevant points I can think of are that the thread runs a while 1: loop and is set to run as a Daemon. The service waits only for the stop command. It doesn't seem to be operating system specific (happens on both XP and 2000). It doesn't seem to be file size specific, it stops at various file sizes ranging from 5K - 50K. It doesn't seem to be time specific - sometimes it'll stop after about a day. Sometimes it'll stop after two days. Any help would be great. Thx. Matt From stacom at stacom-software.de Fri Jul 25 09:22:17 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Fri, 25 Jul 2003 15:22:17 +0200 Subject: data conversion question (binary string to 'real string') In-Reply-To: References: Message-ID: <3F212F09.2060107@stacom-software.de> Manish Jethani wrote: > Alexander Eisenhuth wrote: > > >>maby I don't see the forest because of all that trees, but : > > > Maybe I don't understand your question... > > >>from struct import * >> >> >># how can I convert >>f = float(0.5) >> >># with >>bin_str = pack('!f', 0.5) >> >># now bin_str is '?\x00\x00\x00' >> >> >># to "3F000000" ????? > > > ??????????????? > What is your question? > > -Manish > Sorry ... This two lines converts 0.5 to a string in binary representation >>>from struct import * >>>bin_str = pack('!f', 0.5) now bin_str is '?\x00\x00\x00', wich is the representation of 0.5 in the memory. I need now to convert this binary string to "3F000000", where '3F' is the hex value of the '?' in ascii - table. Any ideas ?? Thaks Alexander From steve at ferg.org Mon Jul 7 14:24:48 2003 From: steve at ferg.org (Stephen Ferg) Date: 7 Jul 2003 11:24:48 -0700 Subject: Python is a gem ,another successful day .... References: Message-ID: > I'd be interested in knowing some of the arguments you used to win over VB, > as I've been asked to put a couple of articles together suggesting why VB > users might consider switching to Python. I really hope you're able to do those articles comparing Python and VB. I'm trying to promote Python within the Federal government, and my own agency, the Bureau of Labor Statistics. Right now, the chief alternative at BLS to Python is Java, but not too long ago it would have been VB and PowerBuilder. Folks are moving away from PowerBuilder mostly because of concern about the vendor's longterm support/viability, but VB actually may rise again, as there is a small but noticeable groundswell of discontent with Java's clumsiness and verbosity. Bottom line: If we can develop materials making a convincing case for Python compared to VB, there are situations where such material might be of real help. -- Steve Ferg From dgallion1 at yahoo.com Tue Jul 8 17:50:03 2003 From: dgallion1 at yahoo.com (Darrell Gallion) Date: Tue, 8 Jul 2003 14:50:03 -0700 (PDT) Subject: win32security.LogonUser In-Reply-To: <3F0B14CF.6040102@btinternet.com> Message-ID: <20030708215003.43274.qmail@web21407.mail.yahoo.com> Here's all the privileges I try to get. Only SE_UNSOLICITED_INPUT_NAME fails. I'm part of a domain and there's something about the domain overriding local settings. Thanks for your help. --Darrell SE_SYSTEMTIME_NAME SeSystemtimePrivilege SE_ASSIGNPRIMARYTOKEN_NAME SeAssignPrimaryTokenPrivilege SE_PROF_SINGLE_PROCESS_NAME SeProfileSingleProcessPrivilege SE_SYSTEM_PROFILE_NAME SeSystemProfilePrivilege SE_SYSTEM_ENVIRONMENT_NAME SeSystemEnvironmentPrivilege SE_LOCK_MEMORY_NAME SeLockMemoryPrivilege SE_AUDIT_NAME SeAuditPrivilege SE_CHANGE_NOTIFY_NAME SeChangeNotifyPrivilege SE_LOAD_DRIVER_NAME SeLoadDriverPrivilege SE_SHUTDOWN_NAME SeShutdownPrivilege SE_INCREASE_QUOTA_NAME SeIncreaseQuotaPrivilege SE_SECURITY_NAME SeSecurityPrivilege SE_TCB_NAME SeTcbPrivilege SE_CREATE_PAGEFILE_NAME SeCreatePagefilePrivilege SE_INC_BASE_PRIORITY_NAME SeIncreaseBasePriorityPrivilege SE_MACHINE_ACCOUNT_NAME SeMachineAccountPrivilege SE_UNSOLICITED_INPUT_NAME SeUnsolicitedInputPrivilege Fail SE_REMOTE_SHUTDOWN_NAME SeRemoteShutdownPrivilege SE_RESTORE_NAME SeRestorePrivilege SE_DEBUG_NAME SeDebugPrivilege SE_CREATE_PERMANENT_NAME SeCreatePermanentPrivilege SE_CREATE_TOKEN_NAME SeCreateTokenPrivilege SE_TAKE_OWNERSHIP_NAME SeTakeOwnershipPrivilege SE_BACKUP_NAME SeBackupPrivilege SeChangeNotifyPrivilege SeTcbPrivilege SeAssignPrimaryTokenPrivilege Testing winprocess.py... CMD.EXE exit code: Traceback (most recent call last): File "E:\su.py", line 64, in ? stdout=out, stderr=out) File "C:\Python22\lib\site-packages\win32\demos\winprocess.py", line 163, in run child = Process(cmd, **kw) File "C:\Python22\lib\site-packages\win32\demos\winprocess.py", line 104, in __init__ hUser = logonUser(login) File "C:\Python22\lib\site-packages\win32\demos\winprocess.py", line 34, in logonUser win32con.LOGON32_PROVIDER_DEFAULT pywintypes.error: (1314, 'LogonUser', 'A required privilege is not held by the client.') __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From bokr at oz.net Mon Jul 14 14:54:01 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 18:54:01 GMT Subject: Newbie with sort text file question References: Message-ID: On Mon, 14 Jul 2003 07:10:39 -0600, Bob Gailer wrote: [...] >> >>Here's a handy idiom for what you want >> >> fruits[fruit] = fruits.get(fruit, 0) + 1 > >Don't you want setdefault() instead of get()? > In this case that would set the original value twice, once on either side of the '='. Setdefault is more useful when you are maintaining a mutable, such as a list of things that you append to, as the key's associated value. You could use a length-1 list here, (initialized by the default to hold the count starting value of 0), e.g., fruits.setdefault(fruit,[0])[0]+=1 and then later retrieve the actual count as fruits[fruit][0] Regards, Bengt Richter From dl at grosss.net Thu Jul 10 15:55:46 2003 From: dl at grosss.net (Paul) Date: Thu, 10 Jul 2003 14:55:46 -0500 Subject: Getting Started with python In-Reply-To: <3f0d2cb9$1@news.comindico.com.au> References: <3f0d2cb9$1@news.comindico.com.au> Message-ID: The Python Cookbook is a good place to find code snippets. Here is a link to the section on databases. http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Databases Tony Steward wrote: > Hello All, > Ok i've decided to try Python can anyone point me at a simple demo of a > windows program operating a database (maybe an address book) so I can see > how it is done. > > Thanks in advance > Tony > > From nirmalkannan at hotmail.com Fri Jul 11 00:32:14 2003 From: nirmalkannan at hotmail.com (N.K) Date: 10 Jul 2003 21:32:14 -0700 Subject: Convert between Windows style paths and POSIX style paths References: Message-ID: <5b04353b.0307102032.1581abff@posting.google.com> os.path.join is what you are looking for, i beleive eg: appendedpath = os.path.join(dir1,filename) Regards Nirmal noah at noah.org (Noah) wrote in message news:... > Does anyone have a function to convert back and forth between > NT style paths and POSIX style? It seems trivial, but > I want to make sure I don't overlook some obscure detail. > Is it a simple matter of translating / and \ characters? > > FYI, I need a Python function that does what cygpath does so that > I can run a script on either NT or UNIX or Cygwin. > I want my config files use one style of path. > > Yours, > Noah From gh at ghaering.de Mon Jul 7 13:43:00 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Jul 2003 19:43:00 +0200 Subject: looking for UDP package, network programming guidance In-Reply-To: References: Message-ID: <3F09B124.1070008@ghaering.de> Tom Plunket wrote: > [...] > Searching the web turned up Twisted, although it seems like it > might be a bit bigger than I would have hoped (in terms of, > "there's a huge package here to figure out"), but as far as I can > tell it's the only UDP solution out there. Is this the case? [...] No, Python's standard library supports socket as well, and that's what Twisted builds upon :-) Something like this should be a rough start for an UDP client (untested): #v+ import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto('Bing!', ('192.168.0.1', 5555)) #v- For an example UDP client and server this heartbeat recipe might be useful: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 > [...] Finally, I'm also somewhat of a babe in the woods with network > programming in general. The socket module is low-level, it's only a thin wrapper for what your OS offers. Twisted would be a higher-level framework. IMO there's nothing wrong with using the low-level module if you want to learn socket programming anyway :-) > Any good references for learning about > this stuff, [...] Sorry, not that I knew of. There is a (very short) Python Socket Programming Tutorial, but it only covers the very basics. Probably there is some good material out there for doing socket programming in C which you could easily map to Python, because the concepts and even the names of the functions are pretty much the same. -- Gerhard From bokr at oz.net Tue Jul 1 16:07:43 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2003 20:07:43 GMT Subject: Howto: extract a 'column' from a list of lists into a new list? References: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Message-ID: On Tue, 01 Jul 2003 10:03:11 +0200, Max M wrote: >Greg Brunet wrote: > >> but I'm not sure about how to do that. I can do this: >> >>>>>for g in tbl.Fields(): print g[0] >> >> ... >> STOCKNO >> DACC >> DEALERACCE >> D-ACCRTL >> D-ACCCST >> >> but I expect that one of those fancy map/lamda/list comprehension >> functions can turn this into a list for me, but, to be honest, they >> still make my head spin trying to figure them out. Any ideas on how to >> do this simply? > >fields = [ > ('STOCKNO', 'C', 8, 0), > ('DACC', 'C', 5, 0), > ('DEALERACCE', 'C', 30, 0), > ('D-ACCRTL', 'C', 9, 0), > ('D-ACCCST', 'C', 9, 0) >] > > > ># The "old" way to do it would be: >NAME_COLUMN = 0 >results = [] >for field in fields: > results.append(field[NAME_COLUMN]) >print results > > > > ># But list comprehensions are made for exactly this purpose >NAME_COLUMN = 0 >results = [field[NAME_COLUMN] for field in fields] >print results > Or you can take advantage of zip: >>> fields = [ ... ('STOCKNO', 'C', 8, 0), ... ('DACC', 'C', 5, 0), ... ('DEALERACCE', 'C', 30, 0), ... ('D-ACCRTL', 'C', 9, 0), ... ('D-ACCCST', 'C', 9, 0) ... ] >>> zip(*fields)[0] ('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST') Or a list of all the columns of which only the first was selected above: >>> zip(*fields) [('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST'), ('C', 'C', 'C', 'C', 'C'), (8, 5, 30 , 9, 9), (0, 0, 0, 0, 0)] Since zip gives you a list of tuples, you'll have to convert if you really need a list version of one of them: >>> list(zip(*fields)[0]) ['STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST'] Regards, Bengt Richter From gradha at titanium.sabren.com Sat Jul 26 18:25:56 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sun, 27 Jul 2003 00:25:56 +0200 Subject: ANN: mailbox_reader 1.0.3 -- Python module to read UNIX mailboxes sequentially. Message-ID: <20030726222556.GA13502@pedos.es> CHANGES Better documentation. New Parse_error exception raised when the opened file is not a unix mailbox. Now reading past the end of the archive keeps returning None instead of raising exceptions. DESCRIPTION The module provides two classes: Mailbox, a file-like object which allows you to iterate through the contents of a mailbox, and Email, an object which holds the individual emails returned by Mailbox. Mailbox inherits from Mailbox_base, but usually you don't need to even know about this class. Mailbox_base implements the file like mailbox reading part of the class, and the Email object creation. Use the Mailbox class in your code, which will always maintain the same API for backwards compatibility. This module has been written with simplicity in mind, and low memory consumption. Unless you do something bad, I estimate maximum memory consumption as twice the memory required by the largest email of the opened mailbox. But I'm guessing, maybe it is lower, like one time your biggest email. DOWNLOAD http://gradha.sdf-eu.org/program/mailbox_reader.en.html http://www.vex.net/parnassus/ http://freshmeat.net/ LICENSE GPL -- Please don't send me private copies of your public answers. Thanks. From jdhunter at ace.bsd.uchicago.edu Tue Jul 1 09:45:41 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 01 Jul 2003 08:45:41 -0500 Subject: Partition names with Python In-Reply-To: <20030701082545.GA18721@frobozz> (Andrew Bennetts's message of "Tue, 1 Jul 2003 18:25:46 +1000") References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> <20030701082545.GA18721@frobozz> Message-ID: >>>>> "Andrew" == Andrew Bennetts writes: Andrew> Or simply reading /etc/mtab or perhaps /proc/mounts (this Andrew> one is linux-specific, I think), rather than spawning a Andrew> process. Good advice! This seems to do it: import os for line in file('/etc/mtab'): if line.find('/dev/') !=0: continue columns = line.split() print columns[0].split('/')[-1] JDH From peter at engcorp.com Wed Jul 9 14:59:07 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 14:59:07 -0400 Subject: SNMP support for Python under Windows References: <538fc8e.0307091027.1825b454@posting.google.com> Message-ID: <3F0C65FB.1B86A0C2@engcorp.com> WIWA wrote: > > I'm looking for SNMP support in Python. I have found pySNMP, but I'm > not sure whether this works under Windows as well. Yes, it does. > A few questions: > > 1) Where do I need to install the pySNMP files? Doesn't it install with distutils? If so "python setup.py --install" or whatever it says in the README would work. Sorry, I haven't installed it lately. If it doesn't have instructions, put the files under the c:/python/lib/site-packages directory. > 2) What do I have to do in order to be able to write somethin like: > "from pysnmp import session" Install, then type "from pysnmp import session".... ;-) > Thakns in advance for all input (If you're having troubles, please note versions and platform next time, for Python, PySNMP, and Windows.) -Peter From ben at dadsetan.com Sun Jul 6 18:06:24 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Mon, 07 Jul 2003 00:06:24 +0200 Subject: Using Loops to track user input In-Reply-To: References: Message-ID: <3F089D60.4030203@dadsetan.com> hokiegal99 wrote: > I don't understand how to use a loop to keep track of user input. Could > someone show me how to do what the program below does with a loop? > > Thnaks! > > ---------------------------- > #Write a program that reads 10 numbers from the user and prints out the > sum of those numbers. > > num0 = input("Enter a number: ") > num1 = input("Enter a number: ") > num2 = input("Enter a number: ") > num3 = input("Enter a number: ") > num4 = input("Enter a number: ") > num5 = input("Enter a number: ") > num6 = input("Enter a number: ") > num7 = input("Enter a number: ") > num8 = input("Enter a number: ") > num9 = input("Enter a number: ") > > num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9 > > print num > ---------------------------------- > # If you are want to loop a fixed amount of time, as I understand a way # would be: sum = 0 for i in xrange(10): sum += input("Enter a number: ") average = sum/10 print average # I guess however it would be more pythonic, because you do not really # need that counter, to do something like: entries=0 sum=0 while entries < 10: try: sum += input("%d) Enter a number: " % (entries + 1) ) entries += 1 except: print "You need to enter 10 values." print "The average is %d" % (sum) # And when you need you would want to make a "general" tool out of your # case... entries=0 sum=0 try: while 1: sum += input("%d) Enter a number: " % (entries + 1) ) entries += 1 except: if entries == 0: print "You did not enter any number. Can not make average of nothing." else: print "The average of all %d numbers entered is %d" % (entries, sum/entries) From donn at u.washington.edu Wed Jul 16 13:28:43 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jul 2003 10:28:43 -0700 Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> Message-ID: In article <20030716081156943-0600 at news.xmission.com>, Adam Ruth wrote: > In <1058328099.572993 at yasure> Donn Cave wrote: > > Quoth Adam Ruth : > > .... > >| In Python, there is no situation where "you really can't avoid > >| pointers". > > > > That's trivially true, no such situation can exist because that > > Python can't be coded. I'll repeat an example that I proposed > > a couple days ago, though: user implemented sequences could be > > implemented with a single simple indexing function, returning > > a pointer/target/whatever; Python could assign directly to that, > > making "seq[i] = x" the same kind of operation as and automatically > > symmetrical with "x = seq[i]". > > > > It can't be done without pointers, as far as I can see. You may not > > care if it can be done, but I think you'd agree that "there is no > > situation that I care about where you really can't avoid pointers" > > would be kind of a lame version of your assertion. > > > > Donn Cave, donn at drizzle.com > > > > I did a quick google search and couldn't find the thread you're > referring to. Could you summarize it for me? It sounds interesting. I > do so love the taste of my foot in my mouth. http://groups.google.com/groups?selm=1058154004.286325%40yasure&output=gp lain There isn't much more to it. Today's assignment: replace the __getitem__/__setitem__ with a single function, __item__, that the system can use to either retrieve or deposit a value. The __item__ function must not be required to actually retrieve or deposit the value itself. I'm not saying it's worth it. I do think it would be a good thing if "seq[i] = x" were symmetrical with "x = seq[i]", and a single indexing function would be a better sequence API, but the overall effect of a pointer type on the language would be unfortunate. Python is already far too complicated. Really I think that's the main point. There are some useful and relevant features that Python doesn't have and will never have, and that's OK. The real limitation of any programming language tends to be its external interfaces - if you really can't write a decent web browser in FORTRAN-IV, that's probably the real reason, not any fundamental limitation of the language. That doesn't mean FORTRAN-IV is a good language, it means that its badness can't be expressed in terms of fundamental limitations, so this question of whether you "really need" something tends to make a poor basis for discussion. Donn Cave, donn at u.washington.edu From skchim0 at engr.uky.edu Thu Jul 10 01:47:05 2003 From: skchim0 at engr.uky.edu (satish k.chimakurthi) Date: Thu, 10 Jul 2003 01:47:05 -0400 Subject: LOADING DATA INTO ARRAYS Message-ID: <200307100147.05841.skchim0@engr.uky.edu> Hi, I am trying to collect the following data in X,Y,Z arrays as following: 1.00000000000000 0.00000000000000D+000 0.00000000000000D+000 0.932113519778473 0.362166241174114 0.00000000000000D+000 0.737671227507627 0.675160099611485 0.00000000000000D+000 0.443073128844408 0.896485472551578 0.00000000000000D+000 8.83176797852179D-002 0.996092358889152 0.00000000000000D+000 -0.145819420809848 0.989311223283493 0.00000000000000D+000 -0.391263558087552 0.920278668726310 0.00000000000000D+000 -0.625821331717327 0.779966448488364 0.00000000000000D+000 -0.822296905793933 0.569058695322129 0.00000000000000D+000 -0.953713306870443 0.300717356163965 0.00000000000000D+000 After loading them into X,Y,Z arrays, I should be in a position to access the first line as X[0],Y[0], Z[0] and second line stuff as X[1],Y[1],Z[1]. I have written the following code which is not working for some reason. Can anyone suggest any changes: ifile1 = open('fluidcylinder', 'r') #fluidcylinder contains the above data for line in ifile1: xval,yval=string.split(line) x.append(xval) y.append(yval) The error I am getting after the compilation is as follows: xval,yval=string.split(line) ValueError: unpack list of wrong size I would really appreciate if someone can help me with this. Thanks in advance, SATISH From adalke at mindspring.com Sun Jul 27 19:10:33 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 27 Jul 2003 17:10:33 -0600 Subject: looking for design pattern name Message-ID: I'm looking for the name used for a pattern like what Qt uses for it's container hierarchy. I'm doing this design for molecules, so I'll use that as my example. There's a container, in this case, a Molecule. A Molecule has Atoms and Bonds. When an Atom, it is passed the parent container as part of the constructor, as in mol = Molecule() O1 = Atom(mol, 8) # note the parent in the constructor O2 = Atom(mol, 8) Bond(O1, O2, 2) # (the parent is implicit - comes from the atoms) I want to compare this to a design like mol = Molecule() O1 = mol.add_atom(8) O2 = mol.add_atom(8) mol.add_bond(O1, O2) which does not allow a user-derived Atom and Bond class and one like mol = Molecule() O1 = Atom(8) mol.add_atom(O1) O2 = Atom(8) mol.add_atom(O2) b = Bond(2) mol.add_bond(b) which allows user-defined types but which has a more complicated ownership pattern (eg, you can have atoms and bonds which aren't contents of a Molecule). Anyone have good names for any of these three styles? Thanks! Andrew dalke at dalkescientific.com From max at alcyone.com Thu Jul 31 13:23:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 31 Jul 2003 10:23:21 -0700 Subject: .setdefault() References: Message-ID: <3F295089.4C9EECFA@alcyone.com> Tino Lange wrote: > I just realized that .setdefault *always* executes the second > argument - even if it's not necessary, because the requested item in > the first argument exists. > > This is not what I expected - why evaluate the second argument if it's > not needed? Also this can lead to side-effects! Because Python doesn't have macros or special forms that look like functions. If you see something that looks like a function, it evaluates all arguments before it calls the function. Always. Changing this would cause confusion, not resolve it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ There's a reason why we / Keep chasing morning \__/ Sandra St. Victor From tzot at sil-tec.gr Mon Jul 21 22:03:12 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 05:03:12 +0300 Subject: Python textbook exercises for C/C++ programmers Message-ID: Tests to let you know if you grok "the Python way". Definition: TOPKA = The Object Presently Known As [A] Variables/values vs names/objects. Write a function in C/C++ and one in Python that: 1. accepts an integer as an argument named i (enforced in C/C++, assumed in Python) 2a. [C/C++] prints the address of the i variable using printf, "%p" and the & operator 2b. [Python] prints the id of TOPKA i using print and the id() builtin 3. adds 1 to i using the += operator 4a. same as 2a 4b. same as 2b Explain why the C/C++ function *always* outputs two identical values, then why the Python function *always* outputs two different values. [B] Assignment and mutable/immutable confusion. Fill out the ellipses in the following Python program: a = ... # any valid expression you like b = a # -------------------- # if TOPKA a and/or b is mutable, you are free # to mutate it here by calling some of its methods # then ascertain that they still are the same object # -------------------- b = ... # any valid expression you like print "a = <%s>" % a print "b = <%s>" % b Explain why there is no friggin' way to change TOPKA a by assigning anything to the name b (hint: you might print two identical strings, but you can't change TOPKA a.) [C] "By reference if mutable, by value if immutable" confusion. Given the following two Python functions: def foo(arg): dummy = arg bar(arg) assert dummy is arg def bar(arg): try: arg = "anything but " + repr(arg) except: arg = "nice try" Choose an appropriate mutable or immutable argument so that foo fails at the assert statement (hint: rewrite python from scratch). A particular disclaimer by Knuth comes to mind that seems appropriate here... anyway, I only wrote this so that, next time someone complains about how python does things, I can point them to the post; should their answers satisfy me, I might consider helping them write a PEP to change things the way they want them to be. Cheers everyone. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From alanmk at hotmail.com Thu Jul 10 09:44:33 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 10 Jul 2003 14:44:33 +0100 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> <3F0D4728.45284530@hotmail.com> <3f0d5cfd$0$13154$edfadb0f@dread15.news.tele.dk> Message-ID: <3F0D6DC1.A7104D1C@hotmail.com> Kim Petersen wrote: > It *is* a service - i agree completely and even if i don't use the > support i'll prolly patch the problem and send the result upstream - > that really isn't an argument to use in the below. The reason for > that statement was simply that in opensource situations, we'll > _maybe_ locate the bug ourselves (or patch the product to do what > we want - which *cannot* be done in closed-source) and i'm not > talking beer! I agree that it's a good thing that you can find and patch bugs yourself, because it's open source. But I do feel compelled to point out that if the patch is to be accepted back into the product, that requires time from the maintainer, to review your patch, and test it in all scenarios and on all platforms. I'm sure you appreciate this, but I think a lot of people don't. > Regarding the free marked - i agree - against the other - what is it > *exactly* that makes mxODBC a better quality product - noone has > seemed to be able to tell (and yes - you do in the above claim that...). Hmm, I'm not sure I get what you're trying to say here: what do you mean by "noone has seemed to be able to tell"? If by that you mean "what is it that makes mxODBC a better quality product", try the following 1. Continually kept up to date with all versions of python 2. Continually kept up to date with all versions of ODBC standards 3. Continually maintained on a wide variety of platforms 4. Optimal memory and time efficiency because it's mostly coded in C 5. Etc, etc. If these aren't the kinds of things that make software "better quality", then I have no idea what you mean. > So i > can't even tell my customers that [even if i believed that your > argument of telling customers about developing methods have any > substance for them *at all* (its the product that counts - not > the methods)]. No, it's the method that counts when you're talking about the cost of development. You complained about how expensive a developer license for mxODBC was, which is your methods, not your products. Let's try a simple little thought experiment. Say you hire a freelancer, and you pay them ?1000/week to work on your product. You hire them for 6 months, or 26 weeks, so that's ?26,000 that pay your freelancer. Now say you get a nasty little bug, that requires detailed investigation. You're fortunate enough to have a quality freelancer that is able to find the bug, after 3-4 days of investigation, fix the bug in 2 days, and then test the fix for another 2 days. So that's 7-8 days, @?200/day. And that's just one bug. Seems to me that the cost of your software "developer" licenses are actually quite cost effective after all. > essence of my argument - the pricing of this *little* (but > essential) component drives the pricing of the end-product up > a substantial amount - that imho is not corresponding to the > usefulnes of the product.[and to use your argument from before - > i need to find another product then]. No, you're thinking about it all wrong. This little component, an ODBC driver, *does* correspond to the "usefulness" (i.e. quality) of the product. Or more correctly, if one is using a poor quality ODBC driver, then that contributes to the "uselessness" of one's product. > Can you mention even on spot where i complained against paying for > software ? (hint: the amount - not that it has a price). Kim Petersen wrote: > I'm not arguing that thats not important - *but* paying 70$ pr. > customer, is the equivalent of paying you for 1hr of support for > each customer [not installation mind you], where our own > licence/supportcost is already getting lower and lower... I find > that _extremely_ steep Fair enough, it was the amount you complained about, not that there was a cost. But is $70 really such a high cost? What percentage of the end-user cost of your product is required to pay for mxODBC? > TANSTAAFL! I think we definitely agree on that. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jdhunter at ace.bsd.uchicago.edu Wed Jul 9 11:28:54 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jul 2003 10:28:54 -0500 Subject: OT: Genetic Algorithm Recipe Bug Fix In-Reply-To: (anton@vredegoor.doge.nl's message of "Wed, 09 Jul 2003 16:12:41 +0200") References: Message-ID: >>>>> "Anton" == Anton Vredegoor writes: Anton> In the process of finding a heuristic solution to the Anton> problem I came to understand your module a bit better and Anton> I've also tinkered a bit with it (minor changes) and I have Anton> produced a heuristic solution for the submatrix Anton> problem. (it counts 59928 zero's, for insiders :-) Interesting -- my random version of Jon's algorithm with modified row/col choice criteria found 59928 zeros too. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=images&threadm=mailman.1057641194.24737.python-list%40python.org&rnum=2&prev=/groups%3Fsafe%3Dimages%26ie%3DUTF-8%26oe%3DUTF-8%26as_uauthors%3Djdhunter%2540ace.bsd.uchicago.edu%26lr%3D%26hl%3Den Anton> If someone is interested it's here: Anton> http://home.hccnet.nl/a.vredegoor/twomax Hmm, now if I can only figure out what it all means :-) JDH From P at draigBrady.com Wed Jul 2 09:37:17 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Wed, 02 Jul 2003 14:37:17 +0100 Subject: splitting a string into 2 new strings In-Reply-To: References: Message-ID: <3F02E00D.4030303@draigBrady.com> Mark Light wrote: > Hi, > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 > strings > 'C H O' and '6 12 6'. I have played with string.split() and the re module - > but can't quite get there. > > Any help would be greatly appreciated. import re molecule_re = re.compile("(.+?)([0-9]+)") def processMolecule(molecule): elements=[] numbers=[] for item in molecule.split(): element, number = molecule_re.findall(item)[0] elements.append(element) numbers.append(number) elements = ' '.join(elements) numbers = ' '.join(numbers) return (elements, numbers) print processMolecule('C6 H12 O6') From andreas.kuntzagk at mdc-berlin.de Wed Jul 2 12:11:15 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 02 Jul 2003 18:11:15 +0200 Subject: os.fork() different in cgi-script? References: Message-ID: >> I googled for this but only found a similar question from 1997 and no >> answer. > > Which is strange since this common problem and has nothing to do with > Python. Not so strange, because assuming a Python feature I also included "python" in the googlequest(tm). Andreas From list.adam at twardoch.com Tue Jul 15 04:09:06 2003 From: list.adam at twardoch.com (Adam Twardoch) Date: Tue, 15 Jul 2003 10:09:06 +0200 Subject: PDF Parser? References: <33803989.0307062318.3695d11@posting.google.com> Message-ID: "John Hunter" > A little more info would be helpful: do you need access to all the pdf > structures or just the text? AFAIK, there is no full pdf parser in > python. If you need to access the graphical elements, you may use pstoedit to convert the PDF into SVG (Structured Vector Graphics). Since SVG is XML, you can then use any Python-based XML toolkit to parse the data. http://www.pstoedit.net/pstoedit Adam From martin at v.loewis.de Wed Jul 30 17:04:56 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 30 Jul 2003 23:04:56 +0200 Subject: How to get Windows physical RAM using python? In-Reply-To: References: Message-ID: Mark wrote: > OK, How to check the amount of Windows physical RAM using python? You should call the GlobalMemoryStatus(Ex) function. To my knowledge, there is no Python wrapper for it, yet, so you would need to write one. Regards, Martin From tim.one at comcast.net Fri Jul 4 00:17:40 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 4 Jul 2003 00:17:40 -0400 Subject: A possible bug in python threading/time module? In-Reply-To: Message-ID: [Tim] > ... > I expect there may be a bug *somewhere* in Python because a few > thousand threads is really far fewer than I expect to create trouble > on Windows. The evidence I saw suggested the program actually > finished all its "useful" work, and got hung in threading.py's > _MainThread.__exitfunc(), waiting to join one of the worker threads > at Python shutdown time. Turns out that the Windows implementation of the Python C API function PyThread_start_new_thread() contained several "laziness" errors, most damningly: 1. Not arranging to raise a proper exception if the MS _beginthread() function fails (which it can do if many threads are created quickly, as the test program does). 2. Not even considering that the Win32 CreateSemaphore() can fail. 3. Not accounting for that, if a great many threads are created very quickly, it may in fact take more than 5 seconds for any particular bootstrap function to finish. I'm testing putative fixes on a Win98 box and don't see any hangs any more. However, with more than about 3000 threads, thread.error: can't start new thread gets raised because MS's _beginthread() fails (with errno == EAGAIN == "there are too many threads"). From peter at engcorp.com Tue Jul 8 09:27:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 09:27:20 -0400 Subject: Socket Win32 IO References: <99071af2.0307070647.6ab3e329@posting.google.com> <3F099791.6AA68B8F@engcorp.com> <99071af2.0307080439.2bacd2d4@posting.google.com> Message-ID: <3F0AC6B8.A94C0435@engcorp.com> jose maria wrote: > > Hello Peter tanks for you attenion and time > > Yes really I forget put in the message one parameter in the function > I put the traceback and all code I hope that this help you. Thousands > of pardons for my bad English > > Traceback: > > ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on > Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on wi > Type "help", "copyright", "credits" or "license" for more informatio > >>> from socket import * > >>> import win32api > >>> import win32file > >>> Ip=getprotobyname("ip") > >>> SIO_RCVALL=0x98000001 > >>> ip=('xxx.xxx.xxx.xxx',0) > >>> Sock=socket(AF_INET,SOCK_RAW,Ip) #Raw Socket > >>> Sock.bind(ip) # Bind Socket to ip > >>> fh=Sock.fileno() # Get file handle > >>> test=win32file.DeviceIoControl(fh,SIO_RCVALL,"", 0,None) # The > function > Traceback (most recent call last): > File "", line 1, in ? > pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.') I still get a different result (the second of the two that I posted before) even if I add that "None" argument, not what you show above. Are you certain you are cutting and pasting *exactly* what you typed? I note you have 'xxx.xxx.xxx.xxx' above, so presumably you have edited the transcript manually in at least one way... any others? I'm not likely to be able to solve the problem, since I have no idea what DeviceIoControl is for, nor what you're trying to accomplish. I just thought I'd report that I do not get the results you are getting when I try what you show you are trying. -Peter From aahz at pythoncraft.com Mon Jul 14 16:22:11 2003 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2003 16:22:11 -0400 Subject: www.python.org hacked? References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> Message-ID: In article <3F12FA18.B04B400E at engcorp.com>, Peter Hansen wrote: > >Have we been hacked, or is this human error during maintenance? Yes to both. :-( We were actually hacked a while ago, then failed to do a complete cleanup. When we got the disk full problem, I attempted to update the main page so people would know what was going on; I thought that vi was capable of managing the re-write inplace. I was wrong. We're back on the air, with special thanks to Thomas Wouters for interrupting his post-OSCON snooze. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From rastm2 at aol.commorespam Mon Jul 28 03:17:20 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 28 Jul 2003 07:17:20 GMT Subject: Help with Boa on Win98 with unicode installed References: Message-ID: <20030728031720.02490.00000585@mb-m21.aol.com> >rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) schreef: > >> Has anyone ever struggeled with that install of Boa in Win98. >> I've followed the Docs. Tryed the "-E" switch while in DosPrompt. Made >> sure the wxPython version matched Python version... >> >> What am I missing folks? > >Don't use the unicode version of wxPython on Win9x, if that's possible? > >Unicode wxPython gives problems on my Win98SE system too, but Boa starts up >fine when I run it with ANSI wxPython (didn't try to actually use it yet). > >-- >JanC > And it's JanC to the rescue. THANKYOU! It's just like you said it would be! Boa nirvana. Ray--Rastm2@@OL.completelyunsatisFactory From roy at panix.com Mon Jul 14 16:28:22 2003 From: roy at panix.com (Roy Smith) Date: 14 Jul 2003 16:28:22 -0400 Subject: % operator -- did Python or C++/boost come first? Message-ID: Up until recently, Python was the only language I'd ever seen that used the % operator for string replacement. Today, I was perusing the C++ Boost libraries, and discoverd that boost::format uses a very similar syntax. The following lines print the same thing in Python and C++, respectively. print "int->%i, string->%s" % (42, "wugga, wugga") cout << boost::format ("int->%i, string->%s\n") % 42 % "wugga, wugga"; The question is, which came first? Did boost adapt the Python syntax, or the other way around, or did they both evolve in parallel? I'm not talking about the use of % in the C/printf style format specifier, but the use of % as an operator to connect the format specifier with the data to be formatted. From staschuk at telusplanet.net Wed Jul 16 22:13:20 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 20:13:20 -0600 Subject: hex to signed integer In-Reply-To: ; from tomg@em.ca on Thu, Jul 17, 2003 at 12:04:36AM -0000 References: Message-ID: <20030716201320.C656@tibia.amotlpaa.bogus> Quoth Tom Goulet: > My question basically is: What is the opposite of the following? > | "%08X" % -1 Here's one way, very like what you already have: def hex2signed(s): return struct.unpack('!i', binascii.unhexlify(s))[0] (This will not be the inverse of '%08x' % n in Python 2.4, when '%x' % -1 will produce '-1', but I think it does what you want.) Another approach: def hex2signed(s): value = long(s, 16) if value > sys.maxint: value = value - 2L*sys.maxint - 2 assert -sys.maxint-1 <= value <= sys.maxint return int(value) -- Steven Taschuk staschuk at telusplanet.net "Please don't damage the horticulturalist." -- _Little Shop of Horrors_ (1960) From mwh at python.net Tue Jul 29 07:53:54 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jul 2003 11:53:54 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> <7x65lmzf20.fsf@ruckus.brouhaha.com> Message-ID: <7h3k7a1k0qv.fsf@pc150.maths.bris.ac.uk> Paul Rubin writes: > I see now that that the problem is subtle enough that IMO, a fully > worked out solution should be written and included in the Python > library or at least the Python cookbook. I also think that this is a problem without One True Answer wrt. endpoint handling which makes a library solution a bit of a challenge. Maybe I'm wrong, though (haven't done numeric stuff for a while now). Cheers, mwh -- 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 o_otaotao at hotmail.com Sun Jul 27 22:14:06 2003 From: o_otaotao at hotmail.com (PythonMan) Date: Mon, 28 Jul 2003 10:14:06 +0800 Subject: Can't compile, miss library/modules ............... ? Message-ID: warning: py2exe: * The following modules were not found: warning: py2exe: * SOCKS warning: py2exe: * rourl2path warning: py2exe: * ic when i compile btdownloadheadless.py of BitTorrent , justmsg is shown , the souce code should have no error , but why i get such error ? how get back this modules ? thx~~~ -- From bokr at oz.net Mon Jul 21 22:06:25 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2003 02:06:25 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: <7h3znjbzscu.fsf@pc150.maths.bris.ac.uk> <7h3n0f8yspt.fsf@pc150.maths.bris.ac.uk> Message-ID: On Mon, 21 Jul 2003 18:33:27 -0400, "Mike C. Fletcher" wrote: [...] >Michael Hudson wrote: [ ... evil code ... ;-) ] > >But really, I don't think either of us will deploy that particular >pattern in a production system. Still, fun proposal, thanks for >playing, we have lots of marvelous parting gifts for you :) . > >BTW: You know this, but in case others are wondering why it's not usable >in real life: it's possible to have threads get/set the value without >triggering the descriptor if they happen to ask for it during the period >when the descriptor is deleted. > Did you have a chance to look at my post (posted ~12+ hours before Michael's, if you are looking by date/time ;-) (It is threaded as a reply to Aahz in this thread -- I probably should have split out the section for you ;-/). It factors property-making and installing in customized classes in a couple ways. It uses metaclasses, but I'm not sure any of it qualifies as evil ;-) I guess I should just wait quietly, but I am curious to get your reaction ;-) Regards, Bengt Richter From martin at v.loewis.de Sun Jul 13 09:49:53 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 13 Jul 2003 15:49:53 +0200 Subject: installing python library modules (general question) References: <79ad5955.0307122013.6780fc53@posting.google.com> Message-ID: juliagoolia301 at hotmail.com (Julia Goolia) writes: > ImportError: libmad.so.0: cannot open shared object file: No such file > or directory > > I know the file /usr/local/lib/libmad.so.0 exists, but python can't > seem to find it. I tried adding this path to LD_LIBRARY_PATH, but > that didn't help. Can you please be precise on what "this path" is? Adding "/usr/local/lib/libmad.so.0" would be wrong, whereas adding "/usr/local/lib" should work. > I guess that I just really dont' know enought about libraries and > linux (redhat 9). I don't really know where they are supposed to go > after being compiled, and how python "loads" and uses them. You might also edit /etc/ld.so.conf to add /usr/local/lib, and run ldconfig afterwards; this would remove the need to set LD_LIBRARY_PATH HTH, Martin From rnd at onego.ru Sun Jul 6 03:01:32 2003 From: rnd at onego.ru (Roman Suzi) Date: Sun, 6 Jul 2003 11:01:32 +0400 (MSD) Subject: Bewildered graphs In-Reply-To: <1057446809.1204.20.camel@emilio> Message-ID: Here is ploticus.i file I made 30 minutes ago: (READ DISCLAIMER AT THE END) ------------------------------------------------------------------ /* ploticus.i */ %module ploticus %{ /* Put header files here (optional) */ %} %name(init) extern ploticus_init( char *device, char *outfilename ); %name(arg) extern ploticus_arg( char *name, char *value ); %name(begin) extern ploticus_begin(); %name(execline) extern ploticus_execline( char *line ); %name(execscript) extern ploticus_execscript( char *scriptfile, int prefab ); %name(end) extern ploticus_end(); %name(setvar) extern ploticus_setvar( char *name, char *value ); %name(getvar) extern ploticus_getvar( char *name, char *value ); ----------------------------------------------------------------------- If you have SWIG, just do this: 0. install SWIG 1. get Ploticus source (plsrc211.tgz in my case) untarred 2. cd plsrc211/src 3. make -f Makefile_api 4. put my ploticus.i into current dir (plsrc211/src) 5. run: swig -python ploticus.i gcc -c ploticus_wrap.c -I /usr/local/include/python2.3 ld -shared ploticus_wrap.o -l gd libploticus.a -o ploticus.so (/usr/local/include/python2.3 - in my case, your Python could be somewhere else) 6. check: python >>> import ploticus >>> dir(ploticus) ['__doc__', '__file__', '__name__', 'arg', 'begin', 'end', 'execline', 'execscript', 'getvar', 'init', 'setvar'] >>> # do whatever with it DISCLAIMER: I never used neither SWIG nor Ploticus before. So it is hard to tell if ploticus Python wrapper works ;-) Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From pinard at iro.umontreal.ca Wed Jul 23 21:44:12 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 23 Jul 2003 21:44:12 -0400 Subject: Reading Keyboard Scan Codes In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4706@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4706@admin56.narex.com> Message-ID: [Fran?ois Pinard] > [...] I do not know if reading scan codes or key codes is easily done > within X, nor on MS-Windows. I would like finding or discovering recipes > in this area. So, please share your tricks in this area, if any! :-) [Bjorn Pettersen] > I'm assuming you can use the msvcrt module: > >>> def getch(): > ... import msvcrt > ... while not msvcrt.kbhit(): pass > ... return msvcrt.getch() > ... > >>> getch() > 'a' > >>> This does not give scan codes (or key codes of some sort). I would like being able to detect, for example, if Ctrl is being held while Keypad-5 is entered, or any other such (possibly unusual) combination of keys. -- Fran??ois Pinard http://www.iro.umontreal.ca/~pinard From ben at dadsetan.com Thu Jul 3 21:21:26 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Fri, 04 Jul 2003 02:21:26 +0100 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3f04727e@news.swissonline.ch> Message-ID: <3F04D696.1060305@dadsetan.com> Russell Reagan wrote: > "F. GEIGER" wrote > > >>[OT] That's not a pro, that's a con on the C++ side. And actually that's > > the > >>reason why there's so much bad C++ software. A C programmer first has to >>forget C to be able to program in C++ - well, to be able to program OO in >>C++. > > > C++ is not an OO language. It is a multi-paradigm language that happens to > support OO features. No one is required to program OO in C++. It's even very > debatable if it's better to program OO in C++. We are getting very philosophical here and I guess we are getting a little off-topic, but what is an OO language? Isn't one that supports OO features? Ok, You can write C code and compile it with a C++ compiler, but does it disqualify C++ as being a OO language? The advantages you talk about writing C and using a C++ compiler are pretty weak. C++ is certainly not just about the "typedef" feature... It is a very powerfull language that can be used to express exactly what you want the computer to do, and in the same time kind of abstract details to a level where you can still see what your program was written for. Agreed, it is a terrificly complex language all together, but it has its use. If you actually respect the thousand rules from M. Meyer plus a few from M. Lakos, you can build very reliable and stable applications. If you are a genius or have some technique and experience, you can even have a somewhat bigger code where you still have an overview. The big disadvantage to its C compatibility is that lots of people beleive they have C++ experience and present themselves at C++ jobs. You just need an IT management which has no clue about OO technology/C++ (managers that understand anything at this level are in minority) and you soon have a C programmer who used a C++ compiler converted into a Java programmer. Little after you will see something really funny, C compiled by a Java programmer. Is Java therefore not a OO language? I mean Java will allow C programmers to build classes with only static methods, with classes of 6000 lines without constructor and all variables declared as public class members? I have seen this, and I am not exagerating at all in the description... it actually took me two days to understand why I did not understand how the programmer cut the program. Yes, I was naive enough to think one can only write OO in Java, like in the advert. Anyway, let us talk about something else, I hate being reminded how often our IT industry has been guarenteeing our jobs life-time by making every thing more complicated and more expensive instead of making things simpler and cheaper as we were entrusted to do. Note that I do not think we do that on purpose :-) That said, python does make life easier in many occasions, so there is maybe some hope that a little tiny community of our IT industry is not reaping off our dear sponsors (IT users including IT people). Thanks pyguys for your beautiful contribution, please continue just as you are now. You have been doing a wonderful job. If you could only replace VB for all the usages it has now, and convince the planet of that as well, I would be thankful for ever. :) Ben. From rnd at onego.ru Tue Jul 22 06:33:41 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 22 Jul 2003 14:33:41 +0400 (MSD) Subject: [OT] SCO is Going After End Users In-Reply-To: <23891c90.0307220139.1909fc63@posting.google.com> Message-ID: On 22 Jul 2003, Paul Boddie wrote: > clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) wrote in message news:<4868482a.0307211336.4ca9493a at posting.google.com>... > > > > I realize that this is OT, but SCO's action strikes at the heart of > > Open Source. Somebody with the right patents can try to tax or shut > > down the rest of us, regardless of the validity of their claims. If > > IBM, Red Hat, and the decide that the the cost of settling is less > > than the cost of litigation, we all loose. Fortunally, the claim > > against IBM is so big, $3B that they may fight it instead of settling. > But thanks for the reminder that we really are lucky to be able to use > technologies and tools like Python, that the climate in which they > have been developed has so far been favourable to such innovation, and > that we should strive to maintain such a favourable environment > through the appropriate forums and channels. I hope GvR never put any propriatary Fortran, Pascal or Basic source code into Python. Otherwise SCO-like firms will claim they own Python because of for-loop and some comments they found in Python source, representing their best IP to date. Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From JensRie at gmx.de Thu Jul 10 07:56:41 2003 From: JensRie at gmx.de (Jens Riedel) Date: Thu, 10 Jul 2003 13:56:41 +0200 Subject: Zope problem: objectValues('Folder') References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> <3F0D2405.1070606@gmx.de> <3F0D2EAC.2010605@mxm.dk> <3F0D4C74.5040304@gmx.de> <3F0D500A.8010108@mxm.dk> Message-ID: <3F0D5479.6090401@gmx.de> Max M schrieb: >>I used the objectValues('Folder')-method in a DTML-method named >>'navigation'. I include in a >>'standard_html_header' DTML method, and this standard_html_header is >>used in the index_html document. > Does it work if you render only the navigation method? Yes, that's what confuses me. The navigation works completely if I call it with http://localhost:8080/ZopeZoo/navigation, also the standard_html_header does. But when I include it in the index_html, the list of folders vanishes, the rest of navigation works. > Also, you will find it much easier to find replies to Zope questions on > the zope mailing list. thanx for the hint, I'll try it. regards, Jens From alanmk at hotmail.com Thu Jul 31 06:07:46 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 31 Jul 2003 11:07:46 +0100 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> Message-ID: <3F28EA71.6A863E7@hotmail.com> [Carl Banks] > Am I the only person to say "kudoi to everyone"? I've never heard anyone say "kudoi". But I suppose it's all about whether you consider "kudos" to be singular or plural. If it's singular, then "kudoi" is the only correct (Greek) plural of the (Greek) singular "kudos". So all of those Americans who seem intent on turning "kudos" into the plural of "kudo" (which does not exist, yet) should heed your advice :-) http://dictionary.reference.com/search?q=kudos But, of course, the main point of the whole thread is to confer kudos, i.e. "acclaim or praise for exceptional achievement", on the Python Development Team. Thanks People! regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From max at alcyone.com Tue Jul 1 00:00:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 30 Jun 2003 21:00:07 -0700 Subject: Identity inconsistency and unification of types and classes References: <6f03c4a5.0306301943.d822a6d@posting.google.com> Message-ID: <3F010747.EB2DC633@alcyone.com> Rim wrote: > With the great unification of types and classes, what will happen to > the > following identity inconsistency? > > >>> class myint(int): pass > ... > >>> a=int(1); b=int(1) > >>> a is b > 1 > >>> a=myint(1); b=myint(1) > >>> a is b > 0 Whether or not int(1) is int(1) is purely an optimization issue, so one wonders why one would be concerned about it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ They have rights who dare defend them. \__/ Roger Baldwin From ianb at colorstudy.com Mon Jul 21 13:40:56 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 21 Jul 2003 12:40:56 -0500 Subject: Google URLs (was: Re: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21)) In-Reply-To: References: Message-ID: <1058809255.28066.3576.camel@lothlorien> Here are the corrected Google URLs: On Mon, 2003-07-21 at 04:58, Irmen de Jong wrote: > Raymond Hettinger intrigues with the second episode of a series of > mysterious Python puzzles. http://groups.google.com/groups?threadm=VorQa.15236$Kw1.587 at nwrdny02.gnilink.net > Tom Plunket starts a huge thread about the way Python treats > objects, names, variables, assignment, references and what not. > Various people have different opinions about what would be the best > way to do things, but in the end, the QOTW of Tim Roberts (above) > kind of says it all. http://groups.google.com/groups?threadm=13t0hvsb7idh0g6ac3upe5k0qd6flc17ah at 4ax.com > Michele Simionato likes to have an endswith method that accepts a > list of strings, instead of a single string argument. But things are > not that easy. http://groups.google.com/groups?threadm=2259b0e2.0307200604.44d343f4 at posting.google.com > Alan Kennedy shows what you might do if you need to build a list of > database rows (from a query), without allocating the list beforehand > because you don't know the size. He uses an iterator to do the trick. > http://groups.google.com/groups?threadm=3F16B745.9CF3EF54 at hotmail.com > Andrew Kuchling has started a mailing list for discussion about > Python Web frameworks. > > This is partly because perhaps Python needs a single 'standard' way > to create web applications, as Andy Robinson points out. http://groups.google.com/groups?threadm=d5mm9v8em9j41kus2tvj2raipd7dagv18k%404ax.com From alanmk at hotmail.com Wed Jul 16 09:25:31 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 16 Jul 2003 14:25:31 +0100 Subject: XML <=> Database References: Message-ID: <3F15524B.C4904536@hotmail.com> vivek at cs.unipune.ernet.in wrote: > Is there any module available which does the same work as the XML > Integrator in Java. I don't know about XML Integrator. However, I do know that there are a million and one ways to address the problem of mapping XML (i.e. hierarchical object) structures to RDBMS (i.e. table) structures. There's a chap called Ron Bourret who has been working hard in this area since the early days of XML. He also wrote and maintains an open source Java product called "XML-DBMS" which allows one to explicitly specify a mapping from XML to RDBMS and vice versa. You can find out more information here http://www.rpbourret.com/ Ron also maintains an *extremely* comprehensive page on the different ways to tackle the problem, and the list of products that employ the various approaches. You can read that page here http://www.rpbourret.com/xml/XMLDatabaseProds.htm Note that there are three products listed on that page using the name "Integrator", any one of which, or none of which, might be the "XML Integrator" you inquired about. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mis6 at pitt.edu Wed Jul 30 17:13:53 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 30 Jul 2003 14:13:53 -0700 Subject: Python debugger References: Message-ID: <2259b0e2.0307301313.28426c1b@posting.google.com> "Andrew Chalk" wrote in message news:... > I am sure that it has been asked before but could someone tell a newbie > whether there is a Python debugger out there? > > In case it is relevant, i am using v2.2 on Windows. > > Many thanks. idle has a debugger. M.S. From wayne at mishre.com Mon Jul 7 09:10:55 2003 From: wayne at mishre.com (Wayne Pierce) Date: 7 Jul 2003 06:10:55 -0700 Subject: NNTP mirror of c.l.p? Message-ID: <2a897f11.0307070510.37a4ad41@posting.google.com> Does anyone know if there is a public server where I can download c.l.p? I typically use GG, but want to test a program on my Palm-based system for accessing NNTP servers. Thanks, -Wayne From webmaster at beyond-thoughts.com Wed Jul 9 06:32:27 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Wed, 09 Jul 2003 12:32:27 +0200 Subject: Python Global Constant In-Reply-To: <3F0BE68B.893EB7E5@engcorp.com> References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: <3F0BEF3B.2020505@beyond-thoughts.com> >>*** module any *** >>import dirs; >>def CheckDir(Dir): >> if Dir=dirs.Const_Up: xxx > > > This code should work fine, although you might want to follow > the Python conventions ........ What about using __builtins__ wouldn't make this the constant really global? cbf From usenet_spam at janc.invalid Thu Jul 10 00:07:16 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 10 Jul 2003 04:07:16 GMT Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: Moshe Zadka schreef: > [I was *shocked* to discover, for example, I can't associate > all .html files in a directory with PHP. I am sure it is a great > visibility booster for PHP to have pages end with .php, but I didn't > care much for it.] I have no problems doing that with Apache? Just create a .htaccess (or whatever it is on your system) in that directory and put the following line in it: AddType application/x-httpd-php .html Also make sure httpd.conf allows you to define types in a .htaccess file. If you want, you can set the "local AddType" in httpd.conf too, I think. (Tested with Apache 1.3.27 + PHP 4.3.0 on my Win98 desktop) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bgailer at alum.rpi.edu Thu Jul 17 09:41:06 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 17 Jul 2003 07:41:06 -0600 Subject: list() coercion In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE8D3D5C@au3010avexu1.global .avaya.com> Message-ID: <5.2.1.1.0.20030717073907.01c3ee70@66.28.54.253> At 10:42 AM 7/17/2003 +1000, Delaney, Timothy C (Timothy) wrote: > > From: Ian Bicking [mailto:ianb at colorstudy.com] > > > > Is there a way I can keep this from happening? Maybe something list() > > tries first that I can make fail. (I notice list() catches any > > exceptions in __len__ and then will just skip that step) > >Simplest thing is probably: > >ll = MyListLikeObject() >li = iter(ll) >l = list(li) > >i.e. explicitly create an iterator (which doesn't have a __len__) and >create the list from that. > >OTOH, if the problem is that creating the iterator is causing the problem >(calling __len__), you may need to create a proxy object that doesn't have >a __len__ and call list() on that. I have just read the docs 2.2.5 Iterator Types. Unfortunately this page seems to be written for someone who already understands the page. Is there any other explanation or examples? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From jarausch at igpm.rwth-aachen.de Thu Jul 31 06:11:54 2003 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 31 Jul 2003 12:11:54 +0200 Subject: Exploring a ftp with python to find pdf In-Reply-To: References: Message-ID: <3F28EB6A.1070700@igpm.rwth-aachen.de> conatic wrote: > I want to make a script that connect to a ftp and get a list of all pdf > stored in the ftp with their path to use the list later. > > I have tried some script with recursion but can't do something good. > Could you help ? I don't know if there's something similar to wget or ncftp in Python. Have you looked at the ftplib module and at the script dist/src/Tools/scripts/ftpmirror.py in the Python Source distribution? -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From martin at v.loewis.de Fri Jul 25 18:17:07 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Jul 2003 00:17:07 +0200 Subject: LGPL and Java, and Python? References: Message-ID: Alexandre Fayolle writes: > Could anyone confirm or infirm this impression? To answer that question, one would need to know on what grounds the FSF lawyer has decided that section 6b) of the LGPL is inapplicable to Java. Regards, Martin From gh at ghaering.de Thu Jul 10 11:41:39 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 10 Jul 2003 17:41:39 +0200 Subject: delete file from python cgi In-Reply-To: <2c6431ab.0307100711.780a65ad@posting.google.com> References: <2c6431ab.0307100711.780a65ad@posting.google.com> Message-ID: <3F0D8933.8070401@ghaering.de> lamar_air wrote: > I have a python script and i want to delete a file on my computer > c:\....\...\.. .txt what's the script to do this? I know how to write > to files but i also need to know how to delete a file. os.unlink() or os.remove(). They're the same. -- Gerhard From shannon at news.widomaker.com Tue Jul 8 15:21:31 2003 From: shannon at news.widomaker.com (Charles Shannon Hendrix) Date: Tue, 8 Jul 2003 15:21:31 -0400 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: In article , Tim Shoppa wrote: > And it's not the same as Makefiles, either. Everybody has at one time > been bitten by how 8 spaces is not at all the same in a Makefile as > one tab; and it doesn't help that with many editing/viewing tools that it > is impossible to see the difference. Listing one bad thing to defend another? I hate that part of make too. However, its very easy to tab a makefile properly, because the logic is implicit in the rule sets. You just find each rule and indent its members properly. It's not ambiguous. You also get an error... in Python, you'll just have a different flow of logic, which may or may not show errors. As long as you are strict and careful, Python is OK, but I will likely never like invisible flow-control characters. In makefiles either... :) >> > Python uses it for actually determining the logic in your program, which >> > IMHO is dangerous. > > Again, it is certainly no use than Makefiles. Heh heh... I agree... >> Well, no matter WHAT the language, I find tabs are evil little things >> that introduce special cases and the need for code to handle them. > > Compare that to all the punctuation marks that *some* other languages require. > Remember the Dilbert where PHB complains that his programmers are using > way too many semicolons? :-) Don't get me started on code reviews by non-programmers. Somewhere I have one saved, that I still can't figure out. -- UNIX/Perl/C/Pizza____________________s h a n n o n at wido !SPAM maker.com -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 80,000 Newsgroups - 16 Different Servers! =----- From rtomes at ihug.co.nz Thu Jul 3 06:13:24 2003 From: rtomes at ihug.co.nz (Ray Tomes) Date: Thu, 03 Jul 2003 22:13:24 +1200 Subject: zip() or what? References: <3F03AFA8.7030905@ihug.co.nz> <3F03B4DB.545DC6B5@alcyone.com> Message-ID: <3F0401C4.1010306@ihug.co.nz> Erik Max Francis wrote: > Ray Tomes wrote: >>request to flip array ... > zip(*x) >>Alternatively, is there a construct to get x[*][i] if you know what I >>mean? > [i[1] for i in x] Thanks Erik, these do just what I want. I can understand the 2nd one, but I don't get the meaning of the * in the first. Is this like the opposite of putting [] around something or what? Under what circumstances can an * be used like this, and what is it called? - I don't know how to look for it in the docs :-) also, ... achrist at easystreet.com wrote: > Ray Tomes wrote: >>This I am trying to flip an array around so that the "subscripts" happen >>in the opposite order > [x[-i-1] for i in range(len(x))] Thanks Al, but that was not the flip I was looking for sorry - I hadn't realised it could be taken another way. I wanted to swap the subscripts with each other (a 45 degree reflection) not within one subscript end to end (a 90 degree reflection). Erik has done the one I wanted. From jdhunter at ace.bsd.uchicago.edu Wed Jul 9 13:56:09 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jul 2003 12:56:09 -0500 Subject: LOADING DATA INTO ARRAYS In-Reply-To: <200307100147.05841.skchim0@engr.uky.edu> ("satish k.chimakurthi"'s message of "Thu, 10 Jul 2003 01:47:05 -0400") References: <200307100147.05841.skchim0@engr.uky.edu> Message-ID: >>>>> "satish" == satish k chimakurthi writes: satish> I have written the following code which is not working for satish> some reason. Can anyone suggest any changes: [snip] satish> xval,yval=string.split(line) ValueError: unpack list of satish> wrong size The problem is with this line of code. xval,yval=string.split(line) As the error indicates you are unpacking the results of the split (which has 3 elements x,y,z) into 2 variables xval, yval. You need to do xval, yval, zval = line.split() But then xval, yval and zval are strings and I bet you want them to be floats. So this would be better xval, yval, zval = map(float, line.split()) Finally, if you are doing number crunching, you will be much happier with Numeric http://pfdubois.com/numpy/. If holding the whole list in memory is not a problem before initializing to array, you can do from Numeric import array a = array([float(val) for val in line.split() for line in file('myfile.dat')]) This uses list comprehensions rather than map to do the float conversions but it's the same idea. Now you can access the first row with a[0], or the first column with a[:,0], etc.... Numeric comes with lots of support for analysis, etc... In addition, many of the python plotting packages and other analysis packages are designed to work with Numeric. JDH From alanmk at hotmail.com Fri Jul 4 10:36:11 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 04 Jul 2003 15:36:11 +0100 Subject: CGI script is in plain text References: <3F04B0A4.32692.3596CD0@localhost> Message-ID: <3F0590DB.8EE8D7CF@hotmail.com> BMA TRADING wrote: >>> When I start CGI script from a web browser, the result is >>> plain text( the copy of that script) Ian Bicking wrote: >> Try renaming the file to .cgi -- as long as the #! line is right, it >> doesn't matter the extension. Also, you may have to put the script in >> the cgi-bin directory. BMA TRADING wrote: > Thank you for your reply. > I tried to rename it but it does NOT work. > In the same directory I can successfully run Perl script( .pl > extension) but no Python scripts. Any idea? Quick sanity check: You are sending a content-type from the script? e.g. you have code like this in your script? print "Content-Type: text/html; charset=iso-8859-1" print -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From gh at ghaering.de Wed Jul 2 11:14:54 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 02 Jul 2003 17:14:54 +0200 Subject: ASP In-Reply-To: References: Message-ID: Padam Jain wrote: > Q1.How do u generated GUID's in Asp Pages Enter "python guid" into Google. > Q2.How do u pass x-y coordinates to ASP Pages when u click on an > Image. Not a Python question, please use a HTML/JavaScript group. It's called an image map if you're looking for the right keywords for a search engine. > Q3.How do u call a VBScript function in an Anchor Tag. Not a Python question. I'd suggest you ask in a HTML or M$ VBScripg group. > Q4.How do u access Object Instance or a variable in another Frame. Again, not a Python question. > [...] -- Gerhard From jhaveri at usc.edu Tue Jul 1 18:36:11 2003 From: jhaveri at usc.edu (jinal jhaveri) Date: Tue, 01 Jul 2003 15:36:11 -0700 Subject: Circular Inheritance Message-ID: <234cc7238020.238020234cc7@usc.edu> Hi All, I have one question regarding circular inheritance I have 3 files 1) A.py , having module A and some other modules 2) B.py having module B and some other modules 3) C.py having module C and some other modules Now I want to import Module C in B.py but C requires A.py and A requires B.py so B requires C C requires A A requires B and when I try to do this using from ...import.... it tells me that you cannot import this. So any suggestions on this? thank you Jinal From hokiegal99 at hotmail.com Mon Jul 14 19:51:28 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Mon, 14 Jul 2003 19:51:28 -0400 Subject: Which Python Book Message-ID: <3F134200.8060708@hotmail.com> I have an option, I can buy either O'reilly's "Python in a Nutshell" or "Python Cookbook", but not both. Which book is better? I'm leaning toward "Python Cookbook" right now, as it seems more applied. A college professor once told me that Romans liked to build roads while Greeks liked to talk about *how* to build roads. I'm more of a Roman than a Greek. I've found that I learn better when I look at actual programs written to solve problems, instead of abstract, theorhetical code that could be used to solve problems. I guess it would be best if I could take the abstract, theorhectical code and apply it to real-world problems, but that's a bit of a leap for me... don't get me wrong, I can do it, but it takes me longer than it does if I've already seen the code applied in a practical fashion. Thanks for any suggestions! From bac at OCF.Berkeley.EDU Wed Jul 9 18:14:29 2003 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Wed, 09 Jul 2003 15:14:29 -0700 Subject: python-dev Summary for 2003-06-01 through 2003-06-30 Message-ID: <3F0C93C5.4030401@ocf.berkeley.edu> python-dev Summary for 2003-06-01 through 2003-06-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from June 1, 2003 through June 30, 2003. It is intended to inform the wider Python community of on-going developments on the list and to have an archived summary of each thread started on the list. To comment on anything mentioned here, just post to python-list at python.org or `comp.lang.python`_ with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the eighteenth/nineteenth summary written by Brett Cannon (has his own room with a door for the first time in his life). All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; its simple and is accepted for `PEP markup`_. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the original text file. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when wanting to look up any documentation on something mentioned here. Python PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . .. _python-dev: http://www.python.org/dev/ .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. contents:: .. _last summary: http://www.python.org/dev/summary/2003-05-16_2003-05-31.html ===================== Summary Announcements ===================== I lost Internet on the morning of June 18 and did not regain it until June 29. Since it was so close to the end of the month I decided to just combine the next summary into this month-long summary. During my Internet blackout that reminded me of the days back when I spent my days playing video games and watching television, my future life as a graduate student began to form. Since I am going to have the joy of taking three upper-division undergraduate courses this upcoming fall semester I don't think I am going to have the time to do the summaries when school starts, at least in the capacity I am doing them currently. At minimum I suspect I will have to cut back on the depth of them since I refuse to put the summaries before hacking on the core (hacking is more fun and I would like to think I can contribute more to Python that way). If you want this job I will be willing to give it up starting in September (I want a full year's worth of summaries behind me before I am willing to pass the torch). But if no one takes it I can probably continue to do them in a rather informal way by summarizing only big threads that I find interesting until someone steps forward to do a good, thorough job. If you *really* want to do the summaries at the same level of depth as I am currently doing them and are interested in taking over starting in September, give me an email at brett at python.org . ================================================ `Descriptor write-up [Draft: Please comment]`__ ================================================ __ http://mail.python.org/pipermail/python-dev/2003-June/035922.html Related threads: - `Descriptor write-up [second draft]`__ __ http://mail.python.org/pipermail/python-dev/2003-June/035936.html Raymond Hettinger has written an paper on descriptors covering what they are to how to write your own. Since not only are properties class methods, static methods, and 'super' object descriptors (more on the last one later on in this summary) but descriptors are used throughout Python now to create bound objects for functions, methods, etc. It would behoove all serious Python programmers to read http://users.rcn.com/python/download/Descriptor.htm . ====================================== `Where to put the interrupt module?`__ ====================================== __ http://mail.python.org/pipermail/python-dev/2003-June/036265.html Not earth-shattering, but to make sure that people know when new things are added to the stdlib I figured I should make this thread have a full-blown summary. Thanks to the development work on IDLEfork_, a new function in the thread module called interrupt_main has been added. It raises KeyboardInterrupt in the main thread of a program. The reason the exception is KeyboardInterrupt and not some new exception is because KeyboardInterrupt is the only asynchronous error in Python. There was discussion of making it much more general, which led to the PyThreadState_SetAsyncState API that allows the raising of an exception in another thread. .. _IDLEfork: http://idlefork.sf.net/ ========================================== `Can't compile _tkinter.c with Redhat 9`__ ========================================== __ http://mail.python.org/pipermail/python-dev/2003-June/036277.html `Red Hat`_, apparently, modified their distribution of Tcl_ so as to support `UCS-4`_ text encoding so that their distribution of Python 2.2 could be compiled with UCS-4 support. Problem is that this does not allow Python to compile with UCS-2 support; you **have** to compile with UCS-4 support and not UCS-2 under Red Hat 9 with their custom version of Tcl. Thanks to Martin v. L?wis, 2.3 has been modified so that Python compiled in either UCS-4 or UCS-2 will work with standard Tcl which is UCS-2 natively. .. _Red Hat: http://www.redhat.com/ .. _Tcl: http://www.tcl.tk/ .. _UCS-4: http://www.wikipedia.org/wiki/UCS-4 =========== `PEP-317`__ =========== __ http://mail.python.org/pipermail/python-dev/2003-June/036027.html Splintered threads: - `Exception masking/chaining`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036070.html A discussion of PEP 317 broke out on python-dev. You can read the PEP for details but it advocated removing string exceptions (they are going to be gone in Python 3) and implicit exception instantiation (that is not changing). The PEP was eventually rejected and has the details of why it was rejected in the end. Part of this discussion forked off to discuss exception masking. The idea came up that it might be nice for an exception to keep a reference to a previous exception that was still uncaught at that point. An example is an exception in the function passed to map; the function gets returned without knowing that it was in map. Masking it wouldn't work though since you then wouldn't know about the error in the function itself. But if there was a way to raise an exception from map that reference the original exception from the function then no information would be lost. Chaining the exceptions together would most likely just be sticking the previous exception in an attribute of the new one. This was all originally discussed `in January `__ and `February `__ of this year. There was also discussion of adding the traceback for an exception as an attribute of the exception. This would make getting respective tracebacks easier period but also easier if exception chaining was implemented. The traceback would most likely be attached to the exception when it is caught and not at instantiation. Both of these ideas are just that, ideas. They most likely won't occur until exceptions are moved over to new-style classes which probably won't be for a while. =========================== `towards a faster Python`__ =========================== __ http://mail.python.org/pipermail/python-dev/2003-June/036059.html Related threads: - `problem with assignment shadows builtin warning`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036422.html A new warning has been added to Python for when you inject an attribute into a module to shadows a built-in:: import os os.open = 42 This is in hopes of making this kind of thing illegal so as to allow the bytecode to be optimized for accessing built-ins. It also led to package imports, such as ``import A.B.C`` to work directly on the namespace dict instead of doing essentially ``setattr(A, 'B', A.B); setattr(A.B, 'C', A.B.C)``. ============================ `Sneaky 'super' instances`__ ============================ __ http://mail.python.org/pipermail/python-dev/2003-June/036155.html Splinter threads: - `PEP 246 and Protocols`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036235.html Discovering that an instance to the 'super' type is both an instance of a class *and* a non-data descriptor was causing issues for pydoc and inspect led to the question of whether there was any definitive way to tell whether an object was an instance of a class defined by using the 'class' statement in Python. It turns out there is: if object.__class__.__flags__ >> 9 & 1 is 1 (which is the Py_TPFLAGS_HEAPTYPE in C) *and* its metaclass is or a subclass of type. This then spawned a discussion about protocols and interfaces (which was discussed once way back when under the title `type categories`_) since protocols could supposedly allow one to define a protocol for what makes up a 'super' instance. None of this will get into the language (if it ever gets in) until Guido can really think it through and that will be a while. .. _type categories: =================================== `Details on Python shutting down`__ =================================== __ http://mail.python.org/pipermail/python-dev/2003-June/036386.html What happens while Python is shutting down? Well, it calls Py_Finalize in Python/pythonrun.c . This means that signals are turned off, gc.collect is called, calls PyImport_Cleanup in Python/import.c, and then calls. gc.collect one more time. PyImport_Cleanup is where modules are torn down. __main__ is deleted, then everything but sys and __builtin__, and then sys and __builtin__ (in that order). Now "deletion" as mentioned he is setting the module to None in sys.modules, setting all names starting with a single underscore to None in the module, and then all others sans __builtins__ . This is why when you define a __del__ method you need to make sure that all things referenced in it are local; global names in the module will have been set to None by the time the code is called if the object is collected during shutdown and raise an exception. ================================================================== `Re: [Python-checkins] python/dist/src/Objectslistobject.c,2.15`__ ================================================================== __ http://mail.python.org/pipermail/python-dev/2003-June/036445.html list.index now has optional start and end arguments. ========================== `RELEASED: Python 2.3b2`__ ========================== __ http://mail.python.org/pipermail/python-dev/2003-June/036623.html Related threads: - `2.3b2 this weekend`__ - `Python 2.3b2 branch tag created`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036596.html __ http://mail.python.org/pipermail/python-dev/2003-June/036614.html Title says it all. Big thing with this beta release is the new version of IDLE. As with all betas, please download it and give it a whirl to try to shake out any bugs that need fixing *ASAP*; we are going to aim for an August 1 release date for final thanks to Apple planning to incorporate Python 2.3 into Panther_. .. _Panther: http://www.apple.com/macosx/panther/ ============================================= `Re: Activating `-i' from inside a script?`__ ============================================= __ http://mail.python.org/pipermail/python-dev/2003-June/036579.html Related threads: - `Delayed `-i'! :-)`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036636.html Thanks to Skip Montanaro and someone curious at comp.lang.python_ you can now set the PYTHONINSPECT environment variable to something and then be started into an interactive interpreter if an exception propagates all the way to the end of a program without being caught. ======== Quickies ======== Weekly Python Bug/Patch Summary ------------------------------- - `2003-06-01`__ - `2003-06-08`__ - `2003-06-15`__ - `2003-06-22`__ - `2003-06-29`__ __ http://mail.python.org/pipermail/python-dev/2003-June/035926.html __ http://mail.python.org/pipermail/python-dev/2003-June/036021.html __ http://mail.python.org/pipermail/python-dev/2003-June/036364.html __ http://mail.python.org/pipermail/python-dev/2003-June/036525.html __ http://mail.python.org/pipermail/python-dev/2003-June/036610.html `BaseHTTPServer parsing`__ --------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/035948.html Code marked as internal to a module in the stdlib means you should not directly reference it in your code lest you are willing to deal with possible future breakage when a refactoring of that module is done. `popen2.py strangeness`__ ------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/035955.html A race condition in popen2 was found and fixed in 2.3 but was not solved in time for 2.2.3 . It has been marked for backporting for 2.2.4 . `timsort?`__ ------------ __ http://mail.python.org/pipermail/python-dev/2003-June/035958.html The new sorting algorithm for lists (known affectionately as "timsort" since Tim Peters wrote that tricky piece of code) is a 2.3 feature. But if you would like it for older versions of Python you can get it from http://py-stablesort.sourceforge.net/ . `Mundane dict __setitem__...`__ ------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/035970.html The hash value for an object in a dictionary is not guaranteed to be done based on identity; having two names set to equal tuples and used as keys will overwrite each other. `Meaning of trailing comma?`__ ------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/035990.html Improper for python-dev, but Michael Chermside was nice enough to answer the question nonetheless. `test_strptime failed`__ ------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/035995.html A failing test was reported. Follow-up on the thread is still pending. `IDLEfork Re-integration into Python`__ --------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/035994.html The new version of IDLE (being developed by the `IDLEfork`_ team) is going to be kept in Lib/idlelib/ . `On Syntax Extensibility (again)`__ ----------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036002.html Samuele Pedroni's thoughts on blocks (like thunks) in Python. This goes way back to the `2003-02-01 summary`_ and the `thunks `__ summary. .. _2003-02-01 summary: http://www.python.org/dev/summary/2003-02-01_2003-02-15.html `The Python interpreter is not fully thread-safe.`__ ---------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036004.html It is going to be added to the documentation for threading in the Python core that it does not support free threading. For those of you who aren't familiar with what free threading is (it apparently comes from the Windows programming world), it means that something can be called at any time from any thread. In other words it is thread-safe without requiring any special API. `urllib2 proxy support broken?`__ --------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036005.html This was initially covered in the `last summary`_. The broken proxy support in urllib2 has been fixed. `Re: [Python-checkins] python/dist/src/Lib pprint.py`__... ----------------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036008.html A patch applied to pprint to try to notice if a type's __repr__ had changed was backed out. `mimetypes.guess_all_extensions()`__ ------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036076.html Now returns the empty list when there are no matching extensions. `[OT] Thank you, python-dev`__ ------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036083.html An email from me to python-dev thanking the list for everything they have done since it helped get me into grad school. `Re: [DB-SIG] API suggestion: expose 'quote' method`__ ------------------------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036108.html Email about adding an optional quote function to the Python `DB-API`_ spec. .. _DB-API: http://www.python.org/topics/database/ `Updated 2.3 Release Schedule`__ -------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036163.html Don't expect 2.3 final to be released until some time after OSCON (it ends on July 11). `cPickle coredump with 2.3/cvs`__ --------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036187.html Someone was having core dump on them thanks to cPickle, but with no one else able to reproduce the problem so it's up to the OP to help solve this one. `Patch to remove eval from csv sniffer`__ ----------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036203.html A patch for the new csv package was questioned since 2.3 is in beta. Guido gave the clear, though, since the chances of people's code being dependent on the package were negligible. `Proposal to drop f_tstate`__ ----------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036204.html A misunderstanding on the use of the f_tstate value in frames in C code. `Caching of builtins and globals in action`__ --------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036228.html Samuele Pedroni playing with caching accesses to globals and built-ins. `Two useful patches involving tracebacks`__ ------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036230.html After discussing a useful patch, the idea of refactoring the cgitb and traceback module for 2.4 came up and seemed to be agreed upon to be a good idea. `PEP-311 operational?`__ ------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036282.html Someone asking if PEP 311 has been applied. `Can we switch different "byte code interpreters"?`__ ----------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036105.html Answer: no. Lesson learned: when you want to start a new thread do not piggyback on an existing one unless it is somehow related. `Sporadic test failures in Lib/test/test_mimetools.py`__ -------------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036299.html When writing tests that base results on the time difference between time measurements you *must* make sure that the difference is big enough to be noticed by a platforms time.time function (Windows only measures 18.2 times a second). `porting problems`__ -------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036308.html Someone has gotten Python to run on an XBox and GameCube. =) `Python language standard; LSB`__ --------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036325.html Python has no "standard"; CPython is as close as you are going to get. `VC 7.1 compiler for key developers - last call!`__ --------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036339.html Guido asked for key developers who wanted a free copy of VC 7.1 to speak up. `PEP280 and my experiment`__ ---------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036356.html Taking cues from PEP 280, Samuele Pedroni experimented with caching access to builtins and globals and got about a 15% increase. `On the possibility of "optimizing" range() calls in for-loops`__ ----------------------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036358.html The idea of optimizing the bytecode for calls to range in 'for' loops is still being thrown around. Alex Martelli, though, pointed out that if you just need to do something a set number of times nothing beats itertools.repeat . `Changes to IDLE`__ ------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036366.html All new bugs and patches in regards to IDLE should go into the Python tracker. `zipfile.py (SF #755031)`__ --------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036372.html A bug with zipfile was found and subsequently patched. `New PEP: 319`__ ---------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036387.html A new PEP on adding a keyword for synchronizing code has been put online. `Py2.3 Todo List`__ ------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036453.html Related threads: - `More work on SRE`__ __ http://mail.python.org/pipermail/python-dev/2003-June/036520.html Essentially a discussion as to whether to apply Gustavo Niemeyer's patch to remove the recursion limit from the re module and to add sys.(get|set)defaultsourceencoding functions. The former is in (with help of a coverage tool that comes with gcc and is talked about at https://moin.conectiva.com.br/GustavoNiemeyer/2003-06-19 ) and the latter had new tests added but won't have the code removing recursion limits applied until after 2.3. .. _EuroPython: http://www.europython.org/ `Handler.setLevel()`__ ---------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036466.html Misunderstanding over how the method worked. `No Net at home`__ ------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036485.html I lost Internet, as you probably know from the `Summary Announcements`_ section, on June 18 and didn't get it back until June 29. `SF CVS hosed?`__ ----------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036489.html Usual issues with cvs. Some talk about Subversion_. .. _Subversion: http://subversion.tigris.org/ `curses module has_key emulation`__ ----------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036501.html Problem with curses was found and a proposed patch at http://www.python.org/sf/759208 has been created. `A vote against dict(keyword=value) sugar`__... ----------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036502.html What the subject says. `Python on dual-processor Macs?`__ ---------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036530.html Greg Ewing was worried about a bug he heard about on dual-processor Macs. Jack Jansen said it was solved, though. `Patch 595601`__ ----------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036537.html A race condition with files and closing/reading is being worked on at http://www.python.org/sf/595601 . `cookie support for FancyURLopener?`__ -------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036553.html Someone asking if a certain feature was under development. `proposed Tkinter change; any likelihood of acceptance?`__ ---------------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036555.html Not for 2.3.0, but maybe for 2.4 or 2.3.1 . `Python hash function`__ ------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036556.html Damien Morton continues to try to speed up Python, this time by trying to speed up the hashing of strings. `Py2.1`__ --------- __ http://mail.python.org/pipermail/python-dev/2003-June/036564.html Backporting a fix all the way to Python 2.1 is only needed if it is really critical. `deprecate dbm module & add bsddb185 module for 2.2`__ ------------------------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036569.html "No" and probably "if you put the effort into it yourself". `OSCON Lightning Talk Proposals still being accepted`__ ------------------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036574.html If you want to give a lightning talk at OSCON_, read this email. .. _OSCON: http://conferences.oreilly.com/oscon/ `Yet more SRE`__ ---------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036575.html Gustavo Niemeyer fiddles with the re module some more. `Python 2.3b1, distutils and PEP 263`__ --------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036577.html Bug in Distutils is squashed involving the shebang line. `test_copy_reg failing in 2.3 CVS`__ ------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036582.html Dealt with by a comment. `socket timeouts and httplib`__ ------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036587.html Dealt with by adding a specific exception for timeouts. `Embedding Python, threading and scalability`__ ----------------------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036589.html David Abrahams redirecting a question to python-dev. `[ANN] SciPy '03 -- The 2nd Annual Python for Scientific Computing Workshop`__ ------------------------------------------------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036591.html Title says it all. `Proposed DNS query library`__ ------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036604.html Take a look at dnspython_ if you need DNS stuff. .. _dnspython: http://www.dnspython.org `Problems in stdlib before 2.3b2`__ ----------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036606.html They are being/have been dealt with. `Running tests on freebsd5`__ ----------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036611.html ...had two failures. They are being worked on. `threads duplicated on fork() prevent child from terminating properly`__ ------------------------------------------------------------------------ __ http://mail.python.org/pipermail/python-dev/2003-June/036619.html Person was told to file a bug report. `Meaty debugging mystery`__ --------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036627.html ... which Martin v. L?wis figured out the basic cause although how it is happening is still unknown. `2.3b2 known bugs?`__ --------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036632.html The bugs listed previously at http://www.python.org/2.3/bugs.html have been fixed but two new ones take their place. `Problem with 2.3b2 tarfile?`__ ------------------------------- __ http://mail.python.org/pipermail/python-dev/2003-June/036637.html Solaris tar was choking on a *really* long pathname in the stdlib. The pathname will most likely end up being changed to be under 100 characters so as to meet the POSIX tarfile format specification. From aahz at pythoncraft.com Fri Jul 11 10:23:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 10:23:58 -0400 Subject: Embedding Python, threading and scalability References: <3F0E9125.10185EB9@hotmail.com> Message-ID: In article <3F0E9125.10185EB9 at hotmail.com>, Alan Kennedy wrote: >Simon Wittber (Maptek) wrote: >> >> To write scalable applications in Python, one must write the >> 'scalabilty-required' parts n C. > >Or Pyrex? Or Boost? > >Do either of these products release the GIL when control is >transferred to the C/C++ extensions? Not automatically, that's for certain; dunno if either provides any features to make the job easier. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From bokr at oz.net Wed Jul 16 11:05:26 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 15:05:26 GMT Subject: Mix lambda and list comprehension? References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> <2259b0e2.0307150441.22921165@posting.google.com> Message-ID: On 15 Jul 2003 05:41:02 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >peter.barth at t-online.de (Peter Barth) wrote in message news:<6f5b3f88.0307142302.1a1531f3 at posting.google.com>... >> Hi, >> trying to mix lambda expresions and list comprehension >> doesn't seem to work. >> --- >> >>> [lambda x:x+y for y in range(10)][9](2) >> 11 >> >>> [lambda x:x+y for y in range(10)][4](2) >> 11 >> --- >> I expected the second expression to return 6. >> What did I do wrong? Any hints? >> Thanks >> - Peter > >It is a scope issue. The last value for y is used for all >the created lambdas. All lambdas users are bitten by that, >soon or later. The solution is to make y local to the >lambda function, with the optional argument trick: > >>>> [lambda x,y=y:x+y for y in range(10)][4](2) >6 or you could capture y as constants in the lambdas ;-) >>> [eval('lambda x:x+%s'%y) for y in range(10)][4](2) 6 Regards, Bengt Richter From imbosol at aerojockey.com Mon Jul 28 14:05:35 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Mon, 28 Jul 2003 18:05:35 GMT Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Message-ID: Bengt Richter wrote: > On Mon, 28 Jul 2003 02:22:59 GMT, Carl Banks wrote: > [...] >> >>The most robust way to handle this is to iterpolate, i.e., instead of >>passing start, stop, and step, pass start, stop, and n_intervals: >> >> def interiter(start, stop, n_intervals): >> diff = stop - start >> for i in xrange(n_intervals+1): >> yield start + (i*diff)/n_intervals >> > > To guarantee the exact end points, maybe: > > def interiter(start, stop, n_intervals): > fn=float(n_intervals) > for i in xrange(n_intervals+1): > yield ((n_intervals-i)/fn)*start + (i/fn)*stop Good. > but shouldn't that be xrange(n_intervals) and leave out > the final point (thus exact but invisible ;-). Well, I thought about that. In the interests of practicality beats purity, when you're interpolating (instead of stepping as in range) you should include the final endpoint. In my experience, when when you divide a segment into intervals, you almost always want to include both endpoints. If you use the Python convention of not including the final point in the iteration, and someone decides they do want the final endpoint, then it's kind of a pain to calculate what point you should use to get the final "endpoint", and you lose accuracy on top of it. So, my suggestion when iterating over an interval is this: If you pass in a stepsize, then don't include the final point. If you pass in a number of intervals, then do include the final point. I think the practicality of it justifies the different conventions. -- CARL BANKS From bogus at antispam.com Tue Jul 15 19:03:33 2003 From: bogus at antispam.com (Alex) Date: Tue, 15 Jul 2003 19:03:33 -0400 Subject: Curses module. Message-ID: Hello all, I'm trying to learn Python, in particular the curses module. My system is running Slackware 9.0 and the verion of Python that comes installed with Slackware 9.0 is Python 2.2.2. I've been trying to access the curses.wrapper module without any success. I know that the wrapper exists in /usr/lib/python2.2/curses yet any reference that I make to it is rebuffed by the interpreter. Here's the python script I'm trying to run: [code] #!/usr/bin/python # # My first attempts at writing a curses interface using python import curses def newWindow(): begin_x = 20 ; begin_y = 7 height = 5 ; width = 40 win = curses.newwin(height, width, begin_y, begin_x) return # Pass the function to the curses wrapper curses.wrapper(newWindow()) [/code] This is the error message that I get when I try to run the script from the CLI: Traceback (most recent call last): File "./curses3.py", line 15, in ? curses.wrapper(newWindow()) AttributeError: 'module' object has no attribute 'wrapper' Any ideas as to what I could be doing wrong? Alex the Python Newbie From alan.gauld at btinternet.com Sun Jul 13 18:01:38 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Jul 2003 22:01:38 GMT Subject: Multiple Class Inheritance Question References: Message-ID: <3f11d5b0.530577480@news.blueyonder.co.uk> On Sun, 13 Jul 2003 19:28:15 GMT, YoTuco wrote: > Does (can) an inheritance scheme like this have any adverse effects > (pitt-falls) for the App class inheriting class 'A' twice? > > class App(B,C): > def __init__(self): > B.__init__(self) > C.__init__(self) The way you wrote it no since neither B nor C called A's init method! But assuming they did then there are obvious potential problems in calling any method twice. For instance if it modifies an external global value it will be modified twice... If it modifies a class value similarly it will be modified twice. But because those are "obvious" issues the designer can work around them... In the case of calling methods implemented by A and inherited by B or C there is no such problem since the message search algorithm stops when it finds an implementation so it will only ever call the method once. Provided you make sure the order of B,C in the inheritance list is right fo you then it should be OK. (Recall that App(B,C) is not the same as App(C,B) ) HTH, Alan G. Alan g. http://www.freenetpages.co.uk/hp/alan.gauld/ From BPettersen at NAREX.com Thu Jul 24 16:41:02 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 24 Jul 2003 14:41:02 -0600 Subject: easy way to remove nonprintable chars from string Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE471A@admin56.narex.com> > From: Isaac Raway [mailto:isaac at blueapples.org] > >Don Hiatt wrote: > > >Greetings, > > > >Is there an easy way to remove multiple non-printable > >(e.g. "not strings.printable") from a string? Perhaps > >something like foo.replace(list_of_nonprintables, '') > >if it only existed? :-) > > This seems to work. Not sure how fast it'd be, though. > > def stripNoPrint(str): > results = "" > for char in str: > if string.printable.find(char): > results += char > return results try it on the string '0 plus 1 equals 1' :-) -- bjorn From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 2 19:38:09 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 02 Jul 2003 23:38:09 GMT Subject: what is self? References: <6071d159.0307020846.7653afaa@posting.google.com> Message-ID: On 2 Jul 2003 09:46:32 -0700, paul h wrote: > however, i have no idea what self is? You haven't read through the tutorial then. Please do so now, it will fill in many missing pieces of knowledge you currently have about Python: -- \ "Either he's dead or my watch has stopped." -- Groucho Marx | `\ | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ambiod at sbcglobal.net Sat Jul 26 02:35:36 2003 From: ambiod at sbcglobal.net (ryan) Date: Fri, 25 Jul 2003 23:35:36 -0700 Subject: imgv 2.8.6 released Message-ID: <000f01c35340$1fd87e40$c915fea9@h5p1n4> imgv is a cross-platform image viewer written entirely in Python, using Pygame. It includes standard features such as a file/directory browser, slideshows, zooming in and out, flipping, and rotating. It also has special features such as the ability to view 4 images on the screen at once (and slidedhow them), adjustable thumbnail sizes, image playlists, the ability to view images on Web sites, MPEG movie support, a customizable/unique interface, and much more. imgv 2.8.6 includes an improved UI, improved URL parsing, keyrepeat for image panning and some code cleanup. for more more info visit: http://imgv.sourceforge.net/ From aahz at pythoncraft.com Sun Jul 6 20:16:02 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2003 20:16:02 -0400 Subject: anything new on the ternary operator? References: Message-ID: In article , Bob Gailer wrote: >At 10:59 PM 7/6/2003 +0200, Tor wrote: >> >>What's the current status on the ternary operator that may or may not >>be added to python. Haven't heard much about that since the vote was >>announced for a couple of months ago. What's the best way to follow >>that dicussion? Or are we just waiting for the developers to make >>their decision? > >Last I heard it was killed by Guido, which makes me wonder why we spent >so much time discussing and voting. If he did not want it I wish he had >killed it at the start. I thought the vote was to determine the best >choice, and I was looking forward to having it. Guido made clear before the vote that only a clear statement from the community would drive the addition of the ternary operator. Given that the vote did not present a clear result, he did what he said he'd do. How's that a prbolem? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From mertz at gnosis.cx Tue Jul 1 14:26:51 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 01 Jul 2003 14:26:51 -0400 Subject: Good code patterns in Python References: <2259b0e2.0307010528.29b95fea@posting.google.com> Message-ID: |hwlgw at hotmail.com (Will Stuyvesant) wrote: |> if some_condition: |> some_name = some_value |> else: |> some_name = other_value |> is often a mistake. Much better, safer, would be: |> some_name = some_value |> if not some_condition: |> some_name = other_value mis6 at pitt.edu (Michele Simionato) wrote previously: |I am sorry, but I feel that the first form is MUCH more readable than the |second one; the first form is crystal clear to me, whereas I must read |the second form two or three times to understand what it is going on. Moreover, actual code often assigns from computations, not simply one name to another. The harder-to-read form risks bad side effects (or simply a performance hit): some_name = some_computation() if not some_condition: some_name = other_computation() The straightforward if/else form avoids superfluous computations. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From tjreedy at udel.edu Sat Jul 5 21:31:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Jul 2003 21:31:07 -0400 Subject: problems with sf cvs server? References: Message-ID: "Ben Wolfson" wrote in message news:slrnbgeu10.o3b.wolfson at senator.cs.uchicago.edu... > Is anyone else experiencing trouble checking the python source tree > out of the sf cvs server? I hang forever here: > > cvs server: Updating python/nondist/src/Compiler/tests/output Yes, there is current discussion on PyDev about what to do. From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 07:31:24 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 31 Jul 2003 21:21:24 +0950 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> <3F28EA71.6A863E7@hotmail.com> Message-ID: On Thu, 31 Jul 2003 12:09:09 +0100, Robin Becker wrote: > 1) SyntaxWarning: assignment to None > eg for None, name in colorNamePairs: > what is the preferred way to do this nowadays? It's fairly > trivial to go through and change these to for notUsed, x in .... > but is there a nicer way. Seems nice enough. You'll only be able to assign to a mutable object anyway; None is not mutable, and will soon be a keyword. Define (or just go ahead and use) your own not_used name. > 2) FutureWarning: hex/oct constants > sys.maxint will return positive > values in Python 2.4 and up > eg self.assertEquals(ttf.read_ulong(), 0x81020304) # big-endian > Is there no way to preserve the clarity of the above in future? Declare large positive constants as being longs: >>> foo = 0xFFFFFFFF :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up >>> foo -1 >>> foo = 0xFFFFFFFFL >>> foo 4294967295L You probably want the numbers to behave as positive anyway. > The same applies to > > FutureWarning: x< in Python 2.4 and up > eg sum = (hi << 16) | (lo & 0xFFFF) Same answer applies too: >>> hi = 0xDEAD >>> lo = 0xBEEF >>> sum = ( hi << 16 ) | ( lo & 0xFFFF ) __main__:1: FutureWarning: x<>> sum -559038737 >>> hi = 0xDEADL >>> lo = 0xBEEFL >>> sum = ( hi << 16 ) | ( lo & 0xFFFF ) >>> sum 3735928559L If you want to deal consistently (across Python versions) with numbers larger than sys.maxint, whether decimal, hex or octal, ensure you set them up as longs to begin with. > Is Python moving away from the machinery? I don't see why not; fiddling with low-level bits is pretty architecture-dependent, as these hacks show. If you want C, you know where to find it. > Are there efficient recipes for doing these 32 bit operations? Hopefully you'll agree the solutions I've presented are just as "efficient", even if they expose the bit-fiddling hackery somewhat more. > Certainly cut and paste to and from java/c/c++ will be a lot harder. I've never known that to be a priority for Python. -- \ "I went to a restaurant that serves 'breakfast at any time'. So | `\ I ordered French Toast during the Renaissance." -- Steven | _o__) Wright | Ben Finney From candiazoo at mac.com Wed Jul 16 00:46:12 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Wed, 16 Jul 2003 04:46:12 GMT Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> <120720032321075007%candiazoo@mac.com> <3344b1fa.0307140325.67be7b8c@posting.google.com> Message-ID: <160720030045562219%candiazoo@mac.com> Oh CRIPES! I have 3 different sets of header files for MySQL!!! Now the problem becomes: which do I select? /usr/includes/mysql is out... I have a set under /Library/MySQL/include and a set under ... oh wait... those are in an application package - so nevermind. I guess I just answered my own question! Thanks Peter... Mike In article <3344b1fa.0307140325.67be7b8c at posting.google.com>, Peter Wilkinson wrote: > "Michael S. Jessop" wrote in message > news:<120720032321075007%candiazoo at mac.com>... > > [[ This message was both posted and mailed: see > > the "To," "Cc," and "Newsgroups" headers for details. ]] > > > > I tried supplying host as well, same error. :/ Something is hosed. > > I guess I could try reinstalling. I really want to get this to work. > > I am trying to write a maintenance program for my wife, so she can > > remotely modify the database containing information about her artwork, > > distribution lists, etc. > > > > I've just sorted out the problem on my machine and it appeared to be a > set of include files from a previous install of MySQL that were > sitting in /usr/include, once I removed that and rebuilt with setup.py > pointing to the Fink include paths it works fine. > > Peter. From gordons_lists at gmx.net Fri Jul 11 19:05:27 2003 From: gordons_lists at gmx.net (Gordon Wetzstein) Date: Sat, 12 Jul 2003 01:05:27 +0200 (MEST) Subject: socket problem Message-ID: <24472.1057964727@www25.gmx.net> Hello everyone, I have a problem with python sockets. I broadcast a lot of pickled objects with socket. sendto(...), that works. Ireceive them on the other site with socket.recvfrom(16384) The pickled objects are smaller (like 10000 bytes) than the max bytes. The problem appears if I send too many pickled objects very quickly one after another, then I only receive a part of the sent objects. I print them before I send them, they are there but they never reach the destination. When I do a time.sleep(0.1) (but not lesser than 0.1) after socket.send() all is good but it's too slow! Does anyone know what the problem is? And maybe a solution! thanks gordon -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ Jetzt ein- oder umsteigen und USB-Speicheruhr als Pr?mie sichern! From buki at bukis.org Mon Jul 14 15:23:13 2003 From: buki at bukis.org (Andreas Bauer) Date: Mon, 14 Jul 2003 21:23:13 +0200 Subject: some questions References: <3f12f613$0$8731$9b622d9e@news.freenet.de> Message-ID: <3f13031b$0$4026$9b622d9e@news.freenet.de> > Where have you already looked? Have you tried "Python tutorial" on > google? > Have you tried Python.org? Python itself comes with a tutorial (maybe > you are unaware of this, or maybe you want another?). I know there is one. But I don't like it. Don't know what kind of tutorial I'm looking for. Just some hints would be enough. >> Can't hardly find any. > > Was ist das? Can't or can? Or do you really mean "Can't hardly find > nothin'?" ;-) Meant Can. From yaipa at yahoo.com Tue Jul 15 16:14:24 2003 From: yaipa at yahoo.com (yaipa h.) Date: 15 Jul 2003 13:14:24 -0700 Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> <3F13703C.C12392D6@engcorp.com> Message-ID: <6e07b825.0307151214.3d2cce2@posting.google.com> All, Worked like a charm for me too! I used it to develop an automated attendant for a Serial Oven Controller. The attendant ran from Sparc Solaris using Python 2.1 and pySerial. The only weird thing, which I didn't get a chance to debug, was a perfectly working script under RS-232 got terribly out of sync when R/W I/O to a RS-485 serial network. Any reason why that would be? Thanks, just a bit of trivia if the boss wants me to revisit it again. --Alan Peter Hansen wrote in message news:<3F13703C.C12392D6 at engcorp.com>... > Conrad wrote: > > > > I'll give them a shot tomorrow. USPP made me a little > > nervous, because frankly, it looks like it died a year > > and a half ago, with outstanding Linux bugs > > Thanks for checking that out better than I did. I was > worried about that myself, having seen nothing about it > for a very long time, but the name had stuck in my head. > > > pyserial seemed from it's docs > > to require jython - which means pulling in a whole slew > > of third-party DLLs for Java. > > No! Try PySerial first, for sure. It does NOT require > Jython, but does support it. As the home page says, > "It provides backends for stadard (sic) Python running > on Windows, Linux, BSD (possibly any POSIX compilant system) > and Jython. The module named "serial" automaticaly (sic) > selects the appropriate backed (sic)." > > (Chris, if you'd like, I'll happily proofread that page > and correct a few spelling errors for you. ;-) > > -Peter From bertvansesamstraat at hotmail.com Fri Jul 18 06:33:03 2003 From: bertvansesamstraat at hotmail.com (Maurice) Date: Fri, 18 Jul 2003 10:33:03 +0000 Subject: how to compile python program to linux executable Message-ID: Gerhard H?ring wrote: > Ruslan Spivak wrote: > >> Hello. >> >> Is it possible to convert python program to linux executable program? >> [...] > > > You can make an executable that contains both your Python script and > modules and the interpreter runtime. It's called 'freezing'. The utility > for this is in the Python source distribution. There's also Gordon > McMillan's Installer that makes the process easier. He offers Linux and > Windows versions. > > Why would you want to do that? There's almost certainly a better > solution for your problem, *if* there is any problem in the first place. > > -- Gerhard > Hello, I can have the same 'problem'. I am currently developping a tool that uses other modules. This tool I want to distribute to other people in my group which also use Linux but that don't have installed the modules. Is it then possible to pach all libraries and modules and so on into one exec. and give this to someone else. Or can I only do this when they have exactly the same Linux version. Or is it only possible when they have installed the other progames containing the modules. The modules I'm thinking of is for example wxPyhton and/or VTK. Maurice From adechert at earthlink.net Sun Jul 20 21:37:51 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 01:37:51 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xk7acai97.fsf at ruckus.brouhaha.com... > "Ulrich Petri" writes: > > "Alan Dechert" schrieb im Newsbeitrag > > news:P9DSa.111436$Io.9552373 at newsread2.prod.itd.earthlink.net... > > > > Sorry but why on earth you dont just print that on paper and let people make > > their crosses where they want? > > In the past there has been a lot of trouble with manual ballot > systems, because people can't understand the instructions, the ballots > get printed incorrectly, stuff like that. You might remember the big > mess in the 2000 US presidential election, that revolved around such > problems. Choosing the US President turned out to mostly be a battle > between lawyers over which ballots to count rather than about what the > voters wanted, and a lot of the legal decisions were made according to > the political leanings of the particular judges. The ballots > themselves didn't get a thorough tabulation until long after the > January inauguration and people disagree about how to intepret the > results even to this day. > > US elections are also different than elections in most other countries > because a lot of different issues get voted in them. Rather than just > choosing one of a bunch of different parties like in a parliamentary > system, we vote separately for (potentially) the President, Senator, > Congressional representative, Governor of the state, Lieutenant > governor, Attorney General, Mayor of the town, members of the local > school board, ballot initatives on whether to collect an extra tax on > soda bottles, on whether to build a new highway somewhere, and so on > and so on. Dozens of different things, all in one election. Counting > ballots by hand would require reading off from each ballot all the > separate votes on each of these issues. It's not like in France or > Canada (I have no idea about Germany) where there's basically just one > question to vote on. > You make a lot of good points. As I understand it, Canada administers national, province, and local elections separately. They happen at different times and are conducted by different entities. The U.S. is one of very few where you see federal, state, and local contests on the same ballot. Alan Dechert From sross at connectmail.carleton.ca Thu Jul 10 16:31:13 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 10 Jul 2003 16:31:13 -0400 Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: "Steve Pinard" wrote in message news:6cd58b6.0307101214.34e99f2a at posting.google.com... > I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? Apparently, you get None to remind you that you've done an inplace sort, see http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.020.htp From noah at noah.org Sun Jul 13 09:27:02 2003 From: noah at noah.org (Noah) Date: 13 Jul 2003 06:27:02 -0700 Subject: Reading packets from a tun device. References: Message-ID: Andre wrote in message news:... > I'm trying to read packets from a tun device in Python, the code I used > for this is the following: > f = file( '/dev/tun0', 'r+' ) > pkt = f.read( 1500 ) > > The problem is that the f.read() call doesn't return. When I used a small > value in the f.read() call instead of the 1500, like 1 or 5, it did > return the first bytes of the packet. > I then went to the manuals and found that file() uses stdio's fopen, so I > changed my code to make file() not do any buffering, like this: > > f = file( '/dev/tun0', 'r+', 0 ) > pkt = f.read( 1500 ) > But the behavior of the program is the same as the one above. > What I'm looking for is a way to open a file in Python without using > stdio, or a way to read from a tun device using it. I'm not sure if this problem is due to buffering on your client side, but you can open plain file descriptors in Python. The buffering could also be on the server side of the tun device. What is connected to the other side of the tun? Is that code that you wrote too? If so then send a copy of that and I can understand better what is going on. The 'os' package supports raw file descriptor file IO which is below stdio. import os fd_tun = os.open ('/dev/tun0', os.O_RDWR) data = os.read (fd_tun, 1500) os.close (fd_tun) Let me know how this goes. Yours, Noah From skip at pobox.com Wed Jul 23 09:59:24 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jul 2003 08:59:24 -0500 Subject: needs a logo In-Reply-To: <7fe97cc4.0307230144.9119f89@posting.google.com> References: <7fe97cc4.0307230144.9119f89@posting.google.com> Message-ID: <16158.38076.265722.759965@montanaro.dyndns.org> Xah> it would be good if Bash and Python have a decent logo. Xah> the current logos of simplistic font Xah> http://cnswww.cns.cwru.edu/~chet/img/bash-org.jpg Xah> http://python.org/pics/pythonHi.gif Xah> are homely. Have you browsed http://www.python.org/pics/ ? There are a lot of PyBanner*.gif images there. Maybe you could use one of them as the starting point for a new logo. Skip From intentionally at blank.co.uk Mon Jul 14 22:06:14 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:06:14 +0100 Subject: anything like C++ references? References: Message-ID: <7tm6hvcqtqaigelrnfb9sd1qatnfvbk21g@4ax.com> On Mon, 14 Jul 2003 06:28:09 GMT, "Bryan" wrote: > >"Stephen Horne" wrote in message >news:rp94hvc8fg6h91oe7ctqq9jn9ku3nlud1k at 4ax.com... >> On Sun, 13 Jul 2003 22:42:21 GMT, "Bryan" wrote: >> >> > >> >> 3. Why is there no way to reference an immutable object via a >> >> pointer, other than stuffing it into a mutable object designed for >> >> some purpose other than simple pointer behaviour? >> >> >> > >> >>>> a = (1, 2, 3) >> >>>> b = a >> >>>> id(a) >> >15471760 >> >>>> id(b) >> >15471760 >> >>>> print b[1] >> >2 >> >>>> >> > >> > >> >i just referenced an immutable object via a "pointer" and i __did_not__ >> >stuff it into a mutable object as you say. >> >a and b "point" to the same object. >> >> Technically, but what is the point? You can't do pointer-style things >> with it. You can't change the object in any way without changing the >> id, and you can't use the mechanism to, for instance, allow 'var' >> parameters. >> > >can you show what functionality is missing by not being able to do >"pointer-style things"? here are two variables: > >a = (1, 2, 3) >b = [1, 2, 3] > >one immutable, one mutable. please show an example of what "pointer-style >things" you would like to do. In my view, mutability should be a property of *objects* - not the same as values, in the pedantic language that has become necessary in this thread. The existence of mutability shouldn't break the principle of variables being bound to values. This is my point. Pointer types are a side issue - something that becomes necessary (or rather more obviously important) if the principle of variables being bound to values is respected. This doesn't mean that Python can't use binding of variables to objects as an implementation, but that implementation shouldn't be visible (except for performance, and for operations that explicitly deal with objects rather than values) in the results. Starting from your example, I'd want to see results like this... >>> a = [1, 2, 3] >>> b = a >>> c = (1, 2, 3) >>> d = c >>> b[2] = 4 >>> a [1, 2, 3] >>> b [1, 2, 4] >>> d[2] = 4 Traceback (most recent call last): File "", line 8, in ? TypeError: object doesn't support item assignment Having done this, mutable objects could not be abused to give pointer-style functionality (a fact of life at the moment) so the need for real explicit pointers should become obvious. >i've read this entire thread so far, and from a practical point of view >(because that's all i really care about and what pays the bills), i really >don't understand what the problem is. personally, i don't care about the >strict definitions of computer science terms and what "variable" or >"pointer" means. i do care about how fast problems can be solved, how much >resources must be involved in solving that problem, and how much money can >be made/saved. for me, python is a winner in all this area. not having >pointers like c/c++ is such a blessing. i can't believe anyone would even >suggest that pointers and/or doing things with pointers be brought into >python. ok... one more time... let's bring this conversation down to >something practical. please show an example of pointer-style functionality >in any language that is missing/awkward/complicated in python. i'm not an >expert in python, i'm just very curious to understand what the true >practical issue is. There is none that is currently missing because mutable objects can be abused to create the required effect. If Python respected the concept of variables being bound to values, though, that wouldn't be true. You wouldn't be able to write... >>> def f(x) : ... x[0] += 1 ... >>> a = [1] >>> f(a) Or rather you could, but you'd get... >>> a [1] ...and not... >>> a [2] So instead of abusing lists, you'd have to use an explicit pointer type... >>> def f(x) : ... *x += 1 ... >>> a = 1 >>> f(&a) >>> a 2 Note - in many cases, you could return multiple values and avoid the need for pointers. That wouldn't be the case, however, for objects which don't support copying. It *might* be possible to pass such an object directly into a function (depending on how the variable-to-value binding is implemented) but modifying the parameter would require that it binds to a new object - a copy of the original object - to prevent the mutation of the callers variables. Passing the parameter and returning it *might* be acceptable, but modifying it within the function would require copying of the object. As there are a number of important object types that don't (and shouldn't) support copying, this wouldn't be a trivial concern. From akineko at pacbell.net Tue Jul 8 22:24:49 2003 From: akineko at pacbell.net (Aki Niimura) Date: 8 Jul 2003 19:24:49 -0700 Subject: Python and freeze (something odd) Message-ID: Hello Everyone, I feel sorry to bother you guys as I posted another yesterday, too. Finally my script which accesses a web site from a Python script is functioning fully. It works very nicely (upload / download / does operations). Now I'm trying to "freeze" my script to a single executable file under Solaris using freeze. I have done such many times and it worked magically (until now). However, maybe I'm out of luck. When I started the generated executable, I got the following: Traceback (most recent call last): File "websc.py", line 284, in ? File "websc.py", line 276, in main File "websc.py", line 125, in upload_files File "websc_upload.py", line 173, in httprequest File "/usr/local/lib/python2.2/email/Message.py", line 113, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/local/lib/python2.2/email/Generator.py", line 103, in flatten self._write(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 131, in _write self._dispatch(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 157, in _dispatch meth(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 231, in _handle_multipart g.flatten(part, unixfrom=False) File "/usr/local/lib/python2.2/email/Generator.py", line 103, in flatten self._write(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 138, in _write self._write_headers(msg) File "/usr/local/lib/python2.2/email/Generator.py", line 172, in _write_headers elif _is8bitstring(v): File "/usr/local/lib/python2.2/email/Generator.py", line 44, in _is8bitstring unicode(s, 'us-ascii') LookupError: unknown encoding: us-ascii // As I mentioned earlier, it works fine if it is invoked from .py files. Also, I created a simple test program which just does unicode(s, 'us-ascii'). The frozen version of such test program works without a hitch. Guido mentioned in a document for 'freeze' saying: "... It may still be confused -- it will not know about calls to the __import__ built-in function, ..." I guess my program confused 'freeze' as unicode is a built-in function. However, he didn't offer any further information. Any thoughts, any suggestions? Thanks in advance. Best regards, Aki Niimura From dave at boost-consulting.com Tue Jul 8 11:39:31 2003 From: dave at boost-consulting.com (David Abrahams) Date: Tue, 08 Jul 2003 11:39:31 -0400 Subject: does lack of type declarations make Python unsafe? References: <3EEE3036.1080105@removeme.free.fr> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) writes: > Confronting the Martellibot is like flirting with an encyclopedia, I'd > rather not do it myself, but I respect those who do, because it > produces knowledge. Yeah, and fun! I'm a little disappointed that Alex disappeared from this discussion because I thought it was going somewhere interesting and was looking forward to some more cogent arguments. Any chance of re-opening it, Alex? I'm referring, in particular, to http://tinyurl.com/gbq0 -- Dave Abrahams Boost Consulting www.boost-consulting.com From anthony at interlink.com.au Sun Jul 6 00:33:37 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Sun, 06 Jul 2003 14:33:37 +1000 Subject: Frustration with spurious posts. In-Reply-To: <5.2.1.1.0.20030705095656.01a4e060@66.28.54.253> Message-ID: <200307060433.h664XbxC025004@localhost.localdomain> >>> Bob Gailer wrote > Does anyone know why we keep getting these posted to the list. Is there a > way to stop it? Viruses that forge email from addresses, and are forging 'from: python-list at python.org'. I believe Greg's trying to get spambayes trained up on these messages to try and block them. Other than that, mandating that people stop using crappy insecure *cough* Microsoft *cough* mail clients would also stop it :) -- Anthony Baxter It's never too late to have a happy childhood. From bogus at antispam.com Mon Jul 21 23:22:51 2003 From: bogus at antispam.com (Alex) Date: Mon, 21 Jul 2003 23:22:51 -0400 Subject: Stopping a loop with user input in curses References: <20030720135329.18124.00000260@mb-m15.aol.com> Message-ID: Thank you so much! That worked fantastically! I'll have to read up on the select module. It seems like I'll be using it a lot for the application I'm writing. Once again, thank you. Alex From martin at v.loewis.de Fri Jul 25 01:18:15 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 25 Jul 2003 07:18:15 +0200 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> Message-ID: rimbalaya at yahoo.com (Rim) writes: > So what problem is the new.instancemethod() trying to solve? It has no side effects on the class it is an instancemethod of. Regards, Martin From grante at visi.com Thu Jul 24 12:02:02 2003 From: grante at visi.com (Grant Edwards) Date: 24 Jul 2003 16:02:02 GMT Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> Message-ID: <3f2002fa$0$164$a1866201@newsreader.visi.com> In article , Leopold Faschalek wrote: >> 1) Send an arbitrary Ethernet packet. [Well, not completely >> arbitrary, the source MAC will be "right", but the protocol >> number is a proprietary (not IP) one, and the packet isn't >> anything standard. >> >> 2) Receive any incoming packets with a specified protocl >> number -- same proto number as in 1) above. > the new winsock2.h supports more socket types: > /* > * Types > */ > #define SOCK_STREAM 1 /* stream socket */ > #define SOCK_DGRAM 2 /* datagram socket */ > #define SOCK_RAW 3 /* raw-protocol interface */ > #define SOCK_RDM 4 /* reliably-delivered message */ > #define SOCK_SEQPACKET 5 /* sequenced packet stream */ > > so you have only to define 3 as type in the socket() call AFAICT, winsock's SOCK_RAW isn't what I need. It lets you imipliment protocols on top of IP -- at least that's what the documentation implies, and that's what's being done by all the example code I can find. I don't want to build on top of IP. I want to build an arbitrary protocol on top of Ethernet, specifying the Ethernet protocol number which I want to send/receive. -- Grant Edwards grante Yow! By MEER biz doo at SCHOIN... visi.com From BPettersen at NAREX.com Thu Jul 24 15:21:55 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 24 Jul 2003 13:21:55 -0600 Subject: Tokenize Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4712@admin56.narex.com> > From: Ken Fettig [mailto:kfettig at state.nd.us] > > Does Python have an equivelent to the Java StringTokenizer? > If so, what is it and how do you implement it? I have no idea what the Java StringTokenizer class does (this being a Python group and all -- references always welcome ), but perhaps the split() method on strings gets close to what you want (http://www.python.org/doc/current/lib/string-methods.html)? -- bjorn From tjreedy at udel.edu Thu Jul 24 16:47:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2003 16:47:07 -0400 Subject: easy way to remove nonprintable chars from string References: <2b012c5e.0307241138.177e5c8c@posting.google.com> Message-ID: "Don Hiatt" wrote in message news:2b012c5e.0307241138.177e5c8c at posting.google.com... > Is there an easy way to remove multiple non-printable > (e.g. "not strings.printable") from a string? Perhaps > something like foo.replace(list_of_nonprintables, '') > if it only existed? :-) >>> help(str.translate) translate(...) S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. >>> s_identity=''.join([chr(i) for i in range(256)]) # the 'table' you need Terry J. Reedy From bgailer at alum.rpi.edu Sun Jul 6 19:52:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 06 Jul 2003 17:52:39 -0600 Subject: Using Loops to track user input In-Reply-To: References: Message-ID: <5.2.1.1.0.20030706175121.025ac950@66.28.54.253> At 02:33 PM 7/6/2003 -0700, Cousin Stanley wrote: >| Write a program that reads 10 numbers from the user >| and prints out the sum of those numbers. Not to neglect the 1-liner: import operator; reduce(operator.add,[int(raw_input("Number>")) for i in range(10)]) Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From justinjohnson at fastmail.fm Wed Jul 9 14:19:24 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Wed, 09 Jul 2003 12:19:24 -0600 Subject: process.py problems In-Reply-To: <20030709170030.51BDE37470@www.fastmail.fm> References: <20030708153117.127C0326C0@www.fastmail.fm> <20030708094057.C9520@ActiveState.com> <20030708210829.B3BBE3886D@www.fastmail.fm> <20030708170131.C13603@ActiveState.com> <20030709123005.C0B58374AF@www.fastmail.fm> <20030709123628.66ACA3771B@www.fastmail.fm> <20030709170030.51BDE37470@www.fastmail.fm> Message-ID: <20030709181924.7445236056@www.fastmail.fm> My testing doesn't always seem consistent, but currently I can only reproduce this when my script runs as a windows service using win32service. When I run it on the commandline it works fine. I'm guessing this has something to do with the logging mechanism I'm using. So the only problem I'm positive about is that dir and other shell commands work on win2k but not on winnt. Sorry for all the emails and the confusion. -Justin On Wed, 09 Jul 2003 11:00:30 -0600, "Justin Johnson" said: > I guess this really is a problem. I found that it sometimes hangs on > p.stdout.read(). > > >>> p = process.ProcessOpen("cleartool lsvob -s") > >>> p.stdout.read() > '\\import_test\n\\pvob\n\\vob\n\\adminvob\n\\adminvob2\n' > >>> p = process.ProcessOpen("cleartool lsview -l") > >>> p.stdout.read() > *** just hangs here *** > > > On Wed, 09 Jul 2003 06:36:28 -0600, "Justin Johnson" > said: > > Never mind the part about commands hanging.... that appears to be > > related to something else in my code. I think your process stuff is > > working fine for .exe commands. :-) > > > > So just the dir command is failing now. > > > > On Wed, 09 Jul 2003 06:30:05 -0600, "Justin Johnson" > > said: > > > After replacing my process.py I still get an error with the dir command > > > (see below). > > > > > > I'm getting some wierd results with normal .exe commands though. > > > Commands that don't have much output come back just fine, but commands > > > that have more output, even if they don't take long to run necessarily, > > > seem to get stuck and just hang, never returning. > > > > > > E:\ccase\python\uhg\uht>python > > > ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on > > > Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 > > > Type "help", "copyright", "credits" or "license" for more information. > > > >>> import process > > > >>> p = process.ProcessOpen("dir") > > > process: info:ProcessOpen.__init__(cmd='dir', mode='t', cwd=None, > > > env=None) > > > process.res: info:[11054544] ProcessOpen._start(): create child stdin: > > > <_FileWra > > > pper: file:None fd:3 os_handle:> > > > process.res: info:[11054544] ProcessOpen._start(): create child stdout: > > > <_FileWr > > > apper: file:None fd:4 os_handle:> > > > process.res: info:[11054544] ProcessOpen._start(): create child stderr: > > > <_FileWr > > > apper: file:None fd:5 os_handle:> > > > process: debug:_whichFirstArg: first='dir', rest='' > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "process.py", line 1118, in __init__ > > > self._startOnWindows() > > > File "process.py", line 1289, in _startOnWindows > > > cmd = _fixupCommand(cmd, self._env) > > > File "process.py", line 516, in _fixupCommand > > > cmd = _whichFirstArg(cmd, env) > > > File "process.py", line 325, in _whichFirstArg > > > candidate = which.which(first) > > > File "which.py", line 251, in which > > > raise WhichError("Could not find '%s' on the path." % command) > > > which.WhichError: Could not find 'dir' on the path. > > > >>> > > > > > > >>> p = process.ProcessOpen("cleartool lsvob -l") > > > process: info:ProcessOpen.__init__(cmd='cleartool lsvob -l', mode='t', > > > cwd=None, > > > env=None) > > > process.res: info:[18469440] ProcessOpen._start(): create child stdin: > > > <_FileWra > > > pper: file:None fd:3 os_handle:> > > > process.res: info:[18469440] ProcessOpen._start(): create child stdout: > > > <_FileWr > > > apper: file:None fd:4 os_handle:> > > > process.res: info:[18469440] ProcessOpen._start(): create child stderr: > > > <_FileWr > > > apper: file:None fd:5 os_handle:> > > > process: debug:_whichFirstArg: first='cleartool', rest='lsvob -l' > > > process: debug:_SaferCreateProcess(appName=None, > > > cmd='"C:\\Program > > > Files\\Rational\\ClearCase\\bin\\cleartool > > > .EXE" lsvob -l', > > > env=None, > > > cwd=None) > > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > > > process: info:_registerprocess(process= > > 0x0119D2 > > > 40>) > > > ***** It doesn't return here ***** > > > > > > > > > On Tue, 8 Jul 2003 17:01:32 -0700, "Trent Mick" > > > said: > > > > > > > > Yup, process.py is expected a which.py <1.0. Crappy. I need to put up a > > > > new process.py. To work around in it in your current build you need to > > > > changes process.py's usages of which.which() to expect a single hit > > > > instead of a list of a all hits. In other words, which.which() changed > > > > from: > > > > >>> which.which("python") > > > > ["C:\\Python22\\python.exe", "C:\\Python21\\python.exe", ...] > > > > to: > > > > >>> which.which("python") > > > > "C:\\Python22\\python.exe" > > > > > > > > This is a little bit of a pain to do though. I have attached an untested > > > > process.py that should have this fixed. I apologize for the informalness > > > > of this. I'll try to get a new process.py version up on > > > > when I get a chance. > > > > > > > > Cheers, > > > > Trent > > > > > > > > > > > > [Justin Johnson wrote] > > > > > Thanks for the reply! > > > > > > > > > > which 1.0.2 > > > > > > > > > > Here's the log output with the dir command > > > > > ----------------------- > > > > > process.res: info:[18392288] ProcessOpen._start(): create child stdin: > > > > > <_FileWra > > > > > pper: file:None fd:3 os_handle:> > > > > > process.res: info:[18392288] ProcessOpen._start(): create child stdout: > > > > > <_FileWr > > > > > apper: file:None fd:4 os_handle:> > > > > > process.res: info:[18392288] ProcessOpen._start(): create child stderr: > > > > > <_FileWr > > > > > apper: file:None fd:5 os_handle:> > > > > > process.res: info:[18392288] ProcessOpen.__del__() > > > > > process: info:[18392288] ProcessOpen.close() > > > > > process: info:[18392288] ProcessOpen: closing stdin (<_FileWrapper: > > > > > file:None fd > > > > > :3 os_handle:>). > > > > > process: debug:[18400496] _FileWrapper.close() > > > > > process: debug:[18400496] _FileWrapper.close: close handle > > > > > process: debug:[18400496] _FileWrapper.close: closing handle raised > > > > > process: debug:[18400496] _FileWrapper.close: done closing handle > > > > > process: info:[18392288] ProcessOpen: closing stdout (<_FileWrapper: > > > > > file:None f > > > > > d:4 os_handle:>). > > > > > process: debug:[18400720] _FileWrapper.close() > > > > > process: debug:[18400720] _FileWrapper.close: close handle > > > > > process: debug:[18400720] _FileWrapper.close: closing handle raised > > > > > process: debug:[18400720] _FileWrapper.close: done closing handle > > > > > process: info:[18392288] ProcessOpen: closing stderr (<_FileWrapper: > > > > > file:None f > > > > > d:5 os_handle:>). > > > > > process: debug:[18403024] _FileWrapper.close() > > > > > process: debug:[18403024] _FileWrapper.close: close handle > > > > > process: debug:[18403024] _FileWrapper.close: closing handle raised > > > > > process: debug:[18403024] _FileWrapper.close: done closing handle > > > > > process: debug:[18400720] _FileWrapper.close() > > > > > process: debug:[18400496] _FileWrapper.close() > > > > > process: debug:[18403024] _FileWrapper.close() > > > > > ---------------- > > > > > > > > > > I also get the following results running commands that are in my path... > > > > > ------------------ > > > > > g`"apper: file:None fd:5 os_handle:> > > > > > process: debug:_SaferCreateProcess(appName=None, > > > > > cmd='C lsview -s', > > > > > env=None, > > > > > cwd=None) > > > > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > > > > > > > process.res: info:[18680944] ProcessOpen.__del__() > > > > > process: info:[18680944] ProcessOpen.close() > > > > > process: info:[18680944] ProcessOpen: closing stdin (<_FileWrapper: > > > > > file:None fd > > > > > :3 os_handle:>). > > > > > process: debug:[18696880] _FileWrapper.close() > > > > > process: debug:[18696880] _FileWrapper.close: close handle > > > > > process: debug:[18696880] _FileWrapper.close: closing handle raised > > > > > process: debug:[18696880] _FileWrapper.close: done closing handle > > > > > process: info:[18680944] ProcessOpen: closing stdout (<_FileWrapper: > > > > > file:None f > > > > > d:4 os_handle:>). > > > > > process: debug:[18696832] _FileWrapper.close() > > > > > process: debug:[18696832] _FileWrapper.close: close handle > > > > > process: debug:[18696832] _FileWrapper.close: closing handle raised > > > > > process: debug:[18696832] _FileWrapper.close: done closing handle > > > > > process: info:[18680944] ProcessOpen: closing stderr (<_FileWrapper: > > > > > file:None f > > > > > d:5 os_handle:>). > > > > > process: debug:[18699984] _FileWrapper.close() > > > > > process: debug:[18699984] _FileWrapper.close: close handle > > > > > process: debug:[18699984] _FileWrapper.close: closing handle raised > > > > > process: debug:[18699984] _FileWrapper.close: done closing handle > > > > > process: debug:[18696832] _FileWrapper.close() > > > > > process: debug:[18696880] _FileWrapper.close() > > > > > process: debug:[18699984] _FileWrapper.close() > > > > > --------- > > > > > > > > > > > > > > > > > > -- > > > > Trent Mick > > > > TrentM at ActiveState.com > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > From trentm at ActiveState.com Mon Jul 21 19:04:38 2003 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 21 Jul 2003 16:04:38 -0700 Subject: Automatically filling in answers to interactive shell command questions In-Reply-To: ; from tbonemp3@yahoo.com on Mon, Jul 21, 2003 at 03:23:25PM -0700 References: Message-ID: <20030721160438.A7318@ActiveState.com> Check out pexpect, a Python version of the popular Tcl-land Expect program: http://pexpect.sourceforge.net/ I haven't used it but I get the feeling that pexpect is Un*x-only if that affects you at all. Trent [Ted Weatherly wrote] > Is it possible to use python to automatically fill in the answers to > interactive shell command questions? For example, I am using a shell > command addperson that behaves as follows: > > > addperson > First Name: Ted > Birthday: 12/08/1977 > Height: 6'0" > Location: San Francisco, CA > > > > I am prompted for "First Name: " and I enter "Ted". I am prompted for > "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 > people or more...it gets tiresome. > > Assuming I can't change the addperson command to read data from a > file, is there any way to use python to fill in the data for the > expected questions? Perhaps a different language would be better? > > -Ted > -- > http://mail.python.org/mailman/listinfo/python-list -- Trent Mick TrentM at ActiveState.com From zneptune321 at zexcite.zcom Tue Jul 15 13:34:00 2003 From: zneptune321 at zexcite.zcom (Conrad) Date: Tue, 15 Jul 2003 17:34:00 GMT Subject: Sio serial module install problem with ActiveState References: Message-ID: OK, I'm posting on top, spank me. Many thanks to Peter and Gary for their help, and to Chris for writing pyserial, which is working just fine for what I'm doing - it took two lines to change my code, because I was already using file-type .write() methods to pump the data out - so I added an import, and changed my open statement, and it just worked. (once I killed the evil VB program that apparently opens the serial port and just hangs on to it forever!) Thanks again, Conrad Years ago, Nostradamus predicted that on Mon, 14 Jul 2003 22:38:57 +0000, Conrad would write, saying: > Greetings, > > I have a need to print from Win98SE to a little > serial label printer provided by United Parcel, so > based on Mark Hammond's recommendation in > 'Programming on Win32' I decided to try the Sio > module at http://starship.python.net/crew/roger/ > > My problem: > > The Sio installer dies looking for: > HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.2\InstallPath > > I am using ActiveStates Python 2.2.2 build 224 on Win98SE. > > ActiveState apparently does do registry setup, for example, > the HKEY_USERS\.DEFAULT\SOFTWARE tree contains the > \Python\PythonCore\2.2\InstallPath keys. I re-installed > Python, thinking I had blown the registry, but the keys > that Sio wants are never set. > > FWIW, PyPGSQL, wxPython, and the egenix MxBase packages all > find Python on machines with ActiveState and install OK. > I don't know what they are checking on install. > > Can anyone suggest a fix/workaround for someone who is just > a bit befuddled by registries, or did I perhaps grab the > wrong Sio? ( I got SioModule22.EXE at 171184 bytes from: > http://starship.python.net/crew/roger/ ) > > BTW, this serial printer is apparently pretty much a 'dump > and go' type device - the only thing the printer seems to > be capable of returning is a 4-byte error code after a special > error report command is sent to the printer - other than that, > all of the data and commands seem to move downstream only, > with no return from the printer expected. Is Sio overkill for > this, i.e. is there some incredibly simple "open a serial port > under Win32 for write only" command I'm missing in the basic > Python stuff? > > Many thanks, > > Conrad From jdhunter at ace.bsd.uchicago.edu Thu Jul 3 12:43:19 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 03 Jul 2003 11:43:19 -0500 Subject: getting a submatrix of all true In-Reply-To: ("Terry Reedy"'s message of "Thu, 3 Jul 2003 02:16:19 -0400") References: Message-ID: >>>>> "Terry" == Terry Reedy writes: Terry> Statisticians have tried a variety of approaches. Googling Terry> for ' statistics "missing data" 'will give you some leads Terry> if you want. I have done some searching. I'm familiar with the common methods (delete every row that contains any missing, replace missing via mean or regression or something clever) but haven't seen any discussion of dropping variables and observations together to yield data sets with no missing values. Have you seen something like this? John Hunter From anton at vredegoor.doge.nl Wed Jul 23 16:34:11 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 23 Jul 2003 22:34:11 +0200 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3f15b04b$0$49114$e4fe514c@news.xs4all.nl> <3f1db69e$0$49116$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: >>>"Als achter vliegen vliegen vliegen, vliegen vliegen vliegen achterna." >> >> >> ...and the meaning is? > > >*spoiler* > > > >If behind flies flies fly, flies fly after flies. > >(I'm not too sure about the correct word order in English, >but this resembles the Dutch sentence most, IMO). This is just a translation. The Dutch sentence already has meaning [1], so claiming that the English translation of the sentence is the meaning of the Dutch sentence seems a bit paraconsistent. If one were to look for a sentence in English which has the same meaning as the original Dutch sentence, I would rather use an analogous sentence: "If there's a cat on the mat, there's a mat under the cat" However this loses the ambiguity of "following something flying". Anton [1] The meaning may be unclear to the non-native speaker From carsten at gehling.dk Wed Jul 16 10:37:28 2003 From: carsten at gehling.dk (Carsten Gehling) Date: Wed, 16 Jul 2003 16:37:28 +0200 Subject: SV: pso - ImportError: No module named url In-Reply-To: Message-ID: Figured out myself - I just removed the line with "from url import Url" - it doesn't seem to be used anywhere ;-) - Carsten > -----Oprindelig meddelelse----- > Fra: python-list-admin at python.org > [mailto:python-list-admin at python.org]P? vegne af Carsten Gehling > Sendt: 16. juli 2003 16:24 > Til: python-list > Emne: pso - ImportError: No module named url > > > I've tried to install pso on my webserver and made the first test example. > > When trying to run it (eg. from the prompt), I get the following error: > > Traceback (most recent call last): > File "test.py", line 3, in ? > from pso.service import ServiceHandler > File "/usr/local/lib/python2.2/pso/service.py", line 31, in ? > from request import ServiceRequest, SERVER_RETURN > File "/usr/local/lib/python2.2/pso/request.py", line 36, in ? > from url import Url > ImportError: No module named url > > I've checked my Python installation - there is no module named "url". > > I thought it might be a misspelling of "urllib", but "urllib" is > explicitly > imported a few lines above in request.py > > System info: > OS: Redhat Linux 7.3 > Python: 2.2.2 > pso: 0.98.C-beta > > - Carsten > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bgailer at alum.rpi.edu Wed Jul 30 13:23:22 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 30 Jul 2003 11:23:22 -0600 Subject: Ver 2.3 install over 2.2? Message-ID: <5.2.1.1.0.20030730112144.02c30b88@66.28.54.253> Is it OK to install 2.3 in my python22 folder, thus preserving all the libs and packages already installed, or do I have to reinstall all of them, or what? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From vze4rx4y at verizon.net Sun Jul 20 11:03:50 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 20 Jul 2003 15:03:50 GMT Subject: How do I get info on an exception ? References: Message-ID: > >You could catch it with: > > > > except socket.herror, inst: > > print inst.args > > > >or more broadly with: > > > > except socket.error, (errno, string_message): > > print code, message > > > > > >> More importantly, where is the answer documented that I should > >> have looked? > > > >The list of possible socket exceptions is in the docs for sockets. > >It also describes the (errno, string) return tuple value of inst.args. > . > . > . > True. > > But unsatisfying--at least to me. Submit a patch. Raymond Hettinger From bgailer at alum.rpi.edu Wed Jul 23 21:15:23 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 23 Jul 2003 19:15:23 -0600 Subject: Cookbook idea - single-shot __init__ In-Reply-To: <3F1E49D4.A539CABF@alcyone.com> References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <5.2.1.1.0.20030723190843.02b64210@66.28.54.253> I have at times had the need to initialize some things once at the class level, and have resorted to techniques like: class foo: first = True def __init__(self): if foo.first: foo.first = False # initialization code Then a "better idea" occurred: class foo: def __init__(self): del foo.__init__ # initialization code Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From eniac at sdf-eu.org Wed Jul 9 15:01:24 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Wed, 09 Jul 2003 21:01:24 +0200 Subject: check if dir exists Message-ID: How can I check if a dir exists ? From no at spam.invalid Tue Jul 1 17:43:25 2003 From: no at spam.invalid (Russell E. Owen) Date: Tue, 01 Jul 2003 14:43:25 -0700 Subject: Newbie: Tkinter and macPython References: Message-ID: In article , gtewalt at earthlink.net (gt) wrote: >Wow. >I never expected anything this thourough for a response. >Thanks Russell. >I have actually installed MacPython 2.3b1. >I tried the package manager, but at the time it wouldnt connect to >the 'database' (if I remember correctly) >At any rate, it looks like I need aqua Tk. >It would seem that I should un-install 2.3b1, install >aqua Tk, then reinstall 2.3b1 and implement the package manager. >Thanks again. Sorry to hear that. The package manager in 2.3b1 had some bugs that are probably fixed in 2.3b2, but it's so new that I don't think there's a binary installer for MacOS X yet. I doubt you need to uninstall your Python. Installing Tk in advance is important if you buld Python from source (because the make script automatically builds Tkinter for you if it can find Tcl/Tk). I don't think it matters when installing from binary. Unfortunately, I do not know how to add Tkinter to the binary installed version of Python 2.3 (given that you are having trouble with the package manager). I'm sure somebody does know. Try posting to the MacPython mailing list. Two other options are: - Build Python from source (e.g. see link below). A bit slow but it certainly does work. - Use Bob Ippolito's binary installer for Python 2.2.2, which includes lots of extras. I've put what I know about building Python for MacOS X at . Probably not much there I didn't already post, but at least now it's in one place and can be updated. I'm hoping Python 2.3 final will be so easy to install that extra information is redundant. -- Russell From spam at spam.com Mon Jul 28 06:51:01 2003 From: spam at spam.com (Ton K.) Date: Mon, 28 Jul 2003 12:51:01 +0200 Subject: MIDI interface on Windows in Python, need advice Message-ID: Folks, I'm planning to build MIDI sysex tools in Python on Windows 98SE. I need a simple read/write to MIDI interface, preferably with a read callback integrated with the Tkinter event loop. I don't need timestamps, sequencing etc... please advise on how to proceed... thanks Ton K. From postmaster at 127.0.0.1 Sat Jul 12 22:12:40 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Sun, 13 Jul 2003 14:12:40 +1200 Subject: Any pure-python relational databases? References: <2a897f11.0307121143.4a37113b@posting.google.com> Message-ID: On Sat, 12 Jul 2003 12:43:25 -0700, Wayne Pierce paused, took a deep breath, then came out with: >> 2) Any kind of relational DBMS written in pure python that'll run on >> 1.5.2? > > While not relational, have you looked at Metakit? > > http://www.equi4.com/metakit/python.html I got Metakit to compile for Python 1.5.2 without undue drama, just a couple of makefile hacks. Uploaded the shared lib and the python wrapper to the host, and it runs just fine. What a sweet little dbms! Thank YOU, Wayne!!! :))) From bokr at oz.net Fri Jul 4 22:53:31 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Jul 2003 02:53:31 GMT Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> <840592e1.0307040900.14e3e668@posting.google.com> <3F05C39D.3F65B89C@engcorp.com> <3F05FFFE.DB98BF44@engcorp.com> Message-ID: On Fri, 04 Jul 2003 18:30:22 -0400, Peter Hansen wrote: >Aahz wrote: >> >> In article <3F05C39D.3F65B89C at engcorp.com>, >> Peter Hansen wrote: >> > >> >Google Groups likely takes its feed directly of a Usenet site, and Usenet >> >in general suffers from large propagation delay. It is that delay, caused >> >by messages filtering slowly across the Usenet network, which leads to the >> >"5 answers" problem, not Google Groups itself. >> >> Actually, Google uses at least two or three feeds (including >> stanford.edu, which has a super-competent news admin), and Usenet >> propagation is actually little short of e-mail speeds these days, >> depending on where you're located. > >That might be, but empirically I've seen posts that I've made take >hours to get there, and I've seen posts that were made to the mailing >list (and copied to me directly) take hours to get there. In both >cases, there is an "upwards" propagation delay towards whatever hosts >Google is milking before stanford.edu or the others will see it... Well, compare just in this thread how stuff got to me (I broke paths with '\\' for clarity and removed return addresses): =============================== Path: news.alt.net!news.maxwell.syr.edu!newsfeed.stanford.edu!postnews1.google.com!not-for-mail From: (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Newsgroups: comp.lang.python Path: news.alt.net!news.maxwell.syr.edu!feed2.news.rcn.net!rcn!nntp.abs.net\ !uunet!dca.uu.net!ash.uu.net!news.baymountain.com!not-for-mail From: Paul McNett Newsgroups: comp.lang.python From: Peter Hansen Newsgroups: comp.lang.python Path: news.alt.net!priapus.visi.com!news-out.visi.com!hermes.visi.com\ !feed2.news.rcn.net!rcn!elnk-atl-nf1!newsfeed.earthlink.net!prodigy.com\ !rip!c03.atl99!cyclone2.usenetserver.com!newsfeeds-atl1!news.webusenet.com\ !newsfeed.on.tac.net!news.sentex.net!not-for-mail Path: news.alt.net!priapus.visi.com!news-out.visi.com!petbe.visi.com\ !newspeer.monmouth.com!news-peer-east1.sprintlink.net!news.sprintlink.net\ !newsfeed!panix!panix3.panix.com!not-for-mail From: (Aahz) Newsgroups: comp.lang.python From: Peter Hansen Newsgroups: comp.lang.python Path: news.alt.net!news.maxwell.syr.edu!newsfeed-east.nntpserver.com\ !nntpserver.com!chi1.webusenet.com!c03.atl99!cyclone2.usenetserver.com\ !newsfeeds-atl1!news.webusenet.com!newsfeed.on.tac.net!news.sentex.net!not-for-mail =============================== Note that path from Peter was not the same both times. Then, looking at one of my own posts in another thread: Path: news.alt.net!oz.net!usenet From: (Bengt Richter) Newsgroups: comp.lang.python Regards, Bengt Richter From max at cNOvSisiPonAtecMh.com Thu Jul 3 15:11:16 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 03 Jul 2003 19:11:16 GMT Subject: [ot continued..] Re: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3f04727e@news.swissonline.ch> Message-ID: > [OT] That's not a pro, that's a con on the C++ side. And actually that's the > reason why there's so much bad C++ software. A C programmer first has to > forget C to be able to program in C++ - well, to be able to program OO in > C++. Well, it is documented as one of the original design goals of the language, if I remember correctly. It is certainly implicitly a goal considering the sacrifices made to preserve C as a subset. I think it was important in getting a lot of people on board with c++, but it certainly there are many problems with it, including the one you mentioned. Of course the problems would not exist if C++ was never accepted. It is similar to saying 'how dare my parents embarass me by having sex'. Take it up with Bjarne :) max. > Best regards > Franz GEIGER -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] From tjreedy at udel.edu Tue Jul 15 03:48:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2003 03:48:44 -0400 Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: "Stephen Horne" wrote in message news:dsq6hv4vi1qhsksv56h8lqd7rlqh58ir05 at 4ax.com... > In mathematics and computer theory, variables bind to values. In real life, names (like "Stephen Horne") bind to 'objects' (including people like you) that are mutable. Python is intended for modeling real life as well as mathematics. I understand that you don't like this. Fine. You are not going to change it. Terry J. Reedy From herrn at gmx.net Sun Jul 13 11:08:53 2003 From: herrn at gmx.net (Marco Herrn) Date: 13 Jul 2003 15:08:53 GMT Subject: Library for pop over ssl? Message-ID: Hi, I know of poplib, which does what I need except that it doesn't support SSL encryption. imaplib has SSL-support. But I want it with pop3. Is there a library available that does this or do I have to implement it myself? Bye Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From martin at v.loewis.de Wed Jul 30 16:24:53 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 30 Jul 2003 22:24:53 +0200 Subject: Upgrading python In-Reply-To: References: Message-ID: Bengt Richter wrote: > How do I know what will happen to file extension associations and the system path search > that takes unadorned python and finds some/path/to/python23.exe? You could ask. Extension associations will get redirected to Python 2.3, and there is no python23.exe. > And how does the old python22 find what it needs? Using sys.executable. > Do I need to go through a .cmd file that sets up its environment > before running? No. > How do I know everything it needs? Again, you might want to ask. > IOW, how do you set up a clean way to run both 2.2.3 and 2.3 "side by side" but separately, > with default "python" going to 2.3? Install Python 2.2 first, then 2.3. > I am being lazy in not reading the install docs yet, > but does it cover the question fully? No. > If so, the answer to this post can just be "yes" ;-) No. Regards, Martin From exarkun at intarweb.us Fri Jul 18 08:19:49 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 18 Jul 2003 08:19:49 -0400 Subject: feature request: a better str.endswith In-Reply-To: <2259b0e2.0307180401.5dae02f2@posting.google.com> References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <20030718121949.GB11052@intarweb.us> On Fri, Jul 18, 2003 at 05:01:47AM -0700, Michele Simionato wrote: > I often feel the need to extend the string method ".endswith" to tuple > arguments, in such a way to automatically check for multiple endings. > For instance, here is a typical use case: > > if filename.endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > > Currently this is not valid Python and I must use the ugly > > if filename.endswith('.jpg') or filename.endswith('.jpeg') \ > or filename.endswith('.gif') or filename.endswith('.png'): > print "This is a valid image file" extensions = ('.jpg', '.jpeg', '.gif', '.png') if filter(filename.endswith, extensions): print "This is a valid image file Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 From mgerrans at mindspring.com Thu Jul 24 03:16:25 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 24 Jul 2003 00:16:25 -0700 Subject: Python and VS.Net References: Message-ID: "Trent Mick" wrote: > > If your Python code could thereby access the .NET libraries, that would be > > another story. That would be like Jython for .NET. I was hoping that was > > what Active State's Python-in-VS.NET-thingy was, but alas it was too good to > > be true: it is only (so far) a color-syntaxing Python editor that takes two > > or three minutes to load up. > > You are mixing up two difference ideas. ActiveState's VisualPython is a > plugin for VS.NET to provide all the IDE stuff (like editting, > debugging, interactive shell, help, intellisense, etc) for Python > programmers. Uh, isn't that pretty much what I said? I don't think I mixed up the ideas. I only said that what ActiveState's Visual Python was and what I was originally hoping it would be were not the same. > The idea of integrating the Python language somehow into the .NET > framework is independent of VS.NET-the-IDE, though I suppose one might > like some level of connection between the two. Mark Hammond, before and > while at ActiveState did do some exploratory work in this direction. But > that is all it has come to so far: exploration. So your "too good to be > true" does (currently) apply to a so called Python.NET. This code is > currently in PyWin32's CVS tree one SourceForge: > http://sf.net/projects/pywin32 > There is also the independent Kobra project that I have not looked at. Yes, I was aware of these, too. Despite Microsoft's claims about the .NET platform being language-independent, it doesn't seem to be a simple task to get Python going on it. So far, I think there are only VB.NET, C++, C# and J#. No Python#, Perl# or Ruby#, as of yet... From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 21 18:05:13 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 21 Jul 2003 22:05:13 GMT Subject: [OT] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: Russ Salsbury enlightened us with: > ComputerWorld says that SCO is going to charge Linux end users a > license fee for "the opportunity to run Linux legally." Utter crap. First they'd better proof their point instead of harassing inocent people. > I realize that this is OT, but SCO's action strikes at the heart of > Open Source. No they don't. If they can't point out what code is theirs, they are obviously having a hard time recognising it. If they can't even recognise it, how can they clame it? > If IBM, Red Hat, and the decide that the the cost of settling is less > than the cost of litigation, we all loose. No we don't. If they point out which code is theirs, we'll rip it out, replace it by better code, and they won't have a leg to stand on. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From trentm at ActiveState.com Wed Jul 23 15:33:27 2003 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 23 Jul 2003 12:33:27 -0700 Subject: Python and VS.Net In-Reply-To: ; from mgerrans@mindspring.com on Wed, Jul 23, 2003 at 12:59:32AM -0700 References: Message-ID: <20030723123327.B356@ActiveState.com> > If your Python code could thereby access the .NET libraries, that would be > another story. That would be like Jython for .NET. I was hoping that was > what Active State's Python-in-VS.NET-thingy was, but alas it was too good to > be true: it is only (so far) a color-syntaxing Python editor that takes two > or three minutes to load up. You are mixing up two difference ideas. ActiveState's VisualPython is a plugin for VS.NET to provide all the IDE stuff (like editting, debugging, interactive shell, help, intellisense, etc) for Python programmers. The idea of integrating the Python language somehow into the .NET framework is independent of VS.NET-the-IDE, though I suppose one might like some level of connection between the two. Mark Hammond, before and while at ActiveState did do some exploratory work in this direction. But that is all it has come to so far: exploration. So your "too good to be true" does (currently) apply to a so called Python.NET. This code is currently in PyWin32's CVS tree one SourceForge: http://sf.net/projects/pywin32 There is also the independent Kobra project that I have not looked at. Trent -- Trent Mick TrentM at ActiveState.com From calderano at sgaspa.it Tue Jul 8 12:01:00 2003 From: calderano at sgaspa.it (Luca Calderano) Date: Tue, 8 Jul 2003 18:01:00 +0200 Subject: printing html document with internet explorer Message-ID: <003401c3456a$20be53e0$410100a4@utente65> Hi people! Does anyone know how-to automatically print an html doc using Internet Explorer ??? I've tried these ways: 1) wxHtmlEasyPrinting 2) win32api.ShellExecute but using both of tese objects the printer setup pop-up window appears on the screen and I have to click on the "OK" button to print my doc. Thanks in advance S.G.A S.p.A. Nucleo Sistemi Informativi Luca Calderano From gh at ghaering.de Thu Jul 31 04:25:56 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 10:25:56 +0200 Subject: Misuse of In-Reply-To: <200307301820.51591.shalehperry@comcast.net> References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> <200307301820.51591.shalehperry@comcast.net> Message-ID: <3F28D294.8080302@ghaering.de> Sean 'Shaleh' Perry wrote: > On Wednesday 30 July 2003 13:20, Michael Sampson wrote: > >>How does the IDLE that comes with the latest release of python handle this? >>When it automaticly indents does it do it with spaces or tabs? If you hit >>tab in the IDLE will it just put 5 spaces in for you? > > thou shalt always use even numbered indents. [...] Why? -- Gerhard From mis6 at pitt.edu Mon Jul 21 13:18:57 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 21 Jul 2003 10:18:57 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> Message-ID: <2259b0e2.0307210918.614892ba@posting.google.com> chrisperkins37 at hotmail.com (Chris Perkins) wrote in message news:<45228044.0307210522.1ef95144 at posting.google.com>... > mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307200721.16ef2ea1 at posting.google.com>... > > Oops! My mistake, I forgot the islice; it should be > > > > the=lambda pred,seq: list(itertools.islice(itertools.ifilter(pred,seq),0,1)) > > > > in such a way that we exit at the first hit, otherwise one could just use > > the standard "filter". > > How about: > > def the(pred,seq): return True in itertools.imap(pred,seq) > > if you really want to use the name "the" ("any" makes much more sense to me). > > Chris That's a good idea, indeed. BTW, in this context I feel that if the(filename.endswith, ('.jpg','.jpeg','.gif','.png')): dosomething() is more clear than if any(filename.endswith, ('.jpg','.jpeg','.gif','.png')): dosomething() which is confusing to me since it seems "any" is referred to "filename" whereas it is referred to the tuple elements. M.S. From ianb at colorstudy.com Sun Jul 20 22:17:35 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 21:17:35 -0500 Subject: Possible use of Python for a voting machine demo project --your feedback requested In-Reply-To: References: Message-ID: <1058753855.28094.2584.camel@lothlorien> On Sun, 2003-07-20 at 19:34, Alan Dechert wrote: > > I really don't know why everyone wants to use touchscreens in voting > > machines. I hate touch screens, they are a horrible input method. > > > A lot of people agree with you. Certainly, the Australians that designed > their system would agree. They went for a keypad. > > http://www.softimp.com.au/evacs.html I think the ATM model is considerably better than a keypad. In a keypad you have to view the number, then change focus and enter in the number, then confirm the number and the selection. Thinking particularly about old people who aren't comfortable with computers, this sort of focus shift is very difficult, though in the case of a keypad likely everyone will have this focus shift and find the process more difficult as a result. The ATM model (buttons on the side of the monitor) doesn't require any shift in focus, because the input devide (the buttons) and the select itself are visually linked. > On the other hand, a lot of people really really like the touch screens. We > can't make them all mouse driven since a percentage of the voters will have > a big problem with that. But there is no reason to give up on mouse driven > systems just because some people can't use them. Mice are very cheap and > most people are used to them. So we just need to have enough non-Mice > systems to accommodate those that need/want them. One nice thing about the > touch screen with our system is that it will look and work exactly the same > whether you use a mouse or touch screen. Mice, unlike keypads, are comfortable for many people. But an older person generally has to think very hard about the movement of the mouse to match it with the screen (since they are often reasoning to themselves about how to move, rather than having an intuitive body-sense of the mouse). Any technique that has different levels of accessibility seems like it would meet criticism for that. People will have to decide which booth to use, will have to be informed about the differences, and may find it easier or harder than they thought once they choose. But maybe it's not a big deal, I don't know. I think the ATM-style buttons should be fairly cheap, though. You already have to create an enclosure for the monitor, and in general while you'll be using commodity PC parts you'll still have to set the system up with a certain amount of care. Speed should be excellent -- because of the tactile feedback and reliability of the input, people could vote more confidently with less error. I would expect 100% accuracy with respect to the actual input (though inaccuracies in reading, or simple indecisiveness will still cause errors). The one problem I would imagine would be the increased difficulty of the interface for changing your vote, and that displaying the current status of your vote would be exclusive with displaying the choices for a particular race to choose among. But since ultimately correctness is ensured by confirming the printed ballot, I'm less concerned about editing if it means you can go through the process more quickly. (You could make the vote a single keypress, but then display at the top of the screen what your last selection was while still presenting the choices for the next race... given enough room you could even just split the screen in two and show all previous selections) Potentially by using braille the keys could be blind-accessible, when accompanied with some sort of audio. Since the system would already be modal when using keys, it wouldn't have to be adapted significantly for that situation -- you'd simply need to change a setting on one of the computers to do audio output and attach headphones, and then you'd have your accessible booth. Anyway, I just like keyboards more than mice if you can't tell... Ian From dave at nullcube.com Wed Jul 30 05:02:15 2003 From: dave at nullcube.com (Dave Harrison) Date: Wed, 30 Jul 2003 19:02:15 +1000 Subject: egenix mx package weirdness Message-ID: <20030730090215.GA1886@dave@alana.ucc.usyd.edu.au> And so go on my solaris woes ;-) Due to my impending insanity I shall keep this brief, Solaris 9, Python 2.1.1, MySQLdb 0.9.1, and mx 2.0.2 I am using these versions because I am plugging into an existing sensitive system, upgrading is pretty much a no go (not my choice). MySQLdb works fine on its own, and mx works fine on its own. But install the two together, and mx breaks MySQLdb. mx however appears to continue to work. The error is quite simply a coredump. Anyone have similar experiences/problems ? any ideas ? grazias Dave From alanmk at hotmail.com Mon Jul 21 17:25:19 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 21 Jul 2003 22:25:19 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> Message-ID: <3F1C5A3F.962BC15E@hotmail.com> [Much discussion elided, because it's definitely way off topic] Bengt Richter wrote: > Which part, though? The encoding, or the fact that you see the encoding > in the above instead of its being rendered with the intended appearance? > > IOW, any solution will involve *some* encoding and the possibility of > rendering it "raw" or interpreted. A smart GUI might have a default > mode showing everything interpreted, and have a "view source" button. I did just want to make one quick point about this. I believe that a major part of the reasons for the success of the URI scheme is their simplicity and transcribability, especially in situations that may not immediately involve a computer. I think most people been through one or more of the following 1. Spoken a URI over the telephone. 2. Seen URIs on passing taxis/trucks/trains/planes/automobiles 3. Scribbled a URI on a business card, or scrap of paper 4. Sent a URI by SMS text message, i.e. tapping it out on a 10-key phone keypad. 5. Printed a URI on their own business card. 6. "Handwritten" a URI into PDA handwriting recognition software. I have a little difficulty with the insistence that 2 character iso-latin-1 escape codes go easily in all the above situations. Should I have to say http://xhaus.com/%F3cinn%E9ide instead of http://xhaus.com/?cinn?ide If I use the latter, then that's an illegal URI. It's a wart. But it's not a python wart, so I'll shut up now :-L regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jul 26 16:23:58 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 26 Jul 2003 22:23:58 +0200 Subject: cgi.FieldStorage not parsing query string Message-ID: <3f22e35d$0$49115$e4fe514c@news.xs4all.nl> Hi I'm using cgi.FieldStorage to parse the HTTP request parameters of a form submission. When the form is submitted using method="GET" it correctly parses all form parameters. However, if the form is submitted using "POST" (that's what I want!) things go different. It only seems to parse the form parameters that are sent *inside* the POST requst body. Usually this is no problem, for instance when you POST it to the following URL: http://www.host.com/script.cgi But if you add URL-encoded parameters, and use POST, the URL-encoded parameters are lost: http://www.host.com/script.cgi?extraarg=foobar "extraarg" does not appear in the FieldStorage object. Looking at the code it appears that FieldStorage is only parsing the URL-encoded parameters (the QUERY_STRING) if the request method is GET or HEAD, not when it is POST. I'm not sure if this is correct. I think it is faulty behavior, because if I do this with a Java Servlet, I *do* get the URL-encoded parameters too. For the time being, I will call cgi.parse_qsl myself and add the resulting list to the FieldStorage list so that I *do* have all parameters. Can somebody tell me if FieldStorage is wrong or that I am mistaken here? Thank you, --Irmen de Jong From staschuk at telusplanet.net Mon Jul 28 16:37:34 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 28 Jul 2003 14:37:34 -0600 Subject: Loading and executing an arbitrary Python script from within Python In-Reply-To: <20030727005710.05032.00000550@mb-m26.aol.com>; from rastm2@aol.commorespam on Sun, Jul 27, 2003 at 04:57:10AM +0000 References: <20030726094624.15169.00000599@mb-m13.aol.com> <20030727005710.05032.00000550@mb-m26.aol.com> Message-ID: <20030728143734.B1276@tibia.amotlpaa.bogus> Quoth Raymond Arthur St. Marie II of III : [...] > Did I get the concept wrong about using > a generater in a try section? Is this code legal anyone? > > Or does this only pertain to the yeild statement in a try. The prohibition is on yield statements in the try section of a try-finally statement. The posted code is fine. (This is prohibited because there is no guarantee that execution will ever return to the generator after the yield -- the caller might never call .next() again -- and so the finally block might never be executed. This was judged too grave a violation of try/finally's semantics to permit.) -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From maxm at mxm.dk Thu Jul 10 04:20:36 2003 From: maxm at mxm.dk (Max M) Date: Thu, 10 Jul 2003 10:20:36 +0200 Subject: Zope problem: objectValues('Folder') In-Reply-To: <3F0D11C7.4010805@gmx.de> References: <3F0D11C7.4010805@gmx.de> Message-ID: <3F0D21D4.3040902@mxm.dk> Jens Riedel wrote: > I try to get a list of subfolders by using >
    > >

  • >
    >
If you have written it exactly like that, it should work. You have no folders inside the folder you are running it in then. > Does anybody know where the problem with "objectValues('Folder/File')" is? I assume you have not written your code that way, but rather: objectValues(['Folder','File']) regards Max M From g2h5dqi002 at sneakemail.com Thu Jul 10 00:20:39 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 10 Jul 2003 16:20:39 +1200 Subject: A story about Python... sort of In-Reply-To: References: Message-ID: Piet van Oostrum wrote: > Both problems can be solved by stopping when space is exhausted, waiting > until technique has evolved enough to upload the state of the computation > to the new extended hardware etc. Hmmm. So, if the universe is open and contains an infinite amount of matter, then we could solve chess eventually, but we might have to wait a while for the limits of the observable universe to expand sufficiently... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pyth at devel.trillke.net Tue Jul 8 12:03:59 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 8 Jul 2003 18:03:59 +0200 Subject: path module In-Reply-To: <87smphf43l.fsf@pobox.com>; from jjl@pobox.com on Tue, Jul 08, 2003 at 04:08:46PM +0100 References: <1057651068.5348.386.camel@lothlorien> <87smphf43l.fsf@pobox.com> Message-ID: <20030708180359.I6906@prim.han.de> John J. Lee wrote: > holger krekel writes: > [...] > > Recently, i also did some experimentation with "virtual-fs" features so > > that you can transparently access http/ftp/svn files/directories. I even > > got that to work with "-completion" but that was quite a hack :-) > [...] > > Note that this overlaps a bit with urllib and urllib2. Just something > that would need thinking about. sure, i used *urllib* under the hood :-) holger From owski at hotmail.com Mon Jul 14 19:38:56 2003 From: owski at hotmail.com (Adam Ruth) Date: Mon, 14 Jul 2003 23:38:56 +0000 (UTC) Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: <20030714173855120-0600@news.xmission.com> In Stephen Horne wrote: > On 14 Jul 2003 10:30:22 -0400, aahz at pythoncraft.com (Aahz) wrote: > >>In article <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv at 4ax.com>, >>Stephen Horne wrote: >>> >>>C++ has precisely one type of variable. That variable is a >>>placeholder for a value of a datatype which is specified in the >>>declaration. The datatype may be a pointer datatype, but so what? >>>Pointer datatypes are not treated any differently than other datatype >>>except that they, like all datatypes, they have their own set of >>>functionality. >> >>Really? I would argue that the differing syntaxes is an argument >>against a single type of variable. What happens with this: >> >>char a; >>a->b; > > To answer this, I simply have to restore the quote you deleted... > >: On 13 Jul 2003 21:03:59 -0700, owski at hotmail.com (Adam Ruth) wrote: >: >: >I don't see the arbitrary change. Python has one type of variable: >: >A pointer that cannot itself be dereferenced. It's much more >: >consistent then having 3 types of variables (in C++). > > This is not referring to data types - there are far more than three > data types in C++. It is referring to whether something is a pointer > or a reference or not. The mistake in Adams post simply being that > these are simply datatypes. > > You will note that even in my words, I tried to keep the distinction > clear by using the word 'datatypes' when I was referring to datatypes. > > In fact, lets look back at my first two scentences in your quote of my > reply. > >>>C++ has precisely one type of variable. That variable is a >>>placeholder for a value of a datatype which is specified in the >>>declaration. > > One *type* of variable, which is associated with its own *datatype*. > > I find it hard to see how you could confuse this, but given my own > mistakes - well, we're all human I suppose. So, then, what makes a different variable type? If not different syntax and semantics, what would be the signature? Let me see if I understand what you're saying. Even though C++ variables can have different syntax and semantics (depending sometimes on context), the're all really the same internally and are therefore perfectly consistent and usable. Python variables, on the other hand ( mutable and immutable) have somewhat different semantics (a debatable point) but identical implementaions (indeed, indistinguishable), but are somehow invalid? You say that there is one gold standard definition for what a variable is. Yet even though C++ deals with variables in three semantically distinct way, they are somehow all valid within that definition? Adam Ruth From alanmk at hotmail.com Wed Jul 23 08:21:15 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 23 Jul 2003 13:21:15 +0100 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> <2259b0e2.0307220744.156c95bf@posting.google.com> Message-ID: <3F1E7DBB.B8D97257@hotmail.com> Daniel Dittmar wrote: > It shouldn't be too difficult to write an iterator wrapper class > that does exactly what you want (not tested): > > class IteratorWrapper: > def __init__ (self, iterArg): > iterArg = iter (iterArg) > try: > self.firstElement = iterArg.next () > self.isEmpty = false > self.next = self.returnFirstElement > self.baseIter = iterArg > except StopIteration: > self.isEmpty = true > self.next = self.throwStopIteration > > def returnFirstElement (self): > self.next = self.baseIter.next > return self.firstElement > > def throwStopIteration (self): > throw StopIteration ^^^^^ Ahem, cough, I think, em, maybe you mean "raise"? That java stuff polluting your mind, eh? ;-) As an aside, I've got to hand it to Java for exception handling. Java was the language that taught me how to do proper and robust exception handling, by "rapping my knuckles" continually, and actually making me think about the exception hierarchies I was generating and processing. You can't just randomly define and generate new exceptions: you have to change your method definition to declare that it can throw the new exception. Which means you either have to handle the exception in the calling method, or change *that* method signature to permit re-throwing of the exception, and so on up the hierarchy. It's not very pythonic though. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From duncan at NOSPAMrcp.co.uk Tue Jul 15 10:24:45 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 15 Jul 2003 14:24:45 +0000 (UTC) Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> Message-ID: "Colin S. Miller" wrote in news:4701fb.8co.ln at 195.171.216.1: >> Matthew 25:35 I was a stranger, and you took me in. > Care to enlighten us with the second meaning? > I'm a native English speaker, but can only see one meaning > 'I was unknown to you, yet you let me stay in your house' > Although 'took me in' could also mean 'accept as a friend' To "take someone in" means to trick or deceive them. >From http://www.chambersharrap.co.uk/chambers/chref/chref.py/main?query=take&tit le=21st (Must be a good dictionary if they use Python): take someone in 1 to include them. 2 to give them accommodation or shelter. 3 to deceive or cheat them. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From max at alcyone.com Thu Jul 24 22:57:44 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 24 Jul 2003 19:57:44 -0700 Subject: file.close() References: Message-ID: <3F209CA8.C694BBAF@alcyone.com> Bryan wrote: > you are correct this is so awesome... at least for me it is... now i > remove > a lot of my clutter too :) i just did some tests on windows by > trying to > delete file1 at the command prompt when raw_input is called. You don't have to use so circuitous a mechanism, just define a custom class with a __del__ method: >>> class C: ... def __del__(self): print 'C.__del__' ... >>> c = C() >>> del c C.__del__ >>> def f(): ... C() ... >>> f() C.__del__ >>> def g(): ... c = C() ... >>> g() C.__del__ > can you explain to me how the file gets closed? i'm sure that garbage > collection hasn't happed at the point that i call raw_input. it must > have > something to do with the reference count of the file object. does > python > immediately call close for you when the reference count goes to zero? > i > want the dirty details... Yes, the CPython implementation destructs objects as soon as the reference count goes to zero. In the latter three cases, you're not explicitly closing the file, but the file object has its last reference removed (either by explicit deletion or by going out of scope in a local block), and so the file is getting closed. You would see different behavior in Jython, for instance, which since it is implemented in Java, uses Java's rules for finalization (namely that it is not specified in how timely a manner finalization occurs). Python the language -- a bigger concept than either CPython or Jython -- leaves it unspecified when objects are destructed. It is _never_ a bad idea to explicitly close files, or explicitly shut down any access to important physical resources. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ War is the province of chance. \__/ Karl von Clausewitz From adsr at poczta.onet.pl Thu Jul 31 04:52:41 2003 From: adsr at poczta.onet.pl (AdSR) Date: 31 Jul 2003 01:52:41 -0700 Subject: Python2.3 and MySQLdb on Windows References: Message-ID: <422a840f.0307310052.501f7c14@posting.google.com> "Mike M" wrote... > Python2.3 and MySQLdb don't seem to work together on Windows. If I > understand the error message correctly, the problem seems to be that the > _mysql binary expects version 2.2 of the Python dll. Does anyone know of a > fix for this, or when a Windows version that works with 2.3 will be > available? >From SF.net support requests tracker: """ Date: 2003-07-30 22:01 Sender: adustman Logged In: YES user_id=71372 The CVS version is compatible now. I hope to have a full release done in the next couple weeks. Windows packages are another question entirely. I can't make these myself, and am not really inclined to anyway. So one will be available when someone (other than me) makes one and lets me know about it. """ Windows installers for Python 2.1 and 2.2 were provided by Gerhard H?ring, let's ask him nicely to do the same for 2.3. Cheers, AdSR From owski at hotmail.com Wed Jul 16 15:25:01 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 19:25:01 +0000 (UTC) Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: <20030716132455272-0600@news.xmission.com> In <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com> Doug Tolton wrote: > I have a function that returns a tuple: > > def checkdoc(self, document): > blen = document['length'] > bates = document['obates'] > > normal, truncated, semicolon = 0,0,0 > for bat in bates: > if len(bat) == 2 * blen: > semicolon += 1 > if len(bat) == blen - 1: > truncated += 1 > if len(bat) == blen: > normal += 1 > > return normal, truncated, semicolon > > on the other side I have 3 variables: > normal, truncated and semicolon > > I would like to be able to do an augmented assignment such as: > > normal, truncated, semicol += self.checkdoc(mydoc) > > however this returns the following error: > SyntaxError: augmented assign to tuple not possible > > I did some reading and it seems that an augmented assignment is > specifically verboten on tuples and lists. Is there a clean way to > accomplish this? I dislike in the extreme what I've resorted to: > > fnormal, ftruncated, fsemicolon = 0,0,0 > > // loop through a file and process all documents: > normal, truncated, semicolon = self.checkdoc(curdoc) > fnormal += normal > ftruncated += truncated > fsemicolon += semicolon > > This solution strikes me as inelegant and ugly. Is there a cleaner > way of accomplishing this? > > Thanks in advance, > Doug Tolton > dougt atcasedata dot com > I don't think it's all that inelegant, and it's definitely clear. I can see, though, why a one liner would seem a little cleaner. Off the top of my head, I'd say to change your checkdoc function to this: > def checkdoc(self, document, normal=0, truncated=0, semicolon=0): > blen = document['length'] > bates = document['obates'] > for bat in bates: > if len(bat) == 2 * blen: > semicolon += 1 > if len(bat) == blen - 1: > truncated += 1 > if len(bat) == blen: > normal += 1 > > return normal, truncated, semicolon And then call it like this: > normal, truncated, semicolon = self.checkdoc(curdoc, normal, > truncated, semicolon) As a side note, I wouldn't have thought that the augmented assign would work the way you tried to use it. I would have thought that it would be analagous to the + operator and sequences: > x = [1,2,3] > y = [1,2,3] > x + y [1,2,3,1,2,3] So that the agumented form would be: > x = [1,2,3] > x += [1,2,3] [1,2,3,1,2,3] But I've never tried it before and didn't know that it didn't work with sequences. You learn something new every day. Adam Ruth From mal at lemburg.com Tue Jul 8 12:04:11 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 08 Jul 2003 18:04:11 +0200 Subject: mx odbc In-Reply-To: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> Message-ID: <3F0AEB7B.1000308@lemburg.com> Kim Petersen wrote: > Regarding ODBC usage in Python... > > it seems to me that there is a couple of ways to use odbc from python, > one of these is the MX version - now that one has a pretty steep licence > cost (imho). So now comes my question (from reading this group quite a > bit): > > - what is the basic reason for using MX versus the others? Having a maintained and actively supported ODBC interface which works on all major platforms, not just Windows ?! -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Jul 08 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2003-07-01: Released mxODBC.Zope.DA for FreeBSD 1.0.6 beta 1 From gcash at luncheonmeat.cfl.rr.com Tue Jul 29 21:58:07 2003 From: gcash at luncheonmeat.cfl.rr.com (gcash) Date: Wed, 30 Jul 2003 01:58:07 GMT Subject: win32: anybody used IE's OnNewWindow2 event?? Message-ID: OK, I've written a tool to do a bunch of Internet Explorer point&click using win32all, and it's been rather fun. I've run into a sticking point though... when I click some links, they open up a new window where they expect you to fill out a form, and when you submit it, it closes the window and forces the main screen to a new URL. Problem is, I can't find *ANY* way of getting control of that window, in order to fill out the form automatically. There's no data structure that seems to lead to other windows associated with a session. Some of the small windows I've simply dissected the code and used httplib to submit the form, then forced the URL navigation myself. However, some of the windows are rather nasty pieces of javascript that aren't amenable to this approach. There's supposed to be an event called "OnNewWindow2" called when a page opens a new window through javascript or a "target" parameter. It has 2 parameters: an object and a cancel flag. These seem to be "out" parameters, and I think you're supposed to whip up a new InternetExplorer.Application.1 and pass it back in the object parameter or set the cancel parameter to false. The new app object is then used for the new window. This event *does* get fired when it should, but both the arguments are "None". I can't figure out how to use this... can somebody help me out? I tried googling about this and got almost no hits. Does anyone have example code? I've also looked at the genpy-generated code, looking for some sort of handle on finding "child" subwindows (not frames, new top-level instances) Is there some trick I'm missing?? Given a link "target" name, can I find the instance of explorer (i.e. the "document" object) that's servicing that window? This is kicking my butt. -gc -- I've never tried emacs because I already _have_ an OS on this peecee. -- mikea at mikea.ath.cx (Mike Andrews) From ableier at axelero.hu Wed Jul 2 13:45:12 2003 From: ableier at axelero.hu (Attila Bleier) Date: 2 Jul 2003 10:45:12 -0700 Subject: My Big Dict. References: <20030702073735.40293ba2.christophe.delord@free.fr> Message-ID: <6d0c7d3b.0307020945.7ebbdffb@posting.google.com> "drs" wrote in message news:... > "Christophe Delord" wrote in message > news:20030702073735.40293ba2.christophe.delord at free.fr... > > Hello, > > > > On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote: > > > > > Greetings, > > > > > > (do excuse the possibly comical subject text) > > > > > > I need advice on how I can convert a text db into a dict. Here is an > > > example of what I need done. > > > > > > some example data lines in the text db goes as follows: > > > > > > CODE1!DATA1 DATA2, DATA3 > > > CODE2!DATA1, DATA2 DATA3 > > > > > > As you can see, the lines are dynamic and the data are not alike, they > > > change in permission values (but that's obvious in any similar > > > situation) > > > > > > Any idea on how I can convert 20,000+ lines of the above into the > > > following protocol for use in my code?: > > > > > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} > > > > > > > If your data is in a string you can use a regular expression to parse > > each line, then the findall method returns a list of tuples containing > > the key and the value of each item. Finally the dict class can turn this > > list into a dict. For example: > > and you can kill a fly with a sledgehammer. why not > > f = open('somefile.txt') > d = {} > l = f.readlines() > for i in l: > a,b = i.split('!') > d[a] = b.strip() > > or am i missing something obvious? (b/t/w the above parsed 20000+ lines on a > celeron 500 in less than a second.) > > -d Just a short notice, l=f.readlines() line is not needed at all. It is a bit more comprehensive to write for i in f.readlines(): instead - as l is not used elsewhere - it is only memory wasting.Not a big deal, but it is worth noticing. Using regexp to justify the line length, and # of exlamation marks etc - is not needed in most cases, I think - it is easier and faster to put the whole stuff into a try : except clause. I admit though that there are cases in which they might come in handy - in this case though, it seems to be an overkill. Attila From aahz at pythoncraft.com Wed Jul 16 16:54:19 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 Jul 2003 16:54:19 -0400 Subject: anything like C++ references? References: <3F149C69.7B990210@alcyone.com> <32cbhvkife283kggrn8btlql91eaitmka2@4ax.com> Message-ID: In article <32cbhvkife283kggrn8btlql91eaitmka2 at 4ax.com>, Stephen Horne wrote: >On Tue, 15 Jul 2003 17:29:29 -0700, Erik Max Francis >wrote: >> >>Python does _not_ have copy semantics, it has binding semantics. > >As you know, that's precisely what I see as a wart. Were you to stick with language that clearly agreed with that assertion, I'd spend a lot less time arguing with you. But you've been writing as if Python's binding semantics are a major design flaw, when in fact they're part of the core language philosophy. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From peter at engcorp.com Fri Jul 4 14:02:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 14:02:32 -0400 Subject: Python is a gem, you need to keep pushing it .... References: Message-ID: <3F05C138.687F5A06@engcorp.com> sismex01 at hebmex.com wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > Sent: Viernes, 04 de Julio de 2003 07:42 a.m. > > > > delphiro wrote: > > > > > [attribution removed... don't do that!] > > > > Python *is* great but lets not pretend that its a good > > > > fit for every problem. > > > > > > I doubt that (unless you develop hardware drivers). > > > > Are you saying that you think Python _is_ a good fit > > for every problem, excluding only hardware drivers? > > > > -Peter > > > > Seems like he is; in my experience Python has been flexible > enough to fit any problem I've tossed at it. As it has for me, but neither you nor I have thrown *every* problem at it, and the OP appears to be stating that he believes we would never find Python inadequate, no matter what we threw at it (exception hardware drivers again). As an example, one could argue that embedded systems are not merely "hardware drivers" (one could also argue that they are, but I do not), yet we've found Python suitable in only one of our embedded system products. -Peter From martin at v.loewis.de Tue Jul 29 00:39:16 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Jul 2003 06:39:16 +0200 Subject: minidom xml attribute creation References: Message-ID: "Nate Gelbard" writes: > Any ideas? Verify that you are running precisely the same software on both systems. In particular, print xml.dom.minidom.__file__. Regards, Martin From ben at dadsetan.com Wed Jul 9 02:40:31 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 09 Jul 2003 08:40:31 +0200 Subject: __eq__ and __ne__ In-Reply-To: References: <3F0AEC76.8080304@zope.com> <1057681289.2342.34.camel@slothrop.zope.com> Message-ID: Shane Hathaway wrote: > Jeremy Hylton wrote: > Actually, C++ generates a compiler error if you try to do that. (See > the attached program.) Java doesn't run into this because it has a > simpler interface: the only operator you can override is equals(). So > in this case, C++ is fully explicit and Java is fully implicit, while > Python makes a guess. If we can't make it implicit like Java, then it > seems preferable for Python to raise an exception, similar to C++, when > you use the != operator with an instance that implements __eq__ but not > __ne__. > > Shane > +1 would be probably very helpful The only problem I see is that it would break "perlish" code (code you would not understand the behaviour of 3 weeks later). Of course some code might never use the __ne__ of its "__eq__ overloaded class" and therefore lived happily so far, but it is dangerous code anyway. Regards, Ben. From llafba at gmx.net Tue Jul 8 05:17:37 2003 From: llafba at gmx.net (Tom) Date: Tue, 08 Jul 2003 11:17:37 +0200 Subject: start script automatically Message-ID: Hi, I have a problem because I don't know how to start my script automatically after a special event happens. In detail: I store data from a PLC. Every 30 seconds the data is stored in a new file. After the file is stored I would like to start my script that analyzes the data right away. Any help how to do this is deeply appreciated. Thank you very much in advance. Regards, Tom From trp at smyrncable.net Wed Jul 2 08:20:20 2003 From: trp at smyrncable.net (trp) Date: Wed, 02 Jul 2003 08:20:20 -0400 Subject: splitting a string into 2 new strings References: Message-ID: Mark Light wrote: > Hi, > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 > strings > 'C H O' and '6 12 6'. I have played with string.split() and the re module > - but can't quite get there. > > Any help would be greatly appreciated. > > Thanks, > > Mark. I'm, assuming that these are chemical compounds, so you're not limited to one-character symbols. Here's how I'd do it import re re_pat = re.compile('([A-Z]+)(\d+)') text = 'C6 H12 O6' # find each component, returns list of tuples (e.g. [('C', '6'), ...] component = re_pat.findall(text) #split into separate lists symbols, counts = zip(*component) # create the strings symbols = ' '.join(symbols) counts = ' '.join(counts) --Andy From st.brodowski at eucrea.com Fri Jul 11 02:20:51 2003 From: st.brodowski at eucrea.com (Steffen Brodowski) Date: 10 Jul 2003 23:20:51 -0700 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> <381a2b17.0307090622.2e22a716@posting.google.com> Message-ID: <381a2b17.0307102220.3b048352@posting.google.com> Hi Ian, > from cStringIO import StringIO > def CreateBarcode(...): > # create image object > output = StringIO() > image.save(output, 'GIF') > return output.getvalue() Yes, it works! Thank you!! Steffen Brodowski From skip at pobox.com Thu Jul 31 14:47:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 13:47:50 -0500 Subject: Python's biggest compromises In-Reply-To: <899f842.0307310555.56134f71@posting.google.com> References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <16169.25686.954375.649811@montanaro.dyndns.org> Anthony> What to you think python largest compromises are? Anthony> The three that come to my mind are significant whitespace, Anthony> dynamic typing, and that it is interpreted - not compiled. Anthony> These three put python under fire and cause some large projects Anthony> to move off python or relegate it to prototyping. Your message is sure to get the pot boiling. I don't think of any of the above as compromises. They were all design decisions. Considering the whitespace issue, calling it a compromise suggests that Guido had to cave in to some outside forces. He couldn't decide between BEGIN/END or {/} as block delimiters, so he chose significant whitespace. It doesn't make sense. Anthony> What about immutable strings? I'm not sure I understand Guido's Anthony> preference for them. Performance is one reason. The Python interpreter creates a huge number of strings at runtime. Knowing exactly how long the string is going to be and that it will not grow means that a single malloc can be used to allocate the object header and the storage for the data. If strings were mutable, the structure of the string object storage would probably be much different and you'd need at minimum two mallocs per string, one for the object header and one for the data itself. Skip From ianb at colorstudy.com Thu Jul 10 22:58:38 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Jul 2003 21:58:38 -0500 Subject: Securing 'pickle' In-Reply-To: <3F0E1875.574DC6D7@alcyone.com> References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> Message-ID: <1057892317.3737.1356.camel@lothlorien> On Thu, 2003-07-10 at 20:52, Erik Max Francis wrote: > > Because now you need a mechanism to store the session info on the > > server, and you might want it to work across multiple load-balanced > > servers that fail over to one another, etc. > > That's far superior to presenting the opportunity to exploits in the > first place, in my opinion. Depending on the contents of the contents > of that cookie, what you suggest may not be a problem at all (depending > on how critical the data contained therein is). Security isn't a big deal -- or rather, securing cookies isn't a big deal. I think reliability will be a bigger problem. Cookies can cause problems even when you are just storing a simple session ID. If you start storing more information you're likely to run up against other problems -- cookies can be hard to dispose of, who knows where they'll get chopped off to preserve storage (it happens quickly), and IE has a bug where you can't redirect and set a cookie at the same time, which can really drive you crazy if you don't know about it. Hidden fields are a much better way of keeping information on the client. They tend to make for more navigable pages too. But if you really want session, not transaction data, then you just need to figure out server-side sessions. The biggest advantage of a web application is that it runs in a controlled environment (the server) and you should take advantage of that. Ian From FBatista at uniFON.com.ar Tue Jul 15 17:03:07 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 15 Jul 2003 18:03:07 -0300 Subject: String Manipulation Message-ID: >>> orig = "aaa/bbb/ccc/dd" >>> orig.split('/')[orig.count('/')] 'dd' >>> . Facundo #- -----Mensaje original----- #- De: lamar_air at hotmail.com [mailto:lamar_air at hotmail.com] #- Enviado el: Martes 15 de Julio de 2003 5:23 PM #- Para: python-list at python.org #- Asunto: String Manipulation #- #- #- I need a piece of code that takes a string like this string1 = #- "aaa/bbb/ccc/dd" and extracts a string containting the #- character after #- the last "/" #- #- So for this example the result would be "dd" #- #- like this: #- for i=0; string1.right(i) != '/'; i++ #- #- result = string1.mid(i, string1.length()) #- #- but in python. #- -- #- http://mail.python.org/mailman/listinfo/python-list #- From simonb at webone.com.au Tue Jul 29 18:58:55 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 30 Jul 2003 08:58:55 +1000 Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> Message-ID: On Wed, 30 Jul 2003 08:31:47 +1000, Simon Burton wrote: > On Tue, 29 Jul 2003 22:06:20 +0000, Raymond Hettinger wrote: > >> "David C. Fox" wrote in message >> news:9sBVa.12998$o%2.6289 at sccrnsc02... >>> Is there a function which takes a list of tuples and returns a list of >>> lists made up of the first element of each tuple, the second element of >>> each tuple, etc.? >>> >>> In other words, the the inverse of the built-in zip function? >> >> When used with the * operator, zip() is its own inverse: >> OK, i think i see now. it's swapping rows<->columns, and might help this other guy with his gridcontrols. But zip() should return (). No? Simon. From bart.NOSPAM.de.waal at quicknet.nl Tue Jul 1 16:08:18 2003 From: bart.NOSPAM.de.waal at quicknet.nl (bart) Date: Tue, 01 Jul 2003 22:08:18 +0200 Subject: placing text at point on console Message-ID: <1057090010.408280@cache2> I'm trying to place text at a certain point on the console. But I can't figure out any way to do this. For instance place a '@' at point 6,8. Any hints? (I'm trying to display a 'map'. Think nethack) Thanks, Bart From aahz at pythoncraft.com Mon Jul 7 09:44:20 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2003 09:44:20 -0400 Subject: Python vs PHP References: Message-ID: In article , Catalin wrote: > >Can Python replace PHP? >Can I use a python program to make an interface to a mysql 4.X database? The short answer is "yes" to both questions, but with a caveat: Python is a general-purpose programming language, where PHP is designed to write web applications. So it's not quite as simple/straightforward to use Python the same way you use PHP for plain web pages; conversely, if you've been running into difficulty with PHP in trying to write complicated program logic, you'll find Python a big help. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From detlev at die-offenbachs.de Sun Jul 27 13:20:40 2003 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 27 Jul 2003 19:20:40 +0200 Subject: eric3, pyqt, qscintilla - guru needed. References: Message-ID: reh wrote: > reh wrote: > >> Have installed on Redhat 9.0 in the following order; >> >> Qscintilla >> sip >> PyQt >> >> When I install eric3 (python install.py), I get this error; >> Sorry, please install QScintilla and/or reinstall >> PyQt with QScintilla support. >> >> It seems the errors occurs in the install.py file at: >> from qtext import QextScintilla >> >> From qtext.py, I have typed in at the python prompt; >> >>> import libsip # ok here >> >>> from qt import QWidet # ok here >> >>> from qt import QObject # ok here >> >>> from qt import QPrinter # ok here >> >>> import libqtextc # error here >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: libqscintilla.so.2: cannot open shared object file: No >> such >> file or directory >> >>> >> >> Been through all readme files, tried just about everything. >> Anyone have an idea what's wrong. >> > Forgot to say that the libqscintilla.so.2 is in; > /usr/lib/qt-3.1/lib > and the same path is in my /etc/ld.so.conf Did you do a "ldconfig" after the installation of qscintilla? Detlev -- Detlev Offenbach detlev at die-offenbachs.de From gumuz at looze.net Thu Jul 3 11:33:37 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 3 Jul 2003 17:33:37 +0200 Subject: Python Code Snippets References: Message-ID: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> You're gonna love this :) http://aspn.activestate.com/ASPN/Cookbook/Python "Aur?lien G?ron" wrote in message news:be1hs0$111s$1 at biggoron.nerim.net... > Hi, > > Does anyone know where I can find a lot of Python code snippets? > > I searched the Python wiki and Internet but could not find more than five or > ten code snippets at a time. > > I'm looking for a kind of organized list (GUI snippets, database access > snippets, I/O snippets, etc.). I find that there's no better way to learn a > language than to be able to cut&paste actual working bits of code. > > Thanks, > Aur?lien > > From dreed at capital.edu Wed Jul 2 18:34:35 2003 From: dreed at capital.edu (Dave Reed) Date: Wed, 2 Jul 2003 18:34:35 -0400 Subject: python 2.3b[12] Message-ID: <200307021834.35914.dreed@capital.edu> I originally tried compiling python 2.3b1 on a Solaris 9 system with --enable-shared and ran into some problems that someone helped me resolve and said fixes were in CVS. I thien tried python 2.3b2 and it compiled fine so the fixes made it in; however, it reports: ./python Python 2.3b1 (#1, Jun 14 2003, 15:08:24) [GCC 3.2.3] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> I thought maybe this was just someone forgetting to update the startup message for the new beta, but I've seen other messages that show Python 2.3b2. Any ideas on what happened? Dave From brian at sweetapp.com Sat Jul 12 18:45:03 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 12 Jul 2003 15:45:03 -0700 Subject: anything like C++ references? In-Reply-To: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <000301c348c7$3c501980$21795418@dell1700> > void change(int& i) > { > i++; > } The idiomatic way to write this code in python would be: def change(val): return val + 1 If you don't want to write it this way for some reason, you will have to explain why. Cheers, Brian From bokr at oz.net Tue Jul 15 16:32:30 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2003 20:32:30 GMT Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: On Tue, 15 Jul 2003 02:40:27 +0100, Stephen Horne wrote: >On Mon, 14 Jul 2003 00:07:44 -0700, Erik Max Francis >wrote: > >>Stephen Horne wrote: >> >>> Imagine, for instance, changing all assignments and other 'copying' to >>> use a copy-on-write system. Then add a pointer type and a 'newcopyof' >>> operator. And nick the C-style prefix '*' for dereferencing and add >>> '&' as a 'make a pointer to this object' operator (absolutely NOT a >>> physical memory address). >> >>The problem is that this misses the point that Python is not C++. You >>shouldn't try grafting syntaxes and approaches that make Python look >>more like C++, you should be learning to use Python on its own merits. > >Not true. > >If you eliminate all violations of the idea of variables bound to >values (basically the whole point of my thread), then mutable >containers cannot achieve the same thing. > >If a copy-on-write scheme is added to Python, you'd get the following >results from using mutable containers... > >>>> a = [1, 2, 3] >>>> b = a >>>> b[2] = 4 >>>> a >[1, 2, 3] >>>> b >[1, 2, 4] > Yes, but it would be hugely inefficient for the case where, e.g., you are modifying lines read from a 20MB log file. Imagine inducing a 20MB copy every time you wanted to delete or modify a line. Now you have to invent a way to program around what can be done very conveniently and efficiently thanks to Python's semantics. When you actually want a copy, just make one. There is syntax for that: >>> a = [1, 2, 3] >>> b = a[:] >>> b[2] = 4 >>> a [1, 2, 3] >>> b [1, 2, 4] >That is, mutability of the list object could be used to conveniently >and efficiently rebind the variable b (in this case to the value [1, >2, 4]) but that doesn't implicitly rebind the variable a which has >nothing to do with this assignment. In the implementation, Python it's not a variable in your sense, it's an alias. >would create a copy of the object bound to [1, 2, 3] just in time to >apply the change that object, without affecting the object that a is >bound to. > >Efficient, and it implements the variable-bound-to-value concept. Hugely inefficient, whether by brute force copying or by storing complex everything-but-this-and-with-that-mod dumb-pointer kludges to try to avoid bulk copying. > >Having done this, there would be a need for a way of indirectly >referencing objects. You wouldn't be able to abuse containers for this >goal. Pointers are the logical way to achieve the goal of indirect >referencing - they don't need to be associated with a type of >container which may have nothing to do with the problem, and they can >be used to reference *any* type of object. > >>Or, to put it another way, if you want to program in C++, why not use >>C++? > >I don't want to program in C++ (though sadly I have to). > >The concept of a pointer as an indirect way of referencing an object, >however, is useful. It isn't just a C++ concept. It is a widely used >concept from many languages which has gone out of fashion, mainly >because of the low level detail of how pointers are implemented in >languages such as C++ (ie simple store addresses). Ok, and Python makes major use of "indirect way[s] of referencing an object." Just not quite the way you have in mind ;-) > >I don't want the C++ bug-prone implementation of pointers. I want >something which allows indirect referencing of objects in a logical >and safe, high level way - and something which doesn't require the >language to break the principle of variables bound to values. > Python doesn't break that. Python deals in aliases, not your "variables." >The fact that pointers are generally useful can be seen in the regular >abuse of single item lists to fake the functionality of pointers. > That is a valid point, but the solution is not wholesale change of semantics followed by special syntax to allow us to do what we are already doing. In a past post I suggested using := as an update operator, which would allow you to write def foo(x): x:=123 and have foo(z) cause z to be updated with 123 -- if it was an updatable object. And updatable objects would have a __update__ method, so that x:=123 would be equivalent to x.__update__(123). (I called it __update__ rather than e.g. __setval__ because it is not a value replacement operation in general). I've also floated the idea of being able to create what might be called bound properties. I.e., something that looks like a plain x but acts like some_class_instance.x where x is a property of that class. I.e., when you assign to it, it calls the setter function and when you use it in an expression it calls the getter function. Something like you can do (on the read side) with parameterless functions in Pascal (IIRC). But that is a lot of change to be able to write x instead of o.x ;-) Hm, if there were a name space where name bindings would work the way you want, would that make you happy? I.e., where you could write ns.a = [1, 2, 3] ns.b = ns.a ns.b[2] = 4 ns.a ns.b Here's a start: >>> class NSHorne(object): ... from cPickle import dumps, loads ... def __setattr__(self, name, val): ... object.__setattr__(self, name, self.loads(self.dumps(val))) ... >>> ns = NSHorne() >>> ns.a = [1, 2, 3] >>> ns.b = ns.a >>> ns.b[2] = 4 >>> ns.a [1, 2, 3] >>> ns.b [1, 2, 4] >If people are routinely faking the abstraction, maybe that is because >it is a useful abstraction to have. Maybe it would be better to >support it explicitly instead of forcing people to use tricks and >hacks. Or maybe it can be solved short of creating a whole new language ;-) Regards, Bengt Richter From nagylzs at freemail.hu Wed Jul 9 08:17:58 2003 From: nagylzs at freemail.hu (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Wed, 09 Jul 2003 14:17:58 +0200 Subject: copy list, which way is best? /style References: <3f0bfc4e$0$45185$65c69314@mercury.nildram.net> Message-ID: <3F0C07F6.50606@freemail.hu> > > > >from copy import copy >l2 = copy(l1) > >or > >from copy import deepcopy >l2 = deepcopy(l1) > >I don't know what the difference is, if any, but I think this way is more readable. > The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): * A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. * A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. From intentionally at blank.co.uk Mon Jul 14 20:11:22 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 01:11:22 +0100 Subject: anything like C++ references? References: , <000301c348c7$3c501980$21795418@dell1700> Message-ID: On 14 Jul 2003 06:02:54 -0000, Moshe Zadka wrote: >On Sun, 13 Jul 2003, Stephen Horne wrote: > >> The problem is that you are confusing implementation with semantics. >> The meanings of 'variable', 'value', 'assignment' etc are defined by >> computer science. > >This is not just wrong, but as far as it is right, the semantics agree >with Python's :) >In computer science, the theoretical model one first learns is a turing >machine. Turing machines have no variables or values, merely tapes. While >I'm sure you can creatively translate the terms to turing machiens, this >exercise seems fairly pointless. Ram machines are similar. More abstract >models, like recursive functions, deal with integers only, so again you >would need hard to associate terms with them [you can implement a list >of integers with the p_1^n_1*....p_k^n_k, where p_1,...,p_k are distinct >primes. I'm not completely sure how this would translate to Python, though :)] Ever seen Euclids algorithm for the highest common factor? Euclid was around somewhat before turing. Algorithms are a mathematical concept. When you solve a quadratic equation by completing the square, you are applying an algorithm for instance. In maths, variables bind to values. Not to intermediate things that implement or represent values. How Python implements its binding of variables to values is its own business, but IMO if it merely binds variables to objects - and does not correctly implement binding to values using that mechanism - then it is behaving in a confusing and error-prone way. >However, computer science did have a minor notational revolution: Lisp. >Lisp was originally invented as an abstract way to express computations >in a more natural, and yet well-defined, way. The fact that lisp can be >*implemented* was somewhat of a shock, but it turned to be a fairly useful >language. Funny. From what I recall of Churches lambda calculus, variables bind to values. Changing the value bound to one variable does not change the value bound to any other variable. After all, why would Church worry about the details of implementation on a computer? He was a mathematician. His ideas were developed in the 1930s, IIRC - they weren't applied on computers until much later. Lisp was created as a way of implementing Churches lambda calculus. In doing so, some compromises were made due to the state of technology at the time. >[Note that in Lisp conses, for example, are actually mutable. However, >many functions treat them as immutable objects. This is perfectly fine, >and was a concious design decision in Lisp. Similarily, Python wouldn't >*need* tuples: they can be implemented as lists. The immutability allows >the implementation to play tricks with memory usage, though.] No - mutability allows the implementation to play tricks with memory usage. With immutables, Python binding of variables to objects correctly implements binding of variables to values. From martin at v.loewis.de Wed Jul 9 01:32:16 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jul 2003 07:32:16 +0200 Subject: Shared vs static link performance hit --and Windows? References: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> Message-ID: Andrew MacIntyre writes: > AFAIK, Windows & OS/2 don't really use the concept of PIC code for DLLs, > as the DLLs get mapped into system address space rather than user address > space, and all processes that access DLL code access the code at the same > address. Wrong, atleast for Win32. In Win32, there is no "system address space"; each process has its separate address space. Each DLL has a preferred load address, and it is linked to that address. If the dynamic loader can, at run-time, link the DLL to that address also, there won't be any relocations. If that address is already in use, the dynamic loader choses a different address, and they are not shared across address spaces anymore. For Python standard DLLs and PYDs, PC/dllbase_nt.txt lists the addresses that have been assigned for each DLL to avoid conflicts. For custom extension DLLs, most likely, the linker default is used, which will conflict with all other DLLs which don't use the /BASE linker flag, either. Regards, Martin From guettler at thomas-guettler.de Thu Jul 3 10:29:11 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 03 Jul 2003 16:29:11 +0200 Subject: Emacs + py-mode + tkinter problem References: Message-ID: Tom Locke wrote: > Hi All, > > I'm having trouble with the python shell within emacs. It's hanging when I > use tkinter. Setup is: > > Windows XP > emacs 21.3 > py-mode 4.6 > > Recipe: > From a python-mode buffer, launch the python shell (C-c !), then in the > shell Sorry, I don't know an answer since I only start the interactive prompt from a terminal. Since I am quite happy I would like to konw why you want the python interpreter in emacs? thomas From nirina at mail.blueline.mg Mon Jul 21 00:45:27 2003 From: nirina at mail.blueline.mg (Raseliarison nirinA) Date: Mon, 21 Jul 2003 07:45:27 +0300 Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: <00e701c34dd4$636d0340$f7a2383e@raseliar> Message-ID: <007301c34f43$6c9df440$f3a2383e@raseliar> the first attempt does not work well if the channels are not identical. here is a revisited version.it works with wave files supported by wave module i have two questions: - how to handle correctly the exceptions raised by wave, chunck and other modules? is there a 'right way' to do this? - Python seems to work fine when the '\' to pass a new line is missing. when the backslash ought to be used to break a long line in several one? best regards -- nirinA -- #-----stereo2mono.py revisited---------- '''stereo2mono.py convert recursively all stereo wave file to mono if both channels are identical http://www.faqts.com/knowledge_base/view.phtml/aid/12121/fid/538 usage : python stereo2mono.py wave_directory ''' import wave, os, sys FORMAT = {'11':'1b','12':'1h','21':'2b','22':'2h'} # format for wave files encoded in 8 and 16 bits SAMPLING = 128 class CompareError(Exception): def __init__(self, message): self.message = message class Stereo2Mono: '''open the wave file and get its parameters compare the channels it will be done in two steps. samples are first compared, then if the samples are identical further comparison is performed and the mono wave file created ''' def __init__(self, name): self.name = name self.w = wave.open(self.name) def isStereo(self): if self.w.getnchannels() == 2: return 1 else: return 0 def format_in(self): self.fmt = ''.join((str(self.w.getnchannels()), str(self.w.getsampwidth()))) return FORMAT.get(self.fmt) def format_out(self): self.fmt = ''.join(('1', str(self.w.getsampwidth()))) return FORMAT.get(self.fmt) def Parameters(self): return self.w.getparams() def Compare(self, amplitude): if amplitude[0] == amplitude[1]: return 1 else: return 0 def CompareSampling(self): for i in range(1, self.Parameters()[3],SAMPLING): if self.Compare(wave.struct.unpack( self.format_in(),self.w.readframes(1))): pass else: raise CompareError('Test fail at %i!'%i) def CompareAndSave(self): '''Compare all and save to mono''' self.w.rewind() self.chars = '/-\\|' self.Save = wave.open(self.name.split('.')[0]+ '-mono'+'.wav','w') self.newparams = (1, self.Parameters()[1], self.Parameters()[2], self.Parameters()[3], self.Parameters()[4], self.Parameters()[5]) self.Save.setparams(self.newparams) for i in range(1, self.Parameters()[3]+1): self.UnPack = wave.struct.unpack( self.format_in(), self.w.readframes(1)) if self.Compare(self.UnPack) == 1: self.Save.writeframes(wave.struct.pack( self.format_out(), self.UnPack[0])) sys.stdout.write(chr(13)) sys.stdout.write('%s %i/%i ' % ( self.chars[i % 4], i, self.Parameters()[3])) sys.stdout.flush() else: raise CompareError('save fail at %i!'%i) self.w.close() self.Save.close() def main(): directory = sys.argv[1] os.chdir(directory) for name in os.listdir('.'): if name.lower().endswith('.wav'): try: print name w = Stereo2Mono(name) if w.isStereo(): try: w.CompareSampling() except CompareError, e: print 'channel not identical;', e.message else: w.CompareAndSave() print 'Done' else: print '%s already in mono'%name except wave.Error: print 'this wave file is not supported' print sys.exc_info()[1] else: pass if __name__ == '__main__': main() #nirinA From lamar_air at hotmail.com Tue Jul 15 11:43:02 2003 From: lamar_air at hotmail.com (lamar_air) Date: 15 Jul 2003 08:43:02 -0700 Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> <3F0D962E.23DA9F59@engcorp.com> <2c6431ab.0307110529.7a336f30@posting.google.com> <3F0EBFED.BB283660@engcorp.com> Message-ID: <2c6431ab.0307150743.7dd52f3f@posting.google.com> Peter Hansen wrote in message news:<3F0EBFED.BB283660 at engcorp.com>... > lamar_air wrote: > > > > Peter Hansen wrote in message news:<3F0D962E.23DA9F59 at engcorp.com>... > > > "Bartolom? Sintes Marco" wrote: > > > > > > > > I have a program that unzip some zip files. After unzipping them, > > > > I want to delete the zip files with os.remove, but I get this error: > > > > OSError: [Errno 13] Permission denied: .... > > > > > > Close the files properly after unzipping them, perhaps? If that > > > doesn't help, please specify operating system, and give details > > > on how you are unzipping. Is it using Python's zipfile module, > > > or some other method, and exactly how do you do it? > > > > I want to be able to delete a file on my C: drive through my python > > script. My script writes a file. So i want to delete the file if it > > already exists then write it. What's the best way to do this? > > Your question is still not clear, if it's the same as the original > question. Please read http://www.catb.org/~esr/faqs/smart-questions.html > for assistance in formulating your questions a little better. > > The simplest answer is that if *you* are creating the files, you > just open them with "w" mode (as in "f = open('filename', 'w')") > and it will automatically truncate the file if it already exists. > > Hoping that helps, > -Peter I am using this remove method and it works well as long as the file is there os.remove("C:\Inetpub\wwwroot\Cgi-bin\output.txt") If the file doesn't exist then i get an error that the file is not found. I want to stay away from using f2=open('C:\Inetpub\wwwroot\Cgi-bin\output.txt', 'w') so how can i check if the file exists first? From kent at NOSPAMspringfed.com Sat Jul 19 18:02:41 2003 From: kent at NOSPAMspringfed.com (Kent Tenney) Date: Sat, 19 Jul 2003 17:02:41 -0500 Subject: distutils.core not in Debian python2.2 package Message-ID: Howdy, I did; # apt-get install python2.2 # python Python 2.2.1 ... >>> then checked docutils out of CVS and did; docutils# python ./setup.py install ImportError: No module named distutils.core How do I install distutils? Thanks, Kent From paul at boddie.net Fri Jul 11 04:57:39 2003 From: paul at boddie.net (Paul Boddie) Date: 11 Jul 2003 01:57:39 -0700 Subject: Using xml.xpath question. References: Message-ID: <23891c90.0307110057.bbe91e3@posting.google.com> bvelkur at yahoo.com (0wl) wrote in message news:... > Hi, > > I am trying to get the value of child from > > xmlstr = """ DataType="String">Hellpppp""" > > using > doc=parseString(xmlstr) > nodeList = xml.xpath.Evaluate("/p:root/p:child/text()", doc) > > and am getting the following exception: > > xml.xpath.RuntimeException: Undefined namespace prefix: "p". The problem is that the XPath query engine doesn't know what the prefix "p" is, and it won't automatically deduce it from your XML document. In other words, the prefixes used in your query are effectively independent from those used in your document, although this does give you the luxury of changing either your query or your document without having to go through the other adjusting the prefixes to match. Try this: >>> c = xml.xpath.Context.Context(doc) >>> c.setNamespaces({"p" : "http://tempuri.org/string"}) This makes a context and then adds the definition of the prefix for the XPath query engine. I think xml.xpath.CreateContext(doc) may be more appropriate, but I always use the above style. Also, you could probably specify the prefix/namespace definitions in the Context constructor, but this is just as easy. >>> e = xml.xpath.Compile("/p:root/p:child/text()") I compile the expression in order to allow the context to be used. We need a context because there apparently isn't any way of specifying the prefix/namespace definitions directly in an Evaluate call. Therefore, we have to set up a context first to contain those definitions. >>> e.evaluate(c) [] Yes, it works! ;-) Paul From johnroth at ameritech.net Tue Jul 1 16:03:17 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 1 Jul 2003 16:03:17 -0400 Subject: function overloading References: Message-ID: "Simon Burton" wrote in message news:pan.2003.07.01.19.42.06.202399 at webone.com.au... > > I just wrote the following rediculous code. > What do people do when they need to overload like this? > > Simon. > > > > ###################################################### > # PIL stuff > > class Im: > def __init__(self,x,xx=None): > if xx is not None: > w,h = x,xx > im = Image.new("I",(w,h)) > elif type(x)==str: > filename = x > im = Image.open(filename) > else: > im = x > self.im = im > I'd subclass it. I see three classes here: class Image: def __init__(self, oldImage) class NewImage(Image): def __init__(self, height, width): class ImageFromDisk(Image): def __init__(self, fileName): The subclasses only override the __init__ method of the base class. An alternate method of dealing with the situation is to do lazy initialization. In other words, don't provide any parameters on the construction, and provide three different methods for initializing the resulting object. John Roth From skip at pobox.com Fri Jul 25 12:07:42 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Jul 2003 11:07:42 -0500 Subject: Python 2.3c2 In-Reply-To: References: Message-ID: <16161.21966.867278.657560@montanaro.dyndns.org> >>>>> "Doug" == the rev dharma roadkill writes: Doug> Just grabbed and tried it on Tru64 5.1A (hp/compaq alpha ES40): Doug> Looks good: Doug> make test gives: Doug> ............ Doug> 221 tests OK. Doug> 34 tests skipped: Doug> test_aepack test_al test_audioop test_bsddb test_bsddb3 test_bz2 Doug> test_cd test_cl test_curses test_dl test_email_codecs test_gdbm Doug> test_gl test_imageop test_imgfile test_linuxaudiodev test_locale Doug> test_macfs test_macostools test_mpz test_nis test_normalization Doug> test_ossaudiodev test_pep277 test_plistlib test_rgbimg Doug> test_scriptpackages test_socket_ssl test_socketserver Doug> test_sunaudiodev test_timeout test_urllibnet test_winreg Doug> test_winsound Doug> Ask someone to teach regrtest.py about which tests are Doug> expected to get skipped on osf1V5. Doug, Can you confirm that you anticipate those skips on osf1V5? If so, I'll the appropriate entry in regrtest.py. Also, assuming you're connected to a network, can you try: ./python Lib/test/regrtest.py -unetwork where you executed make test before? Thanks, Skip From theller at python.net Tue Jul 29 05:13:46 2003 From: theller at python.net (Thomas Heller) Date: Tue, 29 Jul 2003 11:13:46 +0200 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> Message-ID: Mark Hammond writes: > Giles Brown wrote: >> I'm feeling quite dumb this morning. >> I'm trying to build a COM server DLL using py2exe and it ain't >> working. > Does the sample server work for you? I have tested it with 2.2.2 and 2.3rc2, and win32all build 154 and 155. > Not too surprising seeing as it was checked in just days ago :) > >> Command line for registering dll: >> regsvr32 c:\pvcs\madeupname\model\dist\application.dll >> Result when I try to register dll: >> """DllRegisterServer in c:\pvcs\madeupname\model\dist\application.dll failed. >> Return code was: 0x80040201 >> """ > > This generally just means that there was a Python exception. As > regsvr is a GUI app, the exception is lost. You may like to add > "import win32traceutil" at the top of your script (see > win32traceutil.py for details) - or if that fails, at the top of > boot_com_servers.py. > >> I have tried an exe server, but this does not register either. > > Try an EXE server build with the console flag set. This should allow > you to see the exception without redirecting error output. > >> Also does anyone know what argument to use to get py2exe to build something >> other than "application.[dll/exe]". I thought 'output_base' as an argument >> to setup() would do it, but no joy. > > Can't recall - sorry. There is no such flag. I simply forgot to remove the commented-out 'output_base' option from the sample file. Thomas From ianb at colorstudy.com Thu Jul 31 15:16:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2003 14:16:46 -0500 Subject: Python's biggest compromises In-Reply-To: <899f842.0307310555.56134f71@posting.google.com> References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <1059679006.12753.337.camel@lothlorien> On Thu, 2003-07-31 at 08:55, Anthony_Barker wrote: > The three that come to my mind are significant whitespace, dynamic > typing, and that it is interpreted - not compiled. These three put > python under fire and cause some large projects to move off python or > relegate it to prototyping. I think these are valid as "compromises", not to be confused with flaws. These are all explicit choices, and ones for which the original justifications remain valid. A lot of stuff in Basic is simply flaws, or based on justifications that no longer apply to today's programming world. Anyway, I might add mine: the nature of modules as executed code is a compromise. That is, a module isn't a declaration, it's a program to be executed in its own namespace. When you import a module, you are executing the module then looking at the namespace. There are some advantages to this, particularly in the transparency of the implementation -- things don't always work the way you might want (e.g., circular imports), but it's usually not that hard to understand why (and often the way you want things to work has nasty gotchas that you wouldn't have thought of). It also opens up a lot of possibilities for dynamicism in class and function declaration, like doing this in the top level: if something: def func(x): ... else: def func(x): ... But it's a compromise, because it makes things more difficult as well. It's a *big* problem in any long-running process, where you may want to modify code underlying the system without rebuilding the entire state. Classes aren't declared, they are simply constructed, so by reloading a module all the persistent instances still exist and refer to the defunct class. You can modify classes at runtime, but this is different from simply rerunning the class definition. (A clever metaclass *could* make those equivalent, though... hmmm...) A related problem is that Python objects generally can accept any instance variable names, and names are not declared anywhere. Again, this makes it difficult to deal with long-lived objects. If you change the class so that all instances get a new attribute, old objects won't be updated. I'm thinking about both of these things in terms of Smalltalk, where they make tools possible that really add to the ease of developing in its environment. Not that I don't like the fun tricks Python lets you do. Prototype-like programming (as in Self) is very accessible in Python, and classes are only a suggestion not a dominant concept. So, it's a compromise. There are lots and lots of compromises in Python -- every aspect has pluses and minuses to it. Personally I like whitespace sensitivity well enough, but in the larger sense I think it probably was the wrong choice -- but that's based on how I weigh various benefits and problems, and other people will validly weigh them differently. Ian From alienoid at is.lg.ua Wed Jul 16 03:39:33 2003 From: alienoid at is.lg.ua (Ruslan Spivak) Date: Wed, 16 Jul 2003 10:39:33 +0300 Subject: hex check Message-ID: <3F150135.8030708@is.lg.ua> Hello. Does anybody have a hint how to check if input hex number is in correct hex format? Thanks in advance. Best regards, Ruslan From martin at v.loewis.de Thu Jul 17 19:14:30 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 18 Jul 2003 01:14:30 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3f172794$0$49102$e4fe514c@news.xs4all.nl> Message-ID: <3F172DD6.5050602@v.loewis.de> Irmen de Jong wrote: > Exactly, it renders perfectly okay for me (mozilla 1.4). > I wonder one thing: how did you type it in? The Greek one, I copied from the XML file that Alan sent: I did as he said. Save file to disk, open it in the browser. I then copied the characters from one browser window to another. For the umlauts, I just pressed the relevant characters on my German keyboard. For the Arabic, I copied some string from a web page (the demo page of worldnames.net). Notice that this is right-to-left, so don't be surprised if your cursor is on the left end of the text at the end of pasting. Just pressing the closing parenthesis will switch back to left-to-right mode. Regards, Martin From mis6 at pitt.edu Sun Jul 20 11:21:52 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Jul 2003 08:21:52 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> Message-ID: <2259b0e2.0307200721.16ef2ea1@posting.google.com> Oops! My mistake, I forgot the islice; it should be the=lambda pred,seq: list(itertools.islice(itertools.ifilter(pred,seq),0,1)) in such a way that we exit at the first hit, otherwise one could just use the standard "filter". not-yet-good-enough-with-itertools-but-improving-ly your's Michele From sismex01 at hebmex.com Tue Jul 1 17:19:07 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 1 Jul 2003 16:19:07 -0500 Subject: Suggesting for overloading the assign operator Message-ID: > From: rimbalaya at yahoo.com [mailto:rimbalaya at yahoo.com] > Sent: Martes, 01 de Julio de 2003 12:07 p.m. > > Well, what about the idea of providing another statement, the one I > proposed in the original post? > > '=' statement assigns type and value > ':=' statement assigns value only > > Rim > Probably the reason most prople on this list don't quite like these threads is that there's no *need* for this "value-assignment" operation. For one, how would you implement it for immutable data types? This ":=" statement you're talking about already exists for lists, you can do something like: A[:] = some_other_list Why? Because you're assigning to a slice of A (which happens to be the whole list) the contents of the second list. But, what about strings, for example? Or ints? Or longs, floats, complexes? These data types are not mutable, an int object like, for example, 123, cannot change it's value to some other value, like 124. It's created with that value and lives like that until destroyed, or the end of the program. Same goes for all those other immutable types mentioned above. Why would you need such an operation? Is there some unsurmountable programming problem that cannot be solved except by such a vile hack as an overloadable assignment operator? The existance of huge software projects already done in python (such as Zone, Yahoo, and others) tells me that the language really doesn't need it. Another question would be, why not tell us what you're trying to do (which most probably looks like a C++ algorith or something like that) and how can we help you turn it into a Python algorithm? Programming C++ in Python is difficult. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From Mike at kordik.net Fri Jul 4 23:41:12 2003 From: Mike at kordik.net (Mike) Date: Sat, 05 Jul 2003 03:41:12 GMT Subject: RTS/CTS and DTR/DTS control References: <3F060F8D.94E47DCD@engcorp.com> <3F064661.33614890@engcorp.com> <3F0646DE.6344484E@engcorp.com> Message-ID: WOW! Thanks! I do not exactly remember the timing either but I did it in Java so the timing can't be too tight. I got the X10 stuff last year and started to play with it in Java. I got busy with other things... well you know how it goes. Just this year I started using Linux and am looking for something fun, but useful, to do in Linux. I thought Python would be interesting to learn. I will look up the site you gave me. Again, thanks for the posts. You have been most helpful! I noticed that there are some X10 stuff already out there but I thought it would be fun to make my own. :-) Mike On Fri, 04 Jul 2003 23:32:46 -0400, Peter Hansen wrote: > Peter Hansen wrote: >> >> A quick search again with Google using TIOCMSET and TIOCM_CTS and a >> bunch of others finally led to this, which might be the best yet, and >> includes some constant definitions that might let you get something >> working, if this doesn't directly solve your problem: >> >> http://sparc.dnsalias.net/Python_stuff/PosixSerial.py > > Look at the main site... you might find something else of interest > there. > > -Peter From amk at amk.ca Tue Jul 15 21:04:02 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 15 Jul 2003 20:04:02 -0500 Subject: Curses module. References: Message-ID: On Tue, 15 Jul 2003 19:03:33 -0400, Alex wrote: > Traceback (most recent call last): > File "./curses3.py", line 15, in ? > curses.wrapper(newWindow()) > AttributeError: 'module' object has no attribute 'wrapper' Do you have a ./curses.py in the same directory as curses3.py? You might be importing your module instead of the standard library with that name. Try running python with the -v switch to confirm this. --amk From alanmk at hotmail.com Thu Jul 17 10:24:58 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 15:24:58 +0100 Subject: list() coercion References: Message-ID: <3F16B1BA.97793556@hotmail.com> Bob Gailer wrote: > I have just read the docs 2.2.5 Iterator Types. Unfortunately this page > seems to be written for someone who already understands the page. Is > there any other explanation or examples? Try A. M. Kuchling's "What's new in Python". http://www.python.org/doc/2.2.1/whatsnew/node4.html And if you want to look under the covers http://www.python.org/peps/pep-0234.html HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ianb at colorstudy.com Tue Jul 8 04:23:36 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 03:23:36 -0500 Subject: Image Streaming In-Reply-To: <381a2b17.0307072326.211c21b5@posting.google.com> References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: <1057652616.5348.390.camel@lothlorien> On Tue, 2003-07-08 at 02:26, Steffen Brodowski wrote: > Hello everyone, > > since one week, I'm programming with python. Its a realy interesting > tool. I wrote a script for generating barcodes in jpg-format. > Everything is ok, but my function "CreateBarcode" should write the jpg > data into an outstream. All barcodes will be generate online, without > saving the jpgs on harddisk. > > Can you give me a tip witch objects I need and how to put the jpg into > an outgoing stream? > > import Image, ImageDraw > def CreateBarcode(SourceString,Linewidth,WriteText): > blablabla > ... > NewImage = Image.new("L",NewSize,Backcolor) > ImgDraw = ImageDraw.Draw(NewImage) > .... > > #How to put the image into an stream? have that function return the image object. Then, assuming you are doing this in CGI (easily adapted if not), do something like (untested): import sys image = CreateBarCode(...) print 'Content-type: image/jpeg\n' image.save(sys.stdout, 'JPEG') Ian From jerf at jerf.org Wed Jul 2 21:14:44 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Jul 2003 01:14:44 GMT Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: On Wed, 02 Jul 2003 15:21:45 +0200, Aur?lien G?ron wrote: > I'd be interested to know about > projects where they automate unit tests for GUIs, but I suspect it would be > just as cumbersome. I'm doing one right now. It's designed from the ground up by me, so it's testable. It almost has to be, since it's fairly complicated and Needs To Work. For the record, I've found Tkinter does *great* with this, because you can drive the GUI without ever actually starting the event loop. It doesn't seem perfect but largely works, much better then it has any right to. wxPython doesn't work at all without an event loop, so I never did get it tested, which has contributed to me dropping it. ;-) (I'm gonna guess that never entered into anybody's head when they were designing toolkits...) > In all those cases, I much prefer having a human being go out and do the > unit tests manually. The thing is, they won't. We've got about 50 years of collective experience backing that up. From andrew-pythonlist at puzzling.org Wed Jul 2 05:48:33 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 2 Jul 2003 19:48:33 +1000 Subject: Good code patterns in Python In-Reply-To: <3f027b11$0$97204$edfadb0f@dread12.news.tele.dk> References: <3f027b11$0$97204$edfadb0f@dread12.news.tele.dk> Message-ID: <20030702094833.GD21059@frobozz> On Wed, Jul 02, 2003 at 08:28:28AM +0200, Max M wrote: [...] > > if some_condition: > some_name = some_value > else: > if some_exotic_condition: > some_name = third_value > else: > some_name = other_value > > > It would have been a simpler and less error prone procedure to change > the code if it it had used the first form. > > > some_name = other_value > if some_condition: > some_name = some_value > else: > if some_exotic_condition: > some_name = third_value For this specific example, I think I'd prefer: if some_condition: some_name = some_value elif some_exotic_condition: some_name = third_value else: some_name = other_value Regardless, I always feel uneasy about: x = some_val if cond: x = special_val I think it's the reassignment of 'x' here that bugs me -- conceptually, this code is setting x to a value depending on a certain condition, and so having to mentally trace through "it's set to val -- oh, no, now it isn't" is an unwelcome distraction, whereas: if cond: x = special_val else: x = some_val can be "read" more-or-less directly into English: "if the condition is true, then 'x' is set to 'special_val'; otherwise, 'x' is set to 'some_val'". Saying "'x' is set to 'some_val'. Now, if some condition is true, 'x' is set to 'special_val'" is counter-intuitive to my way of thinking. That said, I can readily recognise both idioms (despite having a slight preference for one form), so it's really a non-issue... it's-all-fun-and-games-until-someone-mentions-ternary-operators-ly yrs, Andrew. From rick_hunter357 at hotmail.com Mon Jul 28 20:44:13 2003 From: rick_hunter357 at hotmail.com (Rick) Date: 28 Jul 2003 17:44:13 -0700 Subject: Papers on Python Message-ID: <8b36138c.0307281644.f6569ea@posting.google.com> I have been given an assignment to collect 5 papers on Python and write a report on each of the papers. I went ahead and researched and collected 9 papers; all from the internet with most of them coming from the International Python Conference. But then I got thinking. What are the 5 (or 6 or 7 or 10) most seminal papers in the history of Python in the opinion of members of this newgroups? I might replace all or some of my papers from those suggested by the members on this newsgroup. -RH PS. Before someone starts on how college kids are using the internet (or the help available on the 'net) to do the work for them, No I am not cheating. The actual assignment is to select 9 papers that you find interesting and write a report on each of them. I already have my 9 papers selected. Now I want to know if I would like to replace some from my collection. From norproaj at yahoo.com Tue Jul 8 17:22:43 2003 From: norproaj at yahoo.com (Dianne Combs) Date: Tue, 8 Jul 2003 14:22:43 -0700 (PDT) Subject: Advocate Media/The Northeast Progressive Advocate Journal/San Francisco Bay Message-ID: <20030708212243.40985.qmail@web60001.mail.yahoo.com> Dear Online Reader or Editor ... If you could ... please take a look at our new online treeless edition newspapers, The Northeast Progressive Advocate-Journal and our sister newspaper the San Francisco Bay Gazette, which are produced exclusively by our joint staffs to serve the Northeast and West Coast areas - with additional non-mainline media perspective. News stories and columns are researched, thoughtful and blend politics with society, regional and local topics, etc. - in the tradition of the premier monthly magazines and the cosmopolitan newspapers. We do accept ads and subscription requests for online weekly e-mail links to the latest edition - so please take advantage of these services, provided your interest justifies it. Here are the following online links to the newspapers... www.norprogaj.com ... www.sfbaygazette.co-inc.com Again, if you feel its appropriate, please take advantage of our ad service - a competitive rate sheet is available upon request. Online subscription requests are also currently offered at $5.00 USD a month to help support our activities as truly progressive publications - committed to providing factual news and stories that just do not appear on the local or for that matter the national scene. We truly appreciate your time and let others know about it ... The Northeast Progressive Advocate-Journal. ... thanks again ... Walter Harry Combs, Editor-in-Chief Dianne Combs, Features Editor & Ads/Subscriptions Contact norproaj at yahoo.com or sfbaygazette at yahoo.com (9a-5p EDT - Phone) (518) 793-8501 (24/7 Fax/Phone-Voicemail) (360) 252-673 __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From andreas.kuntzagk at mdc-berlin.de Wed Jul 9 07:07:39 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 09 Jul 2003 13:07:39 +0200 Subject: copy list, which way is best? /style Message-ID: Hi, There are three ways to (shallow)copy a list l I'm aware of: >>> l2=list(l) >>> l2=l[:] >>> l2.copy.copy(l) Are there any differences? Are there more (reasonable) ways? I think the first is the most pythonic, second looks more like this other p-language and third requires an import, so I would prefer the first. Do you agree? Andreas From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jul 23 23:12:57 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Jul 2003 13:02:57 +0950 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: On Wed, 23 Jul 2003 20:29:27 -0700, Erik Max Francis wrote: > Bryan wrote: >> is what i'm doing is overkill? > > Use of external resources -- which should be released as soon as > you're done with them -- are best done in try/finally clauses. It seems that nesting the 'try' clauses doesn't scale well. What if fifty files are opened? Must the nesting level of the 'try' clauses be fifty also, to close them promptly? -- \ "God forbid that any book should be banned. The practice is as | `\ indefensible as infanticide." -- Dame Rebecca West | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From lol at lolmcNOSPAM.com Fri Jul 4 16:58:51 2003 From: lol at lolmcNOSPAM.com (Rogue 9) Date: Fri, 04 Jul 2003 21:58:51 +0100 Subject: Import statement help required by newbie please Message-ID: <3f05ea76@shknews01> Hi All, I have a small problem in a program I'm developing and could do with some guidance as to how I resolve it. The hierachy of my program is as follows: 1)The toplevel package is called oop_lb 2)Beneath oop_lb are 3 packages - analysis,process and tests oop_lb | | ------------------------------------------------------- | | | analysis process tests I am using the very excellent unittest module to help me to create a program that is as bug free as I can make it and the tests are as you cn guess in the tests package mentioned above. I have developed several modules which reside in the process package and succesfully created tests in the tests package which ensure the code does what I intended.When I moved on to the analysis package however,things went a bit wonky as the modules in this package called classes which resided in the process package and when using the import statements to make them available I found that either I could get the oop_lb module to run with one set of import statements but the tests I wrote would not recognise the modules from process in the import statements and produced the following type of error: Traceback (most recent call last): File "CalculateMedianTest.py", line 14, in ? import oop_lb.analysis.CalculateMedian File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 14, in ? from process import GetDraw ImportError: No module named process This occurs with the following import statement in the CalculateMedian.py module from process import GetDraw If I change this to import oop_lb.process.GetDraw then the test program will work but the oop_lb.py file fails with the following error Traceback (most recent call last): File "oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file File "/home/lol/disk/python/lotto/oop_lb/analysis/CalculateMedian.py", line 13, in ? import oop_lb.process.GetDraw File "/home/lol/disk/python/lotto/oop_lb/oop_lb.py", line 21, in ? from analysis import CalculateMedian # import class definition from file ImportError: cannot import name CalculateMedian So.....my problem is that I can't seem to find the proper way to import the modules to satisfy both the testing modules in the oop_lb.tests package and also allow oop_lb.py to run without import errors. I apologise for the length of the post and any ambiguities I may not have managed to clear up whilst proff reading this before posting. Thanks,Lol -- Remove NOSPAM from my email address to use it,please. From akineko at pacbell.net Tue Jul 8 00:50:49 2003 From: akineko at pacbell.net (Aki Niimura) Date: 7 Jul 2003 21:50:49 -0700 Subject: Accessing Web site contents from a Python script (with use of Cookie) Message-ID: Hello everyone, I have been trying to write a Python script to access a Web site. I'm currently having a problem completing my script because the contents I would like to access in the Web site is a dynamic content and it is generated based on the Cookie contents which are set in another page. url-a (setting Cookies) url-b (dynamic content based on the Cookie value) I'm using httplib.HTTPConnection() to first access the url-a to get other info (and Cookies in header). Then my script accesses the url-b but it doesn't work as no Cookie info is returned when the url-b is being accessed. The Cookie values vary time to time such that the script must obtain them from the url-a. Also, no expiration is set in the Cookies such that they are supposed to live only in browser not in Cookie files. Is there any way to handle the situation mentioned above? Any comments, any hints are highly appreciated. Best regards, Aki Niimura From skip at pobox.com Tue Jul 8 10:46:24 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 09:46:24 -0500 Subject: Python is a gem ,another successful day .... In-Reply-To: References: Message-ID: <16138.55616.369570.36950@montanaro.dyndns.org> Nick> * Who makes Python? A lot of the culture is still mired in the Nick> idea that a corporate entity is required for a product to be Nick> fully supported, or viable in the long term. I like to remind Nick> them how well Sun's stewardship has "served" the Java Nick> community, but I need more than negative counterexamples. Is Apache used by your organization? Nick> * Who provides training? I mean no disrespect to my coworkers, Nick> and present company is of course excluded, but a lot of the Nick> federal workforce has no incentive to learn on their Nick> own. Unless a training course is provided, with certifications Nick> and free tote bags, there is very little motivation for people Nick> to learn new technology. There are people (like Mark Lutz and Wesley Chun) and larger organizations (perhaps ActiveState?) who do Python training. Nick> * How do we deploy Python? Until we upgrade all the systems Nick> here to recent versions of Redhat Linux (joke!), installing a Nick> Python environment is an extra step. I can point out that Nick> finding an appropriate JRE is a worse nightmare, but as above, Nick> I need more than negative counterexamples. It should be a small extra step. If you can't use Sean Reifschneider's RPMs directly, you can probably build RPMs for your version of RH Linux using his spec files, then install that across your organization. Similarly, for Windows users the installer is easily run. Skip From tomas at fancy.org Sat Jul 12 17:00:49 2003 From: tomas at fancy.org (Tom Plunket) Date: Sat, 12 Jul 2003 14:00:49 -0700 Subject: any such thing as list interleaving? Message-ID: I find myself often doing the following sort of thing (sorry for lack of whitespace, I don't want the line to break): for entry, index in map(lambda e,i:(e,i),aList,range(len(aList)): # ... This definitely seems like a roundabout way to loop through parallel lists together. Is this map routine truly the easiest/ best/most straight-forward way to do a for loop through parallel lists, if I feel that the Python anti-idom of: for index in range(len(myList)): entry = aList(index) anotherEntry = anotherList(index) # ... ??? This also brings up a similar problem for me when iterating over dictionaries: for key in myDict: value = myDict[key] # ... This seems a pretty sloppy way to go about it, imo. There must be something more in the Python spirit! :) Thanks. -tom! From jdhunter at ace.bsd.uchicago.edu Mon Jul 7 12:12:51 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 07 Jul 2003 11:12:51 -0500 Subject: PDF Parser? In-Reply-To: <33803989.0307062318.3695d11@posting.google.com> (tebeka@cs.bgu.ac.il's message of "7 Jul 2003 00:18:48 -0700") References: <33803989.0307062318.3695d11@posting.google.com> Message-ID: >>>>> "Miki" == Miki Tebeka writes: Miki> Hello All, I'm looking for a PDF parser. Any pointers? A little more info would be helpful: do you need access to all the pdf structures or just the text? AFAIK, there is no full pdf parser in python. The subject has come up several times before, so check the google.groups archives http://groups.google.com/groups?q=pdf+parser+group%3A*python*&ie=UTF-8&oe=UTF-8&hl=en&btnG=Google+Search Things people have suggested before: 1) use pdftotext and parse the text 2) wrap xpdf's parser. For example, if you have pdftotext, the following will give you a python file-like handle to the source: def pdf2txt(fname): return os.popen('pdftotext -raw -ascii7 %s -' % fname) If you just want to search and index pdf, see http://pdfsearch.sourceforge.net. John Hunter From news at exultants.org Sat Jul 5 01:17:22 2003 From: news at exultants.org (Van Gale) Date: Sat, 05 Jul 2003 05:17:22 GMT Subject: Server Push In-Reply-To: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> References: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > John Bradbury wrote: > >> I want to send updates from a long running cgi. I have tried copying >> perl >> examples of server push and can not get them to work. >> Does anyone have an idiot proof example of a working server push or >> sending >> output in chunks in Python? > > to work). The other method is just flushing your output and > continue to write more data... I don't know the details, so this is hearsay, but there's another way apparently used by KnowNow (www.knownow.com) to implement a 2-way web interface. Each browser page has 3 frames, one of which is hidden and is receiving non-ending Javascript from the server (which apparently modifies a visible frame as it comes it comes in). This lets them do some slick things like auto-completion in web forms. (Apologies to John for not providing any actual help with this post :/) Van From adam6No_Spam_Please at speedy.co.il Fri Jul 25 18:12:45 2003 From: adam6No_Spam_Please at speedy.co.il (Adam) Date: Sat, 26 Jul 2003 00:12:45 +0200 Subject: Retrieving commands history on Pythonwin Message-ID: Hi I want to be able to retrieve (e.g. as a list) the commands history (i.e. previous commands issued) on the Pythonwin IDE. Any leads? Adam From staschuk at telusplanet.net Fri Jul 25 17:22:13 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 25 Jul 2003 15:22:13 -0600 Subject: Why does Python do this? In-Reply-To: ; from gre7g-d-1059579503.1d83b3@wolfhome.com on Fri, Jul 25, 2003 at 09:38:30AM -0600 References: Message-ID: <20030725152213.A205@tibia.amotlpaa.bogus> Quoth Gre7g Luterman: [...] > Python 2.2.2 (#3, Jun 16 2003, 19:11:56) [...] > >>> class b: > ... def __str__(self): > ... print "printed" > ... return "returned" [...] > >>> print y > printed > returned > > Note the extra space printed when I executed the "print y" command. I don't know why this happens in 2.2, but I observe that it doesn't in 2.3. Presumably some softspace fix has been made. > At first I thought it was just a quirk of the print command being > interrupted by another, but I don't think it is quite that simple. Note > that: [...] > >>> print str(y) > printed > returned [...] > So it only seems to happen when you interrupt a print statement with > another print statement during an implicit string conversion. Indeed -- because that's the only way to actually "interrupt" one print statement with another. Consider the bytecode: >>> def bar(x): ... print str(x) ... >>> dis.dis(bar) 2 0 LOAD_GLOBAL 0 (str) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE Here the "inner" print statement occurs during the function call (6), entirely before (hence not interrupting) the "outer" print statement (9). -- Steven Taschuk staschuk at telusplanet.net "[T]rue greatness is when your name is like ampere, watt, and fourier -- when it's spelled with a lower case letter." -- R.W. Hamming From postmaster at 127.0.0.1 Wed Jul 16 08:42:06 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Thu, 17 Jul 2003 00:42:06 +1200 Subject: Testers wanted - new Python DHTML framework References: Message-ID: On Wed, 16 Jul 2003 11:05:51 +0000, Moshe Zadka paused, took a deep breath, then came out with: > On Wed, 16 Jul 2003, David McNab wrote: > Have you demonstrated it? Did you give the documentation to someone, > and had him writing useful software? That's what I'm doing *now* in *pre-announcing* to this ng. > Or is this just an assumption > based on the fact that you find it easy to use, and did not have > to learn it? An assumption based on the fact that I used the same design style with which I've written other python software (for which I've received very positive feedback on its accessibility). I try hard to write my software in a way that doesn't force its user to contort his/her mind in umpteen weird directions to understand it. I don't think I'm alone in the fact that I don't like having to smell a programmer's dirty socks or analyse his pizza stains in order to understand how to use his code. >> - lets you build your pages with a simple, intuitive and coherent >> document object model (DOM) > > Is your DOM more simple, intuitive and coherent than minidom? microdom? > DOM is usually used in reference to the W3C standard. If you deviate > from the standard, it's probably best not to call what you have "DOM". I'm using Document Object Model in a generic sense, similar to how the word 'window' in a GUI sense doesn't always refer to M$ software. I'm a bit cynical about DOM standards anyway, given how the client-side DOMs between IE, Mozilla family, Konqueror and Opera etc are highly disparate, and writing portable Javascript is such a CATPITA. >> - extremely extensible > > Did you try to extend it, and are reporting success? Yes. One of the examples on the website (and the website which coughs up its own source code on request) both demonstrate this. > With two different > extension directions? What do you mean by this? What constitutes a 'direction'? Subclassing? >> , lends itself well to templating > > You mean each person has to implement templating on his own? Or does > it have a templating system? User implements his/her own templating. In that respect, pyWeb can be considered a bit more low-level than template-based systems. But for some, the freedom to roll their own (and be in full control, and hot have to conform to other people's abstractions) is a *good* thing. Thanks for your feedback, moshez, but please recall that this is a *pre*-announcement. The version is 0.1.0, not 1.0. I know it's not immediately serving you the moon on a plate with a sprig of parsely. But I feel you're jumping on it pretty hard, especially since I'm only asking for testers. It's not like I've made any kind of formal release announcement. >> - oersistent datastore that is stored on browser as compressed cookes. >> secured via hmac/sha1, can store 10-25k of data on browser. > > That probably depends on the browser. The standard states: > ''' > * at least 4096 bytes per cookie (as measured by the size of the > characters that comprise the cookie non-terminal in the syntax > description of the Set-Cookie header) When the persistent data object gets pickled, it gets broken up into cookies of max size 2048 bytes each. If there's more data, the pickle gets broken up into several cookies then reassembled at the next request. Apache seems to barf when the incoming 'Cookie:' header exceeds 8k, so this appears to be the driving constraint. > ''' > which means that cookies might get cut off or not stored at all by > the client. Correct. > You might be splitting the cookies off transparently, which > should let you go up to 80k, but would probably make the job of anyone > wanting to send his own cookies hard. My apache has an 8k limit on total size of all incoming cookies. If you use more persistent datastore, you've got less space for 'physical' cookies, and vice versa. That is the user's responsibility. However, thanks for your noises on this - makes me aware that I should add to the doco to explain these constraints to the user. BTW - the persistent data object supplements raw cookies, it doesn't take the place of them. The 'session' object contains a SimpleCookie instance, the use of which is explained in the doco. > The standard also says, however, > ''' > Applications should use as few and as small cookies as possible, and they > should cope gracefully with the loss of a cookie. > ''' > [All quotes are from http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2109.html] > >> Accessed in >> python code by simply reading and setting attributes of an object I leave it to the user (pyWeb programmer) to make their own decision on this. Similar to the fact that gcc could be used to write very insecure code, but that is not the fault of the compiler developer. > It also matters, probably, that you use a secure RNG generator for the > "secret" in the sha1/hmac schemes, otherwise a malicious client can still > force you to execute code. The 'secret' key gets chosen by the pyWeb programmer, with no prng involved. Granted, I should probably provide some scheme to make it easier for the user to supply their own hmac 'secret', and possibly even assist them in generating such. Finally, note that there is no support for back-end database. This is a deliberate decision, since it's targeted at people running their sites on budget web hosts. There are hordes of hosts that offer (mostly) great deals (eg CGI, 100MB storage, 10GB traffic) for around $5-$10/month. But a lot of these hosts only have python 1.5.2, with no MySQL interface module. If you look through the examples, you'll see one which uses the Metakit database engine (which can be uploaded in binary form to such hosts, and which runs fine). Cheers David From drs at ecp.cc Sat Jul 12 13:14:07 2003 From: drs at ecp.cc (drs) Date: Sat, 12 Jul 2003 17:14:07 GMT Subject: How do I have a client shutdown a win32 COM server? References: Message-ID: "Noah" wrote in message news:c9d82136.0307120847.4fdd12fa at posting.google.com... > Hi, > > How do I shutdown a win32 COM server? > can you just do a >>> del x ? From stacom at stacom-software.de Fri Jul 25 10:08:45 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Fri, 25 Jul 2003 16:08:45 +0200 Subject: data conversion question (binary string to 'real string') In-Reply-To: <3waUa.5$gZ.161@news.oracle.com> References: <3F212EB3.7020600@stacom-software.de> <3waUa.5$gZ.161@news.oracle.com> Message-ID: Manish Jethani wrote: > Alexander Eisenhuth wrote: > > >>This two lines converts 0.5 to a string in binary >>representation >> >> >>>from struct import * > > > from binascii import hexlify > > >> >>>bin_str = pack('!f', 0.5) >> >>now bin_str is '?\x00\x00\x00', wich is the representation >>of 0.5 in the memory. I need now to convert this binary >>string to "3F000000", where '3F' is the hex value of the '?' >>in ascii - table. >> >>Any ideas ?? > > > foo = hexlify(bin_str) > print foo > > -Manish > > PS: You posted the same message thrice, by mistake. > Thanks, that's it From milyon at wp.pl Wed Jul 9 10:20:47 2003 From: milyon at wp.pl (K) Date: Wed, 9 Jul 2003 16:20:47 +0200 Subject: Newbie - No module named stdwin Message-ID: hello All time all write programm's in Visual Basic but now i'm very excited and learn a Python so install 2.2.3 version... When i wanna open a window (like windows) i write inport stdwin stdwin.open ('my window') and i have ImportError: No module named stdwin Did i must install some package?? please help me From fperez528 at yahoo.com Tue Jul 8 13:06:55 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 08 Jul 2003 11:06:55 -0600 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: Steffen Brodowski wrote: > Hello everyone, > > since one week, I'm programming with python. Its a realy interesting > tool. I wrote a script for generating barcodes in jpg-format. > Everything is ok, but my function "CreateBarcode" should write the jpg > data into an outstream. All barcodes will be generate online, without > saving the jpgs on harddisk. Just a side comment: jpg is the absolutely worst possible format you could use for barcodes. jpg suffers from aliasing (see Gibbs phenomenon in any numerical analysis or Fourier series textbook), which you see as 'ringing shadows' around sharp black/white transitions. JPG was designed for smooth color, photographic images. It was a format designed to approach the exact opposite end of the image spectrum than a barcode is. For barcodes, use png, tiff or even gif (the patents expired recently). If this is just an exercise in learning python, then it doesn't matter. But if you care about the quality of your generated barcodes (or black/white images in general, such as scanned text), never use jpg for that. If you are for some reason absolutely forced to use jpeg, then use as high a 'quality factor' as you can afford. It will give you very large files, but at least the problems won't be as noticeable. Best, f. From skip at pobox.com Mon Jul 21 10:42:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 21 Jul 2003 09:42:29 -0500 Subject: "Pure Python" MySQL module like Net::MySQL In-Reply-To: <87fzl0q82k.fsf@pobox.com> References: <7xk7advy4c.fsf@ruckus.brouhaha.com> <87fzl0q82k.fsf@pobox.com> Message-ID: <16155.64469.927247.366272@montanaro.dyndns.org> I saw Paul's quote in John's reply. I've yet to see Paul's not. Hopefully I'm not taking anything out of context. Skip> libraries haven't been ported. On the other hand, the MySQL wire Skip> protocol is probably not part of the official external interface, Skip> so the author has to track changes to the protocol. Paul> What the heck? If the wire protocol isn't part of the official Paul> external interface, then how on earth are external applications Paul> supposed to talk to the database? By using the client library MySQL provides. As far as I can tell, the MySQL wire protocol is not documented in the current version of the manual (http://www.mysql.com/documentation/mysql/bychapter/). That suggests to me that the protocol is not part of the external interface, and anyone implementing it directly can't really complain if it changes. Skip From klapotec at chello.at Thu Jul 31 11:52:26 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 31 Jul 2003 15:52:26 GMT Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <3hdiivgqgrkn66caba8kop4matdnh20986@4ax.com> On 31 Jul 2003 06:55:52 -0700, anthony_barker at hotmail.com (Anthony_Barker) wrote: >I have been reading a book about the evolution of the Basic >programming language. The author states that Basic - particularly >Microsoft's version is full of compromises which crept in along the >language's 30+ year evolution. > >What to you think python largest compromises are? > [snip whitespace, dynamic typing, interpreted] I don't see those as compromises, but mostly as assets. Significant whitespace (you probably mean significant indentation - whitespace isn't more or less significant in Python than in other modern languages) I have only experienced as a boost in readability, clarity and, most of all, consistence; and there's no possibility of 'brace style wars'. Dynamic typing vs. static typing has already long ago reached the status of holy war, so I'll decline to comment. That python is not (yet) compiled, is mostly a non-issue (and if PyPy is a success, it won't even be that). If it was just about performance, then coding the really performance-intensive parts in C should suffice, apart from kernel hacking and similar . In my experience, the decision to convert a (successfully functioning) project from 'a scripting language' to C/C++/Java has always been a political one, and not really based on technical considerations. That said, the only large compromise in Python language design I can detect, is the decision to be quite strictly backwards-compatible between versions, which is definitely not a bad thing, as long as the language doesn't go baroque because of it. And Python 3.0 will hopefully throw out any accumulated cruft. --Christopher From theller at python.net Wed Jul 9 11:38:23 2003 From: theller at python.net (Thomas Heller) Date: Wed, 09 Jul 2003 17:38:23 +0200 Subject: tracebacks in embedded python References: <7049ba55.0307090708.36f2a696@posting.google.com> Message-ID: mmueller at dgfz.de (Mike M?ller) writes: > When I embed Python into C there is no traceback message on the screen > after an uncaught exception. Using sys.exc_info() I can print may own > traceback but I would need to insert try except statements at > different places. Is there a way to "turn on" traceback writing to > std.err (that also shows up at the screen)? You should check the return value of the Python API call for failure. Most functions return NULL or -1 on error. Then you call PyErr_Print(). Thomas From adalke at mindspring.com Sat Jul 12 16:23:45 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 12 Jul 2003 14:23:45 -0600 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. References: Message-ID: Grzegorz Adam Hankiewicz: > The module provides two classes: Mailbox, a file-like object > which allows you to iterate through the contents of a mailbox, > and Email, an object which holds the individual emails returned by > Mailbox. What does this do that the standard Python library doesn't support? mailbox - http://python.org/doc/current/lib/module-mailbox.html This module defines a number of classes that allow easy and uniform access to mail messages in a (Unix) mailbox. email - http://python.org/doc/current/lib/module-email.html The email package is a library for managing email messages, Andrew dalke at dalkescientific.com From max at nospam.com Wed Jul 23 15:54:47 2003 From: max at nospam.com (max) Date: Wed, 23 Jul 2003 19:54:47 GMT Subject: Design tool In-Reply-To: References: <3f1e985d$0$236@hades.is.co.za> Message-ID: > Personally, I use Dia: > http://www.lysator.liu.se/~alla/dia/ > > Some people use argo (which I find slow). .. but work on windoze... From posselt at hotmail.com Fri Jul 11 02:39:37 2003 From: posselt at hotmail.com (Peter Vestergaard) Date: Fri, 11 Jul 2003 08:39:37 +0200 Subject: command prompt change dir Message-ID: Hi Probably a simple question but I have not been able to find out how: I want my python script to generate a path based on some simple lookups and then change my path so that when the script exits my command prompt (from which I launched the script) is standing at this path. The path already exists. I have tried chdir(path), system('cd '+path) and many others but none changes my actual path. Hope anyone can help Regards, Peter Vestergaard From afriere at yahoo.co.uk Wed Jul 30 22:41:24 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 30 Jul 2003 19:41:24 -0700 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> Message-ID: <38ec68a6.0307301841.dfb951a@posting.google.com> "Keith Jones" wrote in message news:... > On Wed, 30 Jul 2003 17:25:05 +0000, max wrote: > > > The problem with spaces is that you need to do 5 times the work of a tab > > to get decent-looking indentation :). > > Not if you have a good editor.. Use vim or emacs. In vim, try :h sts (I > think, or :h softtabstop) ...it would suck to have to type > all the time, but you don't. :) If you use vim remember to put 'set expandtab' (or if you wanna be fancy 'au BufRead,BufNewFile *.py set expandtab' ) into your .vimrc (or .exrc) file. This way you can use '[Ctrl]-[T]' and '[Ctrl]-[D]' to in- and un-dent in insert mode, as well as '>>' and '<<' in command mode, without fear of hard tabs being inserted. (Though the way vi(m) mixes tabs and spaces is consistent enough that you wouldn't usually get into any trouble with it.) From sismex01 at hebmex.com Wed Jul 30 10:19:08 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 30 Jul 2003 09:19:08 -0500 Subject: python in parallel for pattern discovery in genome data Message-ID: > From: BalyanM [mailto:manojbalyan at ccmb.res.in] > Sent: Mi?rcoles, 30 de Julio de 2003 06:19 a.m. > To: python-list at python.org > Subject: python in parallel for pattern discovery in genome data > > > Hi, > > I am new to python.I am using it on redhat linux 9. > I am interested to run python on a sun machine(SunE420R,os=solaris) > with 4 cpu's for a pattern discovery/search program on biological > sequence(genomic sequence).I want to write the python code so that it > utilizes all the 4 cpu's.Moreover do i need some other libraries. > Kindly advice. > > Thanks > > Sincerely, > > Manoj > Well, when designing and writing your code, take into account that Python has a single central interpreter lock, so if you use multiple threads, only one will be running in any given instant, even if you have four processors. What you'd need to do is write your utilities in two parts, one that does "all the work", and another one a front end. The front end dispatches jobs to the backends, keeping a pool of back end active backend processes, and since each backend is an independant process, you can use as many processors as you have. Good luck, hope this helps. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From missive at frontiernet.net Fri Jul 4 18:25:50 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 04 Jul 2003 22:25:50 GMT Subject: Form using HTML on PythonCard References: Message-ID: > Somebody know how make html forms or python forms inside html to use as gui > application? > > The idea is make a client application like a web site of my interprise for > customers who don't have good connection, in this way the customer can select > the products off line and connect only to execute the shop. The use of HTML > is to have the same paradigm to application and to site. > How about starting a simple webserver / proxy on their machine? You could just connect to that, and if their connection is up forward the information on to your real server. From simonb at webone.com.au Thu Jul 10 15:59:34 2003 From: simonb at webone.com.au (Simon Burton) Date: Fri, 11 Jul 2003 05:59:34 +1000 Subject: Number Theory modules for Python References: Message-ID: What do you want? What have you found? I don't know much about comp-NT, but ,,, err Grobner bases stuff? And everyone seems to have their own polynomial implementation, the one in SciPy uses Numeric so it seems designed for bigishness etc.,,, Not sure if there is any high grade algebra stuff out there for python, let me know what you find. Simon Burton. On Thu, 10 Jul 2003 17:47:38 +0200, L?tez? wrote: > Hi! > > > I searched the Net and found several Number Theory (NT) related Python > extension modules. Some of them may be used to do some research but > unfortunately almost all promising modules disappeared from the Net, so I > wasn't able to download them. I'm sure, that it's my fault and NT packages > are actually exist and downloadable - somewhere. > > Please send me any known NT related materials/URLs can be used to do NT > research. > > > Thanks: Complex From bgailer at alum.rpi.edu Tue Jul 22 12:48:28 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 22 Jul 2003 10:48:28 -0600 Subject: py2exe command line window problem In-Reply-To: <1ee79758.0307220827.78f8571@posting.google.com> Message-ID: <5.2.1.1.0.20030722104728.04122ec0@66.28.54.253> At 09:27 AM 7/22/2003 -0700, Prashant Singh wrote: >I'm using py2exe to create a standalone executable from a Python >script, and I would like the script to run invisibly, i.e. without a >console window and without any interactive GUI. The script is a helper >app, which simply downloads and runs some other program. > >I've tried passing the -w flag to the script, and I've also tried >renaming it with a .pyw extension, but when the executable is run an >empty console window opens with the title "C:\WINNT\system32\cmd.exe". >I've checked, and there are no print statements, which might cause >py2exe to assume it's still a console app. How are you running the executable? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From martin at v.loewis.de Tue Jul 15 00:56:56 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Jul 2003 06:56:56 +0200 Subject: anything like C++ references? References: Message-ID: Stephen Horne writes: > Write... > > x = classname() > y = x > > ... and that would be an error. [...] > However... > > x = &classname() > y = x > > ... and everything is fine. If any kind of implicit reference assignment would be an error, then I assume x = classname() x.foo() would also be an error? because that assigns a reference of the object to the implicit 'self' parameter of the method? > > This is completely different from the notion of > >values in C or C++, where each occurrence of the literal 5 creates a > >new value whose state is 5. > > Not true. Each occurence of the literal 5 creates a new 'symbol' which > represents the value 5. The immutability of values is preserved in > C++. That is not true. There are no "symbols" in C beyond those that you use to name functions and global variables. Every occurrence of an integer literal *does* create a temporary object, every time the literal is *executed*. Regards, Martin From phoebe_1 at no_spam.worldnet.att.net Fri Jul 25 00:14:23 2003 From: phoebe_1 at no_spam.worldnet.att.net (Holden Caulfield) Date: Fri, 25 Jul 2003 04:14:23 GMT Subject: Python 2.3C1 Fails to build ? Message-ID: Hi, I am trying to build Python 2.3 RC1 (2.3c1) on Cray SV1 running UNICOS 10.0. And I am difficulty building it on this architecture. Background -------------- . Python 2.2.3 builds withs no problem. (without any changes). . This architecture has all C-datatypes as 8 bytes. Try 1: ------- I got this error message first time around. ~~~~ Cut ~~ cc -h nomessage=450 -h nostdc -h noconform -c -DNDEBUG -h scalar0 -h vector0 -I. -I./Include -DPy_BUILD_CORE -o Parser/grammar.o Parser/grammar.c CC-513 cc: ERROR File = Parser/grammar.c, Line = 45 A value of type "int" cannot be assigned to an entity of type "char *". d->d_name = strdup(name); ^ CC-513 cc: ERROR File = Parser/grammar.c, Line = 105 A value of type "int" cannot be assigned to an entity of type "char *". lb->lb_str = strdup(str); ^ Total errors detected in Parser/grammar.c: 2 make: *** [Parser/grammar.o] Error 1 ~~~~~~ - For some reason the strdup prototype does not get picked by the python build. Anyways, since strdup is there in libc, I just #ifdef'ed the prototype for _CRAY and proceeded. It went further this time around, but now I get this error in obmalloc.c, which seems more problematic to fix. ~~~ Error message cut ~~~ cc -h nomessage=450 -h nostdc -h noconform -c -DNDEBUG -h scalar0 -h vector0 -I. -I./Include -DPy_BUILD_CORE -o Objects/obmalloc.o Objects/obmalloc.c CC-61 cc: ERROR File = Objects/obmalloc.c, Line = 371 The integer operation result is out of range. PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) ^ CC-61 cc: ERROR File = Objects/obmalloc.c, Line = 371 The integer operation result is out of range. PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) ^ Total errors detected in Objects/obmalloc.c: 2 make: *** [Objects/obmalloc.o] Error 1 ~~~~~~~~~~~~~~ Any ideas what is going on? Thanks. From jjl at pobox.com Fri Jul 4 11:43:36 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Jul 2003 16:43:36 +0100 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <87llve8fh3.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > In article , > Russell Reagan wrote: [...] > At the same time, more and more of those games are switching to using > C/C++ only for the rendering engine and using a scripting language (Lua > or Python) for the gameplay itself. Is this true of big-$ commercial games? What sort of market share do high-level / interpreted languages have there? Never having been a (graphical) games player, I don't know the first thing about how games developers do things. John From john.abel at pa.press.net Tue Jul 8 10:25:26 2003 From: john.abel at pa.press.net (John Abel) Date: Tue, 08 Jul 2003 15:25:26 +0100 Subject: win32security.LogonUser In-Reply-To: References: Message-ID: <3F0AD456.5030901@pa.press.net> Hi, Try adding the user running the script, to "Act As PartOf The OS" in the policy editor. It seems that is required, for you to add/remove tokens. Regards John Darrell wrote: >On windows 2000 I tried to use winprocess.py with the login option. >In an effort to run as a diffrent user. >It didn't work and lots of searching didn't help. >This was my best hit. >http://www.faqts.com/knowledge_base/view.phtml/aid/4466 > >Worked around the problem using runas.exe > >This is as far as I got. >The following code tries to give me every Privilege it can then fails. >pywintypes.error: (1314, 'LogonUser', 'A required privilege is not >held by the client.') > >--Darrell > > >import win32con, os, sys >sys.path.append(os.sep.join(win32con.__file__.split(os.sep)[:-2])+os.sep+"demos") > >import winprocess >from ntsecuritycon import * >import ntsecuritycon, win32security, win32api > >def AdjustPrivilege(priv, enable = 1): > print priv > # Get the process token. > flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY |TOKEN_DUPLICATE| >TOKEN_IMPERSONATE > > #flags= TOKEN_QUERY > htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), >flags) > # Get the ID for the privilege. > try: > id = win32security.LookupPrivilegeValue(None, priv) > except: > print 'Fail' > return > # Now obtain the privilege for this process. > # Create a list of the privileges to be added. > if enable: > newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] > else: > newPrivileges = [(id, 0)] > # and make the adjustment. > win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) > ># now set the rights >if 1: > for k, v in ntsecuritycon.__dict__.items(): > if k.find("SE_")==0 and isinstance(v, str): > print k, > AdjustPrivilege(v) > >AdjustPrivilege(SE_CHANGE_NOTIFY_NAME) >AdjustPrivilege(SE_TCB_NAME) >AdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) > >SE_INTERACTIVE_LOGON_NAME = "SeInteractiveLogonRight" >#AdjustPrivilege(SE_INTERACTIVE_LOGON_NAME) > >if __name__ == '__main__': > > # Pipe commands to a shell and display the output in notepad > print 'Testing winprocess.py...' > > import tempfile > > timeoutSeconds = 15 > cmdString = """\ >REM Test of winprocess.py piping commands to a shell.\r >REM This window will close in %d seconds.\r >vol\r >net user\r >_this_is_a_test_of_stderr_\r >""" % timeoutSeconds > > cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile() > cmd.write(cmdString) > cmd.seek(0) > print 'CMD.EXE exit code:', winprocess.run('cmd.exe', show=0, >stdin=cmd, login=".\nuser\nuser1",#administrator\n", > stdout=out, stderr=out) > cmd.close() > print 'NOTEPAD exit code:', winprocess.run('notepad.exe %s' % >out.file.name, > show=win32con.SW_MAXIMIZE, > mSec=timeoutSeconds*1000) > out.close() > > From Frank at no.spam Thu Jul 24 04:20:42 2003 From: Frank at no.spam (Frank) Date: Thu, 24 Jul 2003 04:20:42 -0400 Subject: How do I get info on an exception ? References: Message-ID: On Tue, 22 Jul 2003 17:59:48 GMT, "Raymond Hettinger" wrote: >[Cameron Laird] >> >> But unsatisfying--at least to me. >> > >> >Submit a patch. >> . >> . >> . >> I deserved that. > >It wasn't a jab. >Truly, if you see a way to clarify the docs, submit a patch. >If everyone finds it helpful, it will be accepted. That's how >the docs improve over time. I've personally written or >accepted over a hundred of these in the past year. > > >> There was more to my post, of course. Part of what I was trying to >> express is that exception interfaces are almost always relegated to >> a footnote, with only a generalized description, even in the frequent >> case that a method's exceptions are more complicated than its invoca- >> tions. > >No doubt, exceptions often get less explanation than everything else. >However, in this case, the docs seemed reasonably clear to me. > >The part that could be improved is where it talks about returning a >message or a tuple, as if either one but not both could occur at any >time. It would be more accurate to say, that in all cases an exception >instance is returned; the instance has a __str__ method so it can be >printed as if it were a string; the instance has an attribute "args" which >is the tuple (errno, errmsg); and the instance has a __getitem__ method >so the args tuple can be directly unpacked as if the instance had been >the tuple itself. > >OTOH, that is long-winded and distracts from the flow of knowledge >about sockets. It is also how all exception instances work. > > >> So, Raymond, do you have general guidelines for how you think excep- >> tions should be documented? > >Unless there are interesting values being returned, it is probably >sufficient to name the exception, state what it represents, and >describe where it fits in the class structure (i.e. socket.herror is a >subclass of socket.error). When you think about it, why have >three paragraphs on an exception whose code is as simple as: > > class xyzException(Exception): pass # raised when xyz occurs > >When interesting values are returned, describe the meaning of >each element in the instance's arg tuple (i.e. (errno, errmsg)). >Afterall, the code behind it may be as simple as: > > raise socket.herror(errno, errmsg) # reveal the packet's error information > >Elsewhere in the docs, functions descriptions should list the names >of the exceptions they can raise unless it is obvious or pertains >to a whole collection of functions (i.e. all high-volume socket >operations can potentially raise a timeout). > >In general, I like the documents to be as specific as possible without >replicating the code or locking in a particular implementation. However, >there is a competing force to keep module documents centered on how >to use the module. For example, I found the unittest documentation to >be highly specific and thorough, yet unsatisfactory because you practically >had to read a book on the subject to be able to make basic use of the >module. To fix it, I added a new introductory section that covers >(in one page) the 5% of the module that will meet 95% of your needs >(enough to get you up and running). > > >Raymond Hettinger > Thanks to all for your help. After checking that the input is a string, I try calling gethostbyname/addr depending on whether the first char is numeric and catch: "except socket.error, err:" Will this catch all possible errors? I've tried feeding various errors into my def and caught them all so far. Input might come from users at the keyboard, and crashing the program is not an option, no matter what is typed in. ------------------------------------ I did look for the solution before posting; I checked: Python Lib Ref 2.2.2 Python Language Ref 2.2.2 Lutz - Learning Python Lutz - Programming Python, 2nd Holden - Python Web Programming Brueck - Python 2.1 Bible Martelli - Python in a Nutshell and even Guido's Tutorial. If the complete answer is there, I could not find it or assemble all the parts from the various references. Perhaps with more experience in Python it would have been clearer, but I have to agree with those that say exceptions are not well documented. Complete and precise documentation is probably more important for a language/compiler/interpreter system than any anything else. Frank From bokr at oz.net Fri Jul 25 20:16:22 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 00:16:22 GMT Subject: How to detect typos in Python programs References: <84e0f331.0307251036.6504b16a@posting.google.com> Message-ID: On 25 Jul 2003 11:36:23 -0700, rshaw2 at midsouth.rr.com (Richard) wrote: [...] > >Two words! Unit Testing! > >Just do a google search on "Python unit testing" and I'm sure you'll >get more information than you ever wanted to know. > I'm afraid with that last line you just named a big obstacle to more widespread adoption of unit testing ;-/ Regards, Bengt Richter From jim-usenet at jimdabell.com Wed Jul 30 07:01:48 2003 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Wed, 30 Jul 2003 12:01:48 +0100 Subject: Showing IP address of a user... References: <7b454334.0307291005.53ee8c07@posting.google.com> Message-ID: Fazer wrote: > I was wondering how I can show an IP address of a person who visits a > Python web-page? Would I have to use Environment variables to access > Apache's server variables which hold such values like in PHP or what? I see you've already been given answers to this, however bear in mind that what you are determining is the IP address of the client, not the IP address of the person visiting the page. In many cases, the two are not the same, such as when the visitor is using a proxy. There's no reliable way of getting the IP address of the person, but you can make things a little more reliable by examining the X_FORWARDED_FOR header as well, since many proxies add this header to their requests (also bear in mind that they may be private addresses, such as 10.0.0.1). -- Jim Dabell From intentionally at blank.co.uk Mon Jul 14 20:27:43 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 01:27:43 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> Message-ID: <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> On Mon, 14 Jul 2003 23:38:56 +0000 (UTC), Adam Ruth wrote: >So, then, what makes a different variable type? If not different syntax >and semantics, what would be the signature? In the sense in which you said there were three types of variables in C++, there are no different variable types. Pointer data types are nothing special compared with any other data type. Syntax and semantics vary from one data type to another, just as with the mathematical concept of abstract data types. Nothing wrong with that. In mathematics, an abstract data type is associated with a set of values *and* a set of operations. >Let me see if I understand what you're saying. Even though C++ >variables can have different syntax and semantics (depending sometimes >on context), the're all really the same internally and are therefore >perfectly consistent and usable. Its not about implementation details. Its about respecting the binding of variables to values - a high level concept from mathematics. Binding of variables to objects is a low level implementation detail in programming languages. > Python variables, on the other hand ( >mutable and immutable) have somewhat different semantics (a debatable >point) but identical implementaions (indeed, indistinguishable), but are >somehow invalid? Yes. BY DEFAULT they do NOT respect the binding of variables to values. >You say that there is one gold standard definition for what a variable >is. Yet even though C++ deals with variables in three semantically >distinct way, they are somehow all valid within that definition? C++ does not deal with variables in three semantically distinct ways. It provides a wide range of data types (including pointer types and reference types) and, in keeping with the mathematical concept of an abstract data type, each has both its own set of values and its own set of operations. The only way in which semantics vary from variable to variable is in that some of those semantics are tied to the abstract data type. And C++ respects the binding of variables to values (unless you write buggy code). Even when using pointers, the binding of variables to values is preserved. It is merely that pointer values provide an indirect way of referencing a store location, or placeholder, which may be manipulated (ie bound to a different value) using some other means of identifying that placeholder. That is, the concept of a placeholder referenced potentially by more than one variable only becomes an issue if you specifically ask for it. From jguerin at cso.atmel.com Thu Jul 31 13:02:37 2003 From: jguerin at cso.atmel.com (Justin Guerin) Date: Thu, 31 Jul 2003 11:02:37 -0600 Subject: Misuse of In-Reply-To: <3f27f0e3$1@news.broadpark.no> References: <3f27f0e3$1@news.broadpark.no> Message-ID: <200307311102.37563.jguerin@cso.atmel.com> On Wednesday 30 July 2003 10:20 am, Gisle Vanem wrote: > I'm a .py newbie and fascinated by the simplicity of formatting. > No need for {} as in Perl etc. But the misuse of that many > .py writers do makes it hard to understand how a script operates. > > E.g. > > def main(): > terminate = 0 > def foo(): > line = sys.stdin.readline() > try: > bar() > except: > terminate = 1 > > main() > > Now, with an editor with different tab-settings it's difficult to see where > the try statement belongs. In 'def main()' or in 'def foo()' ? > I'm confused, please enlighten me. > > --gv In this case, you can tell by the except clause. except: can only follow a try:, and they must be on the same indent level. Also, if the try: was in 'def foo()', 'bar()' would have to have a higher indent level than 'line = sys.stdin.readline()'. (From what I can see, it does, but I'm not sure that was intended, as the except came in at a different indent level from either) So for this example, the try: belongs in 'def main()' Justin From jjl at pobox.com Tue Jul 29 17:02:56 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 22:02:56 +0100 Subject: PyQt Help and Advice References: Message-ID: <87u19559mn.fsf@pobox.com> ilyak at red.seas.upenn.edu (Ilya Knizhnik) writes: [...] > However since PyQt is rather new, I have not found much documentation on > it, or examples in it. The only useful tutorial/book I have found is at > www.opendocspublishing.com/pyqt/ but it is not always clear for someone > with almost no GUI experience. > Does anyone have any suggestions? PyQt isn't new. The reason there's not documentation for every API function is that the Python interface slavishly follows the C++ API (actually, I believe you can now pay for documentation, but I don't see the point). The PyQt docs just list the slight deviations from Qt proper. The Qt docs are excellent, and you really don't need to know C++ to understand them. John From peter at engcorp.com Fri Jul 4 23:18:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 23:18:40 -0400 Subject: Python is a gem, you need to keep pushing it .... References: <3F05C138.687F5A06@engcorp.com> <3F05C320.BF195230@engcorp.com> Message-ID: <3F064390.981B1B3@engcorp.com> delphiro wrote: > > In our company however there is not a thing that could not be > done with Python. And as I think of our company as a very regular > IT company ('development keywords'; gui / database / internet / > client-server / sorter-system (well the last is not too regular > I guess :-)) this will fit for a lot of IT companies. > > And off course, if someone wants to have a macro for Word > of Excel, Python won't do but it *will* for almost any regular > IT job. That's my point. Ah, thanks for clarifying then. "IT" is a subset of a much larger area of computing, in which there are likely to be, I believe, a sizable number of areas for which Python is _not_ the *best* tool. My own company is not "IT", but what you'd probably call industrial control. Python has a great many very effective uses in that area, but there are things it is not "best" at, apart from hardware drivers. One, for example, is hard real-time work... it's not very good at all there. :-) -Peter From gh at ghaering.de Mon Jul 21 08:03:11 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 21 Jul 2003 14:03:11 +0200 Subject: distutils.core not in Debian python2.2 package In-Reply-To: References: Message-ID: <3F1BD67F.8040905@ghaering.de> Kent Tenney wrote: > David M. Cooke wrote: >> In general, if you need to compile, or develop, you need the >> corresponding *-dev packages. > > I didn't need to compile or develop, just install. > > I expected > > $ python ./setup.py install > > to work out of the box. [...] From the view of the packagers, you only need disutils for development work. Manually installing modules counts as "development" as well. At least to them. -- Gerhard From sandysj at juno.com Thu Jul 17 18:19:27 2003 From: sandysj at juno.com (Jeff Sandys) Date: Thu, 17 Jul 2003 22:19:27 GMT Subject: ps in windows Message-ID: <3F1720EF.DCA2AD12@juno.com> Not really a Python question except I will use Python to write the script. I have several Windows98SE PCs and a Linux PC on a home network. I want the Linux PC running a cron job to query the Windows PCs to find out what programs they are running. Any pointers on how to do this? Thanks, Jeff Sandys From tl_news at nexgo.de Thu Jul 31 13:13:56 2003 From: tl_news at nexgo.de (Tino Lange) Date: Thu, 31 Jul 2003 19:13:56 +0200 Subject: .setdefault() References: <87ispid400.fsf@pobox.com> Message-ID: <3cjiivs4ippc6v7qjllfhi3knvthrfnj2g@4ax.com> On 31 Jul 2003 18:01:51 +0100, jjl at pobox.com (John J. Lee) wrote: >Because that's the way Python always does function calls? Of course. From the consistency point of view... perfectly right! (I thought that maybe because these are very special low-level methods for built-in types, it might be different....) >Don't, then. :-) Use key in dict, or dict.has_key(key). or the C-like style: >>> a[3] = a.get(1) or b.setdefault(4,1) Thanks! Tino From hwlgw at hotmail.com Tue Jul 22 11:19:38 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 22 Jul 2003 08:19:38 -0700 Subject: How to save web pages for offline reading? References: Message-ID: > [Carsten Gehling] > Well since you ARE on Windows: > > Open the page in Internet Explorer, choose "File" and "Save As...". > You've now saved all necessary files. > I know. But I can't do File - Save As from python :-) I guess it can be done via COM? > > I thought this whole thing would be easy with all those Python > > internet modules in the standard distro: httplib, urllib, urllib2, > > FancyURLxxx etc. Being able to download a "complete" page *from > > Python source* would be very nice for my particular application. > > Well it's doable with those libraries, but you have to put your own meat > on > the bones. > > 1) Use httplib to get the page first. > 2) Parse it for all "src" attributes, and get the supporting files. The > parsin can be done with a html-parser ... That would be htmllib. What you describe is what I am going to do actually, when I have time again. I was about to do it when I thought "somebody must have been doing this before". It seems like mr. Pillai in another reply has done something similar but I couldn't figure out from his source code. Thank you all for the help! -- Agree with them now, it will save so much time. From drs at ecp.cc Wed Jul 2 03:44:57 2003 From: drs at ecp.cc (drs) Date: Wed, 02 Jul 2003 07:44:57 GMT Subject: Date issue Win98 vs NT References: Message-ID: "Stan Cook" wrote in message news:SDsMa.38974$hV.2346862 at twister.austin.rr.com... > Has anyone else had this or a similar problem and is there a workaround? > > This piece of code: > > from time import gmtime, strftime > _log = _log + "\\" + strftime("%m%d%y", gmtime()) + ".log" > > produces a file with the name 'today's date.log' on NT, but creates a file > called 'tomorrow's date.log' on Windows 98. I would really like to know > why this happens. Any help offered is very much appreciated. maybe localtime() will work better than gmtime()? could be a missetting somewhere? not the help you are looking for, but try import os.path os.path.join(_log, '%s.log' % strftime("%m%d%y", gmtime())) or even _log += ('\\%s.log' % strftime("%m%d%y", gmtime())) to get rid of some of the + signs. -d From richie at entrian.com Thu Jul 31 06:26:07 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 31 Jul 2003 11:26:07 +0100 Subject: How to get Windows physical RAM using python? In-Reply-To: References: Message-ID: <9frhiv4im6gf38dqkurd0lr606crbsgn1f@4ax.com> [Mark] > How to check the amount of Windows physical RAM using python? [Martin] > You should call the GlobalMemoryStatus(Ex) function. To my knowledge, > there is no Python wrapper for it, yet, so you would need to write one. Easy with ctypes: ------------------------------------------------------------------------------ from ctypes import * kernel32 = windll.kernel32 class MEMORYSTATUS(Structure): _fields_ = [ ('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulong), ('dwAvailPhys', c_ulong), ('dwTotalPageFile', c_ulong), ('dwAvailPageFile', c_ulong), ('dwTotalVirtual', c_ulong), ('dwAvailVirtual', c_ulong) ] def getTotalPhysicalBytes(): memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(byref(memoryStatus)) return memoryStatus.dwTotalPhys if __name__ == '__main__': bytes = getTotalPhysicalBytes() print "Total physical RAM: %d bytes (%dMB)" % (bytes, bytes / 1024 / 1024) ------------------------------------------------------------------------------ -- Richie Hindle richie at entrian.com From intentionally at blank.co.uk Tue Jul 15 00:02:18 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 05:02:18 +0100 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> <20030714172215452-0600@news.xmission.com> Message-ID: On Mon, 14 Jul 2003 23:22:18 +0000 (UTC), Adam Ruth wrote: > > >I started to write a response, and then I realized that it would be >pointless. We're just gonna have to be happy in each other's ignorance. >Our skulls are too thick for each other's arguments. > >I'm gonna stick with the idea that we're both wrong. > >Even-though-your-more-wrong-erly yours, Whatever. I've admitted the mistakes that I recognise I've made. If you think there are other mistakes that I haven't recognised, its up to you whether you explain them or not. Just 'cause I can't sleep the last few nights, doesn't mean anyone has to read my rantings, much less reply. Even if they *are* accurate rantings ;-) From sjmachin at lexicon.net Wed Jul 30 17:33:49 2003 From: sjmachin at lexicon.net (John Machin) Date: 30 Jul 2003 14:33:49 -0700 Subject: funny slashdot quote regarding python 2.3 release References: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> <3f27b0a9$0$49104$e4fe514c@news.xs4all.nl> Message-ID: John Hunter wrote in message news:... > > Why reinvent the wheel when you've got a brand new Michelin tire > sitting in the garage? Because you have a tyre and you don't have a wheel. From skip at pobox.com Mon Jul 14 15:46:31 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 14 Jul 2003 14:46:31 -0500 Subject: some questions In-Reply-To: <3f13031b$0$4026$9b622d9e@news.freenet.de> References: <3f12f613$0$8731$9b622d9e@news.freenet.de> <3f13031b$0$4026$9b622d9e@news.freenet.de> Message-ID: <16147.2199.923184.730696@montanaro.dyndns.org> >> Have you tried Python.org? Python itself comes with a tutorial >> (maybe you are unaware of this, or maybe you want another?). Andreas> I know there is one. But I don't like it. Don't know what kind Andreas> of tutorial I'm looking for. Just some hints would be enough. Hint: http://www.python.org/doc/Newbies.html Skip From wim_wauters at skynet.be Wed Jul 9 17:35:35 2003 From: wim_wauters at skynet.be (WIWA) Date: 9 Jul 2003 14:35:35 -0700 Subject: SNMP support for Python under Windows References: <538fc8e.0307091027.1825b454@posting.google.com> <3F0C65FB.1B86A0C2@engcorp.com> Message-ID: <538fc8e.0307091335.70526148@posting.google.com> Hi Peter, I did two things, both unsuccessfull: 1) If I install the pySNMP modules under lib/site-packages and then type sth like: from pysnmp import session it gives the error message "ImportError: No module named pysnmp". The same happens if I unstall pySNMP directly under the lib directory. Installs in this context means 'copy paste' the *.py files of the pySNMP distribution. - Do I need to explicitly mention in my script where pySNMP is installed? 2) I installed distutils 1.0.2 for Windows and it installed into the Python directory. So ar so good, I think... I go to DOS prompt and go to the directory where disutils is installed and type in python setup.py install, but DOS replies: 'Python is not recognized as an internal or external command, program or batchfile". - Do I need to do sth special after installing Distutils System coordinates are Windows XP. Python version is 2.2.2 and pySNMP is version 3.0.0. Any feedback is welcome and appreciated Peter Hansen wrote in message news:<3F0C65FB.1B86A0C2 at engcorp.com>... > WIWA wrote: > > > > I'm looking for SNMP support in Python. I have found pySNMP, but I'm > > not sure whether this works under Windows as well. > > Yes, it does. > > > A few questions: > > > > 1) Where do I need to install the pySNMP files? > > Doesn't it install with distutils? If so "python setup.py --install" > or whatever it says in the README would work. Sorry, I haven't > installed it lately. > > If it doesn't have instructions, put the files under the > c:/python/lib/site-packages directory. > > > 2) What do I have to do in order to be able to write somethin like: > > "from pysnmp import session" > > Install, then type "from pysnmp import session".... ;-) > > > Thakns in advance for all input > > (If you're having troubles, please note versions and platform > next time, for Python, PySNMP, and Windows.) > > -Peter From JensRie at gmx.de Thu Jul 10 03:12:07 2003 From: JensRie at gmx.de (Jens Riedel) Date: Thu, 10 Jul 2003 09:12:07 +0200 Subject: Zope problem: objectValues('Folder') Message-ID: <3F0D11C7.4010805@gmx.de> Hello NG, I'm a newbie to Zope and just testing the examples from the Zope Book. All in all it works great but I have a problem with one example: I try to get a list of subfolders by using

(From Zope Book Chapter 6) I always get no entries (but there are 3 folders inside), the same problem occurs if I try objectValues('File') to show a file library. In an example of the Zope Tutorial I use ... and it works fine. I used copy-and-paste to get the code from the Zope Book so I'm sure I made no mistake. I tested on two different Windows systems (NT and 2000) with the current stable Zope release. Does anybody know where the problem with "objectValues('Folder/File')" is? Thanks, Jens From bdesth.nospam at removeme.free.fr Mon Jul 14 16:39:22 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 14 Jul 2003 20:39:22 +0000 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: <3F1314FA.8030209@removeme.free.fr> richardc wrote: > Ive just started playing with Python and have a couple of questions. Welcome > Im looking for an agument parsing library (from the command line), Ive come > across optik and argtools. What other ones are there are any of them any > good, is there a 'standard' lib for doing this. See other posts in this thread > Also how should I '#define' magic numbers in Python. I spent ages looking > around for a 'define' statement or anything that will allow me to create a > constant value 'object'. Am I missing something very obvious ? Idem... The 'obvious' thing you might be missing is that Python relies heavily on programmers following conventions, where other languages impose strict rules... Some conventions are : UPPERCASE_VARIABLE : a constant, don't touch unless you really know what you're doing _NameWithLeadingSingleUnderscore : 'protected' access , don't touch unless you really know what you're doing __NameWithLeadingAndTrailingDoubleUnderscore__ : a 'magic' thing, don't touch unless you really know what you're doing A special case is __NameWithLeadingDoubleUnderscore : In older Python version, it was just a convention for 'private' access, now it makes Python doing some mumbo-jumbo name mangling (which don't strictly enforce 'privacy', but)... Another special case is the 'self' pseudo-key word : the first argument for object methods could be named whatYouWant, but (almost ?) everybody uses 'self'. > Also, what 'IDE/editor' do people recomend for MAC OSX, so far Ive found > 'Hydra' to be the best as it works on plain files and has Python syntax > highlighting... what else is there and are any of them any good. I guess vim and emacs should run on Mac OS X ? > Has nobody written an editor/IDE in Python with wxWindows so that it runs on > all platforms ? You could try boa contructor (a wxPython delphi-like RAD/IDE). Bruno From duncan at NOSPAMrcp.co.uk Wed Jul 9 04:12:43 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 9 Jul 2003 08:12:43 +0000 (UTC) Subject: Deleting specific characters from a string References: Message-ID: Behrang Dadsetan wrote in news:begfb3$7j6$1 at online.de: > I would like deleting specific characters from a string. > As an example, I would like to delete all of the '@' '&' in the string > 'You are ben at orange?enter&your&code' so that it becomes > 'benorange?enteryourcode'. > > So far I have been doing it like: > str = 'You are ben at orange?enter&your&code' > str = ''.join([ c for c in str if c not in ('@', '&')]) > > but that looks so ugly.. I am hoping to see nicer examples to acheive > the above.. Use the third argument to string.translate: >>> identity = string.maketrans("","") >>> string.translate('You are ben at orange?enter&your&code', identity, "@&") 'You are benorange?enteryourcode' >>> -- 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 glenfant at NOSPAM.bigfoot.com Fri Jul 18 11:32:22 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Fri, 18 Jul 2003 17:32:22 +0200 Subject: "\n" in ASCII-file References: Message-ID: "Martin P" a ?crit dans le message de news: bf8j40$bj4e4$1 at ID-108519.news.uni-berlin.de... > Hello, > > for a short exercise-program I have to read the lines in an ASCII-file. > > But every line has a new-line-feed ("\n") at the end of the line. (The > ASCII-file was made with Windows Notepad). > Is this only because I used Windows (and Notepad)? > > And... is there any special method to read lines from a file without "\n"? > > Bye, > Martin > > 3 ways (among others...) : 1/ You just want to remove all EOL characters and keep other blank trailing characters: f = open("myfile.txt", "r") while 1: line = f.readline() if not line: break line = line.replace("\r", "") line = line.replace("\n", "") # process the line your way... 2/ You want to remove all EOL characters other blank trailing characters: f = open("myfile.txt", "r") while 1: line = f.readline() if not line: break line = line.rstrip() # process the line your way... 3/ You got python 2.3 (not me) and there's a new mode for reading the lines without the EOL character(s). Read the manual at the "file object" chapter, or "open" in the builtins chapter. --Gilles From tjreedy at udel.edu Mon Jul 14 22:44:49 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jul 2003 22:44:49 -0400 Subject: bug in my code? References: Message-ID: "Duncan Smith" wrote in message news:bevl84$880$1 at news7.svr.pol.co.uk... > Greetings. I am struggling to track down what I presume is a bug in my > code. The trouble is that it only raises its head occasionally. I have > managed to prune the code to the following: > > shutTest.py > -------------------------------------------------------- > import cPickle > > def test2(iterations): > for i in range(iterations): > try: > f = file('C:\\Python22\\(2, 2, 2, 3, 4).shu', 'r') > try: > dependencies, nodes = cPickle.load(f) > finally: > f.close() > except IOError: > pass > ---------------------------------------------------------------- > > Calling the function with a suitable argument (say, 100) doesn't usually > pose a problem. The file is opened OK and the data unpickled. But > occasionally (or usually if I call the function with 1000 as argument) I get > the all too common, on Windows, > > 'The instruction at {some memory address} referenced memory at {some other > (and on one occasion the same) memory address}. The memory could not be > "read".' ... This sounds like maybe a hardware problem. Is the unpickling necessary to get the error? -- or some discrepancy? If you simply reread the file over and over, do you always get *exactly* the same byte string? Test this by reading once before the loop and comparing subsequent reads to first. What I asking is whether you might have flacky or overheated disk drive giving intermittant errors more often than once a terabyte. TJR From swenggsri at yahoo.com Mon Jul 28 13:49:58 2003 From: swenggsri at yahoo.com (Sriram Chadalavada) Date: 28 Jul 2003 10:49:58 -0700 Subject: Defining/declaring constants in Python Message-ID: Hello everyone, I am a newbie to Python with experience in C programming. For my project, I am re-writing C routines as Python functions. I am currently using raw numerical values and was wondering if there is an equivalent of #define in Python for declaring constants. Is there an elegant way of defining constants in Python? Please let me know. Thanks, Sriram From rastm2 at aol.commorespam Thu Jul 24 04:20:16 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 24 Jul 2003 08:20:16 GMT Subject: Newbie question regarding py2exe. References: Message-ID: <20030724042016.06962.00000711@mb-m06.aol.com> Marco - talking about py2exe said > >Sometimes modulefinder.py complains, other times its VersionInfo.py. > >My question is how robust is py2exe? (Note that I have followed the docs to >the letter.) > >Cheers, Marco > I sympathize Marco. Last night I tryed py2exe for the very first time. I wrote a trivial random LOTTO Picker with GUI, as a test. Used anygui - trying it for the first time also. Just a few labels, a Button to gen the nums and a one line text box for display. Impressed with anygui, I moved on to py2exe. It worked ,,,,,,,eventualy. What I found was that... There are no where near enough docs for py2exe. Yeah there's plenty of info for distutils and setup scripts but the "lazy" hacker is looking for samples. A repository for donated, well doc'ed "setup.py" examples is IMHO needed. Write a working setup - doc it good - mail it to the archive. Donated because I can't expect Thomas Heller to imaginate\dream up every possible way to write one. I used the setup file for Aliens by ShredWheat at REMOVEMEmediaone.net that I found at PYGAME as an example. I hacked it and made it my slave and it did what I expected very well. It's amazingly robust - to answer your question above. I looked forward to the py2exe output to list my unfound dependencies. It did this very well. (aside = Please someone tell me how to capture the output to file in win32 comand line? I didn't see an option for that in the Doc at the website.) Writing the anygui script in Pythonwin made my backend( ) == mswgui. (sounds nasty don't it) This ment that all the anygui imports became the entire list of unresolved modules. I could only imagine that if I had gone ahead and resolved them all in the setup script I would still be resolving them now. ( Am I correct in assuming this would take me all the way down to Win32 sys dll's ? Anybody?) Fortunately, I remembered reading that if the originating script only included pure Python code, then the modulefinder should have no problems. Anygui to the rescue. Switched the backend to TKgui at the import statment. One little change and YIPPIE ! All done. That ment that the setup.py became as simple as ... # setup.py from distutils.core import setup import py2exe setup(name="myscript", scripts=["myscript.py"], ) Made my little 1.76Kb script into a whoppin 2MEGABYTES --- and that's the zip file. I got the entire TCL\TK source in there. 189 files including my script and the Python dll at 5,096kb ,,,,,,,,,, 5.1 MEG and it only took about as much wait time to build as the zip file did to zip it. Does it all have to be in there? I'm fairly certain NO. One of these day's I'll have to add an --exclude statement or 100. But nobody's gonna want this proggy so why. UPSHOT -- I really like both programs and look forward to learing more about them. Robust? You bet ! Ray St.Marie Rastm2 at slpamaol.com From max at alcyone.com Tue Jul 22 22:09:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jul 2003 19:09:21 -0700 Subject: python assignment References: Message-ID: <3F1DEE51.CD7FEB7F@alcyone.com> dan wrote: > What I need is an exact and unambiguous algorithm for determining when > an assignment will change the id of the variable (or should I say, > when the evaluation of an expression will cause a new object to be > created). Some of the issues involved can be discerned from the > following session: ... But this session only involves immutable objects (ints and floats). Since immutable objects can never change, whether two equal immutable objects are identical is an implementation detail and cannot make a difference in the real world. The `is' tests you perform in your sample code are exploring into the realm of transparent implementation-defined behavior; it doesn't matter whether the objects end up being identical, that's a matter of optimization. Try performing analogous operations with _mutable_ objects like a list, and see if you remain confused. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Many things are lost for want of asking. \__/ (an English proverb) From jegenye2001 at fw.hu Mon Jul 21 19:01:18 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Tue, 22 Jul 2003 01:01:18 +0200 Subject: Automatically filling in answers to interactive shell command questions References: Message-ID: If you use Linux then "expect" (a Tcl thing) is written just for this. From owski at hotmail.com Wed Jul 16 16:27:23 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 20:27:23 +0000 (UTC) Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> <20030716123907246-0600@news.xmission.com> Message-ID: <20030716142716509-0600@news.xmission.com> In Donn Cave wrote: > In article <20030716123907246-0600 at news.xmission.com>, > Adam Ruth wrote: >> In Donn Cave >> wrote: >> > In article <20030716081156943-0600 at news.xmission.com>, >> > Adam Ruth wrote: >> > >> >> In <1058328099.572993 at yasure> Donn Cave wrote: >> >> > Quoth Adam Ruth : >> >> > .... >> >> >| In Python, there is no situation where "you really can't avoid >> >> >| pointers". >> >> > >> >> > That's trivially true, no such situation can exist because that >> >> > Python can't be coded. I'll repeat an example that I proposed >> >> > a couple days ago, though: user implemented sequences could be >> >> > implemented with a single simple indexing function, returning >> >> > a pointer/target/whatever; Python could assign directly to that, >> >> > making "seq[i] = x" the same kind of operation as and >> >> > automatically symmetrical with "x = seq[i]". > > .... >> You are correct, 'really need' is not much of an argument. The >> statement I disagreed with was that it was bad to simulate pointers >> in those situations where "you really can't avoid pointers". I was >> expressing that really aren't any such situations, and that it's even >> worse try to simulate pointers when it's not really necessary. > > OK, there really aren't any situations where you can't avoid > pointers ... so you're ready with a solution to the problem > I posed above? > > Class scope containers that hold exactly one item, to pick a > commonly seen usage that I suppose is a simulated pointer - > that's really not necessary, and it's "even worse" (than what?) > > Donn Cave, donn at u.washington.edu "Even worse" doesn't make much sense, there, does it? I meant, faking pointers isn't bad because a pointer would be better, but faking pointers is bad because you don't need a pointer. That makes more sense. As for your problem on the subscript operator, I think my solution is: there's no problem. Having the get and set asymetric is preferrable, in my view. For example, I use it in a number of places where I cache the set operation: def __getitem__(self, name): if name in self.cache: return self.cache[name] else: return someLongOperation(name) def __setitem__(self, name, value): self.cache[name] = value There are other reasons to have them as separate operations, but this is one that I have in a project I'm on now. I think of them as logically separate operations, not necessarily opposite sides of the same coin. Adam Ruth From fredrik at pythonware.com Tue Jul 15 11:47:49 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2003 17:47:49 +0200 Subject: md5 consistent across platforms/Python versions? References: Message-ID: Tim Peters wrote: > > Can someone tell me whether an MD5 hash using Python's MD5 library IS > > guaranteed to return the same results for the same input string, > > across platforms and Python versions? > > Yes, it's the same, and the same as what you'll get from any other correct > program for computing an MD5 digest from that string. historical footnote: if you dig up really old Python versions, the MD5 calculation was broken on 64-bit platforms (the code assumed that a long was always 32 bits) this was fixed in 1996: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Modules/md5.h.diff?r1=2.2&r2=2.3 From a.schmolck at gmx.net Fri Jul 4 13:13:29 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 04 Jul 2003 18:13:29 +0100 Subject: Why so many references to global variables? References: <0S2Na.6305$bD1.721957@news20.bellglobal.com> Message-ID: J-P writes: > Alexander Schmolck wrote: > > J-P writes: > > > > >>It appears that every time the interpreter tests for > >>the value of 'myflag', it keeps a reference to it. > > What makes you think so? This seems rather unlikely to me (not that the > > > references themselves should eat your memory anyway!). > > > Well, sys.getrefcount() does tell me there are 3 millions references > to it and other globals. Even though this doesn't eat up all my memory > (how large is a reference object in Python?), I definitely think there's > something fishy with keeping that many references to global variables that > appear here and there in the script. Erik Max Francis has hopefully already sorted your reference count confusion out (if not, maybe a look under "reference counts" in the C API/extending bits of the python docu might clarify matters), so I'll just give you a simple practical tip: Take one of the suspicious C extension functions, and call it repeatedly from python (passing and returning data structures that are as large as possible and that you discard immediately aftewerwards). Then using 'top' or something equivalent, look at how the memory consumption of your program changes: if you find that with each couple of calls python swallows a few megabytes, you can be pretty sure that something is going wrong (at least if you force gc with gc.collect()). Once you've isolated the function(s) you're in for some fun debugging the corresponding C code, paying particular attention to PY_DECREFs and PY_INCREFs. > > > > > > Chances are, the C extension code doesn't work correctly (C extensions to > > python code have to do memory management by hand; increasing and decreasing > > reference counts for the python objects they deal with as appropriate; so if a > > bit of code forgets to decrease the refcount, the object will stay alive > > forever; my guess would be that this it what happens here). > > Might be, but the ref count for the objects interacting with the C library are > pretty much what I expect them to be, i.e. a few dozens. > > I don't think there are other memory leaks in the bindings to the > library. I've passed it through Purify a couple of times and everything > seems clean. Purify is unlikely to have a deep understanding of python's internal reference counting (memory management) mechanism, right? So while it will be helpful for finding memory *violations* (and leaks not due to refcounts) it's quite unlikely to find problems due to the C extension not *decreasing reference counts*, which is what I bet is happening in your case. 'as From usenet_spam at janc.invalid Tue Jul 22 22:04:38 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 23 Jul 2003 02:04:38 GMT Subject: Possible use of Python for a voting machine demo project --your feedback requested References: Message-ID: "Alan Dechert" schreef: > This ballot has 45 candidates in 10 contests We often have more than 150 candidates for 1 contest here... I guess that's why we only have 1-3 contests/ballots on the same day. ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From djc at object-craft.com.au Fri Jul 11 01:01:56 2003 From: djc at object-craft.com.au (Dave Cole) Date: 11 Jul 2003 15:01:56 +1000 Subject: Securing 'pickle' References: Message-ID: > On Thu, 2003-07-10 at 20:20, David McNab wrote: > > I'm writing a web app framework which stores pickles in client cookies. > > > > The obvious security risk is that some 5cr1p7 X1ddi35 will inevitably try > > tampering with the cookie and malforming it in an attempt to get the > > server-side python code to run arbitrary code, or something similarly > > undesirable. > > > > To protect against this, I've subclassed pickle.Unpickler, and added > > overrides of the methods load_global, load_inst, load_obj and find_class. > > A much easier way to secure your pickle is to sign it, like: > > cookie = dumps(object) > secret = 'really secret!' > hasher = md5.new() > hasher.update(secret) > hasher.update(cookie) > cookie_signature = md5.digest() > > You may then wish to base64 encode both (.encode('base64')), pop > them into one value, and you're off. Though I suppose at that point > you may be hitting the maximum value of a cookie. Hidden fields > will work nicely, though. > > Decoding and verifying is an exercise left to the reader. That is exactly what Albatross does with pickles sent to the browser. In case it is interesting to anyone, here is the class that does the work of signing and checking the sign. - Dave class PickleSignMixin: def __init__(self, secret): self.__secret = secret def pickle_sign(self, text): m = md5.new() m.update(self.__secret) m.update(text) text = m.digest() + text return text def pickle_unsign(self, text): digest = text[:16] text = text[16:] m = md5.new() m.update(self.__secret) m.update(text) if m.digest() == digest: return text return '' -- http://www.object-craft.com.au From BranimirPetrovic at yahoo.com Wed Jul 30 20:01:59 2003 From: BranimirPetrovic at yahoo.com (Branimir Petrovic) Date: 30 Jul 2003 17:01:59 -0700 Subject: How to get Windows physical RAM using python? References: Message-ID: "Martin v. L?wis" wrote in message news:... > Python can't get you Windows physical RAM. You have to order RAM > from a manufacturer or reseller if Windows needs more RAM :-) > > Regards, > Martin "Easy" way to get to physical RAM on Windows is via WMI objects. Before I've discovered (why/how use) Python this example below is how I used to do it from JScript (did not "re-tool" and converted all my stuff to Python yet), but should be good enough to give you an idea of what to look for: function getSysInfo(sHost) { // Returns instance of Object object with these expando properties: // // oObj.Computer NetBIOS computer name // oObj.OSname "Microsoft Windows 2000 Professional" // oObj.OSver 4.0.1398 (for WinNT4), 5.0.2195 (for Win2K), 5.1.??? (for WinXP) // oObj.SPver 2 (for SP2), ... // oObj.OStype "W" (for Workstation), "S" (for Server) // oObj.IPaddr "123.45.67.89" // oObj.WinDir "C:\Winnt" // oObj.SysDir "C:\Winnt\system32" // oObj.RAM In MB // oObj.BootDev "\Device\Harddisk0\Partition1" // oObj.SysDev "\Device\Harddisk0\Partition1" // oObj.ERRMSG will be "" or hold error message string // oObj.ERRNO will be: // 0 if there are no errors, // 1 if system does not exist or is unavailable, // 2 if WMI is not installed on target system, // 3 other reason(s)... var oObj = new Object(); if (!isIP(sHost)) { var oP = new PingerCLS(); oObj.IPaddr = oP.getIP(sHost); } else oObj.IPaddr = sHost; try { var oOSset = GetObject("winmgmts:{impersonationLevel=impersonate}!//"+sHost).InstancesOf("Win32_OperatingSystem") oObj.ERRNO = 0; oObj.ERRMSG = "NO ERRORS"; } catch(e) { switch (e.number) { case 462 : case -2146827826 : // The remote server machine does not exist or is unavailable oObj.ERRNO = 1; oObj.ERRMSG = "Host does not exist or is not available."; return oObj; case 429 : case -2146827859 : // ActiveX component can't create object oObj.ERRNO = 2; oObj.ERRMSG = "Host is missing WMI capabilities."; return oObj; case -2147217405 : // Lacking admim permissions to connect to host oObj.ERRNO = 3; oObj.ERRMSG = "Missing permissions to connect to this host."; return oObj; case -2146828218 : // "Permission denied" - DCOM not enabled error message oObj.ERRNO = 4; oObj.ERRMSG = "DCOM not enabled on host: " + sHost; return oObj; case -2147418111 : // Wierd shit error (only number, no message) // Happens on 2 Win2K Prof with CheckPoint's client... oObj.ERRNO = 5; oObj.ERRMSG = "Wierd one (ERROR# -2147418111)..."; return oObj; default : // Whatever else the cause may be... oObj.ERRNO = e.number; oObj.ERRMSG = e.description; return oObj; } } var oEnm_1 = new Enumerator(oOSset); var oEnm_2; for (; !oEnm_1.atEnd(); oEnm_1.moveNext()) { oEnm_2 = new Enumerator(oEnm_1.item().Properties_); for (; !oEnm_2.atEnd(); oEnm_2.moveNext()) { // Pick only some of available properties (and ignores the rest): switch (oEnm_2.item().Name) { case "CSName" : oObj.Computer = oEnm_2.item().Value; continue; case "Caption" : oObj.OSname = oEnm_2.item().Value; oObj.OStype = (/Server/i).test(oEnm_2.item().Value)? "S":"W" continue; case "Version" : oObj.OSver = oEnm_2.item().Value; continue; case "ServicePackMajorVersion" : oObj.SPver = oEnm_2.item().Value; continue; case "WindowsDirectory" : oObj.WinDir = oEnm_2.item().Value; continue; case "SystemDirectory" : oObj.SysDir = oEnm_2.item().Value; continue; case "TotalVisibleMemorySize" : oObj.RAM = Math.round(oEnm_2.item().Value/1024); continue; case "BootDevice" : oObj.BootDev = oEnm_2.item().Value; continue; case "SystemDevice" : oObj.SysDev = oEnm_2.item().Value; continue; default : continue; } } } return oObj; // >>> } Branimir From jan at jandecaluwe.com Mon Jul 28 02:16:26 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: 27 Jul 2003 23:16:26 -0700 Subject: Checking whether bool is a type References: <3F2442B2.E660E97@jandecaluwe.com> Message-ID: <2e5a8637.0307272216.5adba17d@posting.google.com> "Terry Reedy" wrote in message > > If all you care about is differentiating between 2.2 and 2.3, yes. > But this raises NameError, I believe, on earlier verisons without > 'bool' builtin. What is wrong with using sys.version[:3] >= '2.3'? > (Anyone - has sys.version always been around?) Nothing - I do a general version check like that on 2.2 because I need generators. I was writing unit tests that specifically tests features that I can only support when bool is a type. I found it clearer to directly test for that. Regards, Jan -- Jan Decaluwe - Resources bvba Losbergenlaan 16, B-3010 Leuven, Belgium mailto:jan at jandecaluwe.com http://jandecaluwe.com From tim.one at comcast.net Fri Jul 4 15:38:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 4 Jul 2003 15:38:01 -0400 Subject: A possible bug in python threading/time module? In-Reply-To: Message-ID: [Tim] > Turns out that the Windows implementation of the Python C API function > PyThread_start_new_thread() contained several "laziness" errors > > ... > > I'm testing putative fixes on a Win98 box and don't see any hangs any > more. However, with more than about 3000 threads, > > thread.error: can't start new thread > > gets raised because MS's _beginthread() fails (with errno == EAGAIN == > "there are too many threads"). FYI, these fixes have been checked in and will be part of 2.3 final (and 2.2.4, if that's ever released). The maximum number of threads you can have alive simultaneously on 32-bit Windows in an all-default Python build is actually about 2000. This is because each thread gets a megabyte of stack space by default, and 2048 threads would entirely exhaust the 31-bit user virtual address space just for thread stacks. If you want to know more about that, Google on CreateThread default stack size The top hit is to the current relevant MSDN docs. From faizan at jaredweb.com Thu Jul 31 14:23:23 2003 From: faizan at jaredweb.com (Fazer) Date: 31 Jul 2003 11:23:23 -0700 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> <7b454334.0307301611.1b40ff11@posting.google.com> Message-ID: <7b454334.0307311023.28900d57@posting.google.com> Gerhard H?ring wrote in message news:... > Fazer wrote: > > [...] I am basically looking for a FAST > > alternative to PHP meaning the responce time is fast. Do you think > > that Python with using the CGI module is a good solution? > > No, CGI is not a good solution in this case, no matter what the language > (except those perverts who use something like C with dietlibc for this). > > The base technology to make web requests fast in Python is something > like mod_python or a Python application server. On top of this I'd > recommend you use a Python web framework, of which there are numerous > ones. The hard part is to evaluate them and choose one. > > FWIW I'm currently using Quixote running with mod_scgi against Apache, > mostly because I was fed up with the (lack of) Webware documentation, > which I tried first. > > -- Gerhard Thanks for the reply! I think I am going to give mod_python a try. Would I have to be root to install mod_python? Because that's one of my biggest concerns. I don't have root and I don't want to work on my windows machine since I am kind of more comfortable working on a Linux platform. Basically, most of my Python scripts would just be accessing the MySQL database and just printing out various data. From domma at procoders.net Thu Jul 10 07:35:17 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 10 Jul 2003 13:35:17 +0200 Subject: PYTHON TO ANSYS References: Message-ID: "satish k.chimakurthi" wrote in message news:mailman.1057796495.19578.python-list at python.org... > Can anyone of you tell me if there is any way of interfacing ANSYS, > which is a commercial software to python. I would like to have some sample > codes which were written to interface solvers both commercial and in-house. I don't know ANSYS but such softwares have usually also a C/C++ API. In that case you could use for example boost.python (or one of the other tools like SWIG) to build a python wrapper around the C/C++ API. regards, Achim From http Fri Jul 25 16:35:49 2003 From: http (Paul Rubin) Date: 25 Jul 2003 13:35:49 -0700 Subject: file.close() References: <7xhe5b82ip.fsf@ruckus.brouhaha.com> Message-ID: <7xr84e9wey.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > >"done" here is a generic method that gets called on exiting a "with" > >block. > First reaction == +1, but some questions... > > 1) Is f.done() really necessary? I.e., doesn't an explicit del f > take care of it if the object has been coded with a __del__ > method? I.e., the idea was to get the effect of CPython's > immediate effective del on ref count going to zero, right? The ref count might not be zero. Something inside the "with" block might make a new reference and leave it around. > 2) how about with two files (or other multiple resources)? > > with f1,f2 = file('f1'), file('f2'): > [do stuff with f1 & f2] > > What is the canonical expansion? I think f1.done and f2.done should both get called. > Also, what about the attribute version, i.e., > > ob.f = file(frob) > try: > [do stuff with ob.f] > finally: > del ob.f # calls f.__del__, which calls/does f.close() > > I.e., ob.f = something could raise an exception (e.g., a read-only property) > *after* file(frob) has succeeded. So I guess the easiest would be to limit > the left hand side to plain names... The assignment should be inside the try. If I had it on the outside before, that was an error. From mis6 at pitt.edu Thu Jul 3 10:52:44 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 3 Jul 2003 07:52:44 -0700 Subject: cooperation of buitlin methods usingtsuper References: <2259b0e2.0307020855.478300c2@posting.google.com> Message-ID: <2259b0e2.0307030652.697001dd@posting.google.com> > In <2259b0e2.0307020855.478300c2 at posting.google.com> Michele Simionato wrote: > > Matthias Oberlaender > wrote in message news:...> I would like > to adopt the cooperation paradigm in conjunction with builtin > > > methods and operators, such as len, iter, +, * etc. > > > > Fine. > > > > > But the direct approach does not work with the current implementation of > > > super. For example, 'len(super(Y, y)' will always result in 'len() of > > > unsized object'. > > > > Of course, it must give an error! I think you do not understand how > > super works. But don't worry, that's quite common ;) > > Oh, wait a minute. I think this "of course" is a bit presumptuous. Uhm... I do realize now that what I wrote sounds quite presumptuous indeed. It was not my intention. The "of course" refers to the current implementation of ``super`` which does not do what you ask for. To me this was well known because of recent threads on the subject by Bjorn Pettersen: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&frame=right&th=a385e6aa839a9538&seekm=2259b0e2.0304210750.5eaf5df0%40posting.google.com#link1 http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=2259b0e2.0304300625.4e0ebace%40posting.google.com&rnum=3&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DISO-8859-1%26q%3Dsuper%2Bpettersen%26meta%3Dgroup%253Dcomp.lang.python.* You see that for sure you are not the only one who is confused about ``super`` and there are dark corners about it. I myself do not know nothing about its implementation. > > > > I think you should re-read the documentation and > > google on the newsgroup for 'super'. The use case > > for super is in multiple inheritance, as in this example: > > > > class B(object): > > def __len__(self): > > print 'called B.__len__' return 1111 > > > > class C(B): > > def __len__(self): > > print 'called C.__len__' > > return super(C,self).__len__() > > This is exactly the style of syntax I want to avoid! I'd rather write more > concisely 'len(super(C,self))'. I see now what's your point, which is the same of Pettersen: why >>> class B(object): def __len__(self): return 1111 >>> class C(B): pass ... >>> c=C() >>> super(C,c).__len__() 1111 works, whereas >>> len(super(C,c)) Traceback (most recent call last): File "", line 1, in ? len(super(C,c)) TypeError: len() of unsized object does not work? As you say, the reason is that > at least in Python 2.2.1, its is > a matter of fact that builtins/special method names are treated differently > from ordinary class methods in conjunction with super objects. Do you agree? > My implementation of super seems to fix this gap. Perhaps there are some > other people who would appreciate that too. Or are there good > logical/conceptual reasons againts it? This is what I would like to know. BTW, the same is true for Python2.3b2. I always use the longest form of ``super``,so this problems does not bother me, nevertheless I understand your point. I think you should submit the issue to python-dev; maybe there are technical reasons such that it is necessary to treat special methods differently and this cannot be avoided. In such a case the documentation should report that only the long form ``super(C,c).__len__()`` is correct and that users should not use ``len(super(C,c))`` (idem for other special methods). I would also submit a bug report on sourceforge, since at the best this is a documentation bug. It does not seem to have been reported before and has already bitten at least two persons on c.l.py., therefore it should be made known to the developers Michele From daniel at dittmar.net Wed Jul 9 18:10:21 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Thu, 10 Jul 2003 00:10:21 +0200 Subject: Shared vs static link performance hit --and Windows? In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > I might say something stupid since I am not an "expert" on Windows > architectures, but would it be feasible (and useful) to build a static > python.exe on windows? Or is it that there would be no difference > performance-wise in the final interpreter? On windows, DLLs (and .pyd) can only call function in other DLLs, not in the EXE they are called from. So building a statically linked python would make it impossible to load dynamically .pyd files. OT: One could of course change the Python extending API so that every extension function gets a pointer to the interpreter instances and all API functions are members of the interpreter object. This adds an additional indirection, so it wouldn't help the performace. On the plus side, this would make it at least feasable that extenions are binary compatible to newer Pythons the same way they often are on Unix. Daniel From hanzspam at yahoo.com.au Fri Jul 4 11:03:27 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 4 Jul 2003 08:03:27 -0700 Subject: 'For' loop symmetry with list comprehensions. References: <840592e1.0307021036.508d7d7d@posting.google.com> Message-ID: <840592e1.0307040703.507fed3c@posting.google.com> "Sean Ross" wrote in message news:... > (being symmetrical) we should also be able to write: > > >>> msgs = [] > >>> for x in words: > ... for y in otherwords: > ... msgs.append("%s %s"%(x,y)) > ... > >>> msgs > ['hello foo', 'hello bar', 'bonjour foo', 'bonjour bar'] > > > as follows: > > msgs = [] > for x in words for y in otherwords: > msgs.append("%s %s"%(x,y)) > > > If you really want symmetry, well, this is symmetrical. Do you want this as > well? > > -0 > Sean Ok, I see. Just because new for syntax had to be added to work on one line in list comprehensions doesn't mean that rest of the language should be polluted with the one-liner syntax too. So it wasn't that good of an idea after all :P From nospam at here.com Sun Jul 13 17:15:10 2003 From: nospam at here.com (Richard Townsend) Date: Sun, 13 Jul 2003 22:15:10 +0100 Subject: sample code from John Grayson's "Python and Tkinter Programning" book References: <3f11c0d5.19274484@news.earthlink.net> Message-ID: <1058130815.16008.0@demeter.uk.clara.net> "Ken Erickson" wrote in message news:3f11c0d5.19274484 at news.earthlink.net... > Does anyone know if the example code in John Grayson's book is > available online? He has some interesting examples and I really don't > want to spend hours re-typing his work (too many typo's late at > night). I rather spend time walking through the code via the > debugger. > > TIA. Try: http://www.manning.com/getpage.html?project=grayson&filename=Source.html From rxs141 at cwru.edu Sun Jul 20 14:50:29 2003 From: rxs141 at cwru.edu (Ravi) Date: Sun, 20 Jul 2003 14:50:29 -0400 Subject: "Pure Python" MySQL module like Net::MySQL In-Reply-To: References: Message-ID: Gerhard H?ring wrote: > > Is there any particular reason why you'd need such a beast instead of > just using MySQLdb? > I'm developing for cell phones/PDA's using Jython, because Java is available. Yet, a proper C compiler is not, so libmysql cannot be compiled. I will see if I can put a wrapper on the Java MySQL connector to make it accessible in Jython. Thanks for your help, Ravi From florian.proff.schulze at gmx.net Tue Jul 22 07:13:29 2003 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Tue, 22 Jul 2003 13:13:29 +0200 Subject: Python Mystery Theatre -- Episode 3: Extend this References: Message-ID: On Tue, 22 Jul 2003 07:27:21 GMT, Raymond Hettinger wrote: > ACT I --------------------- > def real(z): > return hasattr(z, 'real') and z.real or z > def imag(z): > return hasattr(z, 'imag') and z.imag or 0 > for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L: > print real(z), imag(z) Duh, I had to look at the output, but after that it was obvious: For 0+6j, hasattr(z, 'real') is true, but t.real is false so z is printed. For imag it's no problem, as it's 0 either way. > ACT II --------------------- > uniq = {} > for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0): > uniq(k) = 1 > print len(uniq) My prediction is between 5 and 7 depending on the hash values for numbers. Uhh, 3 !?! So numbers and strings generate a hash just by their value. And the unicode string has the same hash as a normal string if just ascii is used. Should have been obvious. ps: it should be uniq[k] = 1 or the output would have been a traceback, maybe this was intended ;) > ACT III --------------------- > s = 'abracadabra' > for i in [3, 2, 1, 0]: > print s[i:], s[-i:] Prediction: acadabra bra racadabra ra bracadabra a abracadabra abracadabra Result: acadabra bra racadabra ra bracadabra a abracadabra abracadabra Yep! s[-0:] is the same as s[0:]. > ACT IV --------------------- > pets = list('cat ') > pets += 'dog ' > pets.extend('fish ') > print pets + 'python' I would say this raises a TypeError. But it's at the print not at pets += 'dog ', so the string is used as a sequence here. > INTERMISSION (with output included, oh yeah! ------------ >>>> import operator >>>> 1 - reduce(operator.add, [1e-7]* 10**7) > 2.4983004554002264e-010 Uh! Binary representation of floating point strikes again. > ACT V --------------------- > class Bin: > numitems = 0 > contents = [] > > def add(self, item): > self.numitems += 1 > self.contents += [item] > > laundry = Bin() > groceries = Bin() > > laundry.add('shirt') > groceries.add('bananas') > groceries.add('nuts') > laundry.add('socks') > groceries.add('pretzels') > > print laundry.numitems, laundry.contents > print groceries.numitems, groceries.contents Prediction: 2 ['shirt','bananas','nuts','socks','pretzels'] 3 ['shirt','bananas','nuts','socks','pretzels'] Result: 2 ['shirt','bananas','nuts','socks','pretzels'] 3 ['shirt','bananas','nuts','socks','pretzels'] Contents is a class variable and not unique to an instance. > ACT VI ----------------------------------------- > print "What is the technical name for this algorithm or transformation?" > a = range(0, 100, 10) > import random > random.shuffle(a) > print "Input:", a > swaps = 0 > for i in range(len(a)): > for j in range(i+1, len(a)): > if a[i] > a[j]: > i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1 > print "Output:", a > print "Workload;", swaps I would say it's bubble sort, but it doesn't work and I don't yet understand why. Oh, wait, i and j are assigned first and then a[i] is the a[j] from before and the other way around. But after testing I found out that i and j should never be swapped, as this disturbs the inner loop, because i is wrong then. My guess for the real bugs: ACT I ACT III ACT V Florian Schulze From CousinStanley at hotmail.com Tue Jul 1 01:17:43 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Mon, 30 Jun 2003 22:17:43 -0700 Subject: "Newbie" questions - "unique" sorting ? References: <8da5fvsnidpjtblgfj4484spso2t9e6r95@4ax.com> Message-ID: | ... | Bye the way Cousin Stanley I assume the numbers | in the final result were how many times that string | appeared in the input file ? | | A very interesting number to have. | | When I get time though I might "rem" (is that # ?) out | that/those line/lines so that I have a second URL sorting | python executable that doesn't include the numbers. | | Assuming I can work out which one(s) to disable ! John ... Getting rid of the word_count isn't too bad .... Find the following code block in word_list.py .... for this_word in list_words : word_count = dict_words[ this_word ] str_out = '%6d %s %s' % ( word_count , this_word , NL ) file_out.write( str_out ) Change the above 4 lines to the following 2 .... for this_word in list_words : file_out.write( this_word + NL ) Save the changed file to word_list2.py .... As an alternative, since the words you are interested in in this application are actually URLs, you might want to generate actual clickable HTML links .... for this_word in list_words : file_out.write( '' + NL ) file_out.write( this_word + NL ) file_out.write( '' + NL + NL ) Save the changed file to word_list3.py .... I haven't tested either of the above changes, but this should provide some ideas .... -- Cousin Stanley Human Being Phoenix, Arizona From max at alcyone.com Mon Jul 7 03:38:03 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 07 Jul 2003 00:38:03 -0700 Subject: anything new on the ternary operator? References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> Message-ID: <3F09235B.6F7DE56@alcyone.com> Andreas Jung wrote: > Please stop the discussion. The ternary operator is dead (which is a > very > good thing) > because GvR made the decision. There's not much doubt that the conditional operator will not be making it into Python in the future, but just because the BDFL has made a decree (although a significantly delayed one), it's a little naive to think that discussion of it will not continue. This clause was in the PEP ("the subject better not come up again"), but I'm not sure how this clause will really have much effect. Obviously no more PEPs on the subject will be accepted, and needless to say it won't be considered by the development team in the future, but it seems weird to suggest that because a PEP came up, was (after many months) indirectly rejected in a presentation (the PEP is not even updated to show its rejected status), that all users are precluded from discussing in the future. Mind you, such discussion will not be very constructive, but just saying, "Welp, it's not going to be added, nobody talk about it ever again" is not going to be very effective when new people come in all the time and, one must admit, at least some segment of the user community would have liked the feature. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I am a gentlemen: I live by robbing the poor. \__/ George Bernard Shaw From intentionally at blank.co.uk Mon Jul 14 22:16:08 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:16:08 +0100 Subject: anything like C++ references? References: Message-ID: On 14 Jul 2003 23:31:56 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: > It looks like you've almost reached understanding, though you've been >given a bad start with a very idiosyncratic and monolingual >understanding of what "computer science" teaches--that was certainly not >in the classes I took, but apparently yours were different. Really. My computer science lessons were taught in a way that respected the source of most of the theory in mathematics - algorithms, Church's lambda calculus and that kind of stuff. What did your lessons teach? > Since every operation in Python operates on pointers, there's no use >in having a special syntax for it. You don't need all the * and & and >-> line noise. The point of the thread is not pointers - they are a side issue. When you use variables, you are using a concept from mathematics. In mathematics, variables bind to values. All values are immutable. Python binds variables to objects, not values. For immutable objects this is an unimportant implementation detail. For mutable objects, it breaks the mathematical principle of variables being bound to values. > Stop trying to make Python into C/C++, and you'll be happier with it. >Or stop using Python, if you really don't like the design philosophy. >There are plenty of Algol-derived languages out there. PHP and >especially Perl are more C-like in their internal logic, and you might >find them more pleasant. This is bogus. I don't want Python to become C or C++. I want Python to respect principles that come from mathematics and computer science. Not for reasons of theory pedanticism, but because the current system can and does regularly cause confusion and errors. The fact that Python claims to be a very high level language, and yet you have to worry about the binding of variables to objects - something that should be a low level implementation detail - has very real everyday implications. Respect the idea of variables binding to values and suddenly the need for pointers becomes more obvious. You cannot abuse mutable objects to fake pointer functionality (another everyday fact of Python programming) if the binding of variables to values (rather than just objects) is respected. From intentionally at blank.co.uk Sun Jul 13 11:11:37 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 16:11:37 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: On 13 Jul 2003 10:37:01 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >Stephen Horne wrote: >> >>One of the few things I hate about Python is that mutable objects are >>implicitly shared using a reference system whereas immutable objects >>are not. > >Well, that's incorrect. *ALL* Python objects are implicitly shared with >bindings. The difference is whether updating the value referenced by a >target requires *re*binding the target or simply updating an object. Fine - nit-pick. All you have proven is that it is the distinction between types that get re-bound and those that don't (rather than the use of references) that is unnecessarily confusing and error prone. The wart remains, even if my description was wrong. And even that is a dubious claim. A Python user is interested in how an object behaves - not how it is internally implemented in the interpreter. Immutable objects don't behave as references - the internal use of references for immutable objects is basically a lazy copying optimisation and, apart from performace and a couple of other technicalities (e.g. the 'is' operator), has no relevance. Certainly it has no relevance to the point I was making. From colinsm.spam-me-not at picsel.com Thu Jul 10 13:25:52 2003 From: colinsm.spam-me-not at picsel.com (Colin S. Miller) Date: Thu, 10 Jul 2003 18:25:52 +0100 Subject: UTF-16-LE and split() under MS-Windows XP In-Reply-To: References: Message-ID: Martin v. L?wis wrote: > "Colin S. Miller" writes: > > >>Where have I gone wrong, and what is the correct method >>to verify the BOM mark? > > > readline is not supported in the UTF-16 codec. You have to read the > entire file, and perform .split. Looking at the BOM should not be > necessary, as the UTF-16 codec will do so on its own. Is there any reason why readline() isn't supported? AFAIK, the prefered UNICODE standard line endings are 0x2028 (Line seperator) 0x2029 (Paragraph seperator) but 0x10 (Line feed) and 0x13 (carriage return) are also supported for legacy support. I'm using file.read().splitlines() now, but am slightly worried about perfomance/memory when there a few hundered lines. TIA, Colin S. Miller > > Regards, > Martin > From Jeffrey.S.Whitaker at noaa.gov Sat Jul 5 12:26:34 2003 From: Jeffrey.S.Whitaker at noaa.gov (Jeffrey.S.Whitaker at noaa.gov) Date: Sat, 05 Jul 2003 16:26:34 GMT Subject: Bewildered graphs In-Reply-To: <3F06BF7C.8DC6A978@noaa.gov> References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: On Sat, 5 Jul 2003, Mark Fenbers wrote: > I am investigating Python for the sake of ultimately generating hydrographs > (such as this: http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) > on-the-fly from a web server cluster. I have not used Python previously and do > not yet know if Python is very useful for this or if I am wasting my time. > > Quite frankly, I am a little bewildered. Not only is there Python, but there > are many extention modules which cloud up my view as to what I will need. > There's Scientific Python, which sounds promising, but there's also SciPy which > in itself has gnuplot, xplt and plt modules. I know enough about gnuplot to > know that it won't meet my needs because I need to be able to shade regions > above certain values such as done in yellow on the example hydrograph (the link > above). It also doesn't have many font options or the ability to place an image > such as the NOAA logo. > > Can someone kindly guide me as to what I would most likely need to replicate the > graph shown via the link above? > Mark: NCL (http://www.cgd.ucar.edu/nclapps/gsn/) will do what you need. I've written a simple python module that allows you to embed NCL scripts in python code (http://www.cdc.noaa.gov/~jsw/python/pyncl.html). http://www.ccsm.ucar.edu/csm/support/CSM_Graphics/index.shtml has some nice NCL plotting examples. -Jeff -- Jeffrey S. Whitaker Phone : (303)497-6313 NOAA/OAR/CDC R/CDC1 FAX : (303)497-6449 325 Broadway Web : http://www.cdc.noaa.gov/~jsw Boulder, CO, USA 80305-3328 Office: Skaggs Research Cntr 1D-124 From davidcfox at post.harvard.edu Tue Jul 29 17:36:36 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 29 Jul 2003 21:36:36 GMT Subject: inverse of the zip function In-Reply-To: References: <9sBVa.12998$o%2.6289@sccrnsc02> Message-ID: Terry Reedy wrote: > "David C. Fox" wrote in message > news:9sBVa.12998$o%2.6289 at sccrnsc02... > >>Is there a function which takes a list of tuples and returns a list > > of > >>lists made up of the first element of each tuple, the second element > > of > >>each tuple, etc.? >> >>In other words, the the inverse of the built-in zip function? > > > Go to > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.python > enter 'zip inverse', and check search Python only. > > TJR > > Thanks. I've gotten so used to reading this group with Mozilla Mail that I forgot about google groups. David From adechert at earthlink.net Mon Jul 21 12:56:20 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 16:56:20 GMT Subject: Python voting demo discussion References: Message-ID: "Ian Bicking" wrote in message news:mailman.1058779892.1544.python-list at python.org... > Python is quite appropriate for these sorts of > changes, certainly moreso than C and C++, and arguably C# and Java. > Thanks again, Ian. We will use Python for the demo. It will be on sourceforge.net momentarily. Alan Dechert From richie at entrian.com Thu Jul 31 08:39:47 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 31 Jul 2003 13:39:47 +0100 Subject: Python speed vs csharp In-Reply-To: References: Message-ID: <4t1iiv8ecaf64b4832sr5aro3lr5588l9g@4ax.com> [Mike] > is there anything that can be done to get Python's speed close > to the speed of C#? Using Pyrex takes a million loops from 7.1 seconds to 1.3 seconds for me: ------------------------------- mike.pyx ------------------------------- cdef extern from "math.h": double exp(double x) def erfc(x): cdef double f_x, p, a1, a2, a3, a4, a5, t f_x = x p = 0.3275911 a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 t = 1.0 / (1.0 + p*f_x) return ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * exp(-(f_x**2)) ------------------------------- setup.py ------------------------------- # Run with "python setup.py build" from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = "Mike", ext_modules=[ Extension("mike", ["mike.pyx"]) ], cmdclass = {'build_ext': build_ext} ) ------------------------------- test.py ------------------------------- # This takes about 1.3 seconds on my machine. import time from mike import erfc if __name__ == '__main__': start = time.time() for i in xrange(1000000): erfc(123.456) print time.time() - start ----------------------------------------------------------------------- Given that a million calls to "def x(): pass" take 0.9 seconds, the actual calculation time is about 0.4 seconds, down from 6.2. Not as fast as your C# results, but a lot better than you had before. Using Psyco dropped from 7.1 seconds to 5.4 - not great, but not bad for two lines of additional code: import psyco psyco.bind(erfc) Psyco currently only works on Intel-x86 compatible processors. Hope that helps, -- Richie Hindle richie at entrian.com From ben at dadsetan.com Wed Jul 9 16:09:11 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 09 Jul 2003 22:09:11 +0200 Subject: Deleting specific characters from a string In-Reply-To: References: <5ab0af73.0307091044.254f5aab@posting.google.com> Message-ID: Donn Cave wrote: > In article <5ab0af73.0307091044.254f5aab at posting.google.com>, > MatthewS at HeyAnita.com (Matt Shomphe) wrote: >>Maybe a new method should be added to the str class, called "remove". >>It would take a list of characters and remove them from the string: > Check out the translate function - that's what its optional > deletions argument is for. >>> str = 'You are Ben at orange?enter&your&code' >>> str.translate(string.maketrans('',''), '@&') and >>> str.replace('&', '').replace('@', '') are also ugly... The first version is completely unreadable. I guess my initial example ''.join([ c for c in str if c not in ('@', '&')]) was easier to read than the translate (who would guess -without having to peek in the documentation of translate- that that line deletes @ and &?!) but I am not sure ;) while the second becomes acceptable. The examples you gave me use the string module. I think I read somewhere that the methods of the object should rather be used than the string module. Is that right? Thanks anyhow, I will go for the replace(something, '') method. Ben. From FBatista at uniFON.com.ar Mon Jul 14 14:54:54 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 14 Jul 2003 15:54:54 -0300 Subject: some questions Message-ID: The method string.split() returns a list: >>> s = "This is an example" >>> s.split() ['This', 'is', 'an', 'example'] >>> s 'This is an example' Be warned that split *returns* a string, does *not* modifies the string itself (as you can see above, s is still the original s). As a tutorial, I love "Dive into Python". . Facundo #- -----Mensaje original----- #- De: Andreas Bauer [mailto:buki at bukis.org] #- Enviado el: Lunes 14 de Julio de 2003 3:27 PM #- Para: python-list at python.org #- Asunto: some questions #- #- #- Hi, #- #- I need some information on how to deal with strings which I have #- divided by using split(). I'm new to python and don't know how to #- handle these split up strings. #- And I some one could recommend a good tutorial I would be very #- glad. Can't hardly find any. #- #- Thanks in advance. #- #- Andreas #- -- #- http://mail.python.org/mailman/listinfo/python-list #- From tomas at fancy.org Sun Jul 13 03:41:22 2003 From: tomas at fancy.org (Tom Plunket) Date: Sun, 13 Jul 2003 00:41:22 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <1058050617.28466.279.camel@lothlorien> Message-ID: Dave Brueck wrote: > Your response above (that the normal thing to do in Python is > just return the modified value) made me wonder if most people are > asking about pass-by-reference not because they want pass-by- > reference, but because in C it's generally a nuisance to return > stuff from functions, especially multiple values, so you end up > learning about pointers and/or pass-by-reference. In C++ it's trivial to return multiple values and pass-by- reference is typically (at least, as far as I've seen) used to pass immutables anyway, but sometimes it just seems like the right tool for the job. > IOW, if you could erase the influence of previous languages would > this FAQ become "how can I return multiple things from a > function" more often than it would become "how can I modify an > object from inside a function"? That's a good idea, although I would have to say that multiple return values typically means that your function is doing too many things. ;) -tom! From lbliss at dls.net Thu Jul 10 09:31:47 2003 From: lbliss at dls.net (Lee) Date: 10 Jul 2003 06:31:47 -0700 Subject: Python 2.2 build problems on AIX References: Message-ID: Sac wrote in message news:... > edadk wrote: > > > Hi > > > > I building Python on AIX using > > > > make > > > > However, I get some errors when building > > > > readline > > gdbm > > > > and > > > > -ltermcap > > > > is missing. See below. Can those problems be fixed? > > > > Erling > > > > building 'readline' extension > > cc_r -DNDEBUG -O -I. > > -I/mnt/mds/metawrk/edanders/Python-2.2.3/./Include > > -I/usr/local/include -I/mnt/mds/metawrk/edanders/Pytho > > 2.2.3/Include -I/mnt/mds/metawrk/edanders/Python-2.2.3 -c > > /mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c -o build/t > > ...(Lines Deleted) > > Greetings, > > You may wish to grab some of these tools and utilities from IBM. Many > Open Source packages are available. Project heading is Linux Toolbox > for AIX. > > Source and binaries are available from the following IBM website: > ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox > > Installation instructions are available from > ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/README.txt > > Cheers... You definitely want to install readline, gdbm, etc. They are available either on the Linux CD that came with AIX or from the ftp site above. I was able to complete the build once I installed the termcap libraries from the AIX CDs. From the smit install, search for the string termcap. It will find two filesets. Install both and the build should work. From paddy3118 at netscape.netNOTthisBIT Wed Jul 30 13:26:35 2003 From: paddy3118 at netscape.netNOTthisBIT (Donald 'Paddy' McCarthy) Date: Wed, 30 Jul 2003 18:26:35 +0100 Subject: Misuse of In-Reply-To: <3f27f0e3$1@news.broadpark.no> References: <3f27f0e3$1@news.broadpark.no> Message-ID: Gisle Vanem wrote: > I'm a .py newbie and fascinated by the simplicity of formatting. > No need for {} as in Perl etc. But the misuse of that many > .py writers do makes it hard to understand how a script operates. > > E.g. <> > > Now, with an editor with different tab-settings it's difficult to see where > the try statement belongs. In 'def main()' or in 'def foo()' ? > I'm confused, please enlighten me. The usual rule is to either: 1) Don't use tabs for indentation at all. Or 2) If you must use tabs, then always use just tabs/ If you have an editor that might automatically change several spaces to tabs then turn that feature off or don't use the editor. Cheers, Pad. From alanmk at hotmail.com Fri Jul 18 05:45:56 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 18 Jul 2003 10:45:56 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <3F17C1D4.1A70703A@hotmail.com> "Martin v. Loewis" wrote: > So what do you think about this message?: > > ???????????????? > > Look Ma, no markup. And not every character uses two bytes, either. > And I can use Umlauts (??????) and Arabic (????????.????????????) > if I want to. Martin, I can see from other people's messages that this has been successful for some people with modern software. However, it failed for me on my old Netscape 4.x Messenger. Which is acceptable, I suppose, because I intentionally use ancient email and usenet software. It is also worth noting that although my poor old usenet client failed to display the sequence of characters, the "Navigator" component to which it belongs correctly displayed the greek text when fed Bengt's "gignooskoo.html" file (although it failed on my xml snippet). More worrying however is the failure of modern browsers to display the characters when accessed through Google Groups. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3F172442.2040907%40v.loewis.de I tried to view this in IE6.0 and Netscape 6.2, and all I saw was "?????s??". Whereas that thread still shows my XML snippet intact, still copy&paste-able. kind regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From tim.one at comcast.net Thu Jul 31 22:49:28 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 31 Jul 2003 22:49:28 -0400 Subject: time, calendar, datetime, etc In-Reply-To: Message-ID: [John Roth] > The datetime module is a great piece of work, but I wonder why it > wasn't made more compatible with the time module? It would seem to > be simple enough to provide a sequence interface so the object > supports the 9-tuple directly (for either naive or tz-aware, pick > one,) and also supports the same attributes as the objects in the > time package. The time module consists of thin wrappers around C's mish-mash of quirky, platform-dependent time manipulation functions. We eventually want to pretend the time module never existed <0.9 wink>. 9-tuples are absurd. > I also wonder why anyone made the choice to set the year origin at > 1AD? That decision, by itself, makes it almost unusable for my hobby > (astrological software, which is basically astronomical software > with a different focus.) The datetime design took place on a Zope Wiki: http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage and Zope Corp funded the work. If more astronomers used Zope, the outcome may have been different. As things were, fast field extraction for formatting and fiddling, compact memory representation and pickles, "practical" dates, fast compaison, and exact arithmetic were goals. See especially the SuggestedRequirements page in that Wiki. Astronomers were dissed in its first bullet . From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 29 11:57:02 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 29 Jul 2003 15:57:02 GMT Subject: PyQt Help and Advice References: Message-ID: Ilya Knizhnik enlightened us with: > However since PyQt is rather new, I have not found much > documentation on it, or examples in it. The only useful > tutorial/book I have found is at www.opendocspublishing.com/pyqt/ > but it is not always clear for someone with almost no GUI > experience. You might want to follow the QT tutorials that come with the QT documentation. The best way to read the QT docs is through QT Assistant. You can design GUIs with QT's 'designer' (it's called that way, very original name) and convert the .ui files to .py files with 'pyuic'. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From aahz at pythoncraft.com Fri Jul 4 14:08:10 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Jul 2003 14:08:10 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <87llve8fh3.fsf@pobox.com> Message-ID: In article <87llve8fh3.fsf at pobox.com>, John J. Lee wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> At the same time, more and more of those games are switching to using >> C/C++ only for the rendering engine and using a scripting language (Lua >> or Python) for the gameplay itself. > >Is this true of big-$ commercial games? What sort of market share do >high-level / interpreted languages have there? Depends what you mean by big-$. Humongous Entertainment has recently switched to requiring Python for all new games. Lua is even more prevalent; see http://www.lua.org/uses.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From belred1 at yahoo.com Tue Jul 15 01:53:31 2003 From: belred1 at yahoo.com (Bryan) Date: Tue, 15 Jul 2003 05:53:31 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> <9iu6hv4r968o9s1n5fh887u2j7an94de4e@4ax.com> Message-ID: > In my view, Python does largely what I want it to do regardless > of mathematical correctness. > > -tom! > wow... finally...beautifully said... concise... and i would wager this is what most people think who feel at home with python. and with this, i declare this insane thread to be sys.exit() From bgailer at alum.rpi.edu Wed Jul 16 12:48:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 16 Jul 2003 10:48:39 -0600 Subject: Stop Python from exiting upon error in Windows In-Reply-To: References: <3F136BEA.5B56562@engcorp.com> <3F142B51.94C898BC@engcorp.com> Message-ID: <5.2.1.1.0.20030716104024.027feca8@66.28.54.253> At 03:03 PM 7/15/2003 -0700, Robert at AbilitySys.com wrote: >The trouble there is that sys.argv[0] is consistently the file name of the >script running, whether I do it with python.exe or via IDLE/Run Script. (I >actually use it to open the script within itself and copy itself out to an >audit log for a record of what code created the script's results) > >You're right, it's probably not worth it since it just adds a "press enter" >to the output when I run my script in IDLE (where I don't actually need the >pause). I just thought the cognoscenti out here might have run across a >nifty trick for determining if it was python.exe/PythonWin/whatever since I >couldn't find such a thing in the books or manuals I have... The length of sys.modules can help. The 2.2.2 interpreter __import__s 15 modules; IDLE adds 73, PythonWin adds 213. So code like this might suffice, leaving room for future changes. import sys if len(sys.modules) < 50: ... # raw interpreter elif len(sys.modules) < 200: ... # IDLE else: ... # PythonWin Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From hokiegal99 at hotmail.com Wed Jul 9 10:15:32 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 9 Jul 2003 07:15:32 -0700 Subject: regexp and filenames References: Message-ID: <93f5c5e9.0307090615.1c51f5f7@posting.google.com> I added a few chars to the bad character list and these two print statements to the end of the script: print oldpath print newpath So I could see what filenames were changed and where. I wrote a script that generates broken filenames in the filesystem and then ran your script to see if everything works as expected. Did some testing... so far it works great. See output below. Thanks for the program! I only wanted direction, but you went the extra mile! Also, I d/l 2.3b2 before testing your script. No problems there either. mv test1- "test1*" mv test2- "test2<" mv test3- "test3>" mv test4- "test4:" mv test5- "test5;" mv test6-t "test6\t" mv test7- "test7?" mv test8- "test8|" mv test9-t "test9\"t" mv test10- "test10=" mv test11- "test11+" #--------- cd SPREADSHEETS #--------- mv test1- "test1*" mv test2- "test2<" mv test3- "test3>" mv test4- "test4:" mv test5- "test5;" mv test6-t "test6\t" mv test7- "test7?" mv test8- "test8|" mv test9-t "test9\"t" mv test10- "test10=" mv test11- "test11+" #--------- #-------- cd ../BEN*/NCAA*R* #-------- mv test1- "test1*" mv test2- "test2<" mv test3- "test3>" mv test4- "test4:" mv test5- "test5;" mv test6-t "test6\t" mv test7- "test7?" mv test8- "test8|" mv test9-t "test9\"t" mv test10- "test10=" mv test11- "test11+" #--------- #--------- #1 = * #2 = < #3 = > #4 = : #5 = ; #6 = \ #7 = ? #8 = | #9 = " #10 = = #11 = + emf wrote in message news:... > --On 8 Tuesday, July 2003 20:24 -0400 hokiegal99 > wrote: > > > I have a bit of a problem that I think Python can solve, but I need a > > bit of direction. I'm replacing 12 Macs with PCs. Macs allow > > characters in filenames that Windows does not, specifically the > > following: > > > > : * ? " < > | / \ > > > > I would like to write a script that searches through a directory for > > filenames that contain any of the aboved listed characters and > > replaces them with a - (the minus sign). > > > > I'm familiar with regexp, but I've only used it in Python to act on > > the contents of a file, not filenames in a directory. Any pointers on > > how to approach this are welcome! > > > > This should do the trick. You can steal walk from 2.3 and use it in 2.2 > with hardly any modifications, if you're using 2.2. > > import os, re > > # | and \ have to be escaped; > # the r prefix on the string keeps it from being a huge escape: > badcharset = re.compile(r'[*:?"<>/\|\\]') > > for root, dirs, files in os.walk('/'): #or however you spell root on > your mac > for file in files: > badchars = badcharset.findall(file) > newfile = '' > for badchar in badchars: > newfile = file.replace(badchar,'-') > if newfile: > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,file) > os.rename(oldpath,newpath) > > Hope that helps, > > ~mindlace > http://mindlace.net From logistix at cathoderaymission.net Wed Jul 23 21:44:23 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 23 Jul 2003 18:44:23 -0700 Subject: Getting sub-objects from ADSI References: Message-ID: <3c91a864.0307231744.44a0adbb@posting.google.com> mpnugent at ra.rockwell.com (Michael P. Nugent) wrote in message news:... > How do I get the underlying values from Win::OLE=Hash(0x...) type > objects? I can do it in Perl, but not in Python. > > For instance, I get > > CN=Fred > > > > > > when running > > #! python > > import pythoncom > from win32com.client import GetObject > > UserPath = "LDAP://CN=Fred,OU=Two,OU=One,DC=nw,DC=home,DC=here,DC=com" > > ldap = GetObject(Userpath) > > print ldap.Name > print ldap.Groups() > print ldap.LastLogoff > > I know that Groups is of the type >, but that knowledge does not help me much. I have > fiddled a bit with GetInfo and Dispatch, but it doesn't change the > results. Try: for group in ldap.Groups(): print group.Name #or whatever you really want to do From peter at engcorp.com Fri Jul 4 19:36:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 19:36:45 -0400 Subject: RTS/CTS and DTR/DTS control References: Message-ID: <3F060F8D.94E47DCD@engcorp.com> Mike wrote: > > Is there a library in Python that will give me control over the > > handshaking lines directly? > I am running Linux, Python 2.2.2. It would be nice (not mandatory) > to be cross platform though. You call them handshaking lines, so one might infer you want to use them as such while doing serial communications. Are you in fact actually planning to control them as discrete inputs and outputs, for some kind of control application? (If not, I'm curious why you want to control them directly.) There is Chris Liechti's library, which you can find with http://www.google.com/search?q=python+serial+port but I'm not sure it supports direct control of the I/Os... if it doesn't you should be able to get direct control of those lines under Linux using appropriate fcntl.ioctl() calls, I would think, though I haven't done it myself. -Peter From jeremy at alum.mit.edu Wed Jul 9 10:22:11 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 09 Jul 2003 10:22:11 -0400 Subject: urllib2 for HTTPS/SSL In-Reply-To: <153fa67.0307090129.2d6bef57@posting.google.com> References: <153fa67.0307080233.2f7abdf5@posting.google.com> <153fa67.0307090129.2d6bef57@posting.google.com> Message-ID: <1057760531.29193.9.camel@slothrop.zope.com> On Wed, 2003-07-09 at 05:29, Kylotan wrote: > Jeremy Hylton wrote in message news:... > > On Tue, 2003-07-08 at 06:33, Kylotan wrote: > > > I have no idea how (or if) to use the 'HTTPSHandler' object, or what > > > the correct way for me to request an SSL connection is. Does anybody > > > have any hints? And additionally, is there any chance of the official > > > documentation on this useful-looking module being improved? > > > > Unless I misunderstand your intent, you don't need to use the Handler > > object directly. HTTPS support is provided automatically, so long as > > your local Python has SSL support. (It should.) > > Ok, so what you're saying is that the stuff documented in: > "Python Library Reference - 11.5.14 HTTPSHandler Objects" > is purely an implementational detail? In other words, they're > specifying examples of Handler classes in case you wanted to see how > to write one yourself, but to use the urllib2 library normally you'd > never need to really know this? urllib2 provides a framework for writing custom handlers. If you want to create your own handlers or an opener with a custom set of handlers, this documentation may be helpful. > I'm guessing the OpenerDirector object tries the URL with each > BaseHandler-derived object to see which one should handle it. That's about right. Most of the handlers are registered for particular protocols. So the opener knows to use the HTTPSHandler for https:// requests. Jeremy From thedustbustr at aol.com Sat Jul 26 21:51:39 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 27 Jul 2003 01:51:39 GMT Subject: (Eclipse/TruStudio) Re: I am so impressed References: Message-ID: <20030726215139.14696.00000526@mb-m04.aol.com> My only complaint is that it won't let you use control keys in the interpereter. It's a problem when you put a while 1: in your mainloop and can't KeyboardInterrupt out of it. Great for an editor, as long as you run your apps externally. From max at cNOvSisiPonAtecMh.com Thu Jul 10 16:51:41 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 10 Jul 2003 20:51:41 GMT Subject: Parsing References: Message-ID: Start here: http://diveintopython.org/dialect_divein.html -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] "Michael" wrote in message news:e5fb8973.0307100938.13fcea56 at posting.google.com... > I have been assigned a project to parse a webpage for data using > Python. I have finished only basic tutorials. Any suggestions as to > where I should go from here? Thanks in advance. From scook at elp.rr.com Fri Jul 4 08:31:27 2003 From: scook at elp.rr.com (Stan Cook) Date: Fri, 04 Jul 2003 12:31:27 GMT Subject: File information?? References: Message-ID: Thanks! I'll try that. "Egor Bolonev" wrote in message news:be36cf$j23$1 at news.rol.ru... > Hello, Stan! > You wrote on Fri, 04 Jul 2003 05:59:10 GMT: > > SC> Is there a way to get the file size and modified date of a file? > > os.stat() > > =========Beginning of the citation============== > import os,glob > > a=glob.glob('c:\\*')[0] > print os.stat(a)[6],os.stat(a)[8] > > =========The end of the citation================ > > With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] > From maney at pobox.com Thu Jul 10 13:01:35 2003 From: maney at pobox.com (Martin Maney) Date: Thu, 10 Jul 2003 17:01:35 +0000 (UTC) Subject: Search for mapping solution References: <3F087E85.9D8018E9@hotmail.com> Message-ID: I dedicate this monument to Alan Kennedy, without whom I would probably never have tried to compress things so. :-) Sean Ross wrote: > lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] > costs = {} > # nearly identical to Achim's solution, but with a list comp. > [costs.__setitem__(name, costs.get(name,0)+float(price)) > for name, number, price in lines] > print costs > # outputs: {'sam': 1.0, 'fred': 0.60} It isn't really one line though, is it? For truly cryptic terseness you want to swing functional (I shall adopt your interpretation of the third element although seeing it as a list of integers would have allowed for additional functional yumminess): >>> lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] >>> reduce(lambda d,x: d.update({x[0]: d.get(x[0],0.0) + float(x[2])}) or d, [{}] + lines) {'fred': 0.59999999999999998, 'sam': 1.0} Mind you, I normally despise the whole one-liner phenomenon, which makes me almost pleased about the inelegant necessity of that 'or d' - blame it on either update's lack of a return value or lambda's emasculation. But as I've been working my way through SICP as this summer's project, it certainly seems odd. :-/ -- automation: replacing what works with something that almost works, but which is faster and cheaper. - attributed to Roger Needham From MatthewS at HeyAnita.com Wed Jul 9 14:44:02 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 9 Jul 2003 11:44:02 -0700 Subject: Deleting specific characters from a string References: Message-ID: <5ab0af73.0307091044.254f5aab@posting.google.com> Maybe a new method should be added to the str class, called "remove". It would take a list of characters and remove them from the string: class RemoveString(str): def __init__(self, s=None): str.__init__(self, s) def remove(self, chars): s = self for c in chars: s = s.replace(c, '') return(s) if __name__ == '__main__': r = RemoveString('abc') e = r.remove('c') print r, e # prints "abc ab" -- it's not "in place" removal M@ Behrang Dadsetan wrote in message news:... > Hi all, > > I would like deleting specific characters from a string. > As an example, I would like to delete all of the '@' '&' in the string > 'You are ben at orange?enter&your&code' so that it becomes > 'benorange?enteryourcode'. > > So far I have been doing it like: > str = 'You are ben at orange?enter&your&code' > str = ''.join([ c for c in str if c not in ('@', '&')]) > > but that looks so ugly.. I am hoping to see nicer examples to acheive > the above.. > > Thanks. > Ben. From Olivier.POYEN at clf-dexia.com Mon Jul 7 07:53:22 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Mon, 7 Jul 2003 13:53:22 +0200 Subject: Gathering variable names from within a function. Message-ID: <8963D6370B323E4AA3241200F0EAF7318C0F74@FCEXVEXM002.dcl.int.dexwired.net> > "Xavier" wrote in message > news:... > > Greetings, > > > > I was wondering if there was a way to get a list of all the > variables which > > were executed/created/modified within a function? > > > > Here is a simple example that comes to my mind: > > > > def getVars(func): > > ... > > ... > > ... > > > > def modVar(arg, arg2): > > > > Var1 = arg > > Var2 = arg2 > > Var3 = arg+arg2 > > return Var3 > > > > def main(): > > > > print getVars(modVar('test', 'test2')) > > > > # end > > > > naturally, "Var1", "Var2" and "Var3" should be printed to > the user. Any > > idea? > > > > What about > > def modVar(arg, arg2): > Var1 = arg > Var2 = arg2 > Var3 = arg+arg2 > print vars() > return Var3 > > modVar('test', 'test2') > > => > > {'arg2': 'test2', > 'arg': 'test', > 'Var1': 'test', > 'Var3': 'testtest2', > 'Var2': 'test2'} > > more cryptic, but available from outside modVar: def getVars(func): return func.func_code.co_varnames HTH, --OPQ -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From FBatista at uniFON.com.ar Fri Jul 18 07:37:26 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 18 Jul 2003 08:37:26 -0300 Subject: "\n" in ASCII-file Message-ID: #- And... is there any special method to read lines from a file #- without "\n"? If you're sure you have the '\n' at the end, you can: myfile = file('myfile') for line in myfile: line = line[:-1] ... . Facundo From paul at boddie.net Tue Jul 29 07:58:34 2003 From: paul at boddie.net (Paul Boddie) Date: 29 Jul 2003 04:58:34 -0700 Subject: DOM as a flat dictionary References: <3f21335a_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <23891c90.0307290358.554c7ef8@posting.google.com> Neil Padgen wrote in message news:... > On Friday 25 July 2003 13:38, don't dash! wrote: > > > My thought was to generate a flat dictionary representation of the > > foreign and local formats with the absolute Xpath expression as > > dictionary key. > > You'll lose any ordering of the elements. Not if you employ position indicators, as defined in XPath. Of course, this might not make the "flat" descriptors very readable, but there are other solutions. > With the XML > > > > > topping="fried_egg"> > > Editing this to be a closing tag, of course... > > > translated into a flat dictionary > > { > '/spam': True, > '/spam/eggs': True, > '/spam/bacon': True, > '/spam/lobster_thermidor': True, > '/spam/lobster_thermidor/more_spam': True, > } > > there is no way that you can tell whether /spam/eggs comes before > /spam/bacon in the original XML. You could employ something like this: /spam/*[1] -> refers to "eggs" /spam/*[2] -> refers to "bacon" This isn't nice to read, as I noted above, and in practice it would also rely on you having some kind of schema information for you to know in advance which kind of element was being referred to. For the desired application, I doubt that this is acceptable. You could make things more complicated: /spam/eggs[position() = 1] -> refers to "eggs" but only as the first element in the sequence /spam/bacon[position() = 2] -> refers to "bacon" but only as the second element in the sequence This does indicate which element is being referred to and where that element resides in the sequence of elements. The reconstruction of a document from this information could be easy enough to achieve, although the parsing of the conditional part is slightly more complicated than other (non-XPath) notations. You could invent a simplified (non-XPath) notation: /spam/eggs:1 -> refers to "eggs" but only appearing first /spam/bacon:2 -> refers to "bacon" but only appearing second In the past, I've adopted such notations myself in order to represent hierarchies in rendered HTML forms. There can be alternative interpretations of the position numbers, however, since if you have a schema to work from then you could decide to interpret the numbers as the position of a particular element amongst elements of only that kind, comparable to the following XPath expressions: /spam/eggs[1] -> refers to the first "eggs" element /spam/bacon[1] -> refers to the first "bacon" element (not giving any information about the relative ordering of different elements) There are plenty of alternatives, so I hope one of them is useful. :-) Paul From bignose-hates-spam at and-benfinney-does-too.id.au Sun Jul 27 18:21:13 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Jul 2003 08:11:13 +0950 Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> <20030727.141111.1139901474.9957@demon.mindhog.net> <3f244eff$0$21092$626a54ce@news.free.fr> Message-ID: On Mon, 28 Jul 2003 00:23:26 +0200, Bruno Desthuilliers wrote: > Michael Muller wrote: >> - it is hard to guarantee that the documentation is in sync with the >> code (if you change the type expectations of a function, you can do >> so without changing the documented expectations) > > If your programmers don't care about keeping doc in sync, you're in > trouble whatever the language. If your programmers don't care about keeping block indentation in sync with the logical structure, you're in trouble whatever the language. Oh! That's right, Python enforces block indentation be kept in sync with the logical structure, because it's useful to do so whether or not the programmer cares about it. Programmers may care to a greater or lesser degree; the language can help or hinder. -- \ "I think there is a world market for maybe five computers." -- | `\ Thomas Watson, chairman of IBM, 1943 | _o__) | Ben Finney From rtrocca_SPAM_ME_NOT at libero.it Thu Jul 31 05:44:08 2003 From: rtrocca_SPAM_ME_NOT at libero.it (Riccardo) Date: Thu, 31 Jul 2003 11:44:08 +0200 Subject: Python speed vs csharp References: Message-ID: Another option would be SWIG (www.swig.org). Write a simple function, pass the header file (sometime you do not need to modify it at all) to SWIG and you got your source ready to be compile with distutils (for example). I used that approach several times. I had a look at pyrex and BOOST. I think that pyrex sounds very interesting if you use C (but I NEVER used it myself unless for some stupid demo/test) while I found BOOST learning curve (and installation, etc. etc.) a bit steep. Anyway this is just what I felt using the two of them. Riccardo "Mike" wrote in message news:rkdc7poiachh.1x4jtxjzaf3zo.dlg at 40tude.net... > Bear with me: this post is moderately long, but I hope it is relatively > succinct. > > I've been using Python for several years as a behavioral modeling tool for > the circuits I design. So far, it's been a good trade-off: compiled C++ > would run faster, but the development time of Python is so much faster, and > the resulting code is so much more reliable after the first pass, that I've > never been tempted to return to C++. Every time I think stupid thoughts > like, "I'll bet I could do this in C++," I get out my copy of Scott Meyers' > "Effecive C++," and I'm quickly reminded why it's better to stick with > Python (Meyers is a very good author, but points out lots of quirks and > pitfalls with C++ that I keep thinking that I shouldn't have to worry > about, much less try to remember). Even though Python is wonderful in that > regard, there are problems. > > Here's the chunk of code that I'm spending most of my time executing: > > # Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. 7.1.26) > # Fifth order approximation. |error| <= 1.5e-7 for all x > # > def erfc( x ): > p = 0.3275911 > a1 = 0.254829592 > a2 = -0.284496736 > a3 = 1.421413741 > a4 = -1.453152027 > a5 = 1.061405429 > > t = 1.0 / (1.0 + p*float(x)) > erfcx = ( (a1 + (a2 + (a3 + > (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) > return erfcx > > This is an error function approximation, which gets called around 1.5 > billion times during the simulation, and takes around 3500 seconds (just > under an hour) to complete. While trying to speed things up, I created a > simple test case with the code above and a main function to call it 10 > million times. The code takes roughly 210 seconds to run. > > The current execution time is acceptable, but I need to increase the > complexity of the simulation, and will need to increase the number of data > points by around 20X, to roughly 30 billion. This will increase the > simulation time to over a day. Since the test case code was fairly small, I > translated it to C and ran it. The C code runs in approximately 7.5 > seconds. That's compelling, but C isn't: part of my simulation includes a > parser to read an input file. I put that together in a few minutes in > Python, but there are no corresponding string or regex libraries with my C > compiler, so converting my Python code would take far more time than I'd > save during the resulting simulations. > > On a lark, I grabbed the Mono C# compiler, and converted my test case to > C#. Here's the corresponding erfc code: > > public static double erfc( double x ) > { > double p, a1, a2, a3, a4, a5; > double t, erfcx; > > p = 0.3275911; > a1 = 0.254829592; > a2 = -0.284496736; > a3 = 1.421413741; > a4 = -1.453152027; > a5 = 1.061405429; > > t = 1.0 / (1.0 + p*x); > erfcx = ( (a1 + (a2 + (a3 + > (a4 + a5*t)*t)*t)*t)*t ) * Math.Exp(-Math.Pow(x,2.0)); > return erfcx; > } > > Surprisingly (to me, at least), this code executed 10 million iterations in > 8.5 seconds - only slightly slower than the compiled C code. > > My first question is, why is the Python code, at 210 seconds, so much > slower? > > My second question is, is there anything that can be done to get Python's > speed close to the speed of C#? > > -- Mike -- From gordons_lists at gmx.net Sat Jul 12 13:34:20 2003 From: gordons_lists at gmx.net (Gordon Wetzstein) Date: Sat, 12 Jul 2003 19:34:20 +0200 (MEST) Subject: socket problem References: <3F102395.8C3E3395@hotmail.com> Message-ID: <25988.1058031260@www53.gmx.net> > > I have a problem with python sockets. > > I broadcast a lot of pickled objects with socket. sendto(...), that > > works. > > Ireceive them on the other site with socket.recvfrom(16384) > > The pickled objects are smaller (like 10000 bytes) than the max bytes. > > > > The problem appears if I send too many pickled objects very quickly one > > after another, > > then I only receive a part of the sent objects. > > As Jp Calderone pointed out, UDP is an unreliable protocol. Therefore, > it *will* drop packets occasionally. Worse, it doesn't guarantee > ordering of delivery of packets, meaning that your pickles could > arrive all jumbled up and unusable. > > You have three main choices to get around this problem. > > 1. Use TCP, which guarantees delivery to the destination address once > and only once, guarantees that packets will be received in the order > in which they were sent. However, you can't broadcast with TCP: it's a > point to point protocol. > > 2. Implement your own guaranteed delivery protocol over UDP. This is > usually done by assigning packets a sequence number as they are > transmitted from the publisher. All consumers then keep track of the > sequence numbers they receive, and re-request any packets they missed. > Implementing your own such protocol can get quite tricky, depending on > how complex your requirements. > > 3. Use a pre-made, highly efficient python library which is custom > designed for the job: spread. Spread is designed to solve all of the > problems of reliable broadcasting over UDP, and gives you a wide range > of options for how to balance efficiency versus reliability. And more > importantly, it's industrial-strength robust, stable and platform > independent. Also, it's configurable to work with a wide range of > network topologies. More info from > > http://www.python.org/other/spread/ > > If I were you, I'd seriously consider spending an hour getting up and > running with Spread: could be the most productive hour you'll spend in > this area. > > HTH, > > -- > alan kennedy thanks, i will try it. gordon -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ Jetzt ein- oder umsteigen und USB-Speicheruhr als Pr?mie sichern! From cognite at zianet.com Fri Jul 18 10:39:03 2003 From: cognite at zianet.com (cognite at zianet.com) Date: Fri, 18 Jul 2003 08:39:03 -0600 Subject: python contribs to life sci informatics, enhancing the profile Message-ID: <20030718083903.170ad935.cognite@zianet.com> This venue would surely appreciate the cool stuff being done in python on bioinformatics and python's tools for info parsing and extraction (like fulltext indexing, xml tools, parser builders, graphic display, realtime simulation and communities tools like pygame and ...) It's in San Diego February 9-12, 2004. "Session presentations are 45 or 90 minutes long, and tutorials are either a half-day (3 hours) or a full day (6 hours)." Although the sponsor is pro-python, python isn't mentioned in the call! SC ================================================================== Fw: O'Reilly Life Science Informatics Conf. Call for Participation Begin forwarded message: Date: Thu, 17 Jul 2003 18:30:50 -0700 (PDT) From: Suzanne Axtell To: cognite at zianet.com Subject: O'Reilly Life Science Informatics Conf. Call for Participation For Immediate Release July 17, 2003 For more information, contact: Suzanne Axtell (707) 827-7114 or suzanne at oreilly.com Call For Participation: The 2004 O'Reilly Life Science Informatics Conference Sebastopol, CA--O'Reilly & Associates invites biologists, computer scientists, software engineers, mathematicians, and experts in other related fields to submit proposals to lead tutorial and conference sessions at the O'Reilly Life Science Informatics Conference, slated for February 9-12, 2004 at the Westin Horton Plaza in San Diego, CA. Proposals are due September 1, 2003. For the past two years, the annual O'Reilly informatics conference has focused on bioinformatics as the theme. This year, we're expanding the scope of this conference to reflect the evolutionary changes happening in the field of life science informatics. The conference will explore topics in life science--from the fundamental levels to the advanced--and will focus on the technologies, techniques, and tools used to understand and analyze that biological data. The O'Reilly Life Science Informatics Conference brings together practitioners from biology, molecular biology, computer science, pharmacology, medicine, software engineering, chemistry, and mathematics for four days of information exchange, learning, and fun. This conference explores the intersection points of the various sub-disciplines of life science informatics and focuses on practical ways of applying the tools of computer science to the life sciences. "Practicality is a necessity in life science informatics these days," notes O'Reilly editor and conference chair Lorrie LeJeune, commenting on what has been an over-arching theme for all of the O'Reilly informatics conferences. "As our knowledge of living systems continues to expand, so do the data sets. Storing, managing, and analyzing data sets is the focus of countless tools and techniques. The biological discoveries now being made are absolutely astounding, and will begin to have a wider impact as the field expands. Our first two conferences in this area were very successful, in part because informatics is an area of growth for both computer geeks and scientists. It's essential for the health of the field of informatics to bring these tools and skills to a wider audience." The conference begins with one day of tutorials, providing background information or deep coverage of important issues in life science informatics. Three days of conference sessions follow, covering a wide range of topics and problems in life science informatics, from building tools using languages such as Perl and Java, to learning about systems for high-throughput data analysis. Confirmed keynote presenters include Howard Cash of Gene Codes Corporation and Thure Etzold of LION bioscience Ltd. The O'Reilly Life Science Informatics Conference will also feature a poster session, for which we are also accepting proposals. Submitting Proposals: Individuals and companies interested in making presentations, giving a tutorial, or participating in panel discussions are invited to submit proposals using the online form. Proposals will be considered in two classes: tutorials and conference presentations (sessions). Presentations by marketing staff or with a marketing focus will not be accepted; neither will submissions made by anyone other than the proposed speaker. Session presentations are 45 or 90 minutes long, and tutorials are either a half-day (3 hours) or a full day (6 hours). If you are interested in participating in or moderating panel discussions, or otherwise contributing to the conference, please let us know (and please include your area of expertise). If you have an idea for a panel discussion or a particularly provocative group of panelists that you'd love to see square off, feel free to send your suggestions to lsicon-idea at oreilly.com. Since practicality is a conference theme, we'd particularly like to see proposals that highlight case studies, best practices for a tool or system, and fundamental skills. We'd also like to learn from things that don't work. For example, have you discovered that a popularly accepted approach or solution that simply doesn't work or perform well in your hands? Are there cases where a proprietary Windows app has saved you where Bio (Perl/Python/Java) couldn't do the trick? Did the widespread use of XML leave you gasping for bandwidth or storage where a simple binary format made the problem disappear without noticeable impact on information exchange? Topics of specific interest are systems biology, drug discovery, advanced sequence analysis, cheminformatics and chemogenomics, biomedical informatics, open source efforts, ontologies, controlled vocabularies, taxonomies, standards, and tools and techniques. Proposals need not be works of art--a thoughtful summary or abstract of the talk you plan to give is sufficient for consideration. We prefer outlines for tutorials. The proposal is what the conference committee uses to select speakers, so give the committee enough information to understand the topic you're covering. Additional Resources: For more conference information and to submit a proposal, see: http://conferences.oreilly.com/lsicon/ Check out news coverage from last year's O'Reilly Bioinformatics Technology Conference: http://www.oreillynet.com/biocon2003/ Details from last year's O'Reilly Bioinformatics Technology Conference can be found at: http://conferences.oreillynet.com/bio2003/ For information on exhibition and sponsorship opportunities at the conference, contact Andrew Calvo at (707) 827-7176, or andrewc at oreilly.com. About O'Reilly O'Reilly & Associates is the premier information source for leading-edge computer technologies. The company's books, conferences, and web sites bring to light the knowledge of technology innovators. O'Reilly books, known for the animals on their covers, occupy a treasured place on the shelves of the developers building the next generation of software. O'Reilly conferences and summits bring alpha geeks and forward-thinking business leaders together to shape the revolutionary ideas that spark new industries. From the Internet to XML, open source, .NET, Java, and web services, O'Reilly puts technologies on the map. For more information: http://www.oreilly.com # # # O'Reilly is a registered trademark of O'Reilly & Associates, Inc. All other trademarks are property of their respective owners. -- ;););) blessed are the geeks -- for they shall inherit the source code :):):) From anton at vredegoor.doge.nl Wed Jul 9 10:12:41 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 09 Jul 2003 16:12:41 +0200 Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: "Sean Ross" wrote: >Hi. For anyone who has chosen to use my Genetic Algorithm recipe >(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/199121), I'd like >to make you aware of a fairly serious oversite on my part - I left out the >division part of the standard deviation routine! That's been fixed on the >recipe page, but not on my personal web site - which will be done when I >post the new version I'm building for a study I'll be working on this fall. Importing the math module should also make a big difference for the standard deviation routine :-) Also stddev was only used by the sigmascaling code, which was unreachable ... However, this is a very nice module and I especially like the graphical TSP-solver that is in the other package on your website. I had been looking at it before but I failed to comprehend what you were doing. However recently I developed a taste for Genetic Algorithms as a side result of a thread on c.l.py here ("getting a submatrix of all true"). In the process of finding a heuristic solution to the problem I came to understand your module a bit better and I've also tinkered a bit with it (minor changes) and I have produced a heuristic solution for the submatrix problem. (it counts 59928 zero's, for insiders :-) If someone is interested it's here: http://home.hccnet.nl/a.vredegoor/twomax Anyway, maybe seeing your code used and *changed* will give enough of a jolt to start working on it some more (which I would welcome :-) Anton From skodela at lithium.com Wed Jul 16 05:47:01 2003 From: skodela at lithium.com (sreekant) Date: Wed, 16 Jul 2003 09:47:01 +0000 (UTC) Subject: tkinter In-Reply-To: <3114992.1058316065@dbforums.com> References: <3114992.1058316065@dbforums.com> Message-ID: Checkout python.org and they have some links. cheers sreekant sprmn wrote: > does anyone know of any sites with good tutorials on tkinter on them? > > -- > Posted via http://dbforums.com From ajcoon at hotmail.com Fri Jul 25 13:54:07 2003 From: ajcoon at hotmail.com (aj coon) Date: 25 Jul 2003 10:54:07 -0700 Subject: How to detect typos in Python programs References: Message-ID: <21dbccb.0307250954.5c2125d4@posting.google.com> Manish Jethani wrote in message news:... > Hi all, > > Is there a way to detect typos in a Python program, before > actually having to run it. Let's say I have a function like this: > > def server_closed_connection(): > session.abost() > > Here, abort() is actually misspelt. The only time my program > follows this path is when the server disconnects from its > end--and that's like once in 100 sessions. So sometimes I > release the program, people start using it, and then someone > reports this typo after 4-5 days of the release (though it's > trivial to fix manually at the user's end, or I can give a patch). > > How can we detect these kinds of errors at development time? > It's not practical for me to have a test script that can make > the program go through all (most) the possible code paths. > > -Manish This is one of the things about interpreted languages that I detest- lack of compile-time errors and warnings. With python, you can always open an interactive session with the interpreter and 'import ', but that only catches syntax errors. For things like unreferenced variables and undefined names (typos, as you like to nicely put it ;-), theres a program we use for testing our code: http://pychecker.sourceforge.net/ Have a look. Admittedly, the information it outputs can be overwhelming. Take some time to just examine its behaviors and options. What you'll probably end up doing is customizing its output, either by modifying the source, or running it through grep/awk/sed/python afterwards. But, it's definitely a starting point. -AJ From jarausch at skynet.be Fri Jul 18 15:13:51 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Fri, 18 Jul 2003 21:13:51 +0200 Subject: Using Python as script extension In-Reply-To: <3f183aee_1@dns.sd54.bc.ca> References: <3f183aee_1@dns.sd54.bc.ca> Message-ID: <3F1846EF.1010609@skynet.be> Bob van der Poel wrote: > > I'm looking for some suggestions on a project I'm working at these days... > > I've written my program "Musical MIDI Accompaniment (MMA)" which parses > a text file and generates MIDI output. I've written this in Python, and > all works very nicely. See http://www.kootenay.com/~bvdpoel/music.html > > Now, I am thinking that adding variables and conditional (if/then/else) > possiblities to MMA scripts might be a good thing. If I want to do this > I see several possible routes: > > 1. Add the code to maintain and set variables to my existing code. This > always seems to end up being a lot more work than one plans. Certainly, > adding a command like "Set MyVariable 123" is simple enought, but then > the next thing you know one will be adding math, etc. > > 2. Somehow having Python handle the dirty stuff. I guess that my "Set > MyVariable 123" could be passed along to Python with an eval or exec. > However, I'm not sure how much help this would be since we still end up > with having to write code to handle if/then/else. > > 3. Somehow turn my MMA scripts into python scripts and extend python to > generate the stuff which my program originally set out to produce. This > would involve a major rewrite of my own code and most likely send my > exsiting MMA scripts into the dumpster... > > And I'm sure I'm missing yet another solution. I'd really appreciate > some thoughts and/or ideas on how I might approach this. > Being a Python newbee my, I'd suggest having a look at http://www.alcyone.com/pyos/empy/ it looks as if it is what you are looking for. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jjl at pobox.com Wed Jul 16 14:52:25 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Jul 2003 19:52:25 +0100 Subject: Replacing rexec References: Message-ID: <87fzl6i9sm.fsf@pobox.com> Tim Gerla writes: [...] > We are looking to use plpython in PostgreSQL, but it's being downgraded > to "untrusted" and/or being completely removed because Python's rexec > went away. Why did rexec go away, specifically? I know it had security > issues, but couldn't these have been fixed? Did the module just have too > many integral flaws in the design to be worth saving? http://www.google.com/groups?as_q=rexec%20python-dev > Is anyone working on a replacement? If not, why not? Even if plpython > isn't very widely used, I think it's still important for advocacy. I'd > much rather write Python than PL. It might well be important for advocacy if it's insecure in some important sense -- just not for advocates of Python ;-) Have you considered using Jython, and making use of Java's sandbox scheme? Google tells me PostgreSQL can do Java stored procedures, but I don't know whether it's feasible to get Jython running in that environment. > Anyway, I'm looking for a summary of specific reasons why rexec went > away without a replacement. I understand completely that it had flaws > and was insecure; I'm only confused as to why these flaws were > insurmountable. There were a couple of known flaws, but I don't think the problem was that they were insurmountable -- rather, it was just that the manpower and eyeball-power was (and is) not there to get to a point where people could be justifiably confident in rexec. John From zathras at thwackety.com Thu Jul 17 11:11:58 2003 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 17 Jul 2003 16:11:58 +0100 (BST) Subject: Co-routines In-Reply-To: Message-ID: On Thu, 17 Jul 2003 thewrights at ozemail.com.au wrote: > >From the python grammar: > > funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite > > I want the statements in to be executed [lockstepped] > on a statement by statement basis, with no particular restrictions on > *what* those statements are. Tricky - without jumping in before the code is compiled by python or similar then I can't think of any way to do this. I can however think of a perlesque way to do it. (ie should work, might not be considered nice) One possible way out is if you're willing to change the way you write & run code /slightly/. Rather than write: def func(arg): arg.foo() arg.bla() while arg.foobar(): print arg.state() arg.bla() If you write this in your source files: def func(arg): arg.foo(); arg.bla(); while arg.foobar(): print arg.state(); arg.bla(); Before you run these files you could pre-process them to change all occurances of ";" to "; yield ". Clearly you could do this pre-processing in python and then exec the code. ie your preprocessor would change the above code fragment to: def func(arg): arg.foo(); yield 1 arg.bla(); yield 2 while arg.foobar(): print arg.state(); yield 3 arg.bla(); yield 4 Then to run your functions in lockstep, you simply: gens = [ x() for x in [func1, func2, func3, func4 ] while gens: newgens = [] foreach gen in gens: try: gen.next() newgens.append(gen) except StopIteration: pass gens = newgens (Working on the assumption the generators for different functions will run for differing periods of time) About the only way I can see this working "simply" is using this sort of pre-processing trick. I doubt it'd be considered Pythonic. (Personally I view as more like a perlesque trick) It does however leave your code looking single threaded (in fact I suppose it still is if you don't preprocess it), and doesn't require any odd code structuring. (It does require care if you use semi-colons inside strings/etc) HTH, Michael. From brian at sweetapp.com Mon Jul 14 21:49:57 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 14 Jul 2003 18:49:57 -0700 Subject: anything like C++ references? In-Reply-To: Message-ID: <000901c34a73$656db950$21795418@dell1700> > > > What I specifically want is a way to have a "second-level > > > binding", e.g. a reference to a reference (assuming that the > > > terminology is correct by saying that all Python variables are > > > references). > > > > What for? What would be the practical use for such a thing? > > "Why would you want a bike when you have a car?" > > I would say that I wanted it because I thought it would be the > most straight-forward solution to the problem, so I thought I'd > ask. You haven't articulated your actual problem. Doing so might shed some light on the practical aspects of this issue. Cheers, Brian From tjreedy at udel.edu Mon Jul 14 22:33:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jul 2003 22:33:10 -0400 Subject: (Suggestion) Download Options References: <221d8dbe.0307140147.6417e501@posting.google.com> <3F12FAA4.58026440@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3F12FAA4.58026440 at engcorp.com... > srijit at yahoo.com wrote: > > > > Can we have a download option for upcoming Python 2.3 without TCL/Tk? > > Though I know the extremely popular Tkinter is the default GUI of > > Python, I see one immediate advantage of a download option without > > TCL/Tk > > 1) Download size is less and it is a boon for people like me with slow > > modem connection. > > 2) Tkinter with TCL/TK can be a separate add-on > > > > I look forward to opinions from members. > > Maybe this should be written up as a PEP? See > http://www.python.org/peps/pep-0001.html for more information. Disagree. This has nothing to do with Python the language. Anyone is free to make and host alternate distributions. ActiveState does one with even more batteries included. Some else could do one with fewer -- in fact, I believe this has maybe been done in the past. TJR From duncan at NOSPAMrcp.co.uk Mon Jul 21 09:55:34 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 21 Jul 2003 13:55:34 +0000 (UTC) Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: Marc Wilson wrote in news:kl3lhvgh5iillo5g9jvff92qkc8i2022nm at 4ax.com: > I'm a complete Python newbie, though I know at least one regular in > here. :) > > I've just got Paint Shop Pro 8.0, and the functionality of the old > ImageRobot add-on has been replaced with the new Python Scripting. > > So far, OK. > > What I'm trying to determine is: can I run these scripts from a > command-line invocation? I want to use the scripts to automatically > convert files as they arrive, uploaded onto a website, not > interactively. Have you tried running a script from the commandline? > > Has anyone played with this? I just downloaded the PSP8 evaluation. It installs with a bunch of sample scripts. These sample scripts all have a file extension .PspScript, and the file association set up by the installer associates .PspScript with the command: "...\Paint Shop Pro.exe" "/Script" "%1" Unfortunately whenever I start Paintshop pro it gives me a popup window telling me its an evaluation copy and requiring me to confirm the window before it proceeds. When started with a script that uses a dialog there appears to be a deadlock as the script cannot proceed with this window displayed, and the window won't accept any input. It works alright though for scripts that don't try to do anything interactive, and I would guess that a properly registered copy of the program would run scripts with dialogs correctly, but you are probably in a better situation to determine that than anyone on this newsgroup. -- 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 richie at entrian.com Tue Jul 29 04:05:53 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 29 Jul 2003 09:05:53 +0100 Subject: Seeing next character in an file In-Reply-To: References: Message-ID: <94aciv4hfuq7vq1p4d54vbhvk0j5f5tuq4@4ax.com> [Richie] > seek() works perfectly with text-mode files as long as you only seek to > places given to you by tell(). So if Keith's peek() function had used > tell() and then seek()ed (sought()? 8-) back to that point like his > peekline() does, there would be no problem. [Bengt] > Can you cite a C or C++ standard section that guarantees that seek/tell > will work that way in text mode? (I'm not saying there isn't one, but > I couldn't find one quickly ;-) ANSI C, ISO/IEC 9899:1990, section 7.9.9.2: "For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier call to the ftell function on the same stream and whence shall be SEEK_SET." -- Richie Hindle richie at entrian.com From adsheehan at eircom.net Mon Jul 7 10:40:36 2003 From: adsheehan at eircom.net (Alan Sheehan) Date: 7 Jul 2003 07:40:36 -0700 Subject: SWIG and Python in use? Message-ID: Hi, I am considering scripting a large C++ application. In particular I am interested in test driving and end-user scripting the "application layer" in Python and giving it access to a large collection of C++ objects and their methods. I note that SWIG is a mature tool and refers to supporting Python v1.x. Has/Does anyone use SWIG to bind with Python 2.x ?. Does it still work? Any pitfalls, caveats ? Thanks in advance. Alan From ulope at gmx.de Sun Jul 20 20:36:22 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 21 Jul 2003 02:36:22 +0200 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" schrieb im Newsbeitrag news:7xk7acai97.fsf at ruckus.brouhaha.com... > "Ulrich Petri" writes: > > "Alan Dechert" schrieb im Newsbeitrag > > news:P9DSa.111436$Io.9552373 at newsread2.prod.itd.earthlink.net... > > > > Sorry but why on earth you dont just print that on paper and let people make > > their crosses where they want? > < snip detailed explanation> Thanks for explaining this to me. But i wonder why you simply dont use paper and pens? Here in germany we also have elections where more than one thing is voted upon but if that is the case we have a seperate ballot for each of those descisions and they all go into different "boxes" and are counted by different people. To be honest i was quite shocked when i saw that ballot mockup of the OP that was VERY confusing... here is a sample of a normal ballot we use: http://www.iwi-willendorf.de/wahlzettel.jpg This one was from the election of the german bundestag (parliament) Fore other things (like tax on soda ;) the ballots looke quite similar but with only two or so options to choose from on them.... But i think this is going rather OT now :) Ciao Ulrich From T.A.Meyer at massey.ac.nz Tue Jul 15 18:44:30 2003 From: T.A.Meyer at massey.ac.nz (Meyer, Tony) Date: Wed, 16 Jul 2003 10:44:30 +1200 Subject: FCNTL module deprecation warning Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1302644476@its-xchg4.massey.ac.nz> Thanks to those that answered the question; I understand the problem now. (it's a WinXP system). > Python natively is case-sensitive. Windows 9x and later, and > OS/2 with HPFS file systems, are case-insensitive but > case-preserving. So Python relies on the case preservation > when trying to match a filename to a module name. My question is then why the 2.3b2 Windows binary bothers installing the FCNTL.py file. fnctl isn't available on Windows anyway (going by the docs and that there isn't a fnctl.py file installed). Shouldn't the correct behaviour be to raise an ImportError if a windows user tries to import fcntl or FCNTL? Just like trying to "import mac" or "import posix"? The way it is just causes useless warnings to Windows users - particularly users of httplib :) =Tony Meyer From R.Brodie at rl.ac.uk Tue Jul 1 04:12:13 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 1 Jul 2003 09:12:13 +0100 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> Message-ID: "Tim Roberts" wrote in message news:3g32gvcolis4485956egtc35akm6lh3uq5 at 4ax.com... > Contradicting Fredrik, something I do with great reluctance, the C standard > specifies that the behavior is implementation-defined, so in fact BOTH answers > "implement C semantics". Only if you're looking at an old version of the standard; it's not implementation dependent in C99. From jzgoda at gazeta.usun.pl Mon Jul 14 09:19:12 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 14 Jul 2003 13:19:12 +0000 (UTC) Subject: training for newbies References: Message-ID: OM pisze: >> > do you know any sites with free programs for newbies, which will >> > help me in >> > progress? i know that only way to develop is writing programs, but >> > in my book i don't have programs to write, only questions.. >> >> Check out http://www.uselesspython.com and Python Cookbook at >> http://aspn.activestate.com > > Dzieki:] A polskie ? You can find Polish translation of original Guido tutorial at http://www.python.org.pl. There are some links to other documents in Polish too. Anyway, you can ask your questions in Polish at pl.comp.lang.python newsgroup. -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From alexis.francart at nospam.xagagroup.com Wed Jul 9 07:58:20 2003 From: alexis.francart at nospam.xagagroup.com (Alexis Francart) Date: 9 Jul 2003 11:58:20 GMT Subject: importing re in Jython References: Message-ID: Alexis Francart wrote in news:Xns93B386C32C053alexisfrancartnospam at 193.252.19.141: > Do you know how i can import the RE module in Jython? Ok i've managed to import it. I'm new to jython and python so i think this is basic but unless the command line you have got to enter the whole pass in the script so ihave to enter from org.python.modules import re instead of a simple import re thanks for your help From hokiegal99 at hotmail.com Sun Jul 13 14:19:52 2003 From: hokiegal99 at hotmail.com (tubby tudor) Date: Sun, 13 Jul 2003 14:19:52 -0400 Subject: removing spaces from front and end of filenames Message-ID: Thanks for the tip Jeff. That's the same conclusion that I cam to. I'm new to python and programming in general, but having a language as intuitive as python and a list as helpful as this makes it easy. I can actually solve problems. Thanks again. >From: Jeff Epler >To: hokiegal99 >CC: python-list at python.org >Subject: Re: removing spaces from front and end of filenames >Date: Sun, 13 Jul 2003 11:18:50 -0500 > >On Sun, Jul 13, 2003 at 08:44:05AM -0700, hokiegal99 wrote: > > Erik Max Francis wrote in message >news:<3F10BABB.D548961B at alcyone.com>... > > > hokiegal99 wrote: > > > > > > > This script works as I expect, except for the last section. I want >the > > > > last section to actually remove all spaces from the front and/or end > > > > of > > > > filenames. For example, a file that was named " test " would be > > > > renamed "test" (the 2 spaces before and after the filename removed). > > > > Any > > > > suggestions on how to do this? > > > > > > That's what the .strip method, which is what you're using, does. If > > > it's not working for you you're doing something else wrong. > > > > for root, dirs, files in os.walk('/home/rbt/scripts'): > > for file in files: > > fname = (file) > > fname = fname.strip( ) > > print fname > > > > When I print fname, it prints the filenames w/o spaces (a file named " > > test " looks like "test"), but when I ls the actual files in the > > directory they still contain spaces at both ends. That's what I don't > > understand. It seems that .strip is ready to remove the spaces, but > > that it needs one more step to actually do so. Any ideas? > >Surely you need to actually rename the file: > for root, dirs, files in os.walk('/home/rbt/scripts'): > for name in files: > newname = name.strip() > if newname != name: os.rename(name, newname) > >Jeff _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From jtuc at ev1.net Tue Jul 29 10:35:11 2003 From: jtuc at ev1.net (Jordan Tucker) Date: 29 Jul 2003 07:35:11 -0700 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> Message-ID: <467c9d67.0307290635.8bc8fe6@posting.google.com> > I'm feeling quite dumb this morning. > Don't feel dumb, I'm having the same error. The sample server builds fine for me, both inproc and localserver. But when I try to convert our COM server EXE to an inproc dll, I get the same error as you. I figured it was something going wrong on the python side, so I redirected stdout to a file and got this: Traceback (most recent call last): File "", line 1, in ? File "", line 56, in DllRegisterServer File "win32com\server\register.pyc", line 388, in RegisterClasses AttributeError: 'module' object has no attribute 'argv' The offending line of code at 388 is: scriptDir = os.path.split(sys.argv[0])[0] Somehow sys is no longer sys :) I planned to track it down this morning and post a report/fix, but I checked the newsgroup first. Seems like Thomas and Mark can have a go at it now too :p Jordan From peter at engcorp.com Wed Jul 16 11:05:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jul 2003 11:05:09 -0400 Subject: Choosing the right framework References: Message-ID: <3F1569A5.E2080312@engcorp.com> Thomas G?ttler wrote: > > Carsten Gehling wrote: > > > Oh how often this subject may come up... > > > > The thing is, I've come to the decision of abandoning PHP as much as > > possible (old projects still remain...), and use Python for all purposes. > > Reason: One language to fit it all (instead of having one language for > > webprogramming, one for batches, etc...) > > Where do you want to store your data? [relational database, text files, > ZODB, Berkley DB, pickles, ...] > > If you don't need ZODB (object database), I would not use Zope. Even if you want ZODB, you can always use the standalone one, and still skip Zope, if that's what you want. From anton at vredegoor.doge.nl Fri Jul 18 10:09:09 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 18 Jul 2003 16:09:09 +0200 Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: "Andrew Dalke" wrote: >I haven't followed the thread, just pinged on 'maximum clique problem.' > >Does this help? > http://starship.python.net/crew/dalke/clique/ > >It's code I wrote years ago. Don't ask me any more questions about >it .... unless you want to pay me for it. :) It helps a little. Whether I want to pay you depends on what you eat. Anton From dave at pythonapocrypha.com Mon Jul 7 12:19:26 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 7 Jul 2003 16:19:26 +0000 Subject: A story about Python... sort of In-Reply-To: References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <200307071619.26693.dave@pythonapocrypha.com> On Monday 07 July 2003 02:02 am, Russell Reagan wrote: > > There came a time when it was no longer economically viable to develop an > > entire game in assembly, and IMO we've *already* passed the point where > > no longer economically viable to develop most games entirely in C++ - the > > time to market is too long, it's too expensive to add new features, > > recovering from early incorrect decisions is too costly, etc. Games are > > moving to higher-level languages as much as they can because it's a > > competitive advantage to do so. > > After thinking about it I tend to agree. I'm a little partial to C/C++ > because I develop (as a hobby) a chess playing program, and I like > tinkering with it to see how fast it can go, and finding clever ways of > doing things. A chess program is different from a 3D game in that with a 3D > game, you can stop at some point and say, "ok, this is fast enough." There > is little point in making the game run at 1000 frames per second if no > human eye can see more than 60 (or whatever the number is). True, although rather than let the frame rate continue up the game designers will simply add more polygons, more actors, more textures, greater viewable distance, etc. so they won't ever reach the "fast enough" point either. Instead you always reach the "fast enough for now" limit. There will remain *some* cases where you need a lower-level language in order to get more speed, but those cases are becoming less frequent - for each one there comes a time when the cost of that extra speed becomes too much. Also, some projects (like Pysco) open the possibility of on-par (or even greater, in theory) speed by using a higher-level language. But my main point was that, at least for the stuff I do, there's never any point in writing all or even most of an application in C++ anymore (and the few parts that do need more speed would be in a dumbed-down, simplified C++ at that). If I were writing the chess game I'd probably write the entire thing in Python to begin with anyway, just to get it working. Having a slow, but working app would either help maintain my interest in the project or let me know early on that it's not something I really want to do. If I kept at it then I could, at some point, move some speed-critical code to C or C++, but I'd try to avoid it for as long as possible. For example, you mentioned that your interest was at least in in part about finding ways to do things faster or to make the game smarter. In a higher-level language like Python that sort of expermimentation is relatively cheap - in C++ you might avoid radical experiments because the cost of change is too high. Your biggest speed and smartness improvements after picking the low-hanging fruit are likely to be algorithmic in nature (e.g. using a more ingenious heuristic to reduce the search space of next moves) as opposed to low-level tuning of loops or data storage, so it would be advantageous to do that work at as high a level as possible (and you can always translate those algorithmic optimizations to a lower-level language someday if you want). Just my two cents of course, -Dave From T.A.Meyer at massey.ac.nz Tue Jul 15 04:23:08 2003 From: T.A.Meyer at massey.ac.nz (Meyer, Tony) Date: Tue, 15 Jul 2003 20:23:08 +1200 Subject: FCNTL module deprecation warning Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1302644325@its-xchg4.massey.ac.nz> (I did try to google for an answer to this, but couldn't find anything, although plenty of instances of the warning). I don't understand this warning: >>> import fcntl C:\Program Files\Python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> It seems to be saying that I shouldn't use "import FCNTL" (which gives the same warning), but "import fcntl", but that's what I _am_ doing. (I don't actually even import fnctl, but httplib does, and causes this all over the place. Any light shedding would be appreciated. =Tony Meyer From trentm at ActiveState.com Tue Jul 8 12:40:57 2003 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 8 Jul 2003 09:40:57 -0700 Subject: process.py problems In-Reply-To: <20030708153117.127C0326C0@www.fastmail.fm>; from justinjohnson@fastmail.fm on Tue, Jul 08, 2003 at 09:31:17AM -0600 References: <20030708153117.127C0326C0@www.fastmail.fm> Message-ID: <20030708094057.C9520@ActiveState.com> Justin, Can you try turning logging on in process.py to perhaps get a better picture of what it is trying to do. Look for the "internal logging" section. There should be some "if 0"s that you can turn to "if 1"s for debugging. (Or vice versa -- my process.py version is a little bit different than the public one.) My guess: process.py, in some cases, will try to run command via the local shell (i.e. cmd.exe or command.com on Windows). This is necessary for some commands like "dir" which are not executables themselves but just a part of the shell. However, process.py is not as clean as it should be on when it does and when it does not use the shell. Perhaps process.py is not using the shell when it should here. ... note, there may also be a problem with respect to which.py and process.py version mismatch. which.py 1.x changed its API from which.py 0.x and process.py may not be dealing with that correctly. I may need to put up a new process.py to get that right. What is the output of: which --version or: >>> import which >>> which._version_ Cheers, Trent [Justin Johnson wrote] > Hello, > > I was wondering if anyone has seen this behavior before for the > process.py > module available at http://starship.python.net/crew/tmick/. I've been > using it quite well on windows 2000 servers, but when I try to use it on > a window nt 4.0 box I get the results posted below. I have both > process.py and which.py installed. > > Any help you can provide is greatly appreciated. > > >>> import process > >>> p = process.ProcessOpen("dir") > Traceback (most recent call last): > File "", line 1, in ? > File "process.py", line 1108, in __init__ > self._startOnWindows() > File "process.py", line 1279, in _startOnWindows > cmd = _fixupCommand(cmd, self._env) > File "process.py", line 506, in _fixupCommand > cmd = _whichFirstArg(cmd, env) > File "process.py", line 315, in _whichFirstArg > candidates = list(which.which(first)) > File "which.py", line 251, in which > raise WhichError("Could not find '%s' on the path." % command) > which.WhichError: Could not find 'dir' on the path. > >>> p = process.ProcessOpen("dir.exe") > Traceback (most recent call last): > File "", line 1, in ? > File "process.py", line 1108, in __init__ > self._startOnWindows() > File "process.py", line 1279, in _startOnWindows > cmd = _fixupCommand(cmd, self._env) > File "process.py", line 506, in _fixupCommand > cmd = _whichFirstArg(cmd, env) > File "process.py", line 315, in _whichFirstArg > candidates = list(which.which(first)) > File "which.py", line 251, in which > raise WhichError("Could not find '%s' on the path." % command) > which.WhichError: Could not find 'dir.exe' on the path. > >>> p = process.ProcessOpen("cmd") > Traceback (most recent call last): > File "", line 1, in ? > File "process.py", line 1108, in __init__ > self._startOnWindows() > File "process.py", line 1295, in _startOnWindows > raise ProcessError(msg=ex.args[2], errno=ex.args[0]) > process.ProcessError: The system cannot find the file specified. > >>> > > -- > http://mail.python.org/mailman/listinfo/python-list -- Trent Mick TrentM at ActiveState.com From duncan at NOSPAMrcp.co.uk Fri Jul 18 11:08:03 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 18 Jul 2003 15:08:03 +0000 (UTC) Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> <20030716132455272-0600@news.xmission.com> Message-ID: Robin Munn wrote in news:slrnbhg1vg.1sg.rmunn at localhost.localdomain: > Notice how the id remained the same in list augmented assignment, while > it changed in tuple augmented assignment. That's because in the first > example, l is not rebound; instead, the list object that l points to > gets extended. In the second example, t gets rebound to a *new* tuple > object. Another demonstration: Pedantically speaking, l does get rebound. It just happens that it gets rebound to the same object which is also mutated. It can be significant in cases where you are not allowed to rebind the value e.g. >>> a = [1, 2, 3] >>> b = [a] >>> b[0] += [4] >>> b [[1, 2, 3, 4]] >>> a [1, 2, 3, 4] >>> a = [1, 2, 3] >>> b = (a,) >>> b[0] += [4] Traceback (most recent call last): File "", line 1, in ? b[0] += [4] TypeError: object doesn't support item assignment >>> b ([1, 2, 3, 4],) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From mertz at gnosis.cx Fri Jul 4 23:57:23 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 04 Jul 2003 23:57:23 -0400 Subject: Least used builtins? References: Message-ID: I don't think any of these are a big deal. But I see several motivations for moving a number of the builtins that Bicking disagrees on. The breakage could be made small to non-existent by including a bunch of such things in a file like startup.py that gets loaded automatically, but that can be changed in principle. One general point is that getting rid of builtins can make a minimal Python footprint smaller (and load times slightly faster probably). For embedded systems, handhelds, etc. reducing the required memory usage is a good thing. A second issue is the PyPy project. I think it dovetails with that project to move everything that is a likely candidate for reimplementation *in* Python into non-core modules. Doing this is not strictly a requirement for PyPy, but it fits the style of thinking. A third matter is my support for the function decorator/mutator idea. classmethod, staticmethod, and property are nice method mutators, but as a number of people pointed out in that thread, they are not the only such modifiers one can imagine. Moreover, you can implement these in Python (I incorrectly once doubted this), so spinning them out of core makes sense from a #2 perspective. Yet a fourth matter is that I think it would be slightly easier to teach Python to beginners if __builtins__ did not include a number of functions that were extremely difficult to explain to novices... and that are really only of use to fairly expert Pythoneers. I find that callable, classmethod, id, intern, and a number of others fall in this category. My thinking is that anything meant for experts should need to get imported by specific request. All that said, I have neither any control of what happens, nor any strong attachment to any of my suggested homes for (former) builtins. |> enumerate itertools |Again, this is idiomatic, and it belongs in builtins. This one I strongly disagree with. The fact enumerate is builtin is a little bit of a wart. It's really -just like- the family of functions in itertools; only historical accident introduced it before itertools came into existence. |> filter functional |Only because it's become redundant. I don't at all think filter() is redundant... but I do think that a 'functional' module could grow a lot of extra useful capabilities (currying, composition, etc). The usual filter/map/reduce would make a good start for such a module (and clean up the base interpreter for those FP-haters out there :-)). |Definitely not -- these are very important, importing them would be |obnoxious. Especially since "isinstance(value, str)" is the preferred |technique over "type(value) is str". Actually, I considered listing type() for desired removal to a module. I suppose for consistency with my purport on isinstance() I ought to advocate that. |[super] Again, highly idiomatic, programmers should be discouraged from |using this name for anything else Indeed. But non-advanced programmer won't be using it for its builtin meaning either. Just look at all the threads by quite sophisticated Pythonistas trying to clarify exactly what super() really does. You cannot even understand this function without first getting C3 linearization (and even then, figuring out what the different calling forms all do is still tricky). |zip, like enumerate, is idiomatic -- importing it does not imply |anything about your code, that it comes from itertools lends little |insight into what zip does. Actually, I don't think a separate zip/izip does any good, nor range/xrange. But those are more historical accidents. I wouldn't mind seeing itertools have the same kind of status that sys does now. What's the last script you wrote that didn't import sys? You don't technically need it... until you want to do something with input, output or arguments :-). Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From suresh_vsamy at rediffmail.com Thu Jul 3 09:49:41 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 3 Jul 2003 13:49:41 -0000 Subject: Reading an image file data......... Message-ID: <20030703134941.15069.qmail@webmail26.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From jack at performancedrivers.com Mon Jul 14 16:48:55 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 14 Jul 2003 16:48:55 -0400 Subject: =?iso-8859-1?Q?Python_Mystery_Theatre_--_Episode_2:__As=ED_Fue?= In-Reply-To: <3F130ED4.2030804@skynet.be>; from jarausch@skynet.be on Mon, Jul 14, 2003 at 10:13:08PM +0200 References: <3F130ED4.2030804@skynet.be> Message-ID: <20030714164855.D1005@localhost.localdomain> On Mon, Jul 14, 2003 at 10:13:08PM +0200, Helmut Jarausch wrote: > Raymond Hettinger wrote: > > ACT III ---------------------------------------------------- > > def once(x): return x > > def twice(x): return 2*x > > def thrice(x): return 3*x > > funcs = [once, twice, thrice] > > > > flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)] > > flam = [lambda x:f(x) for f in funcs] > > > > print flim[0](1), flim[1](1), flim[2](1) > > print flam[0](1), flam[1](1), flam[2](1) > > OK, I believe to know why the last line > print '3' three times, since only a reference > to 'f' is stored within the lambda expression > and this has the value 'thrice' when 'print' > is executed. > But how can I achieve something like an > evaluation of one indirection so that > a reference to the function referenced by 'f' > is stored instead. The problem is made up to make a point, just doing flam = funcs will do the right thing. If you really want to wrap the function in a list comp, you could do def wrap_func(func): return lambda x:func(x) flam = [wrap_func(f) for (f) in funcs] # wrap during a list comp flam = map(wrap_func, funcs) # the map() equivilent more awkward versions of the above: wrap_func = lambda func:lambda x:func(x) flam = [(lambda func:lambda x:func(x))(f) for f in funcs] -jack From peter at engcorp.com Mon Jul 14 14:44:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 14:44:40 -0400 Subject: www.python.org hacked? References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> Message-ID: <3F12FA18.B04B400E@engcorp.com> zman wrote: > > Website has been offline for more than an hour 11:18 PT. Actually, the site is not offline, but the front page is missing. All other pages that I've tried are still functional. Connecting manually to port 80 on fang.python.org shows: GET / HTTP/1.0 HTTP/1.1 200 OK Date: Mon, 14 Jul 2003 18:43:37 GMT Server: Apache/1.3.26 (Unix) Last-Modified: Mon, 14 Jul 2003 17:32:05 GMT ETag: "5a751d-0-3f12e915" Accept-Ranges: bytes Content-Length: 0 Connection: close Content-Type: text/html Have we been hacked, or is this human error during maintenance? -Peter From davecook at nowhere.net Fri Jul 11 15:19:29 2003 From: davecook at nowhere.net (David M. Cook) Date: Fri, 11 Jul 2003 19:19:29 GMT Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <55EPa.8760$R92.7900@news2.central.cox.net> In article <246a4e07.0307100613.fc2fc50 at posting.google.com>, Frank Millman wrote: > I would like some advice, and I hope that the good people on c.l.p > will give me the benefit of their experience. I was going to point you to this talk on "partnership" billing: http://www.sdphp.net/node.php?id=10 but I'm having problems unzipping it under Linux, myself; maybe it's OK under windows. Dave Cook From gjego at free.fr Sat Jul 12 10:54:46 2003 From: gjego at free.fr (Georges JEGO) Date: Sat, 12 Jul 2003 16:54:46 +0200 Subject: Windows XP - Environment variable - Unicode In-Reply-To: <3f0e77fc@epflnews.epfl.ch> References: <3f0e77fc@epflnews.epfl.ch> Message-ID: <3f102131$0$10879$626a54ce@news.free.fr> sebastien.hugues wrote: > Hi > > I would like to retrieve the application data directory path of the > logged user on > windows XP. To achieve this goal i use the environment variable > APPDATA. > As an alternative, you can query the registry: from _winreg import * key=HKEY_CURRENT_USER subKey=r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" key=OpenKey(key, subKey ) dataDir=QueryValueEx(key, "AppData") print `dataDir[0]` gives: u'C:\\Documents and Settings\\jego\\Application Data' HTH, -- Georges From rosendo at dbora.com Thu Jul 31 05:35:36 2003 From: rosendo at dbora.com (rosendo) Date: 31 Jul 2003 02:35:36 -0700 Subject: urllib2 http status References: <87y8yh59zj.fsf@pobox.com> Message-ID: Thanks again John. The code goes fine. Rosendo. jjl at pobox.com (John J. Lee) wrote in message news:<87y8yh59zj.fsf at pobox.com>... > rosendo at dbora.com (rosendo) writes: > > > I'm writing a http client to test some applications. > > The code below it's the core of the client: > [snip] > > You're using *both* urlopen *and* add_cookie_header / extract_cookies. > Don't do that. urlopen calls those methods itself. > > Also, HTTPError is a subclass of URLError, so your second except: > suite will never be reached. I'm not sure what the purpose of the > empty except: there is, either -- why not just let the exception > propogate to top level? > > The unreleased version of ClientCookie can do Referer automatically. > Ask me if you want a copy (the release is waiting for somebody to look > at an RFE for urllib2 that I've posted). > > Also, Python doesn't use semicolons , and the second 'argument' > to except receives an exception, not a exception message (string). > > > > Before this code we declare c = ClientCookie.Cookies(), etc...... > > Then i don't know how to know the status of the response, because the > > property: > > response.info().status seems not to function like i wait, that it's > > with an 200, 301, 400, etc..... > > How can obtein this status? > > If you get a returned response, it's always 200. For non-200 > responses, urllib2 always raises an exception. It's probably a wart, > but too late to change now. > > Corrected code (untested, since incomplete): > > try: > start_ts = time.time() > request = urllib2.Request('http://%s%s' % (req.host, req.path), > req.data, req.headers) > request.add_header("Referer", 'http://%s%s' % (req.host, req.path)) > c.clear() > #request = urllib2.Request('http://www.google.com') > try: > response = urllib2.urlopen(request) > data = response.read() > headers = response.info().headers > #status = response.info().status > except urllib2.HTTPError, e: > print "URLError: ", e > # Note: e.msg, e.code are what you want. > # IIRC, HTTPError works just like a response object, too. > duration = time.time() - start_ts > > print ('The result had status: 200 duration: %5.2f http://%s%s' % > (response.info().status, duration, req.host,req.path)) > except: > print sys.exc_type,sys.exc_value > print 'cagadita....' + str(req) > > > John From bokr at oz.net Tue Jul 8 10:56:37 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Jul 2003 14:56:37 GMT Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: On 08 Jul 2003 03:23:36 -0500, Ian Bicking wrote: >On Tue, 2003-07-08 at 02:26, Steffen Brodowski wrote: >> Hello everyone, >> >> since one week, I'm programming with python. Its a realy interesting >> tool. I wrote a script for generating barcodes in jpg-format. >> Everything is ok, but my function "CreateBarcode" should write the jpg >> data into an outstream. All barcodes will be generate online, without >> saving the jpgs on harddisk. >> >> Can you give me a tip witch objects I need and how to put the jpg into >> an outgoing stream? >> >> import Image, ImageDraw >> def CreateBarcode(SourceString,Linewidth,WriteText): >> blablabla >> ... >> NewImage = Image.new("L",NewSize,Backcolor) >> ImgDraw = ImageDraw.Draw(NewImage) >> .... >> >> #How to put the image into an stream? > >have that function return the image object. Then, assuming you are >doing this in CGI (easily adapted if not), do something like (untested): > >import sys >image = CreateBarCode(...) >print 'Content-type: image/jpeg\n' >image.save(sys.stdout, 'JPEG') > In case it's windows, I suspect that script will need to be run with python -u or have some programmed way to ensure binary output. Of course, if it's CGI it's probably a unix platform, in which case that won't be an issue. Regards, Bengt Richter From kp at kyborg.dk Tue Jul 8 09:52:52 2003 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 08 Jul 2003 15:52:52 +0200 Subject: mx odbc Message-ID: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> Regarding ODBC usage in Python... it seems to me that there is a couple of ways to use odbc from python, one of these is the MX version - now that one has a pretty steep licence cost (imho). So now comes my question (from reading this group quite a bit): - what is the basic reason for using MX versus the others? - why do you (newsgroup) seem to think that this package is the preferred one? - in case above is incorrect - what package is preferred? Note: i have nothing against paying for commercial products - but 75$'s for a cpu licence (customer) or >1000$ for a developer single cpu, seems to me to be a bit too steep, for a thing thats basically a requirement for windows programming.... -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From db3l at fitlinxx.com Tue Jul 29 12:53:48 2003 From: db3l at fitlinxx.com (David Bolen) Date: 29 Jul 2003 12:53:48 -0400 Subject: How to detect typos in Python programs References: <3F214977.AEB088C8@engcorp.com> <877k64c0qo.fsf@pobox.com> Message-ID: Manish Jethani writes: > There's a difference between my "abost()" example and the "56" > example. There's no function called abost anywhere in the > program text, so I should be able to detect the error with > static analysis. Even in C, the compiler warns about stray > function calls. But in your example, you were calling "session.abost". Due to Python's dynamic nature, there's no way for a static compile-time analysis to know for sure if the object to which session (I'm guessing it's a global from the code) refers _at the point when that code executes_ has an abost method or not. Or rather, no way I can see other than having the compiler actually execute the code to determine that fact. Given that you want some specific behavior to occur on a close connection event, you're really best served by having a test that actually simulates such an event to verify that your action occurs. That's true in any language, although particularly so in Python. It's certainly best to use automated tests, but even some manual setup for more complicated network situations can help. For example, if I were writing such a system, I'd probably at least manually start up a modified server that explicitly disconnected more frequently so I could exercise that aspect of tear-down more easily. Otherwise (syntax checks or no), I'd be releasing code without really having any idea that it would do the right thing in such a teardown situation. Think of it just as another aspect to "good coding practices". -- David From vivek at cs.unipune.ernet.in Wed Jul 16 05:56:00 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Wed, 16 Jul 2003 15:26:00 +0530 Subject: XML <=> Database Message-ID: <20030716152600.A1315@cs.unipune.ernet.in> Hi all, Is there any module available which does the same work as the XML Integrator in Java. Actually I am working in an educational institute, there somebody asked me to teach Java as a part of a Database course. As I am not very good in Java so I asked for the type of assignments they want to give to students. So here is what they told me: There will be a three tier architechture. One web application, Web Server, one Application Server and the Database backend. The Web server will get the data as a XML document. This will be passed to the application server that will parse the document and will insert/Update/Delete the data in the database Server. Similarly the data will be retrieved from the database and will be converted in a XML document by the application server and will be send to the user's browser through the web server. I told him that we can use python for this purpose as there are a lot of modules available for XML parsing in Python. And also it will be much easier for Students to learn Python as compared to Java. Somehow I managed him to think over it :-). But then he asked me : 1. Is there something in Python which will work as an Application server like EJB ?? 2. He showed me the XML Integrator which is used in Java and which automatically parse the XML document,convert it into a query string and insert it into Oracle database backend. And while retriving data it converts the retrieved data into a XML document. I know that there are modules available in Python for parsing XML documents but I wonder if there is something available for converting the data returned from database query into a XML document?? Also is it possible to have something like Application server between the Web Server and Database server running each on seperate machines, in Python ?? TIA and Kind Regards, Vivek Kumar From Jon_Aquino at shaw.ca Mon Jul 7 16:14:06 2003 From: Jon_Aquino at shaw.ca (Jonathan Aquino) Date: 7 Jul 2003 13:14:06 -0700 Subject: Pychecker + Jython trick Message-ID: To get Pychecker to work with my Jython files, I had to write some stubs for the Java classes. Things like: class SimpleDateFormat: def __init__(self, x): pass def parse(self, x): return Date(None) def format(self, x): return "" It would be nice to be able to do this automatically. For example, someone could make a simple tool to generate Python stubs from jar files. Jon From tjreedy at udel.edu Wed Jul 23 18:34:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2003 18:34:00 -0400 Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88) References: Message-ID: "Ames Andreas (MPA/DF)" wrote in message news:mailman.1058949155.26009.python-list at python.org... > Below is a more selfcontained sample (assume that x, y and z are not > bound before the code is executed): > > >>> class Foo: > ... def __del__(self): > ... print '__del__(%#x)' % id(self) > ... > >>> y = Foo() > >>> print '%#x' % id(y) > 0x8152e7c > >>> z = 0 > >>> print '%#x' % id(z) > 0x80cbf70 > >>> x = y > >>> print '%#x' % id(x) > 0x8152e7c > >>> del y > >>> print '%#x' % id(x) > 0x8152e7c > >>> x = z > __del__(0x8152e7c) > >>> print '%#x' % id(x) > 0x80cbf70 > > The assignment 'x = z' calls Foo.__del__. What I wanted to know is: > > Is Foo.__del__ called *before* x refers to an integer object of value > 0 or *afterwards*. In other words, does x refer to a possibly > (partially) invalid object while Foo.__del__ is executed, or what is > the Python FAQ 4.88 referring to (within the final paragraph which > begins with 'Note:', dealing with atomicity of operations replacing > objects)? This appears not to be defined by the language reference and is thus an implementation specific question. To find out, put 'print type(x)' in the delete method -- or even 'print x'! Then post answer ;-) Terry J. Reedy From aahz at pythoncraft.com Sat Jul 5 17:21:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Jul 2003 17:21:52 -0400 Subject: Name-based insults, round 5 (was Re: A possible bug in python threading/time module?) References: <3F071424.520DC852@engcorp.com> Message-ID: In article <3F071424.520DC852 at engcorp.com>, Peter Hansen wrote: >vm_usenet wrote: >> >> Right after I read Tim's recent post, I went to the python CVS and >> noted that Tim refered to me as an 'anonymous coward'. Well Tim, I >> just wanted to say that I appreciate you being part of the community, >> too. > >See http://www.computerhope.com/jargon/a/ac.htm, definition #2. This >is a fairly well-known term for someone who, like you, for some >strange reason does not want to use their name in discourse with >others (such as those who are helping them, hint, hint) online. (We've just been through this recently, but...) I don't think that the prevalence of a term says anything about its potential for insult. I'm sure you can think of many examples on your own. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From LogiplexSoftware at earthlink.net Tue Jul 1 17:50:05 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 01 Jul 2003 14:50:05 -0700 Subject: Suggesting for overloading the assign operator In-Reply-To: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <1057096205.1457.16.camel@software1.logiplex.internal> On Mon, 2003-06-30 at 20:31, Rim wrote: > The idea is to separate the value assignment from the type assignment, > by introducing a new operator, let's say the ':=' operator. > > '=' remains what it is, assigns type and value at the same time > ':=' assigns only the value On the surface, this idea seems appealing. However, besides the arguments that others have forwarded, you might consider the fact that given two similar "assignment operators", subtle bugs are bound to arise. > >>> class myint(int): pass > ... > >>> a = myint() > >>> a := 6 > type(a) > > >>> a > 6 What if the programmer accidentally uses '=' rather than ':=' (and I think this would be a natural mistake)? It would be legal Python but would probably not have the intended effect. It is not unlike the "allow assignment in expressions" arguments that come up here every 3.2 weeks. Anyway, your arguments cancel themselves out. You asked initially for a way to overload '=' because your users didn't want to have to type something different. But ':=' *is* different, so what are you really looking for?. Worse, because ':=' isn't *very* different, it makes mistakes more likely. In short, I think using a = myint(6) or even a.value = 6 is preferable. Besides, when I used Pascal (many years ago), I found ':=' to be one of the most annoying (and most common) things I had to type. Please don't ask to bring it back. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From mwh at python.net Tue Jul 22 09:36:58 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 13:36:58 GMT Subject: Where can one get Python 1.4 and Pythonwin 1.0? References: <41dqhv43pp8d8kb76r2u2sm3bnbbkic4cm@4ax.com> Message-ID: <7h3d6g2zo3y.fsf@pc150.maths.bris.ac.uk> Richard Lee writes: > Hi. I need to test and document some really old software. For that, I > have to install P 1.4 and Pwin 1.0 (the latter which is based on > P1.4). Yow! > Python.org has downloads going back to P1.5.2. And the link to version > of the earliest Win32 extensions containing Pwin corresponds to > P1.5.2. Didn't look hard enough: http://www.python.org/ftp/python/src/ and http://www.python.org/ftp/python/binaries-1.4/pythonwin/ look hopeful to me (admittedly, I found these by sshing into www.python.org and running 'locate', a course of action not available to everyone...). Cheers, mwh -- Any form of evilness that can be detected without *too* much effort is worth it... I have no idea what kind of evil we're looking for here or how to detect is, so I can't answer yes or no. -- Guido Van Rossum, python-dev From BartolomeSintes at ono.com Thu Jul 10 05:38:15 2003 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Thu, 10 Jul 2003 09:38:15 GMT Subject: Windows Python 2.3b2 bug? Edit with IDLE Message-ID: Hi, I am using Python 2.3b2 in a Windows 98 SE machine. If I right-click a .py file, the menu shows an "Edit with IDLE" option, but when I select it no IDLE window opens, as Python 2.2.2 did. Is it a known bug, or am I doing something wrong? Thanks From peter at engcorp.com Sat Jul 5 14:12:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Jul 2003 14:12:14 -0400 Subject: sqlrelay References: <3f070ec0$0$13370$9b77ed8b@news.comundo.de> Message-ID: <3F0714FE.CD592084@engcorp.com> Torsten Will wrote: > > http://sqlrelay.sourceforge.net/ >From that site: "SQL Relay is a persistent database connection pooling, proxying and load balancing system for Unix and Linux supporting ODBC, Oracle, MySQL, mSQL, PostgreSQL, Sybase, MS SQL Server, IBM DB2, Interbase, Lago and SQLite with APIs for C, C++, Perl, Perl-DBD, Python, Python-DB, Zope, PHP, Ruby, Ruby-DBD, TCL and Java, command line clients, a GUI configuration tool and extensive documentation. The APIs support advanced database operations such as bind variables, multi-row fetches, client side result set caching and suspended transactions. It is ideal for speeding up database-driven web-based applications, accessing databases from unsupported platforms, migrating between databases, distributing access to replicated databases and throttling database access." I think it will also feed your cat... -Peter From paul at boddie.net Wed Jul 23 11:49:14 2003 From: paul at boddie.net (Paul Boddie) Date: 23 Jul 2003 08:49:14 -0700 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: <23891c90.0307230749.44f85fbc@posting.google.com> Duncan Booth wrote in message news:... > Christos "TZOTZIOY" Georgiou wrote in > news:amqqhv0gbdok6dnk6ib9342lejpc4ap5pd at 4ax.com: > > > If I may say it sideways, try searching for google for the french word > > "c?fe", as in "un c?fe s'il vous pla?t". Wanna bet my message will be > > the only one to be found? :) > > Since when is 'c?fe' a French word? It doesn't appear in any French > dictionary I have tried. Case closed, as they say in certain circles. I was once told (by a French speaker) that it was far better, in an ASCII-only situation, to drop all accents than to use the wrong ones in French texts. For other Latin-derived alphabets, there are often established rules for the writing of letters specific to particular languages (and cultures) using those found in ASCII (eg. ? -> aa, ? -> ae, ? -> oe), but it can be quite tiring for people like me to interpret them quickly in a large body of text. As for the "challenge" and its proponents/opponents, I think it's shameful that even relatively modern computing standards (eg. things like HTTP, URLs/URIs) haven't gone far enough to appear inclusive to "non-ASCII cultures", or at least not without convoluted and vague edge cases which effectively force people to use ASCII anyway because of misinterpretations of (or insecurity around) those standards. Paul From shoppa at trailing-edge.com Tue Jul 8 10:02:56 2003 From: shoppa at trailing-edge.com (Tim Shoppa) Date: 8 Jul 2003 07:02:56 -0700 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: Donald 'Paddy' McCarthy wrote in message news:<3F082031.3010503 at netscape.netNOTthisBIT>... > Charles Shannon Hendrix wrote: > > > > The problem with Python is that its use of indentation is not the same > > as COBOL or FORTRAN. Apples and Oranges. And it's not the same as Makefiles, either. Everybody has at one time been bitten by how 8 spaces is not at all the same in a Makefile as one tab; and it doesn't help that with many editing/viewing tools that it is impossible to see the difference. > > Python uses it for actually determining the logic in your program, which > > IMHO is dangerous. Again, it is certainly no use than Makefiles. > Well, no matter WHAT the language, I find tabs are evil little things > that introduce special cases and the need for code to handle them. Compare that to all the punctuation marks that *some* other languages require. Remember the Dilbert where PHB complains that his programmers are using way too many semicolons? :-) Tim. From shangius at yahoo.com Thu Jul 31 05:18:34 2003 From: shangius at yahoo.com (Sami Hangaslammi) Date: 31 Jul 2003 02:18:34 -0700 Subject: Python speed vs csharp References: Message-ID: <6298355.0307310118.7e6c437a@posting.google.com> Mike wrote in message news:... > My second question is, is there anything that can be done to get Python's > speed close to the speed of C#? If you have a single function that is easy to convert to C, you should. Wrapping it with, for example, Pyrex (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/) is easy enough, and you'll get the best of both worlds. From alet at librelogiciel.com Sat Jul 5 09:12:50 2003 From: alet at librelogiciel.com (Jerome Alet) Date: Sat, 05 Jul 2003 15:12:50 +0200 Subject: ANN: PyKota v1.12 is released Message-ID: Hi there, I'm pleased to announce that PyKota v1.12 is out. PyKota is an entirely Python written, GNU GPLed, centralized, full featured, internationalized, and easily extensible, print quota and accounting solution for CUPS and LPRng under Unix like systems like GNU/Linux. It can store print quotas information either in PostgreSQL or in OpenLDAP, and includes many other useful features. Changes since version 1.09 : - Many bug fixes. You'll definitely want to upgrade. - A command line utility called 'pykotme' which produces print quotes is now included. This way one can learn in advance how much a print job will cost him on any printer. Learn more about PyKota, see live reports or screenshots, download the CVS version or buy an official package from : http://www.librelogiciel.com/software/PyKota/action_Presentation Discuss with us, ask for help, report problems or successes, on the mailing list at : http://cgi.librelogiciel.com/mailman/listinfo/pykota Thank you for reading Jerome Alet From jdhunter at ace.bsd.uchicago.edu Thu Jul 10 22:46:09 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 10 Jul 2003 21:46:09 -0500 Subject: more regexp In-Reply-To: (hokiegal99's message of "Thu, 10 Jul 2003 20:52:07 -0400") References: Message-ID: >>>>> "hokiegal99" == hokiegal99 writes: hokiegal99> I can replace all spaces in filenames and directory hokiegal99> names with this bit of code: (thanks to all who helped hokiegal99> me get this!) Sorry if I'm missing something since I'm jumping into this thread late, but if all you want to do is replace spaces, why do you need regexps? Can't you just use string.replace? hokiegal99> Now, I'd like to be able to search for the '%' hokiegal99> character at the begining and the ending of filenames hokiegal99> and dirs and remove them entirely. Could someone hokiegal99> suggest a way to do this? Any tips are welcomed! >>> fname = '%Hi%mom%' >>> fname.strip('%') 'Hi%mom' See also lstrip and rstrip to remove chars (default whitespace) from the beginning or end of a string (strip does both beginning and end). JDH From adalke at mindspring.com Thu Jul 31 17:23:03 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 31 Jul 2003 15:23:03 -0600 Subject: looking for design pattern name References: <87adaud0he.fsf@pobox.com> Message-ID: John J. Lee: > Yuck. Doesn't the standard library reserve TypeError for occasions > where the, um, type of an argument is not appropriate? Quoting from the docs, exception TypeError Raised when a built-in operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. In addition to your comments, this is not a built-in operation, so it's the wrong exception. > Why not ValueError or > your own exception (possibly derived from ValueError)? exception ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. Yup, seems reasonable. I'll change. Thanks! See you at the next Calvinball tournament, Spaceman Lee. Andrew dalke at dalkescientific.com From intentionally at blank.co.uk Mon Jul 14 23:28:21 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 04:28:21 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> Message-ID: <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> On Mon, 14 Jul 2003 16:15:08 -0700, Tom Plunket wrote: >Stephen Horne wrote: > >> All you have proven is that it is the distinction between types >> that get re-bound and those that don't (rather than the use of >> references) that is unnecessarily confusing and error prone. > >As the firestarter (I apologize for the flames that have >erupted) Strong feelings and opinions, IMO, but not really flames. At least I've been willing to admit the mistakes I've made (or the ones I recognise, anyway). >, I must admit that even I know that this distinction >does not exist in Python. There aren't some types that get >rebound and others that don't. Yes - this was a major mistake on my part. I already confessed and apologised elsewhere. My making mistakes in my arguments, however, does not mean that my point is wrong. I believe that my current arguments are not based on any mistakes I've made. >I still feel that there's a wart of some sort, but it's not due >to any inconsistency in the language, despite what I may have >said before (I've been thinking about it a lot over the past few >days). Absolutely the point I've reached, though I've been forced to get a lot clearer in my thinking to reach that point. >> A Python user is interested in how an object behaves - not how it >> is internally implemented in the interpreter. Immutable objects >> don't behave as references - the internal use of references for >> immutable objects is basically a lazy copying optimisation and, >> apart from performace and a couple of other technicalities (e.g. >> the 'is' operator), has no relevance. > >Are they really technicalities, though? I mean, a mutable object >can be changed. It's the same object, just changed. Immutable >objects, however, can't be changed. You can get something that >appears like changing it, but it's actually building a new thing >and binding the label to that new thing. Yes. But the thing being changed *is* an object, *not* a value. Values are always immutable - basic fact of mathematics. Variables in mathematics are bound to values. I think Python should be implemented in a way that respects that. Whether you use objects to represent values, or whether you use some kind of symbolic representation is an implementation detail which should be transparent to the user unless the user specifically requests to deal with the object or whatever. If I type... >>> a = [1, 2, 3] >>> b = a Then in my mind, the point is that both variables get bound to the value '[1, 2, 3]'. The fact that the binding to values might be implemented using binding to the same object at this point should be, to me, a low level detail. If I now type... >>> b[2] = 4 Then the variable b should now be bound to the value '[1, 2, 4]'. That is the whole point of what I've done. However, the fact that it was achieved by modifying a part of an object is an implementation detail. It should not affect the *value* bound to the variable a. In other words, a new object should be created at that point - a copy of the original - which would then be modified. That way, the mathematical concept of variables being bound to values would be respected. This is not difficult to achieve. The implementations of the C++ standard library that I've seen use exactly the same copy-on-write mechanism for strings. This method implements a lazy copying optimisation without violating the concept of variables being bound to values. That is, the hidden use of pointers or references in the std::string class is an implementation detail that you don't have to worry about as a programmer. The programmer worries about the application - not the low level details of the implementation of the language or library. But, like I said before, this isn't about imitating C++. It's about respecting the common definitions of 'variable', 'value' etc from mathematics and computer science - something that people do seem to intuitively expect until the Python way is beaten into them. To me, 'Pythonic' expresses 'doing the right thing'. In this case, in my view, Python does the wrong thing and expects everyone to get used to it. From skip at pobox.com Mon Jul 14 11:54:14 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 14 Jul 2003 10:54:14 -0500 Subject: Confusing automated translators. In-Reply-To: <3F12CE17.76A0A5@hotmail.com> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3F12CE17.76A0A5@hotmail.com> Message-ID: <16146.53798.759651.430032@montanaro.dyndns.org> >> The "Time flies" is a classic. I heard it a few dozens of years >> ago. :-) Another similar classic, for French, is "Le pilote ferme la >> porte.". Alan> ... Or have I missed the point completely (I don't consider Alan> myself a strong french speaker)? Not being any sort of French speaker, I don't understand the "pilote ferme" one at all. Fran?ois? Skip From walter at livinglogic.de Thu Jul 31 17:24:24 2003 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Thu, 31 Jul 2003 23:24:24 +0200 Subject: HTML DOM parser? In-Reply-To: <3f297adb$0$19537$626a54ce@news.free.fr> References: <7x7k5y5wfh.fsf_-_@ruckus.brouhaha.com> <3f297adb$0$19537$626a54ce@news.free.fr> Message-ID: <3F298908.1030807@livinglogic.de> adfgvx wrote: > Try tidy. There are two python wrappers : mxtidy and utidy, the latest is Where can we get utidy? > more recent and use the new tidylib. BUT it will only correct a bad html > page and transform it to an xml or xhtml output that you load after as a DOM > with another parser. Personnaly I use pyRXP. Bye, Walter D?rwald From andy at wild-flower.co.uk Fri Jul 4 18:10:06 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 4 Jul 2003 23:10:06 +0100 Subject: strings problem In-Reply-To: References: Message-ID: <200307042310.06414.andy@wild-flower.co.uk> On Friday 04 Jul 2003 6:41 pm, Jimmy verma wrote: > Hello *.* > > Can you please tell me how can i have the output in no's, instead of string > from this program: > > #/usr/bin/python > import re > import string > > def csNumEncode(num): > if(num>=-107 and num<=107): > return chr(num+139) > elif(num>=108 and num<=1131): > return chr(((num-108)/256)+247) + chr((num-108)%256) > else: > print 'do nothing' > > re_num = re.compile("\-?[0-9]+(\.[0-9]+)?") > > > def CompileCS(source): > result='' > for tkn in re.split('[ \n\t]+', source): > print "Token: %s"%tkn > if re_num.match(tkn): > result = result + csNumEncode(string.atoi(tkn)) > else: > raise SyntaxError, "%s is invalid operator"%tkn > return result > > src1 = '50 800' > > t = CompileCS(src1) > > print t > > > > The output is > > Token: 50 > Token: 800 > \275\371\264 > > > Instead of this i want the output should be in no's like this: > bdF9B4 > > Your suggestions will be welcomed. > > Thanks a lot. > > Regards, > Jim > > _________________________________________________________________ > Looking for love? Yearning for friendship? http://www.msn.co.in/Romance/ > You're in the right place. Jim, I think you want the hex() function: >>> hex(0275) '0xbd' >>> hex(0275)+hex(0371)+hex(0264) '0xbd0xf90xb4' >>> hex(0275)[2:]+hex(0371)[2:]+hex(0264)[2:] 'bdf9b4' >>> hex produces a string from a number, but puts '0x' in front. I used hex(n)[2:] to chop off the first 2 chars. hope that helps -andyj From lists at gregfortune.com Tue Jul 15 15:23:31 2003 From: lists at gregfortune.com (Greg Fortune) Date: Tue, 15 Jul 2003 12:23:31 -0700 Subject: Reloading nested modules References: Message-ID: > I've been intended to write something that will take a module name and > rebind it in all namespaces that have it currently, but haven't got around > to it. If I ever do, I'll post it here :) 0): tmp = reload_me.pop() for x in inspect.getmembers(tmp[1]): if(inspect.ismodule(x[1])): if((tmp, getattr(tmp[1], x[0])) not in reloaded): reload_me.append((tmp[1], getattr(tmp[1], x[0]))) reload(tmp[1]) reloaded.append((tmp[0], tmp[1])) ############################################### From manojbalyan at ccmb.res.in Wed Jul 30 07:18:48 2003 From: manojbalyan at ccmb.res.in (BalyanM) Date: 30 Jul 2003 16:48:48 +0530 Subject: python in parallel for pattern discovery in genome data Message-ID: <1059563927.5183.5.camel@E503BMatrixReloaded> Hi, I am new to python.I am using it on redhat linux 9. I am interested to run python on a sun machine(SunE420R,os=solaris) with 4 cpu's for a pattern discovery/search program on biological sequence(genomic sequence).I want to write the python code so that it utilizes all the 4 cpu's.Moreover do i need some other libraries. Kindly advice. Thanks Sincerely, Manoj -- **************************************************************** Manoj Balyan Scientist- Bioinformatics Centre for Cellular and Molecular Biology(CCMB) Uppal Road, Hyderabad-500007 Andhra Pradesh,INDIA TEl:+91-040-27192772,27160222,27192777 FAX:+91-040-27160591,27160311 EMAIL:manojbalyan at ccmb.res.in, manoj_balyan at hotmail WWW:http://www.ccmb.res.in *************************************************************** If you weep for the setting sun,you will miss the stars:Tagore *************************************************************** From sfb at alysseum.com Wed Jul 9 16:16:25 2003 From: sfb at alysseum.com (Simon Bayling) Date: Wed, 9 Jul 2003 20:16:25 +0000 (UTC) Subject: .join() question References: Message-ID: I would risk a guess that this comes under the "explicit is better than implicit" guideline. ''.join([str(i) for i in lst]) Explains to everyone that you know the list has some non-string things, and you intend them to be str()'ified. Intention-guessingly yours, Simon. "drs" wrote in news:eo_Oa.14415$BM.4645038 at newssrv26.news.prodigy.com: > why does > >>>> ''.join(lst) > > not automatically do > >>>> ''.join([str(i) for i in lst]) > > ? That is, is there ever a time when one does not want .join to make > everything into a string? This seems like reasonable default > behavior, but maybe I'm missing something? > > -doug > > > From andrew-pythonlist at puzzling.org Wed Jul 2 06:12:13 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 2 Jul 2003 20:12:13 +1000 Subject: arbitrary long integer aritmetics In-Reply-To: References: Message-ID: <20030702101213.GE21059@frobozz> On Wed, Jul 02, 2003 at 12:05:29PM +0200, Fredrik Lundh wrote: > "Leo" wrote: > > > i.e. the result of an integer operation is as long as necessary, so that a*b > > never produces an overflow error. > > what's an overflow error? ;-) > > $ python > Python 2.2 > >>> import sys > >>> sys.maxint > 2147483647 > >>> 2147483647 * 2147483647 * 2147483647 > 4611686014132420609L > > (note the trailing L). I also note that your Python 2.2 does arithmetic differently to mine: $ python2.2 Python 2.2.2 [etc etc] >>> 2147483647 * 2147483647 * 2147483647 9903520300447984150353281023L -Andrew. From owski at hotmail.com Tue Jul 15 13:56:32 2003 From: owski at hotmail.com (Adam Ruth) Date: 15 Jul 2003 10:56:32 -0700 Subject: anything like C++ references? References: Message-ID: I really liked your post and it made me realize something: Python has different definitions for words like variable, value, and assignement than the pure 'computer science' version mentioned in this thread. And you know what? The new definitions are better. Much better. From mis6 at pitt.edu Sun Jul 20 10:52:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Jul 2003 07:52:46 -0700 Subject: properties + types, implementing meta-class desciptors elegantly? References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: <2259b0e2.0307200652.131ed45e@posting.google.com> "Mike C. Fletcher" wrote in message news:... As others before me, I am not sure of what you are trying to do and why you are doing so. I use descriptors in this way: class o(object): class p( object ): # descriptor class def __set__( self, client, value, *args, **named ): print '__set__', self, client, value, args, named self.v=value def __get__(self,obj,cls): return self.v v = p() s=o() s.v=3 # v is a p-descriptor print s.v # Output: #__set__ <__main__.p object at 0x4031af8c> <__main__.o object at 0x4031c0ac> 3 () {} #3 Does this code help? Michele From mwh at python.net Tue Jul 29 07:56:54 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jul 2003 11:56:54 GMT Subject: Defining/declaring constants in Python References: Message-ID: <7h3fzkpk0lv.fsf@pc150.maths.bris.ac.uk> Christopher Koppler writes: > If you really, really, REALLY want a varia^Wconstant that cannot be > changed, no matter how hard you try, in Python, have a look at this: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 Of course, it's still possbile to change the values of these 'constants', you just have to muck about quite a bit to manage it. Making something really, truly, constant in Python is probably impossible (and certainly hard enough to be a silly thing to do in real code). Cheers, mwh -- MAN: How can I tell that the past isn't a fiction designed to account for the discrepancy between my immediate physical sensations and my state of mind? -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From davidcfox at post.harvard.edu Mon Jul 21 20:42:29 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 22 Jul 2003 00:42:29 GMT Subject: Python bug with dictionary In-Reply-To: <3F1C84F4.3B1E4F9A@n.com> References: <3F1C84F4.3B1E4F9A@n.com> Message-ID: none wrote: > or is it just me? > > I am having a problem with using a dictionary as an attribute of a > class. This happens in python 1.5.2 and 2.2.2 which I am accessing > through pythonwin builds 150 and 148 respectively > > In the sample code you see that I have class Item and class Dict > class Dict contains a dictionary called items. The items dictionary > will contain instances of Item that are keyed off of the Item name. In > __main__ I create two distinct instances of Dict and 4 distinct > instances of Item. By using the accessor method addItem() in Dict I add > the instances of Item to Dict. In this case I add Item1 and Item2 to > Dict1 and I add Item3 and Item4 to Dict2. When this is done I print > out the instances of Dict and of Item. It appears that the dictionary > items in each of the Dict instances is the exact same instance even > though they were created as distinctly separate classes. The print out > of the results shows them at the same memory address. The items > dictionary inside of each Dict object have the same id when I do > id(dict1.items) and id(dict2.items). This means that each of the items > dictionary in the Dict instances has all four items in it, even though > each should only have two. Apparently when I add the first to Item > instances to dict1 and then the second two Item instances to dict2 they > are being added to the same items dictionary. By creating the attributes items and name in the body of class Dict, you are creating class attributes which are shared by all instances of the class. When addItem refers to self.items, it finds no instance attribute, so it falls back to modifying the class attribute. What you want to do instead is define class Dict: def __init__(self): self.items = {} self.name = "" ... and similarly for Item David > > > class Dict: > items = {} > name = "" > > def addItem(self,item,name): > self.items[name] = item > > > def setName(self,name): > self.name = name > > def getName(self): > return self.name > > def printItemKeys(self): > print "Dictonary Keys: ",self.items.keys() > From bokr at oz.net Fri Jul 25 11:57:39 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 15:57:39 GMT Subject: data conversion question (binary string to 'real string') References: Message-ID: On Fri, 25 Jul 2003 14:57:57 +0200, Alexander Eisenhuth wrote: >Hallo all there, > >maby I don't see the forest because of all that trees, but : > >from struct import * > > ># how can I convert >f = float(0.5) > ># with >bin_str = pack('!f', 0.5) > ># now bin_str is '?\x00\x00\x00' > > ># to "3F000000" ????? > > That leading '?' is the character representation of a string byte whose ordinal value is 3F hex, followed by three characters represented by \x00 (whose ordinal values are zero). I.e., your binary bytes are being represented as characters in a string, and when it's shown interactively you see the values as a sequence of character glyphs (or \x.. hex escape representations if no glyphs are available), which is the normal way to display a string. If you want the *hex string* representation of that string-represented byte sequence, you can convert each byte-as-character first to its ordinal value and then the ordinal value to a 2-char hex string representation, and then join those all into a single string, e.g.,, showing the character transformations: >>> [c for c in struct.pack('!f', 0.5)] ['?', '\x00', '\x00', '\x00'] >>> [ord(c) for c in struct.pack('!f', 0.5)] [63, 0, 0, 0] >>> ['%02X'%ord(c) for c in struct.pack('!f', 0.5)] ['3F', '00', '00', '00'] And finally, all you need is >>> ''.join(['%02X'%ord(c) for c in struct.pack('!f', 0.5)]) '3F000000' Now you have a hex string representation of the network-ordered (big-endian-ordered) bytes of a single precision (32-bit) float. Regards, Bengt Richter From andy at wild-flower.co.uk Fri Jul 18 16:58:13 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 18 Jul 2003 21:58:13 +0100 Subject: Python dictionary syntax, need help In-Reply-To: <56ba0aea.0307181142.7401aa02@posting.google.com> References: <56ba0aea.0307181142.7401aa02@posting.google.com> Message-ID: <200307182158.13059.andy@wild-flower.co.uk> On Friday 18 Jul 2003 8:42 pm, Crew Reynolds wrote: > I want to create a dictionary of note on/off timings and access it by > the name of the object. The following code works for one row. > > a = "Hammer1" > b = [5,45,45,45,45,50,55,57,59,61,60,59] > > notes = {a:b} > print notes["Hammer1"][3] > > >>> 45 > > The problem is, I want to load the data from a file to populate > variables a and b and build a dictionary for "Hammer1" thru > "Hammer10". That way, I can stick the name of the object in the array > index and receive a list of note timings that I can index with an > ordinal as in the above example. > > This is straight Python syntax but I'm hoping someone has done this or > understands the syntax better than I. > > Thanks! Alternative solutions to this concept would be greatly > appreciated. sorry, forgot the file bit... say notesfile.txt has the following structure: hammer1, 5, 45, 45 45, 45, 50, 55, 57, 59, 61, 60, 59 hammer2, 25, 245, 245, 245, 245, 250, 255, 257, 259, 261, 260, 259 hammer3, 35, 345, 345, 345, 345, 350, 355, 357, 359, 361, 360, 359 hammer4, 45, 445, 445, 445, 445, 450, 455, 457, 459, 461, 460, 459 then we'd need to do something like: notes={} # and empty dict notesfile=file("notes.txt") # open the file for line in notesfile.readlines(): # iterate through its lines words=line.split(",") # split the line up at every "," hammer=words[0] # remember the hammer name for n in words[1:]: # go through the remaining words try: # We know this could go wrong if the file contains garbage notes[hammer]=int(n) # try to convert the string to a number except ValueError: # if the conversion went wrong... print "Expected number, got:",n # warn the user notesfile.close() #close the file hth -andyj From t.leeuwenburg at removme.bom.gov.au Thu Jul 17 20:59:23 2003 From: t.leeuwenburg at removme.bom.gov.au (Tennessee James Leeuwenburg) Date: Fri, 18 Jul 2003 10:59:23 +1000 Subject: Jython classpath question References: Message-ID: I can now import every class except the one which I would most like to import. The fully-qualified classname is au.gov.bom.aifs.dv.dv. I can import anything else from the au.gob.bom tree, and also other things from the dv tree such as dv.LayerManager. It's just dv.dv that is causing hassles. Are there any pitfalls or required naming conventions that I should be aware of? Thanks, -Tennessee From johnroth at ameritech.net Wed Jul 2 14:21:35 2003 From: johnroth at ameritech.net (John Roth) Date: Wed, 2 Jul 2003 14:21:35 -0400 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> <3064b51d.0306170436.2b31f9e@posting.google.com> <9a6d7d9d.0307020959.634ceb4e@posting.google.com> Message-ID: "Aaron Watters" wrote in message news:9a6d7d9d.0307020959.634ceb4e at posting.google.com... > David Abrahams wrote in message news:... > > Duncan Booth writes: > > > > I'm not saying that Python isn't a wonderful language -- it is. It's > > great to have the flexibility of fully dynamic typing available. All > > the same, I'm not going to pretend that static typing doesn't have > > real advantages. I seriously believe that it's better most of the > > time, because it helps catch mistakes earlier, makes even simple code > > easier to maintain, and makes complex code easier to write. I would > > trade some convenience for these other strengths. Although it's very > > popular around here to say that research has shown static typing > > doesn't help, I've never seen that research, and my personal > > experience contradicts the claim anyway. > > I'm somewhere on the fence. I've seen static typing catch errors, > but I've also seen static typing (in java, say) make the use of a > hash table into an exercise in code obfuscation. I'd really like some > sort of compromise where you could harden types incrementally. Also > static typing can make it more difficult for bad programmers to do > stupid things... > > I'd like to see research either way. I've heard of rumored research > in both directions. Personally, I suspect the widely repeated statement > "90% of programming errors are typing errors" can be traced back to the > 60's when engineers wrote programs on graph paper-like sheets and > handed them to TYPISTS who then TYPED THEM WRONG onto punch cards. Keypunch operators. Not typists. Please... (Been there, done that. The '50s and '60s hacker's motto: "Sequence numbers are for sissys." I think you've pretty much got my attitude toward static typing down: I think it's an oversimplified reaction to a rather real problem. Notice that 2.2 does several things that static typing claims to do for you: Slots makes it impossible to mistype an instance variable name, and property descriptors allow you to put in whatever amount of type checking you want on instance bind operations. John Roth > > -- Aaron Watters > > "You mean life is not a fountain???" From tsteward at dodo.com.au Thu Jul 10 05:07:06 2003 From: tsteward at dodo.com.au (Tony Steward) Date: Thu, 10 Jul 2003 09:07:06 GMT Subject: Getting Started with python Message-ID: <3f0d2cb9$1@news.comindico.com.au> Hello All, Ok i've decided to try Python can anyone point me at a simple demo of a windows program operating a database (maybe an address book) so I can see how it is done. Thanks in advance Tony From pedro.werneck at bol.com.br Sun Jul 13 15:13:28 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 13 Jul 2003 12:13:28 -0700 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. References: <3F11610B.5090200@mxm.dk> Message-ID: I agree that for a skilled professional programmer, reinventing the wheel is a waste of time, but for amateurs like me, it's worth the learning... for instance, I only managed to understood and use part of Twisted after trying to write my own simple framework... and sometimes I prefer to use it, for the simplicity and size... From tjreedy at udel.edu Tue Jul 22 18:11:02 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2003 18:11:02 -0400 Subject: Iterating order of dict.items() References: <16469f07.0307220706.5e2fe1e4@posting.google.com> Message-ID: "Robin Cull" wrote in message news:16469f07.0307220706.5e2fe1e4 at posting.google.com... > The order the items comes out in appears to be undefined. Correct. > I would have thought that without any other sorting that the items > would just come out in the order that the dict was defined in, No, the whole point of hashing keys is to pseudorandomly spread them more or less uniformly around the storage array with as little dependence on input order as possible. This is what make insertion and deletion close to O(1) rather than O(n) operations. Terry J. Reedy From martin at v.loewis.de Tue Jul 29 00:37:15 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Jul 2003 06:37:15 +0200 Subject: memory leak troubleshooting techniques References: Message-ID: Adam Deutsch writes: > Is there any systematic method of determining how Python is using its > allocated memory? In the debug version, you can get a list of all objects through sys.getobjects. In the non-debug version, you can get a list of all container objects through gc.get_objects. Check whether these lists are growing in size. Regards, Martin From wpeterson1 at socal.rr.com Wed Jul 23 13:45:11 2003 From: wpeterson1 at socal.rr.com (William Peterson) Date: 23 Jul 2003 10:45:11 -0700 Subject: py2exe command line window problem References: <1ee79758.0307220827.78f8571@posting.google.com> Message-ID: <3d0678bb.0307230945.5d79d70b@posting.google.com> prashsingh at yahoo.com (Prashant Singh) wrote in message news:<1ee79758.0307220827.78f8571 at posting.google.com>... > I'm using py2exe to create a standalone executable from a Python > script, and I would like the script to run invisibly, i.e. without a > console window and without any interactive GUI. The script is a helper > app, which simply downloads and runs some other program. > > I've tried passing the -w flag to the script, and I've also tried > renaming it with a .pyw extension, but when the executable is run an > empty console window opens with the title "C:\WINNT\system32\cmd.exe". > I've checked, and there are no print statements, which might cause > py2exe to assume it's still a console app. > > Is there something I'm missing? > > Thanks, > prashant. Not a direct answer to your question, but I've used Installer - http://www.mcmillan-inc.com/install1.html to build standalone executables without a console window. Bill From kp at kyborg.dk Thu Jul 10 08:34:05 2003 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 10 Jul 2003 14:34:05 +0200 Subject: Memory leak ?? Message-ID: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> Memory leak - malloc/free implementation - GC kicking in late - know bug - or ? Using python-2.2.2-26 on RH9 (shrike) x86 -fully patched The following program slowly eats up more and more memory when run on large datasets... can anyone tell what the trouble is? i've run it up to 240000 recsets so far - and it eats about .1% of my mem pr. 1000 (doesn't really matter how much does it?). -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: corr_errors.py URL: From mgerrans at mindspring.com Wed Jul 9 13:02:58 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 9 Jul 2003 10:02:58 -0700 Subject: QUESTION References: Message-ID: > I think you might want to be careful about deleting Python from your > COMPAQ. It appears that COMPAQ did actually deliver Python on some of their > systems: > > http://wingide.com/pipermail/marketing-python/2003-February/001050.html > > Deleting Python from the computer may make future upgrades difficult. Yup, Kevin did the sleuthing, found my name in the scripts then contacted me and I promised to write up a Python success story (http://www.pythonology.com/success) about the pre-installation of Python on HP and Compaq machines. However, in this particular case, the OP says it was a Windows 98 machine, which would have been before the HP-Compaq merger, so it is more likely that the Python was subsequently installed on that machine not pre-installed. Additionally, the Python pre-installion that I've done for HP Pavilions (and now also Compaq Presarios) was originally Python 1.5.2, then was (and still is) Python 2.2, but never Python 2.1.1. Of course, it is possible that Compaq was also pre-installing Python on their systems before the merger, but there is one other piece of evidence which may refute the pre-installed theory: I don't think Python 2.1.1 and Windows 98 OEMs fit the same timeframe (maybe WinMe or the first release of XP...). - Matt From mwh at python.net Tue Jul 22 14:17:29 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 18:17:29 GMT Subject: python22_d.lib? References: Message-ID: <7h3vftuxwk0.fsf@pc150.maths.bris.ac.uk> "solosnake" writes: > Well I thought I would take my first few steps in embedding python > today, and had to stop much sooner then I hoped. Where is > python22_d.lib? Why is it not in the release? I have 2.2.3, but > nowhere is there such a library. Must I get the source and build it > myself? Yes. > I'm using MSVC++ 6.0. Then you shouldn't have too many problems. Cheers, mwh -- If you don't use emacs, you're a pathetic, mewling, masochistic weakling and I can't be bothered to convert you. -- Ron Echeverri From skodela at lithium.com Thu Jul 17 22:03:18 2003 From: skodela at lithium.com (sreekant) Date: Fri, 18 Jul 2003 02:03:18 +0000 (UTC) Subject: Anyone noticed any new changes in tkinter In-Reply-To: References: Message-ID: Thanks for that. sreekant From PoulsenL at capanalysis.com Thu Jul 31 19:53:59 2003 From: PoulsenL at capanalysis.com (PoulsenL at capanalysis.com) Date: Thu, 31 Jul 2003 19:53:59 -0400 Subject: How to read MS msg file in python Message-ID: <72F73B808A78D511A73600034771D9FF718616@dc_exchange2.howrey.com> I have a series of "msg" mail files saved in a folder. Most files have attachments in attachments all in the msg format. Finally nested inside all of these is a word document. Has anyone written a tool to read such files or, ideally, recursively save all the nested attachments in a msg file? Alternatively is there a method to convert these files into something I can parse using the email package? Thanks in advance, Loren From anton at vredegoor.doge.nl Mon Jul 28 07:04:16 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 28 Jul 2003 13:04:16 +0200 Subject: Python and VS.Net References: <221d8dbe.0307272345.63503afd@posting.google.com> Message-ID: srijit at yahoo.com topposted: >1) Both Java and .NET are going to stay and keep competing with each >other for developers' mindshare. Yes, it's a problem, I would be better to have a general framework but initiatives by closed source developers can not provide such a thing. >2) At present Python 2.3 for Windows is based on VC6. This cannot >continue for ever. I consider absence of compatability of Python with >VC7/VS.NET as a major threat for Python's future. Windows is but a platform among many. IMO now would be the time to drop VC in favor of mingw or another free compiler with public sourcecode. >5) Even now, it is not easy to convince management about Python's >adavantages in corporate world. It will be come more difficult, in >future, if Python.NET is not available. In Europe there is some initiative to use public source code in governmental settings. Since the world at large is drifting towards a knowledge based economy, selling computer programs based on proprietary sourcecode will not be a feasible alternative anymore some time in the future. As a result software industries will have to migrate into service based billing systems, but the bills will be paid by bills as I will try to explain below. A service industry can be more efficient the more it knows about its clients and the industry is already deploying initiatives towards this goal, see for example the microsoft passport initiative. However people seem to get more and more reluctant to provide information without receiving equal information "value" back because it's slowly being realized that information is the new money and industries that do not follow the new information exchange "laws of nature" will be left behind. In stark contrast to the old value system that was money based, in the knowledge based value exchange system one will receive more that will spend more. The reason for this is that by freely providing information one enables other information sources to return more specialized highly valuable information in return, however this value is also highly personalized. What you want to know is not necessarily what I want to know. For the moment it is still impossible to make a computer that thinks better than a human so until that happens humans will be the producers of the new kind of currency. Taking these two peculiarities -increasing value return by giving away value, and highly personalized value production and consuming- it is clear that only systems that do not cache information or impede information flow will be the survivors of the new market. So if one must worry, worry about google compliance instead of about microsoft compliance ;-) Of course google itself will survive only if it's not going to make the mistake of trying to sell its service for money or passwords\email adresses\logins\cookies. Google will get "rich" just by getting to know what you want to know and by freely providing this knowledge to those who want to know *that* and thereby getting to know what *those* want to know, enabling them to freely provide even more information ... etc. A key concept here is not forcing the user to provide information, but providing information based on information request. >6) Ruby users are also taking initiative to make Ruby work with .NET >framework. Refer http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&frame=right&th=9fa784e70c5dc0cf&seekm=20030716140638.M85561%40deltadata.dk#link1 > >I am interested to learn what core python team is thinking about >compatability of Python 2.x, 3.x with Windows/VC7/VS.NET. Me too, but this question should probably be asked in the Python developers mailing list, which according to my analysis above should be turned into a newsgroup as soon as possible. Also they'd better answer that they're going to migrate to mingw-compiling soon :-) Personally I'm still using windows products (w2000 and w98) but I'm leaning more and more to using Cygwin for Python related tasks, and unless microsoft is about to make a 180 degree turn in its philosophy about releasing sourcecode (it has happened before with some company, see for example netscape) my next OS will probably be Linux or some other open source thingy. Anton. From adalke at mindspring.com Wed Jul 23 03:23:37 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 23 Jul 2003 01:23:37 -0600 Subject: [OT] RE: Possible use of Python for a voting machine demo project -- your feedback requested References: <1ED4ECF91CDED24C8D012BCF2B034F13026F8E3D@its-xchg4.massey.ac.nz> <1ED4ECF91CDED24C8D012BCF2B034F130212AB7C@its-xchg4.massey.ac.nz> Message-ID: Skip Montanaro: > Stranger things have happened here... For example, here in New Mexico, in Southwest US, if there is a tie in an election then it's broken by a game of chance, like poker or dice. Every few years there's a tie for a local election which is resolved this way. Were electronic voting pushed even more, would that mean we would end up resolving it with video poker? I hope not. There's something visceral about the two candidates, meeting in front of the county courthouse, at noon, mumuring "draw", and playing a game of Hi-Low. Andrew dalke at dalkescientific.com From adalke at mindspring.com Thu Jul 31 18:00:33 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 31 Jul 2003 16:00:33 -0600 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: Edward K. Ream: > There aren't any [compromises in Python] There are definitely compromises in Python. As Christopher Koppler pointed out, Python does compromise for backwards compatibility. If you want, you can write "1 <> 2" and it will work, even though that feature has been deprecated for about 8 years. Similarly, string exceptions were deprecated about 5 years ago, but you can still use them. And now with new-style types you can use class OldSpam: eggs = attribute(_get_eggs, _set_eggs) class NewSpam(object): eggs = attribute(_get_eggs, _set_eggs) and get slightly different behaviours. These exist as a compromise between the old way (plenty of existing source code) and the new way (which provides better ways to do older behaviours). Andrew dalke at dalkescientific.com From guettler at thomas-guettler.de Thu Jul 10 06:17:56 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 10 Jul 2003 12:17:56 +0200 Subject: Maxmium bufsize using open2? References: Message-ID: Maurice wrote: > Dear all, > > I've a problem using popen2 when using large files. > When I use small input files everything works well but when I feed large > inputfile to the pipe nothing happens. Is there a maximum bufsize for > using the pipe. The code I use is written down here below. Do I need to > specify a waittime between line 4 and 5 ? > > > o,i =popen2('command ')) > fh=open(os.path.join(self.dirname, self.filename),'r') > i.write(fh.read()) > i.close() > self.StringData=o.read() > o.close() Hi, Have a look at the select module. thomas From bkelley at wi.mit.edu Wed Jul 30 11:16:35 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 30 Jul 2003 11:16:35 -0400 Subject: filter is Python In-Reply-To: References: Message-ID: <3f27e0fb$0$3938$b45e6eb0@senator-bedfellow.mit.edu> Wiebke P?tzold wrote: > Hi all! > > I have to work with MetaKit. My job is it to filter. For example: If I > search for the initial letter "P", the programm should all results > print with this characteristic. > Couls somebody help me with this task? > > Wiebke The metakit list is probably the place for this. See equi4.com for instructions. That being said: I assume you are filtering a table/view looking at some column. Let's say the table is "foo" and the column is "bar". def myfilter(row): return row.bar[0] == "P" # return the matching indices indices = view.filter(myfilter) # return a new view with only the matching rows newview = view.remapwith(indices) Here is a full example: import metakit storage = metakit.storage() vw = storage.getas("test[bar:S]") data = """My dog has fleas but he is a very good Pooch. Sometimes he likes to Play""".split() for d in data: vw.append((d,)) def myfilter(row): return row.bar[0] == "P" indices = vw.filter(myfilter) metakit.dump(indices) newvw = vw.remapwith(indices) metakit.dump(newvw) From mis6 at pitt.edu Mon Jul 14 13:30:25 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Jul 2003 10:30:25 -0700 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: <2259b0e2.0307140930.4b3c43a5@posting.google.com> "richardc" wrote in message news:<3f129a8a$1 at mail.hmgcc.gov.uk>... > Ive just started playing with Python and have a couple of questions. > > Im looking for an agument parsing library (from the command line), Ive come > across optik and argtools. What other ones are there are any of them any > good, is there a 'standard' lib for doing this. > optparse (a.k.a. optik) is great, whereas I never made my mind up to getopt. To "cure" getopt, I needed to define my own routines for argument parsing; after I started using optparse I had the satisfaction of erasing all of them ;) I vote optparse as the best addition to Python 2.3! (okay, well, there are other niceties, but maybe optparse is the most useful thing; who does agreee with me ?) Michele From khalid.sheikh at silvaco.com Mon Jul 21 19:52:15 2003 From: khalid.sheikh at silvaco.com (Khalid Sheikh) Date: Mon, 21 Jul 2003 16:52:15 -0700 Subject: Newbie question about strings Message-ID: Hi, I have been tasked to Integrate Inktomi Search (now Verity of course) with our website. I am fairly new to Python. The way the search engine is setup is that it has embedded python in a html document. After looking at the html code for a day or so, I was able to pin point the place where I need to make a change but I am having a hard time. I am assuming &$self.text(dbcol[docdb].pretty_name); prints something in HTML but I am trying to figure out it's equivalent in Python. I am assuming this is a string and I need to check it's value against another string say 'XXY' if it is equal then go ahead and print that value otherwise skip to the next item in the list/array. This is what I had before and it worked , Test< &$self.text(dbcol[docdb].pretty_name); >Test when run this prints Test< XXY >Test, Test< ABCD >Test I want it to print only when the string is equal to XXY. otherwise skip to the next string. This is the edited code that I have so far. , Test< &$self.text(dbcol[docdb].pretty_name); >Test I get the following error when I run the program. exceptions.SyntaxError: invalid syntax (line 86) Line 86 if dbcol[docdb] == wlines.append(u' '); Any help would be greatly appreciated. Khalid J. Sheikh Software Engineer Silvaco International http://www.silvaco.com (408) 654-4352 From andrew-pythonlist at puzzling.org Tue Jul 1 21:23:25 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 2 Jul 2003 11:23:25 +1000 Subject: PyQt and async I/O In-Reply-To: <3f01fb8f@usenet01.boi.hp.com> References: <3f01fb8f@usenet01.boi.hp.com> Message-ID: <20030702012325.GA21059@frobozz> On Tue, Jul 01, 2003 at 02:01:43PM -0700, djw wrote: [...] > > If you were to use asyncore for this async I/O, there is no yielding that I > can see. Select() doesn't yield, and there is no time.sleep() in the > asyncore.loop() code. Even if I were to add a time.sleep() to the loop, > wouldn't the fact that select() blocks for some timeout value (default=30.0 > sec) imply that it would only yield after the select() timed out each time > through the loop? That would seem to make for a pretty unresponsive UI. > > Hopefully somebody can clue me into understanding this. Twisted has support for Qt -- see the 'twisted.internet.qtreactor' module. That might give you some ideas; alternatively, you could just use Twisted and stop worrying ;) -Andrew. From ben at dadsetan.com Sun Jul 6 14:40:02 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Sun, 06 Jul 2003 20:40:02 +0200 Subject: absolute beginners question about API documentation In-Reply-To: References: Message-ID: Dave Kuhlman wrote: > Markus Joschko wrote: >>I'm want to know all methods I can use on dictionaries. Where can >>I get an overview about these? >>I looked on python.org but haven't found such an overview. > If you are asking about the *Python* API, then look here: > http://www.python.org/doc/current/lib/typesmapping.html > If you are asking about the C API (which is less likely but > possible), then look here: > > http://www.python.org/doc/current/api/dictObjects.html Maybe one should add for better comprehension that dictionaries in python are builtin types. So when you look for them in documentation, you should look into the basics and not for some Standard Library class as you would in the Java world. Hope it helps, Ben. From kowald at molgen.mpg.de Sun Jul 27 06:20:56 2003 From: kowald at molgen.mpg.de (Axel Kowald) Date: 27 Jul 2003 03:20:56 -0700 Subject: Problems automating Sigmaplot via COM Message-ID: <9b5e8d9.0307270220.119e8ded@posting.google.com> Hi everybody, I try to use python2.2 to automate Sigmaplot 8 via the COM interface. I can fill data into a worksheet, but have problems to create a graph :-( When I use the CreateGraphWizard method I always get the error message: "com_error: (-2147352567, 'Exception occurred.', (65535, 'SigmaPlot 8.0', 'Invalid error bar source argument.', None, 0, 0), None)" However, the type of graph I'm trying to create doesn't have error bars! Any idea what's going wrong? Many thanks, Axel Kowald ===================================================================== #!/usr/bin/env python # # Simple example how to create a Sigmaplot diagram automatically. # 7.2003 A.Kowald # from win32com.client import Dispatch app = Dispatch("SigmaPlot.Application") app.Width = 800 # desired width & height of main window app.Height = 600 app.Visible = True # create notebook and automatically one section with worksheet app.Notebooks.Add # the NotebookItems of the "ActiveDocument" (Notebook) have now 3 items: print app.ActiveDocument.NotebookItems.Count # Item 0 (ItemType 7) = The notebook itself # Item 1 (ItemType 3) = Section 1 # Item 2 (ItemType 1) = Data 1 in Section 1 # Lets name them, so we can refer to them by name. app.ActiveDocument.NotebookItems(0).Name = "MyBook" app.ActiveDocument.NotebookItems(1).Name = "MySection" app.ActiveDocument.NotebookItems(2).Name = "MyData" app.ActiveDocument.NotebookItems.Add(2) # Add graphic page app.ActiveDocument.NotebookItems(3).Name = "MyGraph" dataTab = app.ActiveDocument.NotebookItems("MyData").DataTable # 3 methods are available for data manipulation: # Cell(x,y,value) 0 based # PutData(1D/2Darray, left,top) # 1D/2Darray = GetData(left,top,right,bottom) dataTab.Cell(0,0,17) # puts 17 in the top left corner d = [[1,2,3],[2,4,6]] # col1 = 1,2,3 col2 = 2,4,6 dataTab.PutData(d,0,0) rect = dataTab.GetData(0,0,2,2) # Get 3x3 tuple # Adding column names (name,left,top,width,height=-1) dataTab.NamedRanges.Add('X',0,0,1,-1) dataTab.NamedRanges.Add('Y',1,0,1,-1) # Now lets plot the data graphPage = app.ActiveDocument.NotebookItems("MyGraph") graphPage.CreateWizardGraph("Vertical Bar Chart","Simple Bar","XY Pair",[0,1]) #app.Quit # stop COM server From psimmo60 at hotmail.com Wed Jul 2 10:53:36 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 2 Jul 2003 07:53:36 -0700 Subject: returning a structure using SWIG References: Message-ID: <94974e1a.0307020653.6278d38e@posting.google.com> "kj.kjn" wrote in message news:... > I would like to build a module for the fuction : myReturn find(char ** p1, > int p2) > > The problem is that I dont know how to specify the myReturn Type using swig. > > myReturn is : > > typedef struct{ > char * name; > char * len[10]; > time_t time; > } myReturn > > How to specify a such type in the interface file ? > > Thank you For the structure, all you need to do is paste this declaration into the interface file. Job done. Create the structure within the function, fill it up, return it and (most) everything will work. To implement the function, though, will take a bit more effort. The type of the len/p1 item may cause problems as arrays of chars I believe have to be put together by inline functions within the interface file, as SWIG doesn't put lists/tuples together automatically. However, without a few more details I can't know how easy/complex that'll be. Could the array of string be passed as an big string with an array of lengths? This may be a lot easier to parse, and is understood by SWIG. HTH, Paul From jjl at pobox.com Sun Jul 13 08:36:59 2003 From: jjl at pobox.com (John J. Lee) Date: 13 Jul 2003 13:36:59 +0100 Subject: What's new with Gnosis [wrong thread ?] References: <87d6gf6cc6.fsf@pobox.com> <3F11630D.9090806@removeme.free.fr> Message-ID: <87adbi8uxg.fsf@pobox.com> Bruno Desthuilliers writes: > John J. Lee wrote: > > "Raymond Hettinger" writes: > > [...] > > > >>ACT I --------------------------------------- > >> > > > (snip) > > John, > is it my newsreader going mad, or did you post in the wrong thread ? I posted in the wrong thread. Something about Gnus... haven't figured out why I occasionally do that yet. John From jjl at pobox.com Fri Jul 4 10:56:43 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Jul 2003 15:56:43 +0100 Subject: Python in Excel References: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> Message-ID: <873chm9w7o.fsf@pobox.com> "Tom Locke" writes: > > >Can I write Excel macros/scripts using Python? > > > > > >I mean to actually put Python into an Excel document, not using > > >Python to access data, for example, from some Excel document. > > These days you can script office with any .NET language, and that includes > Python: [...] Or use good old COM. There's an example of controlling Excel (the version from Office 2000) in the Python for Windows Extensions (aka win32all) COM test code. IIRC, it'll be somewhere like C:\Python\win32com\tests\. John From usenet at soraia.com Tue Jul 8 00:30:32 2003 From: usenet at soraia.com (Joe Francia) Date: Tue, 08 Jul 2003 04:30:32 GMT Subject: "Text Processing in Python" review on Slashdot Message-ID: In case any of you missed it, there is a very favorable review of "Text Processing in Python" over on Slashdot: http://books.slashdot.org/article.pl?sid=03/07/06/2253222&mode=nested&tid=126&tid=156 From martin at v.loewis.de Fri Jul 18 20:52:38 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 19 Jul 2003 02:52:38 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: Alan Kennedy writes: > To everyone else: Why does this stuff get so complicated? Why does it > take a multi-lingual + encoding-guru + protocol-guru + markup-guru + > python-bot like Martin von L to get stuff like this done? Does it have > to require somebot who writes better quality software (i.e. less > defective) than the world's leading search engine, Google, who got it > slightly wrong? Indeed, it is the bugs in the software that make it so hard. Fortunately, people like myself have worked hard over the last 10 years or so to get us where we are: writing software, testing software, reporting bugs. Now much new software is unicode aware, and may even support it to a large degree. Still, a lot needs to be done. Most of this is in the minds of developers, to recognize "Unicode good, byte string bad, Unicode good, byte string bad" :-) > The idea of raising this came to me when that Russian individual > posted a message a few days ago that got very garbled in the > transmission, both subject and content. Again, it was only Martin who > was able to figure out its content I made a number of guesses, I admit. It had to be a language which rarely uses ASCII, and whose encodings don't use bytes < 128. So most likely it was Greek or Russian - this is expert knowledge one collects over time. I tried three Russian encodings (again, which one to try are expert knowledge, and I thought of Windows only last). Regards, Martin From tzot at sil-tec.gr Wed Jul 23 10:34:57 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 23 Jul 2003 17:34:57 +0300 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: On Wed, 23 Jul 2003 08:36:57 +0000 (UTC), rumours say that Duncan Booth might have written: >Christos "TZOTZIOY" Georgiou wrote in >news:amqqhv0gbdok6dnk6ib9342lejpc4ap5pd at 4ax.com: > >> If I may say it sideways, try searching for google for the french word >> "c?", as in "un c? s'il vous pla?. Wanna bet my message will be >> the only one to be found? :) > >Since when is 'c?' a French word? It doesn't appear in any French >dictionary I have tried. (A longer explanation was sent by email to Duncan) That was my intention: to misspell as 'c?fe' the french word 'caf?', and then search for it in google groups. This is because the original greek word --used as an example by Alan, Martin etc-- was misspelled as 'gi/gnwskw' instead of 'gignw/skw' (accent 'oxia' in the wrong letter, resulting in an inexistant word), so it's normal that a google groups search shows up Martin's UTF-8 post as the only one containing the word. I did begin my post as "If I may say it sideways..." :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From myles at geocities.com Wed Jul 30 20:50:12 2003 From: myles at geocities.com (Myles) Date: 30 Jul 2003 17:50:12 -0700 Subject: PIL & TIFF transparency? References: Message-ID: Robin Becker wrote in message news:... > Has anyone done transparency with PIL & TIFF? I'm using PIL to generate > a preview TIFF for embedding into an eps file and am being asked for the > TIFF to support transparency. Simple example that makes pure white areas of an RGB image transparent (there's probably a better way to create the mask, and a better way to add the mask to the image, but this gives you a starting point): import Image, ImageChops im = Image.open('/junk/pickme.png') # create mask (will become alpha band i.e. transparency) mask = im.point(lambda i : i == 255 and 255) # create RGB mask mask = mask.convert('L') # mask to grayscale mask = mask.point(lambda i : i == 255 and 255) # mask to B&W grayscale mask = ImageChops.invert(mask) # merge mask with image R, G, B = im.split() nuimg = Image.merge('RGBA', (R, G, B, mask)) nuimg.save('/junk/out.tif', 'tiff') Regards, Myles. From danb_83 at yahoo.com Wed Jul 30 20:08:16 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 30 Jul 2003 17:08:16 -0700 Subject: How to get Windows physical RAM using python? References: Message-ID: Mark wrote in message news:... > OK, How to check the amount of Windows physical RAM using python? The easiest way is to parse the output from $WINDIR/system32/mem.exe . memTotals = os.popen('mem | find "total"').readlines() conventionalMemory = int(memTotals[0].split()[0]) extendedMemory = int(memTotals[1].split()[0]) From max at alcyone.com Sat Jul 12 19:09:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 16:09:16 -0700 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <3F10951B.5C18E6F6@alcyone.com> Tom Plunket wrote: > Is there any way to do references like this in Python? It'd be > like this, though clearly this doesn't change the thing I want it > to change: Hi, Tom. There's no builtin support for this in Python, but you can do it yourself easily enough. Pass in a mutable container, and then twiddle the object you want inside it. >>> def change(val): ... val[0] += 1 ... >>> v = [0] >>> change(v) >>> v [1] I'm a strong believer in writing self-documenting code, so in a case like this I write a (trivial) class that makes my intent crystal clear: >>> class Container: ... def __init__(self, value=None): self.value = value ... def get(self): return self.value ... >>> class Container: ... def __init__(self, value=None): self.value = value ... def get(self): return self.value ... def set(self, value): self.value = value ... >>> def change(container): ... container.set(container.get() + 1) ... >>> >>> c = Container(0) >>> change(c) >>> c.get() 1 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Winners are men who have dedicated their whole lives to winning. \__/ Woody Hayes From giva at users.sourceforge.net Wed Jul 30 12:20:48 2003 From: giva at users.sourceforge.net (Gisle Vanem) Date: Wed, 30 Jul 2003 18:20:48 +0200 Subject: Misuse of Message-ID: <3f27f0e3$1@news.broadpark.no> I'm a .py newbie and fascinated by the simplicity of formatting. No need for {} as in Perl etc. But the misuse of that many .py writers do makes it hard to understand how a script operates. E.g. def main(): terminate = 0 def foo(): line = sys.stdin.readline() try: bar() except: terminate = 1 main() Now, with an editor with different tab-settings it's difficult to see where the try statement belongs. In 'def main()' or in 'def foo()' ? I'm confused, please enlighten me. --gv From R.Brodie at rl.ac.uk Wed Jul 2 09:58:48 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 2 Jul 2003 14:58:48 +0100 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: "Aur?lien G?ron" wrote in message news:bdunoh$1pms$1 at biggoron.nerim.net... > The same goes for GUIs. I'd be interested to know about projects where > they automate unit tests for GUIs, but I suspect it would be just as > cumbersome. I don't think one would necessary need to automate the GUI itself. A lot of applications seem to have poor separation of the GUI, something that the developers of GUI frameworks seem to encourage (not necessarily as part of their evil plan). If the end result of designing a GUI application for testing was that it was both easy to script and to port to another toolkit, as a side effect, than I can see the possible benefit. From guettler at thomas-guettler.de Wed Jul 16 10:05:37 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Wed, 16 Jul 2003 16:05:37 +0200 Subject: Choosing the right framework References: Message-ID: Carsten Gehling wrote: > Oh how often this subject may come up... > > The thing is, I've come to the decision of abandoning PHP as much as > possible (old projects still remain...), and use Python for all purposes. > Reason: One language to fit it all (instead of having one language for > webprogramming, one for batches, etc...) Where do you want to store your data? [relational database, text files, ZODB, Berkley DB, pickles, ...] If you don't need ZODB (object database), I would not use Zope. I would use quixote. thomas From tjreedy at udel.edu Thu Jul 31 20:46:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2003 20:46:16 -0400 Subject: How do I get a reference to a KEY value of a dictionary? References: <645db655.0307311636.71923378@posting.google.com> Message-ID: "Andy C" wrote in message news:645db655.0307311636.71923378 at posting.google.com... > I am new to python, so please bear with me if I am making some > conceptual error. > > Basically I want to create a graph with an adjacency list > representation, but I don't want any of the adjacency lists to have > duplicate strings when it is avoidable. I have a function createEdge > that adds an edge to the graph. The arguments will be distinct since > they are read from text files. But basically I want to use the > dictionary as a string pool, and if the argument string equals > something in the pool already, don't use the argument string, just a > use a reference to something in the string pool already. Thinking in terms of 'references' can both help and hinder. (There have been some long recent discussion.) Are you familiar with this? >>> help('intern') Help on built-in function intern: intern(...) intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. TJR From trentm at ActiveState.com Wed Jul 23 15:26:40 2003 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 23 Jul 2003 12:26:40 -0700 Subject: Python and VS.Net In-Reply-To: ; from tim_one@email.msn.com on Wed, Jul 23, 2003 at 12:24:52AM -0400 References: Message-ID: <20030723122640.A356@ActiveState.com> [Tim Peters wrote] > Note that all current Windows installers from PythonLabs install code > compiled with VC6... As do all ActivePython Windows packages. Trent -- Trent Mick TrentM at ActiveState.com From sschlesi at bigfoot.com Mon Jul 21 12:27:20 2003 From: sschlesi at bigfoot.com (Scott Schlesier) Date: Mon, 21 Jul 2003 16:27:20 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) References: Message-ID: On Mon, 21 Jul 2003 09:58:19 -0000, Irmen de Jong wrote: Am I experiencing a "technical difficulty", or are all of the links below broken? Scott S. >Discussion >---------- > Aahz writes a rebuttal to Artima.com, because a recent interview with > Bruce Eckel on that site might give the wrong impression regarding > Python's type system. > > > Raymond Hettinger intrigues with the second episode of a series of > mysterious Python puzzles. > wrdny02.gnilink.net> > > Tom Plunket starts a huge thread about the way Python treats > objects, names, variables, assignment, references and what not. > Various people have different opinions about what would be the best > way to do things, but in the end, the QOTW of Tim Roberts (above) > kind of says it all. > > > Michele Simionato likes to have an endswith method that accepts a > list of strings, instead of a single string argument. But things are > not that easy. > > > Alan Kennedy shows what you might do if you need to build a list of > database rows (from a query), without allocating the list beforehand > because you don't know the size. He uses an iterator to do the trick. > > > Andrew Kuchling has started a mailing list for discussion about > Python Web frameworks. > This is partly because perhaps Python needs a single 'standard' way > to create web applications, as Andy Robinson points out. > > From h.b.furuseth at usit.uio.no Sat Jul 5 14:23:13 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 05 Jul 2003 20:23:13 +0200 Subject: How to get CGI request-URL References: <3f070d44$0$49099$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Glad to be of assistance, but you didn't tell us what the > actual solution to your problem was... It is always a good idea > to do so because others that have the same problem, and > reading the thread, can immediately benefit :-) Good point. I'll come back when I'm sure my solution actually works... I need to get someone to intall the program first. -- Hallvard From tdelaney at avaya.com Wed Jul 16 20:42:46 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 17 Jul 2003 10:42:46 +1000 Subject: list() coercion Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D3D5C@au3010avexu1.global.avaya.com> > From: Ian Bicking [mailto:ianb at colorstudy.com] > > Is there a way I can keep this from happening? Maybe something list() > tries first that I can make fail. (I notice list() catches any > exceptions in __len__ and then will just skip that step) Simplest thing is probably: ll = MyListLikeObject() li = iter(ll) l = list(li) i.e. explicitly create an iterator (which doesn't have a __len__) and create the list from that. OTOH, if the problem is that creating the iterator is causing the problem (calling __len__), you may need to create a proxy object that doesn't have a __len__ and call list() on that. Tim Delaney From donn at u.washington.edu Wed Jul 16 15:12:19 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jul 2003 12:12:19 -0700 Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> <20030716123907246-0600@news.xmission.com> Message-ID: In article <20030716123907246-0600 at news.xmission.com>, Adam Ruth wrote: > In Donn Cave wrote: > > In article <20030716081156943-0600 at news.xmission.com>, > > Adam Ruth wrote: > > > >> In <1058328099.572993 at yasure> Donn Cave wrote: > >> > Quoth Adam Ruth : > >> > .... > >> >| In Python, there is no situation where "you really can't avoid > >> >| pointers". > >> > > >> > That's trivially true, no such situation can exist because that > >> > Python can't be coded. I'll repeat an example that I proposed > >> > a couple days ago, though: user implemented sequences could be > >> > implemented with a single simple indexing function, returning > >> > a pointer/target/whatever; Python could assign directly to that, > >> > making "seq[i] = x" the same kind of operation as and automatically > >> > symmetrical with "x = seq[i]". ... > You are correct, 'really need' is not much of an argument. The > statement I disagreed with was that it was bad to simulate pointers in > those situations where "you really can't avoid pointers". I was > expressing that really aren't any such situations, and that it's even > worse try to simulate pointers when it's not really necessary. OK, there really aren't any situations where you can't avoid pointers ... so you're ready with a solution to the problem I posed above? Class scope containers that hold exactly one item, to pick a commonly seen usage that I suppose is a simulated pointer - that's really not necessary, and it's "even worse" (than what?) Donn Cave, donn at u.washington.edu From iambrenNOSPAM at sympatico.ca Fri Jul 25 17:37:44 2003 From: iambrenNOSPAM at sympatico.ca (Bren) Date: Fri, 25 Jul 2003 17:37:44 -0400 Subject: Problem build Boost.Python Message-ID: Hi, Pardon my stupid, but I'm having a problem building Boost.Python as per the instructions at http://www.boost.org/libs/python/doc/building.html I got boost-build-2.0-m6.zip from sourceforge and build bjam.exe. I've tried several ways: bjam -a bjam -sTOOLS="msvc" bjam -sTOOLS=msvc I tried with and without the using msvc ; in user-config.jam. In every case I get: C:/Project/boost/tools\boostbook.jam:86: in boostbook.init *** argument error * rule path.make ( native ) * called with: ( ) * missing argument native C:/Project/boost/new\path.jam:42:see definition of rule 'path.make' being called C:/Project/boost/new\toolset.jam:22: in using C:\Project\boost\new\../new\user-config.jam:58: in modules.load C:/Project/boost\build-system.jam:55: in load C:\Project\boost\new\..\kernel\modules.jam:296: in import C:\Project\boost\new\..\kernel\bootstrap.jam:122: in boost-build C:\Project\boost\new\boost-build.jam:2: in module scope Can anyone help? -----= 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 intentionally at blank.co.uk Wed Jul 16 16:33:47 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 21:33:47 +0100 Subject: anything like C++ references? References: Message-ID: On Wed, 16 Jul 2003 06:26:01 -0700, Michael Chermside wrote: >I submit that you may find this be a more useful way to view things -- >not that Python's implementation of assignment fails to match your >expectation, but that Python provides no true access to "values", only >to the more complex construct "objects" (although a strong equivalence >exists for immutable types). > >Do you find this alternate explanation useful? I first wrote more or less this same thing a few days ago, as a description of what is wrong. It's a long thread though, and I seem to have written most of it. Just to explain, in maths, variables bind to values. There are no objects in maths, even though maths does have abstract data types, algorithms and even assignments. IMO a 'very high level' programming language should act as if variables are bound to values by default. It should only behave differently if you explicitly say otherwise. I suspect all the possible arguments against have already been made. From tjreedy at udel.edu Thu Jul 24 14:26:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2003 14:26:20 -0400 Subject: Mystery Theater New Style Classes References: Message-ID: "Bob Gailer" wrote in message news:mailman.1059062857.29503.python-list at python.org... > Predict the output: > > class A(int): > classval = 99 > def __init__(self, val = 0): > if val: > self = val > else: > self = A.classval I am not sure what the point is. However, 1. Rebinding the local variable 'self' (or any other local variable) only affects further code within the function, which there is not any. So the above conditional is equivalent to 'pass'. 2. Because ints are immutable, the value of a new int is set within int.__new__, which is not overwritten. Thus, the above __init__ is irrelevant. In particular, the value of an A object has nothing to do with the defaulted parameter 'val=0'. > a=A(3) 3. This is equivalent to a=int(3). No surprises. > b=A() 4. This is equivalent to b = int(). I thought this might raise an exception. But after seeing the result (0). I remember Guido's decision (and a recent PyDev discussion thereof) that callable builtin types should, if possible, return a null value when getting a null input. Hence >>> int(), long(), float(), tuple(), list(), dict() (0, 0L, 0.0, (), [], {}) > print a,b 3,0 5. Result is same if 'val=0' is changed to 'val=9' or anything else. > [from OP's self followup] The question this leads to is: how does one access the value of such a class within a class method? Since there is no class method presented, this make not much sense. Bob: were you aware of 4.) above when you posted this? Terry J. Reedy From j.vanrooij_at_e-quest.nl Fri Jul 4 09:39:20 2003 From: j.vanrooij_at_e-quest.nl (Joost van Rooij) Date: Fri, 4 Jul 2003 15:39:20 +0200 Subject: Delete item from wxListCtrl Message-ID: <3f05842f$0$49105$e4fe514c@news.xs4all.nl> Hi, I am having problems deleting one item from a list in a wxListCtrl widget. My thought was to select it as presented below: def onSelect(self, event): self.item = event.GetItem() self.list.DeleteItem(self.item) This won't work, it appaers GetItem() is returning an object while DeleteItem() requires a long as its input. How do I pass the item to the DeleteItem function? Regards, Joost From peter at engcorp.com Thu Jul 24 19:20:29 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jul 2003 19:20:29 -0400 Subject: SSH and Windows References: Message-ID: <3F2069BD.1FE2EC2@engcorp.com> Isaac Raway wrote: > > Hello. I'm writing a Python program that connects to servers through > telnetlib to execute a few commands. I've discovered that some of the > servers that I have to connect to with this program run only SSH, so I > need to add support for SSH to the program. I'm looking for a library > that behaves similarly to telnetlib for SSH connections. Does anyone > know of one? I was going to try using pexpect to control the Windows > telnet command, but pexpect only works on Unix. If it's just to execute a few commands, consider downloading PLink (from the PuTTY site) and use it via os.system(). It works well. -Peter From ta-meyer at ihug.co.nz Fri Jul 18 00:49:58 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 18 Jul 2003 16:49:58 +1200 Subject: Regular expression help In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F83EB@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AB4D@its-xchg4.massey.ac.nz> > > How about re.findall? > > >>> re.findall('BEGIN(.*?)END', 'BEGIN foo END BEGIN > bar END') > > [' foo ', ' bar '] > > Actually this fails with the multi-line type of file I was > asking about. > > >>> re.findall('BEGIN(.*?)END', 'BEGIN foo\nmumble END > BEGIN bar END') > [' bar '] You need the re.DOTALL flag. I don't think you can pass this to the findall function, but you can if you compile the re, eg: >>> import re >>> r = re.compile('BEGIN(.*?)END', re.DOTALL) >>> r.findall('BEGIN foo\nmumble END BEGIN bar END') [' foo\nmumble ', ' bar '] =Tony Meyer From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 2 13:48:50 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2003 19:48:50 +0200 Subject: dcom client from non-windows python In-Reply-To: References: Message-ID: <3f031b00$0$49102$e4fe514c@news.xs4all.nl> Paul Rudin wrote: >>>>>>"drs" == drs writes: > > > > > My guess is you would be more successful using pyro for the > > distributed stuff. > > Ya, but that doesn't allow you to talk to, for example, excel running > on a windows box directly. True, but it's probably piece of cake to use Mark Hammond's win32all extensions for Python on the windows box, to actually do the call, and use Pyro for the platform-neutral communication. This won't work if you're not able to run Python on the target machines, of course. > I'm not sure how much reimplementing windows is needed? There are > other non-python tools that achieve this kind of thing - see e.g. > - in theory you just need to know how to drive > the dcom network protocol. Linar's J-Integra dates from august 2001, according to their page. I wouldn't touch it with a 10 foot pole, also given Microsoft's way of changing things without documenting them. Who knows what the exact specs are of the "dcom network protocol"? (If there even is such a thing. And aren't we all going to .NET ?) IMHO you shouldn't spend a second on trying to re-implement a closed protocol such as DCOM. I think there are much better alternatives out there, that are already available, open, documented, supported and actively developed. Just my ?0.02 --Irmen de Jong From cybersamurai at mac.com Sun Jul 13 19:01:43 2003 From: cybersamurai at mac.com (cybersamurai at mac.com) Date: Sun, 13 Jul 2003 20:01:43 -0300 Subject: MacPython and more modules Message-ID: I install MacPython 2.3 on a Jaguar 2.6 on my house but I don't know how I install others modules. When I use python setup install the module is installed on usr/lib/... and not inside frameworks. How I can solve this?? Thanks about help me. From thedustbustr at aol.com Thu Jul 24 19:09:41 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 24 Jul 2003 23:09:41 GMT Subject: generator function within a generator function doesn't execute? Message-ID: <20030724190941.18070.00000520@mb-m17.aol.com> from __future__ import generators from time import time threads=[] def sleep(n): print "In Sleep" t=time() while (t+n>time()): yield None def cutscene(): yield None #start on second pass print "\nEvil Death Knight: I will kill you now!" sleep(1.5) #t=time() #while (t+1.5>time()): yield None print "\nOur Hero: I shall fight you to the death. Bring it on!" sleep(2.5) #t=time() #while (t+2.5>time()): yield None print "\nEnd of cutscene." def ticker(): yield None #wait till second time through print "." t=time() while 1: while (t+1>time()): yield None t=time() print "." def scheduler(): global threads try: while 1: for thread in threads: thread.next() except StopIteration: pass if __name__=="__main__": threads.append(ticker()) threads.append(cutscene()) scheduler() ticker() prints out a period every second. cutscene() is a scripted game sequence. sleep(n) should cause a delay of n seconds (but doesn't block execution of the other microthreads (correct term?)). ticker() and cutscene() should be running simultaneously (in effect, at least). However, when run, the sleep function doesn't execute. It doesn't even print "In Sleep". It never gets called, even though I say sleep(1.5) in cutscene(). Run it for yourself if you don't believe me. Through my testing, any generator function will not execute if called from another generator function. Regular functions work fine. If I comment the sleep statements and uncomment the while loops, it runs as expected. Why doesn't the sleep() function execute? Thanks in advance. Dustin From timr at probo.com Wed Jul 16 23:42:56 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 16 Jul 2003 20:42:56 -0700 Subject: hex to signed integer References: Message-ID: <9j6chvoep7k34fbqutvp364lghnmmohrsj@4ax.com> Tom Goulet wrote: >Hello, > >My question basically is: What is the opposite of the following? >| "%08X" % -1 > >I want to convert a string of hexadecimal characters to the signed >integer they would have been before the statement converted >them. How do I do this in such a way that is compatible with Python >versions 1.5.2 through 2.4, and not machine-dependent? > >This is my current best: >| struct.unpack("!l", \ >| chr(string.atoi(hexbit[0:2], 16)) + \ >| chr(string.atoi(hexbit[2:4], 16)) + \ >| chr(string.atoi(hexbit[4:6], 16)) + \ >| chr(string.atoi(hexbit[6:8], 16))) (Unrelated note: the blackslashes are unnecessary in this example, since it is inside a set of parens.) How slimy is this? try: temp = int(hexbit,16) except: temp = int(long(hexbit,16)-2**32) Equivalently: if hexbit[0] < '8': temp = int(hexbit,16) else: temp = int(long(hexbit,16)-2**32) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From llafba at gmx.net Wed Jul 2 10:32:16 2003 From: llafba at gmx.net (Tom) Date: Wed, 02 Jul 2003 16:32:16 +0200 Subject: undo tab References: <3F02E7D5.4060401@gmx.net> Message-ID: <3F02ECF0.105@gmx.net> Hi, it doesn't work with any editor that I tried. The one I use on a regular basis is the standard python IDLE. Sometimes I also use the editor of pythonwin and Boa-Constructor. Maybe you can just give me a general hint how you do it and which editor you use. That would probably also help. Thank you, Tom. Ulrich Petri wrote: >"Tom" schrieb im Newsbeitrag >news:3F02E7D5.4060401 at gmx.net... > > >>Hi, >> >>as we all know we need tabs if we use for, if ... commands. Sometimes I >>find an easier way to do something and I can get rid of one or more for, >>if ... loops. Unfortunately I couldn't find a convenient way to get rid >>of the now unnecessary tabs. I am looking for something as convenient as >>inserting tabs (mark everything and push the tab key). I tried shift+tab >>and all other possible variations with alt/shift/ctrl. :-) >> >>Thanks for your help. >>Tom >> >> >> > >Would be helpful if you give us a clue what editor you are using.... > >Ciao Ulrich > > > > From tom at liveDELETE-MElogix.com Thu Jul 3 20:02:05 2003 From: tom at liveDELETE-MElogix.com (Tom Locke) Date: Fri, 04 Jul 2003 00:02:05 GMT Subject: Python in Excel References: Message-ID: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> > >Can I write Excel macros/scripts using Python? > > > >I mean to actually put Python into an Excel document, not using > >Python to access data, for example, from some Excel document. These days you can script office with any .NET language, and that includes Python: http://www.activestate.com/Products/Visual_Python/ At one point I know this implementation was horribyl slow - I'm not sure where they're at now. If you want to actually embed the script inside the spreadsheet, I believe that is only possible in Office 2003 - currently in beta. Right now you can write a standalone program that can launch and then control Excel. You can do much more than just access the data - you can do anything that you can do with VB. The only thing missing is embedding the .NET code in the document. Tom. From heikowu at ceosg.de Tue Jul 15 20:53:15 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 16 Jul 2003 02:53:15 +0200 Subject: ANN: Flatten 0.1 Message-ID: <1058316795.664.75.camel@d168.stw.stud.uni-saarland.de> Flatten is a standalone serialization module suitable for converting a Python object to a byte-string and back, and especially well suited for network data transferral. Flatten was first created out of the need for a secure way to pickle class-instances for network transmission, and has in the mean time evolved to become quite something more complex than only this. Flatten offers: - Serialization of base Python types (it better should... ;)) - Serialization of circular data structures (almost perfectly, see the documentation for more info why there are slight quirks) - Serialization of predefined user classes conforming to a special serialization protocol and having been registered with Flatten. - Much much more, look at the source, Luke! ;) Detailing the serialization protocol here would be far too much, but as a little teaser, let me state that Flatten handles class instantiation differently than most other serializers by not only giving the topmost class a chance to serialize/unserialize and restore data, but also all base classes of this class. This allows objects which are received from network to be modified on the fly at each level during unserializing (think of pickle's __getinitargs__, but called on each class in the MRO-tree, and not having __init__ called, but another function). It also does automatic type/data-checking on unserializing stored data. There are several other tidbits I've always wanted a serializer to have but never found one which did, so just look at the documentation to see all that Flatten can do. Flatten is stable in its current version, and has seen about three months of active usage as a network protocol helper library, so there shouldn't be any more bugs in it (okay, I think I've not had an attack on it yet, but anyway I screened the code for bugs more than once). Author: Heiko Wundram Name: Flatten Version: 0.1 URL: http://www.asta.uni-saarland.de/~heiko/flatten Requires: Python 2.3 (developed on Python 2.3b2+, but with some modifications should also run on earlier versions) On a personal note: I was previously hosting most of my projects on my own personal server, but as the university is restricting private use of its Internet connection more and more (even cutting off my internet connection for more than three weeks), I had to move all of them tho this host. This means that you will also find yawPyCrypto, my PyCrypto wrapper library, there. Heiko Wundram. From postmaster at bthub01.bt.com Sat Jul 5 10:56:13 2003 From: postmaster at bthub01.bt.com (postmaster at bthub01.bt.com) Date: Sat, 5 Jul 2003 15:56:13 +0100 Subject: Undeliverable: Re: Movie Message-ID: <5E982A0C1799274AAD22EE21DE6373DD0392D593@cbibipnt08.hc.bt.com> Your message To: N.Winton at axion.bt.co.uk Subject: Re: Movie Sent: Sat, 5 Jul 2003 15:59:01 +0100 did not reach the following recipient(s): N.Winton at axion.bt.co.uk on Sat, 5 Jul 2003 15:56:09 +0100 The recipient name is not recognized The MTS-ID of the original message is: c=gb;a=bt;p=bt;l=CBIBIPNT0803070514563GAHP1WW MSEXCH:IMS:EXCHANGE:BTHUB01:CBIBIPNT08 3550 (000B09B6) 550 5.1.1 ... User unknown -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Movie Date: Sat, 5 Jul 2003 15:59:01 +0100 Size: 1041 URL: From ianb at colorstudy.com Tue Jul 8 13:50:23 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 12:50:23 -0500 Subject: path module In-Reply-To: <20030708113219.H6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> Message-ID: <1057686623.3738.62.camel@lothlorien> On Tue, 2003-07-08 at 04:32, holger krekel wrote: > I agree that something like Jason Orendorff's path module should go into > the standard library. I've coded a similar module and i think that > a discussion about certain design decisions would probably improve our > approaches. > > For example Jason lets the "path" object inherit from "str" (or unicode) > but i think it's better to provide a "__str__" method so that you can say > > str(pathinstance).endswith('.py') > > and *not* base the path object on str/unicode. > > unicode(pathinstance) > > would just fail if your platform doesn't support this. First, i tried > the inheritance approach, btw, but it is ambigous (e.g. for the > join-method (str.join and os.path.join). I'm starting to think the same thing. Not so much because of join, but because it doesn't actually offer many advantages. Many methods that look for a filename will be using "type(arg) is type('')", so you'd have to pass a real string object in anyway -- and people who say "but you should use isinstance(arg, str)" are obviously forgetting that you couldn't do this not very long ago, and lots of code uses type comparison at this point. > Also, my module provides most of the os.path.* methods as "filters" so > you can say > > dirs = filter(isdir, list_obj_pathobjects) > fnames = filter(AND(nolink, isfile), list_obj_pathobjects) > > in addition to > > pathobject.isfile() > etc. That's not necessary with list comprehension, since you can just do: [p for p in list_obj_pathobjects if p.isdir()] > Recently, i also did some experimentation with "virtual-fs" features so > that you can transparently access http/ftp/svn files/directories. I even > got that to work with "-completion" but that was quite a hack :-) > > I am pretty sure that virtual-fs-like-extensibility would be a big > "selling" point and would motivate the use of such a module and > finally the inclusion into the stdlib. Of course, the local-fs should > be the convenient case but it shouldn't be hard to use the same methods > for accessing remote "repositories". Yes, virtual filesystems are certainly an important idea here. Almost makes me wonder if path() should also recognize URLs by default... probably not, as that isn't always desired, and a URL is going to create a significantly different object than a mere filesystem path, even though its interface will be very similar. Ian From jdhunter at ace.bsd.uchicago.edu Wed Jul 2 08:12:52 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 02 Jul 2003 07:12:52 -0500 Subject: My Big Dict. In-Reply-To: ("Russell Reagan"'s message of "Wed, 02 Jul 2003 08:04:26 GMT") References: <20030702073735.40293ba2.christophe.delord@free.fr> Message-ID: >>>>> "Russell" == Russell Reagan writes: drs> f = open('somefile.txt') drs> d = {} drs> l = f.readlines() drs> for i in l: drs> a,b = i.split('!') drs> d[a] = b.strip() I would make one minor modification of this. If the file were *really long*, you could run into troubles trying to hold it in memory. I find the following a little cleaner (with python 2.2), and doesn't require putting the whole file in memory. A file instance is an iterator (http://www.python.org/doc/2.2.1/whatsnew/node4.html) which will call readline as needed: d = {} for line in file('sometext.dat'): key,val = line.split('!') d[key] = val.strip() Or if you are not worried about putting it in memory, you can use list comprehensions for speed d = dict([ line.split('!') for line in file('somefile.text')]) Russell> I have just started learning Python, and I have never Russell> used dictionaries in Python, and despite the fact that Russell> you used mostly non-descriptive variable names, I can Russell> still read your code perfectly and know exactly what it Russell> does. I think I could use dictionaries now, just from Russell> looking at your code snippet. Python rules :-) Truly. JDH From news at yebu.de Fri Jul 18 06:49:54 2003 From: news at yebu.de (Karl Scalet) Date: Fri, 18 Jul 2003 12:49:54 +0200 Subject: "\n" in ASCII-file In-Reply-To: References: Message-ID: Martin P schrieb: > Hello, > > for a short exercise-program I have to read the lines in an ASCII-file. > > But every line has a new-line-feed ("\n") at the end of the line. (The > ASCII-file was made with Windows Notepad). > Is this only because I used Windows (and Notepad)? > > And... is there any special method to read lines from a file without "\n"? > > Bye, > Martin > > If the file isn't very huge, you could try: file('yourfile').read().splitlines() gives you a list of lines w/o '\n'. Karl From zephyr01 at alltel.net Wed Jul 9 11:09:36 2003 From: zephyr01 at alltel.net (Hans Nowak) Date: Wed, 09 Jul 2003 11:09:36 -0400 Subject: Newbie - No module named stdwin In-Reply-To: References: Message-ID: <3F0C3030.7030703@alltel.net> K wrote: > hello > > All time all write programm's in Visual Basic but now i'm very excited and > learn a Python so install 2.2.3 version... > > When i wanna open a window (like windows) i write > > inport stdwin > stdwin.open ('my window') > > and i have ImportError: No module named stdwin > > Did i must install some package?? please help me The stdwin package has been phased out long ago. There are other, better GUIs that can be used with Python. It comes with Tkinter, but it's easy to install a third-party package like wxPython (etc). From brian at sweetapp.com Thu Jul 31 13:17:09 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 31 Jul 2003 10:17:09 -0700 Subject: RELEASED Python 2.3 (final) In-Reply-To: Message-ID: <000501c35787$93219940$21795418@dell1700> > Seems nice enough. You'll only be able to assign to a mutable object > anyway; This statement doesn't make any sense. Assignment to None is a name binding operating is mutability is not a relevant issue. > None is not mutable, and will soon be a keyword. None becoming a keyword is a valid reason. Cheers, Brian From kp at kyborg.dk Fri Jul 11 04:24:23 2003 From: kp at kyborg.dk (Kim Petersen) Date: Fri, 11 Jul 2003 10:24:23 +0200 Subject: Memory leak ?? [resolved - thank you] In-Reply-To: References: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> Message-ID: <3f0e7438$0$13170$edfadb0f@dread15.news.tele.dk> A.M. Kuchling wrote: > On Thu, 10 Jul 2003 14:34:05 +0200, > Kim Petersen wrote: > >>Using python-2.2.2-26 on RH9 (shrike) x86 -fully patched >> >>The following program slowly eats up more and more memory when run on >>large datasets... can anyone tell what the trouble is? > > > Your code uses eval(), which is pretty heavyweight because it has to > tokenize, parse, and then evaluate the string. There have been a few memory > leaks in eval(), and perhaps you're running into one of them. Try using > int() or float() to convert strings to numbers instead of eval. As a bonus, > your program will be faster and much more secure (could an attacker tweak > your logfiles so you end up eval()ing os.unlink('/etc/passwd')?). Thank you very much - it was eval() this solved my trouble (calling get_list instead of eval) - is there a more generic/efficient way of solving reading a list/expression? (i know this one will fail for some strings for instance): def get_value(str): str=str.strip() if str.lower()=='none': return None elif str[0] in ['"',"'"]: return str[1:-1] else: if str[-1]=='j': return complex(str) elif '.' in str or 'e' in str: return float(str) else: return int(str) def get_list(str): try: if str[0]=='(': robj=tuple else: robj=list items=str.strip()[1:-1].split(', ') return robj(map(get_value,items)) except: traceback.print_exc() print str return [] -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From bogal2 at comcast.net Tue Jul 15 19:16:02 2003 From: bogal2 at comcast.net (BogAl) Date: Tue, 15 Jul 2003 18:16:02 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: > Setup.py needs to know what of several things you want to do (just build the > package, build and install the package, build a distribution, etc). Try > this command: > > python.exe C:\PYTHON22\LIB\SITE-P~1\CSV\SETUP.PY install > > That should do any necessary building and install all the files. > > Skip Thanks, Skip. I'm too used to just double-clicking things to run them and missed the part about supplying an argument. At least I've learned a couple of things and maybe improved my setup a bit in the process. BogAl From ad at am9atNOSPAMPLEASEspeedy.co.il Wed Jul 30 12:09:59 2003 From: ad at am9atNOSPAMPLEASEspeedy.co.il (Adam) Date: Wed, 30 Jul 2003 18:09:59 +0200 Subject: reading in lines from a file -FAST! In-Reply-To: References: Message-ID: Rajarshi Guha wrote: > Hi > I have a file containing 168092 lines (each line a single word) and when > I use > > for line in f: > s = s + line > > it takes for ages to read it all in - so long in fact that it makes the > program unusable. Is there any way to do something like C's fread in > Python so that I can just slurp in 1.7MB of data at one go, rather than > reading line by line? > > Thanks, > Rajarshi Assuming f is an open File Object, you can use: string = f.read() Which reads the entire content of f into string. Notice, though, that this solution isn't scalable: reading an entire file to memory becomes messier the larger the file, whereas reading it one line at a time works pretty much the same no matter how big the file is. Adam From jwhitlark at attbi.com Tue Jul 1 00:05:19 2003 From: jwhitlark at attbi.com (Jason Whitlark) Date: 30 Jun 2003 21:05:19 -0700 Subject: Exposing object model in Python? References: Message-ID: "Fredrik Lundh" wrote in message news:... > macrosource = getmacro(macroname) > code = compile(macrosource, macroname, "exec") > context = {} > # populate context with fun things > context["app"] = object_representing_my_app > exec code in context > > (add exception handling as necessary) > > Excellent, I was interested in that too. Ok, here's something similar I've struggled with... How do you provide a macro recorder? I have some idea how to just play back a sequence of actions, (just store signals in a list, then fire them in order), but how do you turn that back into python code, like in Word VB? From timr at probo.com Tue Jul 15 01:13:20 2003 From: timr at probo.com (Tim Roberts) Date: Mon, 14 Jul 2003 22:13:20 -0700 Subject: wxPython - question References: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> Message-ID: <4737hvob87b2699fvqkhl61i9ufqm1jnc4@4ax.com> "Artur M. Piwko" wrote: > >In the darkest hour on Sat, 12 Jul 2003 21:55:39 -0700, >Tim Roberts screamed: > >>>How can I remove program entry from taskbar (not tray)? >> >> PLEASE resist the temptation to built Yet Another Tray Application. Win32 >> programmers seem to use the tray icons as a sign of their guruness, and >> every one of them seems to think that his application is so studly that it >> must occupy permanent real estate on my desktop. I've seen some trays that >> bloat to 20 or 30 icons. >> >> Don't do it. Your application just isn't that important. If you need to >> notify me of something, I find nothing wrong with a good old-fashioned >> dialog box. > >I am writing Jabber/others messenger. In this case, tray icon is not a sign of >guruness, but user friendliness. I disagree. That is strictly a matter of opinion. Now, a tray icon that does not exist until some actionable event occurs is probably a very natural UI, but the same thing could be achieved by plopping up a dialog box. Even if I am running your messenger, yours is not the only application I'm running by a long shot. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sybrenUSE at YOURthirdtower.imagination.com Wed Jul 30 02:58:29 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 30 Jul 2003 06:58:29 GMT Subject: PyQt Help and Advice References: Message-ID: Keith Jones enlightened us with: > Any idea when Qt3.2 will have noncommercial support in windows? Probably when Qt 4.x has been released. If you want to stay current and free, try Linux instead. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From heikowu at ceosg.de Fri Jul 18 12:29:09 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 18 Jul 2003 18:29:09 +0200 Subject: reading Netscape mail folders In-Reply-To: <72F73B808A78D511A73600034771D9FF7185BE@dc_exchange2.howrey.com> References: <72F73B808A78D511A73600034771D9FF7185BE@dc_exchange2.howrey.com> Message-ID: <1058545749.593.8.camel@d168.stw.stud.uni-saarland.de> On Fri, 2003-07-18 at 16:47, PoulsenL at capanalysis.com wrote: > I am attempting to process a number of email files that were copied from > Netscape mail users. I am using the email module, but it doesn't seem to > adequately determine when an email is multipart. In several instances it > refuesed to parse a multi-gig text file as multiple emails. Has anyone > tackled this issue before with success? Just point in the right direction > and I can read on from there. If you're doing what I was doing back then (I changed all my user's mail-spool from Netscape Navigator 4.79 to IMAP by resending all mails to themselves), you might find the attached script interesting. Anyway, it shows how to open the mailbox, and how to iterate over the different messages that are in there. I've never had trouble using it with NS-Mail mbox Files. HTH! Heiko. -------------- next part -------------- A non-text attachment was scrubbed... Name: mailscript.py Type: text/x-python Size: 1098 bytes Desc: not available URL: From gml4410 at ggr.co.uk Thu Jul 3 16:15:33 2003 From: gml4410 at ggr.co.uk (Lack Mr G M) Date: Thu, 03 Jul 2003 16:15:33 BST Subject: Building Python - how to set include and lib paths? Message-ID: <2003Jul3.161533@ukwit01> I'm trying to build (compile and link) Python2.2.3, However, I need to indicate where it can find various library and header files for other extensions which I have already built (things like ssl etc.). How may I configure the Python build process to look in these directories, and to use these same values when building extension modules? All I can see is /usr/local/include and /usr/local/lib being forced into use (I need to remove those, as that is *not* where I put things and anything which is there might cause problems). Or is it impossible to configure Pyhton builds? [I also see it forcing /lib and /usr/lib into the library_dir searches, which doesn't really make sens on an IRIX system, where you should, by default, be looking in /lib32 and /usr/lib32.] I can't find anything in the README file about this, and the configure script doesn't mention any such features. Surely I'm not the only person in the world who doesn't want to/can't put this into /usr/local? -- --------- Gordon Lack --------------- gml4410 at ggr.co.uk ------------ This message *may* reflect my personal opinion. It is *not* intended to reflect those of my employer, or anyone else. From webmaster at beyond-thoughts.com Fri Jul 18 14:09:04 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 18 Jul 2003 20:09:04 +0200 Subject: dumping command-history in python interactive mode In-Reply-To: References: Message-ID: <3F1837C0.5050306@beyond-thoughts.com> Hello, thank You very much. I did not find this tutorial with Google. I often use python to do system administration on a remote machine so I can't use IDLE. ipython looks nice, too. I added one more feature to the startup-script: Pressing C-w will put some code into the python-commandline that dumps the history to stdout. So you can cut'n'paste code (is there a way to define additional functions for key-binding in readline -- not just macros). Unfortuantely it might cause trouble if "readline" was defined before. Yours sincerly, Christoph Becker-Freyseng -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: .pystartup URL: From ianb at colorstudy.com Wed Jul 9 11:38:04 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 09 Jul 2003 10:38:04 -0500 Subject: Image Streaming In-Reply-To: <381a2b17.0307090622.2e22a716@posting.google.com> References: <381a2b17.0307072326.211c21b5@posting.google.com> <381a2b17.0307090622.2e22a716@posting.google.com> Message-ID: <1057765083.3735.1002.camel@lothlorien> On Wed, 2003-07-09 at 09:22, Steffen Brodowski wrote: > > have that function return the image object. Then, assuming you are > > doing this in CGI (easily adapted if not), do something like (untested): > > > > import sys > > image = CreateBarCode(...) > > print 'Content-type: image/jpeg\n' > > image.save(sys.stdout, 'JPEG') > > > I think its more difficult. > > The function CreateBarcode has to return the image directly. > Additional you have to know, that I have to implement it into Zope. So > I use the script as an "external method". Modulname=Barcode, > functionname=CreateBarcode. > > I'm using the following line in Zope DTML > So then you don't want to stream it. You might do something like: from cStringIO import StringIO def CreateBarcode(...): # create image object output = StringIO() image.save(output, 'GIF') return output.getvalue() From peter at engcorp.com Wed Jul 9 05:52:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 05:52:24 -0400 Subject: Comparing python and Perl - Network + administration References: Message-ID: <3F0BE5D8.7F5C6BA1@engcorp.com> hamido wrote: > > I am very-very new in Pyton langguage > In my next project I will promote Python / Perl /Shell Programming Seems a little premature... ;-) > Is there any function or modules to make system administration ( like > shell-bash, Perl) ? Yes. Do you have a specific question? An example of what you are trying to accomplish? Python has many such facilities, including os.system and friends, the shutil module, and many more. Many people use it for sysadmin tasks, as some others use shell scripting and Perl of course. -Peter From news at exultants.org Fri Jul 4 19:10:33 2003 From: news at exultants.org (Van Gale) Date: Fri, 04 Jul 2003 23:10:33 GMT Subject: Apache mod_python and Sessions In-Reply-To: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> Message-ID: <3F0608CC.5030605@exultants.org> Markus Schaber wrote: > Hi, > > Does anybody know a module that works with Apache 1.3 mod_python and provides session tracking? Most of the python web programming frameworks have session handling. Here are a few: Quixote http://www.mems-exchange.org/software/quixote/doc/ Albatross http://www.object-craft.com.au/projects/albatross/ Webware http://webware.sourceforge.net/ Jonpy http://jonpy.sf.net Spyce http://spyce.sf.net JOTweb http://jotweb.tummy.com/ More information can be found at: http://www.python.org/cgi-bin/moinmoin/WebProgramming http://colorstudy.com/docs/shootout.html Here's an example of a module that does its own session handling using MySQL for storage: http://cvsview.tldp.org/index.cgi/LDP/lampadas/pylib/Sessions.py?rev=1.12&sortby=author&content-type=text/vnd.viewcvs-markup Van Gale From mis6 at pitt.edu Tue Jul 29 09:36:26 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 06:36:26 -0700 Subject: metaclasses References: Message-ID: <2259b0e2.0307290536.27e09be0@posting.google.com> Simon Burton wrote in message news:... > It seems this is a more general way to build classes than inheritance. > Is this a reasonable viewpoint? > > >>> > >>> def meth1(self): > ... print "i am meth1" > ... > >>> def meth2(self): > ... print "i am meth2" > ... > >>> Foo = type("Foo",(),{'meth':meth1}) # make a class > >>> foo = Foo() # make an instance > >>> foo.meth() # call a method > i am meth1 > >>> > > Simon. Yes, they are basically class factories. They interfer in the creation of classes in a somewhat magical way, and are inherited. See http://www-106.ibm.com/developerworks/library/l-pymeta.html for more (there is also a second, more advanced paper which should appear soon, we sent it more than a month ago!) Michele From timr at probo.com Sun Jul 13 00:57:29 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jul 2003 21:57:29 -0700 Subject: command prompt change dir References: Message-ID: <0kp1hvsbo0dlgu3200pg1rpk0nacfr2tlj@4ax.com> "Peter Vestergaard" wrote: > >Probably a simple question but I have not been able to find out how: >I want my python script to generate a path based on some simple lookups and >then change my path so that when the script exits my command prompt (from >which I launched the script) is standing at this path. The path already >exists. >I have tried chdir(path), system('cd '+path) and many others but none >changes my actual path. How many times do you need to do this? You can set the PATH environment variable and spawn off a new copy of cmd.exe, which will inherit your modified environment. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nospam at mega-nerd.com Sat Jul 19 23:25:15 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 20 Jul 2003 03:25:15 GMT Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: <9a410299.0307191620.7fe274ab@posting.google.com> Message-ID: <3F1A0B51.F69B258A@mega-nerd.com> klappnase wrote: > > Hi, > > I think there might be at least 24 bit wav-files, if you have a > soundcard that supports 24 bit, may be even more, for professional use > or so. Yep, both 24 bit PCM and 32 bit floating point encoded files are un common use in professional and semi-pro audio recording. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ Windows NT : An evolutionary dead end. From pythonguy at Hotpop.com Tue Jul 29 08:53:26 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 29 Jul 2003 05:53:26 -0700 Subject: Debugging Python ? References: <3c91a864.0307282013.2acb2d1f@posting.google.com> Message-ID: <84fc4588.0307290453.52671e11@posting.google.com> It would be nice if you could give a name to your email address, i.e if you are not that paranoid as it seems. ~Anand logistix at cathoderaymission.net (logistix at cathoderaymission.net) wrote in message news:<3c91a864.0307282013.2acb2d1f at posting.google.com>... > pedro.werneck at bol.com.br (Pedro Werneck) wrote in message news:... > > I use: > > > > if __debug__: print "bla, bla, bla..." > > > > And I was just wondering if it's legal to define a "print" function... > > isn't print a keyword ? > > Instead of defining "print" you can assign a custom class to > sys.stdout. Then all the print statements get automagically > redirected.: > > if __debug__: > class newStdout: > def write(self,string): > print string > else: > class newStdout: > def write(self,string): > pass > > import sys > sys.stdout = newStdout() From kp at kyborg.dk Thu Jul 10 10:24:00 2003 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 10 Jul 2003 16:24:00 +0200 Subject: mx odbc In-Reply-To: <3F0D6DC1.A7104D1C@hotmail.com> References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> <3F0D4728.45284530@hotmail.com> <3f0d5cfd$0$13154$edfadb0f@dread15.news.tele.dk> <3F0D6DC1.A7104D1C@hotmail.com> Message-ID: <3f0d7700$0$13156$edfadb0f@dread15.news.tele.dk> Alan Kennedy wrote: > Kim Petersen wrote: >>Regarding the free marked - i agree - against the other - what is it >>*exactly* that makes mxODBC a better quality product - noone has >>seemed to be able to tell (and yes - you do in the above claim that...). > > > Hmm, I'm not sure I get what you're trying to say here: what do you > mean by "noone has seemed to be able to tell"? If by that you mean > "what is it that makes mxODBC a better quality product", try the > following > > 1. Continually kept up to date with all versions of python > 2. Continually kept up to date with all versions of ODBC standards > 3. Continually maintained on a wide variety of platforms > 4. Optimal memory and time efficiency because it's mostly coded in C > 5. Etc, etc. > > If these aren't the kinds of things that make software "better > quality", then I have no idea what you mean. Those qualities are all general product qualities, and may or may not have effect for your development. [hmm - i'm having a hard time formulating this in english - sorry if it gets out mangled]. A thing like: the type conversion (to and from) the SQL backend is highly efficient - would be a quality in my eyes. In the world where i live, the platforms are fixed and tested for the software [eg. specific versions (Windows, Linux and SCO (urgh!))], memory and time efficiencies may have influence but generally don't (one of the reasons we use python btw. otherwise we'd stick with C/C++ or Delphi). If a customer upgrade's a system to something not recommended - well the trouble will come knocking on his wallet and be a welcome guest in ours. > >>essence of my argument - the pricing of this *little* (but >>essential) component drives the pricing of the end-product up >>a substantial amount - that imho is not corresponding to the >>usefulnes of the product.[and to use your argument from before - >>i need to find another product then]. > > > No, you're thinking about it all wrong. > > This little component, an ODBC driver, *does* correspond to the > "usefulness" (i.e. quality) of the product. Or more correctly, if > one is using a poor quality ODBC driver, then that contributes to > the "uselessness" of one's product. > Let me rephrase the part about why i find the pricing steep: 1 developer licence for Qt: 1550$ 1 developer licence for mxODBC: 1025$ from my point of view - there _should_ be a correspondance between problem-domain and pricing. > >>Can you mention even on spot where i complained against paying for >>software ? (hint: the amount - not that it has a price). > > > Kim Petersen wrote: > > >>I'm not arguing that thats not important - *but* paying 70$ pr. >>customer, is the equivalent of paying you for 1hr of support for >>each customer [not installation mind you], where our own >>licence/supportcost is already getting lower and lower... I find >>that _extremely_ steep > > > Fair enough, it was the amount you complained about, not that there > was a cost. But is $70 really such a high cost? What percentage of the > end-user cost of your product is required to pay for mxODBC? That certainly depends on the product - if we run our full economics package for the customer - it would be negligible. If we're talking about a small contactdatabase (or a minor statistics module to run on a single desktop) - it certainly is substantial. -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From jepler at unpythonic.net Wed Jul 2 11:41:52 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 2 Jul 2003 10:41:52 -0500 Subject: How to keep a Tkinter-Dialog on top of all other windows? In-Reply-To: <3f02d84a$0$43850$39cecf19@news.twtelecom.net> References: <4b66f6d2.0307020435.345ff4f1@posting.google.com> <3f02d84a$0$43850$39cecf19@news.twtelecom.net> Message-ID: <20030702154149.GA19446@unpythonic.net> my similar code here use HWND_TOPMOST. This is apparently different from HWND_TOP: HWND_TOP Places the window at the top of the Z order. HWND_TOPMOST Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated as far as I know, this code works right with only one call, not a call from a timer. Jeff From ccosse at asymptopia.com Mon Jul 28 23:59:51 2003 From: ccosse at asymptopia.com (Charlie Cosse) Date: 28 Jul 2003 20:59:51 -0700 Subject: Asymptopia BlackJack (written in Python) Message-ID: <58329000.0307281959.5bc16221@posting.google.com> Asymptopia BlackJack is written in Python and uses PyGame for multimedia. Version 1.2 contains both Windows and Linux install scripts. Asymptopia BlackJack is a full-featured casino-style blackjack game written in Python using PyGame for graphics. You play with up to 6 robots against the dealer. You can specify which player is you. It is dynamic, addictive, and you don't lose real money. Teaches kids to gamble (and count!) http://www.asymptopia.com From jkpangtang at yahoo.com Fri Jul 11 17:06:10 2003 From: jkpangtang at yahoo.com (JW) Date: 11 Jul 2003 14:06:10 -0700 Subject: Passing pointer to array from C to Python..and modifying same array in python? Message-ID: <3607e8e4.0307111306.16ab4c6a@posting.google.com> Hi, Below is a description of what I would like to do. Would someone tell me if it is possible and if so, how? I have an array (presumably 'large') that is mallocced in a C function and its values are initialized in that same function. I would like to pass just the pointer to the beginning of the array from this C function to a Pyton function. Then the python method can individually access and MODIFY individual members of the array. After the call to the python method, the C function will see any changes to the array. Can this be done? I know how to create a PyTuple_New and change each member of the C array into a PyObject, then add all thos PyObjects to the Tuple, before passing that PyTyple from C to Python, but this seems slow. Thanks in advance for your help. From andymac at bullseye.apana.org.au Wed Jul 9 07:20:00 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 9 Jul 2003 21:20:00 +1000 (EST) Subject: Shared vs static link performance hit --and Windows? In-Reply-To: References: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> Message-ID: <20030709205951.P86568@bullseye.apana.org.au> On Wed, 9 Jul 2003, Martin v. [iso-8859-15] L?wis wrote: > Andrew MacIntyre writes: > > > AFAIK, Windows & OS/2 don't really use the concept of PIC code for DLLs, > > as the DLLs get mapped into system address space rather than user address > > space, and all processes that access DLL code access the code at the same > > address. > > Wrong, atleast for Win32. In Win32, there is no "system address > space"; each process has its separate address space. Thanks for correcting my misconception; my Win32 development experience is limited and skewed away from developing DLLs, so I haven't paid close attention to the fine detail. The important distinction between Win32+OS/2 and Unix is that the dynamic linkage uses relocation fixup records to relocate Windows (& OS/2) DLLs, whereas the dynamic linkage on Unix does not support the relocation action for shared objects - hence the use of PIC on Unix. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From tjreedy at udel.edu Tue Jul 22 18:03:51 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2003 18:03:51 -0400 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> <2259b0e2.0307220744.156c95bf@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0307220744.156c95bf at posting.google.com... > I wanted to check the output of ifilter or imap; at the end I solved > my problem in another way, nevertheless I am surprised there is no > way to check for an empty iterator in current Python, it seems to be > a quite legitimate question, isn't it? As I understand, the iterator protocol was primarily designed to be the *minimum* necessary to work (behind the scene) in for item in iterable: statements, replacing and improving upon the getitem interface (kept only for use by old code and likely to disappear in 3.0 ). It works quite well for this designed purpose. In this context one usually does not even have a handle on the iterator and thereor no means of calling a precheck method. Iterators were secondarily intended for the equivalent iterator = iter(iterable) try: while 1: item = iterator.next() except StopIteration: pass Here the iterator is visibly bound, but the basic idea of 'process each item' is the same. In any case, it is the stark simplicity of the protocol that makes possible the current version of generators and the neat trick of transfering the function body to the .next method. One who wants to add more to the interface should, I think, expect to add code somewhere to make the added function come true. Terry J. Reedy From piet at cs.uu.nl Sat Jul 5 12:27:11 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 05 Jul 2003 18:27:11 +0200 Subject: Newbie: Tkinter and macPython References: Message-ID: >>>>> Piet van Oostrum (PvO) wrote: PvO> I guess you have downloaded a Python installation with proper Tkinter of course that should have been ... without ... -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From exarkun at intarweb.us Fri Jul 18 08:16:20 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 18 Jul 2003 08:16:20 -0400 Subject: python-xlib -- high-level interface? Message-ID: <20030718121620.GA11052@intarweb.us> Does anyone know of a high-level interface (something approximately on par with the level of the other common GUI toolkits) for python-xlib? Is anyone working on one? Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 From pedro.werneck at bol.com.br Mon Jul 14 14:50:32 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 14 Jul 2003 11:50:32 -0700 Subject: training for newbies References: Message-ID: > progress? i know that only way to develop is writing programs, but ... Reading and improving existing good programs is usually a better learning approach, in my opinion, because you will learn which mistakes other people done and avoid them... From bignose-hates-spam at and-zip-does-too.com.au Thu Jul 17 23:30:11 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 18 Jul 2003 13:20:11 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: On Fri, 18 Jul 2003 00:33:38 +0200, Martin v. Loewis wrote: > So what do you think about this message?: > ???????? I think it looks like a series of identical question marks. Presumably you wrote it using a character set my terminal isn't using, and you had no way of instructing my computer to use. Even if you could, it's folly to assume that my computer has a font containing the character set you used. The only characters you know are in my computer's fonts are the printable ASCII characters (ASCII 32-126). Anything else is a minefield of disparate character sets, font mappings and incomplete implementations. Beyond that, even if I could read your message, it's even greater folly to assume that I have some way of responding in kind, or of searching for those characters. I have no obvious way to generate them. I'm not sure what Alan Kennedy's point is, but the current state of play, while improving, does not allow for a universal way of generating, displaying and searching international character sets. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From aahz at pythoncraft.com Fri Jul 4 20:48:12 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Jul 2003 20:48:12 -0400 Subject: Google's netnews speed (was Re: pyBoards.com) References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F05C39D.3F65B89C@engcorp.com> <3F05FFFE.DB98BF44@engcorp.com> Message-ID: In article <3F05FFFE.DB98BF44 at engcorp.com>, Peter Hansen wrote: >Aahz wrote: >> In article <3F05C39D.3F65B89C at engcorp.com>, >> Peter Hansen wrote: >>> >>>Google Groups likely takes its feed directly of a Usenet site, and Usenet >>>in general suffers from large propagation delay. It is that delay, caused >>>by messages filtering slowly across the Usenet network, which leads to the >>>"5 answers" problem, not Google Groups itself. >> >> Actually, Google uses at least two or three feeds (including >> stanford.edu, which has a super-competent news admin), and Usenet >> propagation is actually little short of e-mail speeds these days, >> depending on where you're located. > >That might be, but empirically I've seen posts that I've made take >hours to get there, and I've seen posts that were made to the mailing >list (and copied to me directly) take hours to get there. In both >cases, there is an "upwards" propagation delay towards whatever hosts >Google is milking before stanford.edu or the others will see it... Peter, you're thinking less clearly than usual. ;-) My point was that the delay does *not* come from the time it takes to propagate to Google, but from the delay required to index and publish the index. Google's indexing technology is nothing short of amazing, but it is poor for realtime updating of the index. In the past, they have generally updated the index only twice per day -- and quite frankly, given *my* experience with full-text indexing (I used to work for Verity), I consider that to be *frequent* updating given how bloody fast Google's index is. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From anton at vredegoor.doge.nl Tue Jul 1 06:30:58 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 01 Jul 2003 12:30:58 +0200 Subject: does lack of type declarations make Python unsafe? References: Message-ID: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) wrote: >> Since int doesn't derive from object, this will probably >> fail: >> c.add(1) > > This is true, but it's completely unimportant. It's annoying at >times, but it's an optimization for efficiency; there are good reasons >why Java is several times faster than Python at most tasks. You can use >the primitive wrapper classes: >c.add( new Integer(1) ); Interesting, first define it as unimportant and next focus un Java's strong points. > On the rare occasions that I have to deal with a lot of Integer >objects, I use a cache of the most commonly-used ranges, but Java's >object creation is well-optimized these days, so there's no great harm >in just newing up an Integer. Weaken the use case and insist that it can be done with little extra trouble, if any remaining -unbelievably persistent- user still would think there's a need for it. > Retrieving the value is done by the ugly but standard idiom: >int n = ((Integer)it.next()).intValue(); Show how ugly it would be. > Or you can write your own int container class, if you need to do that >kind of operation frequently. I find that it rarely comes up, because >Java's normally used at a higher level. Associate it with uncommon low level activities. > Java's not *pretty*, but it's a powerful and expressive language. Expose the requested feature as a tradeoff with performance and expressiveness. Reading all this I get a very warped feeling of deja vu, because these kind of techniques are often used here to fend off "attacks" against Python. Maybe the "complete reversal" technique is new so I'll try it out: "does lack of type declarations make Python unsafe?" No it makes it safer, because being able to produce code that is easier to read improves the validity of the code. (Validity is defined here by "Does the program do what you think it does") Since languages using type declarations don't enable the coder to "fly by wire" and force her into all kinds of ugly code constructs, changes are the coder will get lost in the code labyrinth. Therefore for such languages extreme caution and large amounts of tests are unavoidable. Of course these efforts use valuable coder time that would be better employed in "algorithm space" instead of in "implementation space". Anton From jdhunter at ace.bsd.uchicago.edu Tue Jul 8 01:11:39 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 08 Jul 2003 00:11:39 -0500 Subject: getting a submatrix of all true In-Reply-To: (John Hunter's message of "Mon, 07 Jul 2003 17:47:31 -0500") References: <52fe159d.0307041016.4dcb4a5c@posting.google.com> Message-ID: >>>>> "John" == John Hunter writes: John>Using this approach, I was able to find a 893x67 submatrix John>with a score of 59831 versus the 462x81 submatrix with a John>score of 37422. Onwards and upwards.... Since this is beginning to look like a gradient descent algorithm, it is natural to worry about local minima. So I followed the lead of simulated annealing algorithms and added a little noise to the step where the decision to delete the row or column is made, eg, from MLab import randn def trim_missing(a, thresh=(0.05,0.05), sigma=0.005 ): ...snip... if fracRow-vthresh+sigma*randn() vthresh remove any cols where percent missing obs > othresh This is done iteratively rechecking the percent missing on each iteration or row or col removal, with the largest offender removed on each iteration return value is score, rowInd, colInd where the two ind arrays are the indices of the rows and cols that were kept """ othresh, vthresh = thresh # theshold for deletion dr=zeros(a.shape[0]) # Arrays to note deleted rows... dc=zeros(a.shape[1]) # ... and columns sizeleft=list(a.shape) # Remaining dimensions sr=sum(a,1) # Column scores = ij's to remove sc=sum(a,0) # Row scores while 1: # Keep deleting till none left mr=argmax(sr) # index highest row score mc=argmax(sc) # index highest column score fracRow = sr[mr]/sizeleft[1] fracCol = sc[mc]/sizeleft[0] if fracRow<=vthresh and fracCol<=othresh: break # stop when missing criteria are satisfied if fracRow-vthresh+sigma*randn()0.90,1,0) score0, goodRows, goodCols = trim_missing(a, thresh=(0,0), sigma=0) maxScore = 0, score0, len(goodRows), len(goodCols) print 'Deterministic:', score0, len(goodRows), len(goodCols) for sigma in arange(0.0001, 0.01, 0.001): for i in range(10): score, goodRows, goodCols = trim_missing( a, thresh=(0,0), sigma=sigma) if score>maxScore[1]: #print '\t', sigma, score, len(goodRows), len(goodCols) maxScore = sigma, score, len(goodRows), len(goodCols) print '\t', maxScore results.append((score0, maxScore[1], maxScore[1]/score0)) results = array(results) print mean(results) print std(results) From jepler at unpythonic.net Thu Jul 10 18:54:28 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 10 Jul 2003 17:54:28 -0500 Subject: Embedding Python, threading and scalability In-Reply-To: References: Message-ID: <20030710225424.GA13740@unpythonic.net> On Thu, Jul 10, 2003 at 03:54:14PM -0400, Aahz wrote: > Other people have mentioned Perl and Tcl in this thread. I wonder how > they deal with the problem of loading DLLs with static data. As far as I know, tcl enforces a one interpreter to one thread requirement. An extension should have only thread-local data, using a Tcl-supplied API. Jeff From nospamjynyl at yahoo.co.nz Tue Jul 29 04:22:27 2003 From: nospamjynyl at yahoo.co.nz (Peter) Date: Tue, 29 Jul 2003 20:22:27 +1200 Subject: default import path References: <3f24c37e@news.maxnet.co.nz> Message-ID: <3f262f6b@news.maxnet.co.nz> this quote is from GerritM of Tue, 29 Jul 2003 06:40 : > "Peter" schreef in bericht > news:3f24c37e at news.maxnet.co.nz... >> How can I edit the default import path for Python under Windows? >> >> > create a piddle.pth file in the main Python directory (c:\prog~1\python in > your case?), with the pathname of piddle as line of text in the file: > c:\prog~1\python\lib\site-packages\piddle > (check the last part, this is the directory on my machine) Thanks! I'll check it out next time I get to a machine running Windows. cheers Peter From gh at ghaering.de Fri Jul 18 07:59:08 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jul 2003 13:59:08 +0200 Subject: "\n" in ASCII-file In-Reply-To: <3F17D983.3000806@ghaering.de> References: <3F17D983.3000806@ghaering.de> Message-ID: <3F17E10C.7040209@ghaering.de> Gerhard H?ring wrote: > Most of the time, I want to strip any trailing whitespace and do > something like: > > f = file("/path/to/my/file") > for line in f: > line = line.strip() > # ... s/strip/rstrip/g -- Gerhard From shane at zope.com Fri Jul 25 21:00:00 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 25 Jul 2003 21:00:00 -0400 Subject: Static typing In-Reply-To: References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: <3F21D290.30403@zope.com> On 07/25/2003 07:36 PM, Neil Hodgson wrote: > Shane Hathaway: > > >>Well, here's a pattern I've been trying out for this purpose: use assert >>statements at the top of the function. >> >>def foo(bar, baz): >> assert isinstance(bar, int) >> assert isinstance(baz, str) > > > The Wing IDE will read assertions of the above form and provide more > assistance than with identifiers it knows nothing about: > http://wingide.com/psupport/wingide-1.1/node5.html#SECTION00580000000000000000 Excellent. It's nice to have an idea validated. :-) Shane From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 23 03:37:32 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 23 Jul 2003 17:27:32 +0950 Subject: [OT] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: On Wed, 23 Jul 2003 02:56:11 GMT, JanC wrote: > This might be interesting "news" for SCO/Caldera: ... but not for comp.lang.python. Please, don't give this stuff more publicity. -- \ "Remember men, we're fighting for this woman's honour; which is | `\ probably more than she ever did." -- Groucho Marx | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From pipen at beast_tu_kielce.pl Tue Jul 1 06:53:27 2003 From: pipen at beast_tu_kielce.pl (Artur M. Piwko) Date: Tue, 1 Jul 2003 10:53:27 +0000 (UTC) Subject: Partition names with Python References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: In the darkest hour on Tue, 1 Jul 2003 18:25:46 +1000, Andrew Bennetts screamed: >> You might want to try something like >> >> import os >> print os.popen('mount').read() > > Or simply reading /etc/mtab or perhaps /proc/mounts (this one is > linux-specific, I think), rather than spawning a process. > And /proc/partitions. Artur -- Before the Goat of Mendes... we all must take our turn | Artur M. Piwko Into the magic circle... where still the fire burns | mailto:s/_/./ We're spinning round and round... until one takes a fall | -- Mercyful Fate The fallen one will not return, the fallen one must burn | "Witches' Dance" From davidb at mcs.st-and.ac.uk Sun Jul 20 12:03:11 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 20 Jul 2003 09:03:11 -0700 Subject: Browser plugins References: Message-ID: <4de76ee2.0307200803.29c683a4@posting.google.com> "Aur?lien G?ron" wrote in message news:... > I'd like to write a simple portable browser plugin for Internet Explorer, > Netscape and if possible other navigators too. Is there a way to do that > using Python? For now I'd like to develop something like the GoogleBar, but > I'd also like to know how to develop "in-frame" plugins such as Flash or > Realplayer. This would be a cool thing to be able to do but, as you can see from your researches, if it was really easy then it would have been done already. > I searched comp.python.com history but all I came across was someone saying > "why would you want to write Browser Plugins in the first place?". A kind > of disguised "don't know" if you ask me. > I then looked on www.python.org but I soon found myself on ActiveX pages: I > would hate to go that way because it seems neither simple nor portable. There have been some discussions in the past about this. Searching Google Groups using "Netscape plugin group:comp.lang.python" manages to yield some results such as http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&threadm=mailman.1036701490.23212.python-list%40python.org&rnum=3&prev=/groups%3Fq%3DNetscape%2Bplugin%2Bgroup:comp.lang.python%26hl%3Den%26lr%3D%26ie%3DUTF-8%26safe%3Doff%26scoring%3Dd%26selm%3Dmailman.1036701490.23212.python-list%2540python.org%26rnum%3D3 but the further back in time one looks, the less relevant the references are. > Any ideas? Any links to documentation for browser plugins development? Any > code examples or open source project I could check out? I tried embedding Python in a simple wrapper library to use with Mozilla and Konqueror but found that it eventually came down to passing events through to the toolkit that you want to use for the plugin GUI. I didn't have any experience of this at the time so I abandoned the project. However, most of the simple stuff, like returning MIME types and plugin details was fairly straightforward. I've no idea how you'd go about writing Python plugins for Internet Explorer. If only it supported Netscape plugins... Good luck, anyway! David -- davidb at mcs.st-and.ac.uk is not my real address. From quadric at primenet.com Wed Jul 2 13:05:37 2003 From: quadric at primenet.com (quadric at primenet.com) Date: Wed, 02 Jul 2003 10:05:37 -0700 Subject: Running a Python script against an embedded mySQL server. Message-ID: <5.1.1.6.2.20030702095329.00a91238@pop3.norton.antivirus> Hi, I have an application that has an embedded/extended Python interpreter. I need to add database capabilities and for reasons to lengthy to explain in this email, also require an embedded database server. I have tentatively chosen mySQL 4.0 due to the apparent ease of embedding, along with it having all the necessary database functionality I need. The application executes Python expressions as well as running complete Python scripts via its embedded interpreter. The question is, using msSQLdb , can I connect external Python scripts that the application executes to the embedded mySQL server ? If so, are there any special considerations in doing this? Thanks for your help. From skip at pobox.com Mon Jul 14 14:45:48 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 14 Jul 2003 13:45:48 -0500 Subject: Any news on www.python.org being offline? In-Reply-To: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> Message-ID: <16146.64092.514393.134724@montanaro.dyndns.org> >> Website has been offline for more than an hour 11:18 PT. Known problem. We're working on it. Skip From rmunn at pobox.com Fri Jul 18 14:35:26 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 18 Jul 2003 18:35:26 GMT Subject: [OT] A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: (Restoring the [OT] marker in the subject because this is definitely off-topic for a Python newsgroup. Well, I guess it might have a bearing on Python's use of Unicode. Somehow. Remotely.) Martin v. Loewis wrote: > Alan Kennedy wrote: >> For anybody who has MS Internet Explorer 5+, Netscape 6+, Mozilla 1+, >> i.e. any browser that supports XML, simply save this to a disk file >> and open it in your chosen browser. > [...] > >> So, the challenge to the ASCII proponents is: put the greek word >> "gignooskoo" on everybody's screen, originating from a usenet message, >> in the original greek, where "oo" -> greek letter omega. > [...] >> I expect you won't find it as simple as the XML above, although I'm >> also completely prepared to be proven wrong (Alan tries to cover his >> a** in advance ;-). > > So what do you think about this message?: > > ???????? I see eight identical question marks. > > Look Ma, no markup. And not every character uses two bytes, either. > And I can use Umlauts (???) and Arabic (???.????) if I want to. I see an a-umlaut, o-umlaut, u-umlaut. But for the Arabic, I see three question marks, a period, and four question marks. Running slrn version 0.9.7.4 on Linux. My terminal is a PuTTY SSH connection from a Windows box. slrn --version produces: Slrn 0.9.7.4 [2002-03-13] S-Lang Library Version: 1.4.7 Compiled at: Jan 12 2003 08:31:04 Operating System: Linux COMPILE TIME OPTIONS: Backends: +nntp +slrnpull +spool External programs / libs: -inews -ssl -uudeview Features: +charset_mapping +decoding +emphasized_text +end_of_thread +fake_refs +gen_msgid -grouplens +mime -msgid_cache +piping +rnlock +slang +spoilers -strict_from +verbatim_marks DEFAULTS: Default server object: nntp Default posting mechanism: nntp Default character set: isolatin SUPPORTED CHARACTER SETS: isolatin ibm850 ibm852 ibm737 NeXT koi8 Looking at a hex dump of this post, I see that your Unicode characters have become ASCII question marks in my reply. Bad slrn! No biscuit! -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From peter at engcorp.com Fri Jul 4 18:28:28 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 18:28:28 -0400 Subject: RTS/CTS and DTR/DTS control References: Message-ID: <3F05FF8C.AB2AE2B@engcorp.com> Mike wrote: > > Is there a library in Python that will give me control over the > handshaking lines directly? What OS/platform? From christophe.delord at free.fr Wed Jul 2 01:37:35 2003 From: christophe.delord at free.fr (Christophe Delord) Date: Wed, 2 Jul 2003 07:37:35 +0200 Subject: My Big Dict. References: Message-ID: <20030702073735.40293ba2.christophe.delord@free.fr> Hello, On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote: > Greetings, > > (do excuse the possibly comical subject text) > > I need advice on how I can convert a text db into a dict. Here is an > example of what I need done. > > some example data lines in the text db goes as follows: > > CODE1!DATA1 DATA2, DATA3 > CODE2!DATA1, DATA2 DATA3 > > As you can see, the lines are dynamic and the data are not alike, they > change in permission values (but that's obvious in any similar > situation) > > Any idea on how I can convert 20,000+ lines of the above into the > following protocol for use in my code?: > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} > > I was thinking of using AWK or something to the similar liking but I > just wanted to check up with the list for any faster/sufficient hacks > in python to do such a task. If your data is in a string you can use a regular expression to parse each line, then the findall method returns a list of tuples containing the key and the value of each item. Finally the dict class can turn this list into a dict. For example: data_re = re.compile(r"^(\w+)!(.*)", re.MULTILINE) bigdict = dict(data_re.findall(data)) On my computer the second line take between 7 and 8 seconds to parse 100000 lines. Try this: ------------------------------ import re import time N = 100000 print "Initialisation..." data = "".join(["CODE%d!DATA%d_1, DATA%d_2, DATA%d_3\n"%(i,i,i,i) for i in range(N)]) data_re = re.compile(r"^(\w+)!(.*)", re.MULTILINE) print "Parsing..." start = time.time() bigdict = dict(data_re.findall(data)) stop = time.time() print "%s items parsed in %s seconds"%(len(bigdict), stop-start) ------------------------------ > > Thanks. > > -- Xavier. > > oderint dum mutuant > > > -- (o_ Christophe Delord __o //\ http://christophe.delord.free.fr/ _`\<,_ V_/_ mailto:christophe.delord at free.fr (_)/ (_) From upandrunning247 at hotmail.com Sat Jul 19 17:59:08 2003 From: upandrunning247 at hotmail.com (George Henry) Date: Sat, 19 Jul 2003 14:59:08 -0700 Subject: Strange (?) list comprehension behavior Message-ID: I am a Python newbie, using IDLE, writing a lexical analyzer for a small expression language in Python 2.2.3. class PSILex: ops = ["~", "!", "@", ... "|", "||", ... ] ... def __findAtom(self): result = "" ops = [op for op in PSILex.ops if self.text.startswith(op)] ... results in a traceback and "TypeError: expected a character buffer object." In trying to figure out what was going on, in the Python Shell I subsequently tried >>>[op for op in PSILex.ops if "|| hello".startswith(op)] with the same result. Printing type(self.text) immediately prior ot the above line proves that that attribute's type has not been compromised, so the problem appears to be with 'op'. >>>[op for op in PSILex.ops if op.startswith("|| hello")] yields "AttributeError: 'int' object has no attribute 'startswith'," however: >>>[type(op) for op in PSILex.ops] produces a list of objects, as would be expected. So, what is op? Is it a string, an int, or something else? It appears that the interpreter may be confused. I persuaded the interpreter to cooperate by injecting an explicit evaluation of type(op): ops = [op for op in PSILex.ops if type(op) == type("") and \ self.text.startswith(op)] and this does what I want, and what I would expect without 'type(op) == type("") and '. Can someone explain what is happening here? Or should I send my code to ww.python.org as a "defect report?" Regards, George _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From mis6 at pitt.edu Thu Jul 3 11:46:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 3 Jul 2003 08:46:10 -0700 Subject: 'For' loop symmetry with list comprehensions. References: <840592e1.0307021036.508d7d7d@posting.google.com> Message-ID: <2259b0e2.0307030746.37262b78@posting.google.com> hanzspam at yahoo.com.au (Hannu Kankaanp??) wrote in message news:<840592e1.0307021036.508d7d7d at posting.google.com>... > One can currently say this with list comprehensions: > > [x.lower() for x in words if x.startswith('foo')] > > Wouldn't it be better if the normal 'for' syntax was symmetrical > with the notation used in list comprehensions? To be more specific, > it lacks the 'if' part. I.e. this should be possible: > > for x in words if x.startswith('foo'): > print x > > Naturally this is the same as: > > for x in words: > if x.startswith('foo'): > print x > > So one only benefits from one level shorter tabulation in > some situations. I admit this isn't much of a benefit in terms > of making shorter programs, but it would make the language > more symmetrical, which I do consider a win. It's a feature > that wouldn't need any learning or remembering since it's already > used in list comprehensions. +1 Michele From wiebke.paetzold at mplusr.de Wed Jul 30 05:32:38 2003 From: wiebke.paetzold at mplusr.de (Wiebke Pätzold) Date: Wed, 30 Jul 2003 11:32:38 +0200 Subject: filter is Python Message-ID: Hi all! I have to work with MetaKit. My job is it to filter. For example: If I search for the initial letter "P", the programm should all results print with this characteristic. Couls somebody help me with this task? Wiebke From davidcfox at post.harvard.edu Wed Jul 30 16:38:11 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Wed, 30 Jul 2003 20:38:11 GMT Subject: Dict to "flat" list of (key,value) In-Reply-To: References: Message-ID: Nicolas Girard wrote: > Hi, > > Forgive me if the answer is trivial, but could you tell me how to achieve > the following: > > {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] > > The subtle point (at least to me) is to "flatten" values that are lists. Well, I can get you at least part way, but there is an ambiguity in your original data structure which causes problems: 1. d.items() will get you [(k1, [v1, v2]), (k2, v3), ...] 2. Now, you want to expand out the list elements where the second part of each tuple is a list, which you can do with. flatten = lambda u: map(lambda x: (u[0], x), u[1]) or, if the double lambda expression is confusing: def flatten(u): return map(lambda x: (u[0], x), u[1]) (I've used a tuple (u[0], x) instead of a list, because your [k1, vn] are always pairs, but you can use a list if you prefer) Then flatten will take the nested element (k1, [v1, v2]) and convert it to a list of tuples [(k1, v1), [k2, v2])] 3. You want to apply flatten to each element of d.items(), which you can do with lol = map(flatten, d.items()) which will give you a list of lists of tuples, 4. and then reduce that to a list of tuples with reduce(operator.add, lol) Unfortunately, this doesn't quite work with your example above, because flatten won't work properly when applied to (k2, v3). If v3 is a sequence, it will instead give you [(k2, v3[0]), (k2, v3[1]), ...], which is probably not what you want (especially if v3 is a string - try flatten manually and see what happens). If v3 is not a sequence, you'll get a TypeError saying that argument 2 to map() must support iteration. If you *know* that v3 will NEVER be a list, you can modify flatten to handle the special case like so: def flatten(u): if isinstance(u[1], type([])): return (u[1], [u[2]]) return map(lambda x: (u[0], x), u[1]) Alternatively, if you can modify how the initial dictionary is generated to ensure that cases where a key has a single value always appear as k2: [v3] instead of k2: v3, then you can use the steps above without modification. This is probably better if it is feasible, because your original data structure is inherently ambiguous unless you know that v3 will never be a list. David > > Thanks in advance, > Nicolas > > > > ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 15 18:28:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 16 Jul 2003 00:28:19 +0200 Subject: String Manipulation In-Reply-To: References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: <3f148002$0$49112$e4fe514c@news.xs4all.nl> John Hunter wrote: >>>>>>"lamar" == lamar air writes: > > > lamar> I need a piece of code that takes a string like this > lamar> string1 = "aaa/bbb/ccc/dd" and extracts a string > lamar> containting the character after the last "/" > > One good way to do this is to split the string on the '/' character, > which creates a list of strings > > >>> string1 = "aaa/bbb/ccc/dd" > >>> parts = string1.split('/') > >>> parts > ['aaa', 'bbb', 'ccc', 'dd'] > > Now you just want to get the last element of this list; python allows > you to index with -1 to get the last element, -2 to get the second to > last, etc... > > >>> parts[-1] > 'dd' > > JDH > While is is perfectly acceptable, you might want to consider another solution if it is *path names* you are manipulating: >>> import os >>> os.path.split("aaa/bbb/ccc/dd") ('aaa/bbb/ccc', 'dd') >>> os.path.split("aaa/bbb/ccc/dd")[1] 'dd' because this will work correctly on other platforms too when the path separator is not '/'. --Irmen de JOng From mcfletch at rogers.com Mon Jul 21 18:33:27 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 21 Jul 2003 18:33:27 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <7h3n0f8yspt.fsf@pc150.maths.bris.ac.uk> References: <7h3znjbzscu.fsf@pc150.maths.bris.ac.uk> <7h3n0f8yspt.fsf@pc150.maths.bris.ac.uk> Message-ID: <3F1C6A37.1070205@rogers.com> Michael Hudson wrote: >Michael Hudson writes: > > > >>"Mike C. Fletcher" writes: >> >> >> >>>So, does anyone have a pattern which allows setting an attribute on >>>a class which doesn't go through the setattr machinery (i.e. can be >>>used within a descriptor)? >>> >>> >>No. Fun problem to think about, though :-) >> >> > >Actually, that was a lie. Check this horror out: > >I'm quite proud of this one :-) > Rightly so, all evil geniuses should always gloat over their mad creations :) . Unfortunately, it appear to tickle a Python 2.2.3 bug where setting a descriptor on a meta-class doesn't reinstate capturing of the __get__ for the attribute. I filed a bug report for that here: https://sourceforge.net/tracker/index.php?func=detail&aid=775328&group_id=5470&atid=105470 Other than that, and it's intrinsicly *evil* nature, it does, indeed, do what I was looking for. BTW, you're creating a property whose *value* (albeit a static value) is shared by all instances of the meta-class, rather than one that's specific to the individual class. Here's code that, if the bug above weren't active would do the more "normal" per-instance property pattern (with the same evil mechanism): class MetaProp(object): def __init__(self, val): self.val = val def __get__(self, ob, cls=None): print 'metaprop get' for k in ob.__class__.__dict__: if ob.__class__.__dict__[k] is self: delattr(ob.__class__, k) break else: raise Exception, 'not found' newValue = ob.__dict__.get( k, self.val) + 1 setattr(ob, k, newValue) setattr(ob.__class__, k, self) return newValue class Meta(type): p = MetaProp(1) class C: __metaclass__ = Meta class D: __metaclass__ = Meta print C.__dict__.keys() print C.p print C.__dict__.keys() print C.p print C.p print D.p print D.p On Python 2.2.3 that prints out (showing the bug above): P:\temp>metaprop.py ['__dict__', '__weakref__', '__module__', '__metaclass__', '__doc__'] metaprop get 2 ['p', '__module__', '__metaclass__', '__dict__', '__weakref__', '__doc__'] 2 2 metaprop get 2 2 But really, I don't think either of us will deploy that particular pattern in a production system. Still, fun proposal, thanks for playing, we have lots of marvelous parting gifts for you :) . BTW: You know this, but in case others are wondering why it's not usable in real life: it's possible to have threads get/set the value without triggering the descriptor if they happen to ask for it during the period when the descriptor is deleted. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From timr at probo.com Tue Jul 15 02:46:05 2003 From: timr at probo.com (Tim Roberts) Date: Mon, 14 Jul 2003 23:46:05 -0700 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> <20030714172215452-0600@news.xmission.com> Message-ID: Stephen Horne wrote: > >Whatever. I've admitted the mistakes that I recognise I've made. If >you think there are other mistakes that I haven't recognised, its up >to you whether you explain them or not. > >Just 'cause I can't sleep the last few nights, doesn't mean anyone has >to read my rantings, much less reply. Even if they *are* accurate >rantings ;-) By the way, I would like to state for the record my amazement at how civil and intellectual this debate remained, even though there are some very strongly felt and completely contradictory opinions on both sides. It is quite rare that one finds a netnews newsgroup where this kind of debate can go on without collapsing into valueless flame wars. Whether or not I agree with you, you have made me think. That's worth the price of my Internet connection this month. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ebolonev at rol.ru Thu Jul 3 11:04:34 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 02:04:34 +1100 Subject: Reading an image file data......... References: Message-ID: Hello, Suresh! You wrote on 3 Jul 2003 13:49:41 -0000: SK> Hi, SK> I scanned a page of my textbook and stored as a JPEG file. Now SK> i want to read a text from the JPEG image which is at some SK> location, say from (100,100) to (300,300). How can i read it? I am SK> using PIL module for image handling and tkinter. Moreover i am new SK> to PIL module. Is it possible to read a text from a JPEG file in SK> python/tkinter? Do you know what the OCR is? [Sorry, skipped] With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From jepler at unpythonic.net Mon Jul 28 16:22:29 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 28 Jul 2003 15:22:29 -0500 Subject: How to stop screensaver from starting up In-Reply-To: <9a410299.0307280614.444cc2b2@posting.google.com> References: <9a410299.0307280614.444cc2b2@posting.google.com> Message-ID: <20030728202229.GD14508@unpythonic.net> On Mon, Jul 28, 2003 at 07:14:44AM -0700, klappnase wrote: > Hello everyone, > > does anyone know a way to stop the screensaver under linux from > starting up while a certain process is running? > I need this because I experience a memory leak while recording > wav-files every time the screensaver starts. > It is a Tkinter application, btw. > Any help would be very appreciated. For systems using xscreensaver, see xscreensaver-command(1). You could use xscreensaver-command -throttle to force screen blanking (not screensaver) when the system is idle or xscreensaver-command -exit to force the screensaver process to exit. In the former case, you would use xscreensaver-command -unthrottle to restart the screensaver, and in the latter case xscreensaver -nosplash in the latter. This is not robust if multiple processes all try to manipulate the screensaver without some additional kind of locking. Jeff From intentionally at blank.co.uk Wed Jul 16 19:09:13 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 17 Jul 2003 00:09:13 +0100 Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> <20030716160013839-0600@news.xmission.com> Message-ID: On Wed, 16 Jul 2003 22:00:22 +0000 (UTC), Adam Ruth wrote: >In <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed at 4ax.com> Stephen Horne wrote: >> On Wed, 16 Jul 2003 19:06:40 +0000 (UTC), Adam Ruth >> wrote: >> >>>You are correct in that there are times when pointer semantics would >>>be somewhat useful, but they're never necessary. His statement was >>>that there are time that "you really can't avoid pointers". >> >> Hmmm - those words were in a context. I never claimed that "you really >> can't avoid pointers" in *current* Python - that's obviously not true. >> But if the copy-on-write stuff were implemented, the need would arise. >> For example... > >It sure seemed that way to me: > > >>>They're an unhappy necessity, akin to stop-lights. You need them >>>because roads intersect, but if roads don't intersect, don't use them! >> >>Absolutely true. And the worst thing you can do when you really can't >>avoid pointers is to obscure the issue even more by disguising them as >>something else. > Right - "the worst thing you can do when you really can't avoid pointers" is not the same as "really can't avoid pointers". You have taken the condition out of a conditional scentence and quoted it as if it were a statement. That's a pretty clear case of quoting out of context to misrepresent what someone said, isn't it. Now lets restore the rest of what Adam said... : I came to Python from Ada, and all I have to say is: Pointer-like : semantics are evil. They're worse than goto's, they're deadly, : damaging, and should be avoided at all costs. : : They're an unhappy necessity, akin to stop-lights. You need them : because roads intersect, but if roads don't intersect, don't use them! Guess what - when Adam said pointers are an 'unhappy necessity' he was talking about ADA - NOT PYTHON. In Ada, pointers (or rather access types) are definitely not overused (where I worked you needed management permission and a damned good reason to use them due to the military contract terms), but sometimes they are unavoidable. Please be more careful what you snip. >The reference is passed by value >to the function, just as you describe it should. Yes - there has to be pass-by-value at some level since Python is implemented in C. But to me this just says that we are seeing the side-effect of an implementation detail. No need to argue this - you don't need to explain it to me because I understand. It just see things from a different perspective. Python, however, has a >futher layer of abstraction on top of its one data type, and that's >objects. I would venture that it's the extra layer of abstraction that >makes Python work in a more intuitive, proper way. > >This is, however, just my opinion. But it does seem that new >programmers who learn this abstraction find it natural and simple. It's >people coming from C, et al., that seem thrown off by it. No, my background isn't just in C - that is a long way from being the first language I used, and I've used Python regularly longer than C++. >As a side note, based on your description of your eduction and studies >in an earlier post, I realize now how different our backgrounds seem to >be. I'm coming from a world where the focus is engineering (Ada is the >only language purpose-built for engineering, AFAIK). You seem to come >from a background more focused on science and theory. Nope - I just happen to be interested in learning the theory too, and particularly in experiencing a broad range of languages to understand the ideas behind them. How come you didn't notice ada in my list? About the first half of my programming career was working in the defence industry as a software engineer. A lot of that was working at very low level stuff (the 80c196kc microcontrollers I mentioned) and with a lot of messing around with target hardware and in-circuit emulators. The rest of my time in defence was spent using Ada. I first messed around with writing my own language quite young, with an Atari ST. I liked the idea of text adventures and decided to write one, but basically got caught up in the engine and the scripting stuff. Pretty cool, though, through the rose-tinted glasses of memory. Anyway, I stayed interested in compilers and stuff, but the reason I got interested in LR and parsing theory has little to do with parsing as most see it. A grammar, seen as describing a sequence of tokens, can deal with many things - the tokens don't have to be words. They might be events, for instance. And the state of the 'parser' may be used to select a response strategy in an AI. I wanted it for a game I was going to write a few years back which would construct strategies from various elements by building them into a kind of grammar, and use the resulting state model as a real time AI. >Perhaps this is >the cause of our different world views (on this issue). Just a thought, >though it is interesting we both chose Python. Strictly speaking, the reason I chose Python at the time was because at work we used macs with terminal emulators. If you wanted a utility, you either wrote it under VMS or you were stuffed as mac interpreters and compilers were hard to come by. I see it as one of the happiest flukes - I just wish I'd found Python earlier. From Robert at AbilitySys.com Mon Jul 14 20:46:21 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Mon, 14 Jul 2003 17:46:21 -0700 Subject: Stop Python from exiting upon error in Windows Message-ID: Environment: Windows XP, Python 2.2.2 How can I stop the Python interpreter from exiting when an error occurs? When I use IDLE (right click a .py file and choose Edit with IDLE) I can run the app and read the errors in the interpreter window. But when I just double-click on the .py file, it runs OK but the window closes at exit (how to stop that? but not a problem if everything works), but also closes the window after an error - way too fast for me to see what the error actually was. I can Try/Except anything I can think of, but there are always errors I didn't think of, and I'd like to see them, please... :) - Robert From mwh at python.net Thu Jul 17 09:27:52 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 17 Jul 2003 13:27:52 GMT Subject: Replacing rexec References: <87adbd73f1.fsf@pobox.com> Message-ID: <7h3znjd1e8m.fsf@pc150.maths.bris.ac.uk> jjl at pobox.com (John J. Lee) writes: > Isn't it true that the only solution to a program taking up too much > of a system's resources is to cap its resource usage, or stop it > running? Usually, it's the OSs job to do that (which you might view > as almost the definition of an OS, perhaps) -- is that a bad thing? I wouldn't say so, and in some circumstances you can use the OS to limit the other sorts of damage a rogue script can do (chroot(), jail(), whatever). If I had to worry about these sorts of things (which I don't), this would probably be the first place I'd look. 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 peter at engcorp.com Mon Jul 7 11:53:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 11:53:53 -0400 Subject: Socket Win32 IO References: <99071af2.0307070647.6ab3e329@posting.google.com> Message-ID: <3F099791.6AA68B8F@engcorp.com> jose maria wrote: > > Hi all I?m a newbie in python Im try to modify in win32 IOTCL of file > handle socket to set parameter 0x98000001 but i have error > (api_error:(1, 'DeviceIoControl', 'Incorrect function.')) > and I dont know how continue. > the porpuse of this code its to make a simple sniffer > > fh=Sock.fileno() # Get file handle > test=win32file.DeviceIoControl(fh,SIO_RCVALL,'',0) # Failed > .... > .... Is that ("incorrect function") really the error you are getting? Can you post the actual traceback, if it's not? I get either of these when playing with DeviceIoControl, but not what you showed: >>> win32file.DeviceIoControl(3, 0x98000001, '', 0) Traceback (most recent call last): File "", line 1, in ? pywintypes.api_error: (6, 'DeviceIoControl', 'The handle is invalid.') >>> from socket import * >>> s = socket(AF_INET, SOCK_STREAM) >>> s.fileno() 32 >>> win32file.DeviceIoControl(32, 0x98000001, '', 0) Traceback (most recent call last): File "", line 1, in ? pywintypes.api_error: (87, 'DeviceIoControl', 'The parameter is incorrect.') -Peter From cliechti at gmx.net Tue Jul 29 14:13:30 2003 From: cliechti at gmx.net (Chris Liechti) Date: 29 Jul 2003 20:13:30 +0200 Subject: Python on a USB storage device? References: Message-ID: Sybren Stuvel wrote in news:slrnbid6a7.7na.sybrenUSE at sybren.thirdtower.com: > You can also install Linux on a USB storage device and hope the > computer it has to run on supports booting from USB ;-) > >> It would work on Linux too except you need to have permission to >> create mount tables etc. to get the filesystem. > > Running your own Linux off the USB stick solves that problem. Knoppix (http://www.knopper.net/knoppix/) is a bootable Linux CD. that way you dont have to rely on anything on the PC except some RAM and a BIOS that can boot from CDROM. you can keep your own files on a USB stick, a floppy or the same CD. there are even Knoppix derrivates for the small (8cm) CDs and for USB sticks. ok, enough advertising for other things ;-) chris -- Chris From adfgvx at free.fr Thu Jul 31 16:23:53 2003 From: adfgvx at free.fr (adfgvx) Date: Thu, 31 Jul 2003 22:23:53 +0200 Subject: HTML DOM parser? References: <7x7k5y5wfh.fsf_-_@ruckus.brouhaha.com> Message-ID: <3f297adb$0$19537$626a54ce@news.free.fr> Try tidy. There are two python wrappers : mxtidy and utidy, the latest is more recent and use the new tidylib. BUT it will only correct a bad html page and transform it to an xml or xhtml output that you load after as a DOM with another parser. Personnaly I use pyRXP. Bruno Lienard "Paul Rubin" a ?crit dans le message de news: 7x7k5y5wfh.fsf_-_ at ruckus.brouhaha.com... > Is there an HTML DOM parser available for Python? Preferably one that > does a reasonable job with the crappy HTML out there on real web > pages, that doesn't get upset about unterminated tables and stuff like > that. Many extra points if it understands Javascript. Application is > a screen scraping web robot. Thanks. From thedustbustr at aol.com Fri Jul 25 15:28:44 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 25 Jul 2003 19:28:44 GMT Subject: stackless python: continuation module? Message-ID: <20030725152844.18704.00000635@mb-m18.aol.com> I just downloaded the uthread module for stackless python. Whenever I import it it says it can't find the continuation module. Anyone know where I can get it? Thanks, Dustin From adechert at earthlink.net Mon Jul 21 13:44:11 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 17:44:11 GMT Subject: Voting Project Needs Python People Message-ID: We've decided to go with Python for the demo of the voting machine I described on this forum yesterday. Thanks to all of you for your feedback. We have an excellent team together. We're looking for a few good Python coders willing to volunteer for this free open source project. It will be on sourceforge.net later today. I can't offer you any money right now but I think it will be a good opportunity for Python users and the Python community in general. It's likely to be fairly high-profile and will gain significant exposure for Python. Here are some of the people involved: University of California Santa Cruz computer science graduate, Adrianne Yu Wang will be the project administrator and lead the project. http://home.earthlink.net/~adechert/adrianne_resume.doc She will get help from Jack Walther, a UCSC graduate student and big Python fan. http://www.cse.ucsc.edu/~jdw/ They will be advised by computer science professors Doug Jones (U of Iowa) and Arthur Keller (UCSC) http://www.cs.uiowa.edu/~jones/ http://www.soe.ucsc.edu/~ark/ Ed Cherlin will also act in a mainly advisory role but will assist with the design of the project and documentation. http://home.earthlink.net/~adechert/cherlin_resume.doc We anticipate that a successful demo will help expedite funding for the overall project which is aimed at implementing a uniform transparent voting system. We have very prominent academics interested in the project from many of the top universities around the country: Political scientists, lawyers, economists, computer scientists, and psychologists. Stanford computer scientist David Dill has been helpful (he referred Ed Cherlin and Prof Keller to me, among others). Professor Dill has gotten involved in voting modernization issues in a big way. http://www.verifiedvoting.org/index.asp Henry Brady was my co-author for the original UC Berkeley proposal for California. http://home.earthlink.net/~adechert/src_proposal.html Professor Brady is widely known for his papers and books on voting systems. The main author of the Caltech-MIT reports from their voting project, Steve Ansolabehere was one of Henry's students when Henry taught at Harvard. Henry has two Ph.D.s from MIT. http://www.apsanet.org/new/2003chairs.cfm We are pulling together a great voting modernization projects. It's an opportunity to get in on it at an early stage. It should be rewarding for you, your community, and democracy. Please contact me if you want to join us. -- Alan Dechert 916-791-0456 adechert at earthlink.net From ianb at colorstudy.com Sun Jul 27 15:05:02 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 27 Jul 2003 14:05:02 -0500 Subject: Web tool kit : pro - cons ? In-Reply-To: <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> <3f23b02b$0$276$ba620e4c@reader1.news.skynet.be> Message-ID: <1059332701.24476.14709.camel@lothlorien> On Sun, 2003-07-27 at 05:58, vincent_delft wrote: > >> - My pages will be defined with "boxes". I would like to have a tool > >> that can manage easely such "object". > > > > You mean a WYSIWYG web development IDE for Python? I don't think there's > > such a thing. > > > No. Each part of the web page will be "boxes". I would like to be very > flexible and display "dynamically" some selected boxes. > For example the same page (url) will not display the same boxes if you are > administrator, maintener or simple viewer. > An another example will be to have possibility to re-use existing boxes. If > I have a boxes displaying the last 5 news from Slashdot, I don't want to > re-write it each time I need a new bacground color (for example). My Idea > is to use those "boxes" like we use classes : if you need some modification > you subclass it on the rest remains the same. You might want to look at Cheetah, where templates are mapped to Python classes. This allows subclassing of templates, defining methods (e.g., a header method), and of course nesting templates. Ian From essai1 at mci.local Tue Jul 1 08:35:36 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Tue, 1 Jul 2003 14:35:36 +0200 Subject: Want to create an ActiveX object from a Python class References: <34ac6a99.0306300955.4202abb5@posting.google.com> Message-ID: Bonjour ! Peut-?tre en cr?ant un serveur COM, puis en encapsulant celui-ci avec un peu de code, dans VBCCE (=Visual Basic Control Creation Edition, gratuit, chez Microsoft, pour faire des Active-X). C'?tait juste une id?e. Hi ! (sorry for my poor english) Perhaps with : to do an COM server, and use it, in little code, in VBCCE (=Visual Basic Control Creation Edition ; free, at Microsoft, for create Active-X). Just an idea. Url : http://msdn.microsoft.com/vbasic/downloads/tools/cce/default.aspx @-salutations -- Michel Claveau From bgailer at alum.rpi.edu Sat Jul 12 17:06:54 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 12 Jul 2003 15:06:54 -0600 Subject: Newbie with sort text file question In-Reply-To: <86d2ca4.0307121146.3deb854a@posting.google.com> Message-ID: <5.2.1.1.0.20030712141633.02a45568@66.28.54.253> At 12:46 PM 7/12/2003 -0700, stuartc wrote: >Hi: > >I'm not a total newbie, but I'm pretty green. I need to sort a text >file and then get a total for the number of occurances for a part of >the string. Hopefully, this will explain it better: > >Here's the text file: > >banana_c \\yellow >apple_a \\green >orange_b \\yellow >banana_d \\green >orange_a \\orange >apple_w \\yellow >banana_e \\green >orange_x \\yellow >orange_y \\orange > >I would like two output files: > >1) Sorted like this, by the fruit name (the name before the dash) > >apple_a \\green >apple_w \\yellow >banana_c \\yellow >banana_d \\green >banana_e \\green >orange_a \\orange >orange_b \\yellow >orange_x \\yellow >orange_y \\orange > >2) Then summarized like this, ordered with the highest occurances >first: > >orange occurs 4 >banana occurs 3 >apple occurs 2 > >Total occurances is 9 I am developing a Python version of IBM's CMS Pipelines, which is designed for this kind of task. If you'd like to be an early recipient (read beta tester) of this product, let me know. You would invoke this program: Pipe(""" < c:\input.txt | split /_/ | nlocate -//- | sort count | spec 11-* 1 / occurs / 11 1-10 19 | > c:\output1.txt | count | spec /Total occurrences is / 1 1-* 21 | > c:\output2.txt""") Explanation: | == separates each stage of the pipe < == read records from file split == split each record into 2 records at first _ nlocate == select records that do not contain // pad 10 == ensure each record has 10 characters (or whatever the longest fruit name is) sort count == sort; group by unique key and prepend count spec ... == select cols 11-end of input, append literal, append cols 1-10 > == write records to file spec ... == start with literal, append rest of record > == write records to file Or it can be run as a DOS Command: C>python pipe.py spec.txt where spec.txt contains the pipe specification An enhancement to the IBM Pipeline specification for SPLIT will be to route the 2nd part of each record to the secondary output, effectively discarding it in this example, and eliminating the need for the NLOCATE stage. This particular task can also be done fairly easily in Python. The appeal of Pipe is that you focus on the specification rather than writing Python code that is specific to the task. This shortens development time, and enhances readability and maintainability. The Python version: input = file('c:\input.txt') fruits = {} # a dictionary to hold each fruit and its count lines = input.readlines() for line in lines: fruit = line.split('_', 1)[0] if fruit in fruits: fruits[fruit] += 1 # increment count else: fruits[fruit] = 1 # add to dictionary with count of 1 output1 = file('c:\output1.txt', 'w') for key, value in fruits.items(): output1.write("%s occurs %s\n" % (key, value)) output1.close() output2 = file('c:\output2.txt', 'w') output2.write("Total occurrences is %s\n" % len(lines)) output2.close() Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From ilya at cray.glas.net Tue Jul 15 02:41:44 2003 From: ilya at cray.glas.net (Ilya Etingof) Date: Tue, 15 Jul 2003 06:41:44 +0000 (UTC) Subject: pySNMP: SNMPget example References: <538fc8e.0307100356.4bf46554@posting.google.com> <538fc8e.0307140736.19eb777@posting.google.com> Message-ID: I'd suggest you to refer to "high-level" API documentation at http://pysnmp.sourceforge.net/docs/3.x/ for getting used to basic operations on SNMP objects (such as apiGetPdu(), apiSetVarBind()). Also, note, that pysnmp s/w (the third branch) has been closely aligned with the APIs introduced by SNMP RFCs, so reading these RFCs may be helpful too. If you got more specific questions, please, let me know. -ilya WIWA wrote: > Thanks Ilya, > This has been very helpful. I'm able to get data out of my 'device > under test'. > I must be honnest and say that I understand the sample code, but could > not write or produce it myself. > How do you know e.g that > req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) can be > written? I've read through the documentation and could not find > anything similar. Of course, I could overlook it. > Isn't there a tutorial out there that summarizes pysnmpv3 and gives > examples of snmpget, snmpset, snmpwalk, etc... > Thanks in advance for helping me out. > Regards, > Wim > Ilya Etingof wrote in message news:... >> > 2) when using: 'from pysnmp import role' (found on >> > http://pysnmp.sourceforge >> > .net/examples/2.x/snmpget.html), I get the message 'ImportError: >> >> You seems to use pysnmp 2.x API which differs from the latest 3.x branch >> (though, a compatibility layer exists in 3.x distribution). That's why >> I suggest you looking at the 3.x docs and examples at: >> >> http://pysnmp.sourceforge.net/docs/3.x/index.html >> >> > 3) A general question: how can I get a list of what I can type after >> > the 'from >> > pysnmp import ...' >> >> dir() may help but in this case I'd better see an example. >> >> > 4) How can I use: 'from snmpget import snmpget'. It does not accept >> > this. >> >> There is no such module as snmpget in pysnmp. >> >> > 5) Anyone has a simple example for the following application: I have a >> > cable >> > modem (which has an SNMP agent inside). I want to make a script where >> > I can >> > do SNMPgets (and later SNMPSet and SNMPwalk). >> >> Python 1.5.2 (#3, Aug 25 1999, 19:14:24) [GCC 2.8.1] on sunos5 >> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >> >>> from pysnmp.proto import v1 >> >>> from pysnmp.proto.api import generic >> >>> from pysnmp.mapping.udp import role >> >>> req = v1.GetRequest() >> >>> req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) >> >>> tr = role.manager(('router-1.glas.net', 161)) >> >>> (answer, src) = tr.send_and_receive(req.encode()) >> >>> rsp = v1.GetResponse() >> >>> rsp.decode(answer) >> >>> vars = rsp.apiGetPdu().apiGetVarBind() >> >>> print vars >> [('.1.3.6.1.2.1.1.1.0', OctetString('Cisco Internetwork Operating System >> Software\015\012IOS (tm) 5400 Software(C5400-JS-M), Version 12.2(11.8b), >> MAINTENANCE INTERIM SOFTWARE\015\012 Copyright (c) 1986-2002 by cisco >> Systems, Inc.\015\012 Compiled Tue 30-Jul-02 19:02 by pwade'))] >> >>> >> >> > 7) What is the difference between snmpget and getrequest in pysnmp? >> >> The only difference is the SNMP request object (GetRequest vs GetNextRequest) >> you create when building SNMP message. >> >> -ilya From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 20:26:12 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Aug 2003 10:16:12 +0950 Subject: How do I get a reference to a KEY value of a dictionary? References: <645db655.0307311636.71923378@posting.google.com> Message-ID: On 31 Jul 2003 17:36:41 -0700, Andy C wrote: > Is this a waste of time? Because I know in python I cannot be certain > that the argument strings that are read from files are even garbage > collected anyway. I could certainly do the job with duplicate > strings, but it would seem wasteful. I am a C programmer, and old > habits die hard. Python dynamically binds names ("variables") to objects; many types, including immutable strings, will not be duplicated if an identical one is already stored. The upshot is: store an identical string as many times as you like, because PYthon will simply keep references to the one string object for each duplicate. -- \ "Friendship is born at that moment when one person says to | `\ another, 'What! You too? I thought I was the only one!'" -- | _o__) C.S. Lewis | Ben Finney From guettler at thomas-guettler.de Wed Jul 23 10:56:08 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Wed, 23 Jul 2003 16:56:08 +0200 Subject: The global statement References: Message-ID: David Hitillambeau wrote: > Hi guys, > As I am new to Python, i was wondering how to declare and use global > variables. Suppose i have the following structure in the same module (same > file): > > def foo: > > > def bar: > > > > I want to enable some sharing between the two functions (foo and bar) > using one global variable in such a way that each function can have read > and write access over it. Hi David, global BAD BAD=1 def foo(): global BAD print BAD def bar(): global BAD print BAD foo() bar() If foo and bar are in the same file, you don't need the "global". thomas From mwh at python.net Fri Jul 18 07:42:13 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jul 2003 11:42:13 GMT Subject: dumping command-history in python interactive mode References: Message-ID: <7h3d6g81319.fsf@pc150.maths.bris.ac.uk> Christoph Becker-Freyseng writes: > Hello, > > is there a way to dump (and save) the command-history of the python > interactive mode. Yes. Does http://www.python.org/doc/current/tut/node13.html help? Cheers, M. -- 42. You can measure a programmer's perspective by noting his attitude on the continuing vitality of FORTRAN. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From andrew-pythonlist at puzzling.org Tue Jul 1 04:25:46 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 1 Jul 2003 18:25:46 +1000 Subject: Partition names with Python In-Reply-To: References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: <20030701082545.GA18721@frobozz> On Tue, Jul 01, 2003 at 02:45:15AM +0000, Bengt Richter wrote: > > You might want to try something like > > import os > print os.popen('mount').read() Or simply reading /etc/mtab or perhaps /proc/mounts (this one is linux-specific, I think), rather than spawning a process. -Andrew. From chatralias at aol.com Sun Jul 20 11:09:41 2003 From: chatralias at aol.com (Chatralias) Date: 20 Jul 2003 15:09:41 GMT Subject: Stopping a loop with user input. in curses References: Message-ID: <20030720110941.09823.00000321@mb-m11.aol.com> Hi Alex, The only curses that I know are the ones that I use when I have a problem like the one your facing here, but I think I can help. Looks like your not stopping the first while loop when user hits the 'q' key, your just doing curses.beep() (I assume this makes a sound?). Seams to me that you can put all of your active (for want of a better word) code into one while loop so that it is all stoped when the "q" key it hit. Or add a call to the first while loop from the second while loop so that it stops. Because the first while loop is running ever since "theClock()" is called and it never even see the 'q' get pressed. I mean that the code execution never gets to the second while loop. Try this... cus I can't with out curses installed. ...clip.. #! /usr/bin/python # Import curses module import curses, time def main(): finished = 0 # which is like saying "not finished" -see while loop stdscr = curses.initscr() # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() while not finished: # so long as finished is 0 this will loop # If 'q' is pressed, exit c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) if __name__ == '__main__': curses.wrapper(main) ....end clip... As you can see I've made a lot of changes. Let me see if I can explain. First I put every thing into one function main. This assumes that you are not using the "theClock()" function somewhere else, so if you are then don't do this. But, the point is, that if you look at the first variable I defined in the "main()" function - "finished = 0" - then look at the while loop,- "while not finished:"- when the user types 'q', the finished variable is set set to 1 and every thing stops. Hope it works because I don't have a way to test it. Ray Rastm2 at aol.com From menion at asylumwear.com Thu Jul 10 14:24:33 2003 From: menion at asylumwear.com (Joshua Schmidlkofer) Date: 10 Jul 2003 11:24:33 -0700 Subject: Python vs PHP In-Reply-To: References: <3F0D2827.4070501@mxm.dk> <3F0D3E8A.3080204@mxm.dk> Message-ID: <1057861472.12360.1.camel@bubbles.imr-net.com> > You are probably right. I only given a casual look at PHP, so > I can't comment on the language, but I believe you :-). However, > PHP does come with a default (and only) web framework. This > obviously makes it easy to get started than to experiment with > Spyce or CherryPy or Cheetah or WebWare or any of the twenty > different alternatives. > > Looking at it from the perspective of a PHP developer who's > looking into Python as an alternative. Python doesn't provides > her an out of the box solution yet. Think about what the > bewildering list of choices mean to her. This is not only issue > for development but also for deployment. > yeah, well right some nice looping code in PHP. Like loop over 30 or 40 rows in a database, format and display it. Then write it in python. vast difference. OTOH I really don't use PHP anymore, and I don't know if they cleaned up the more recent versions. js From paul_rudin at scientia.com Tue Jul 22 04:48:04 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 22 Jul 2003 09:48:04 +0100 Subject: good python book References: <3f1cbbda_6@news.athenanews.com> <3f1cdce3.516224491@news.blueyonder.co.uk> Message-ID: >>>>> "Alan" == Alan Gauld writes: > On 22 Jul 2003 00:21:46 -0400, anonymous at coolgroups.com wrote: >> i'm looking to start learning python. could someone recommend >> a good beginner's book for me? > Depends. Are you new to programming or just new to the Python > language? > If the latter you should just use the official tutor that comes > with Python and save your money for one of the more advanced > books and/or references. And "Text processing in python", which would be good for experienced programmers new to python, is available online at , although no doubt the author would be keen for people to buy copies as well... From mjackson at alumni.caltech.edu Wed Jul 16 09:35:32 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 16 Jul 2003 13:35:32 GMT Subject: Python Quiz References: Message-ID: Michael Chermside writes: > richardc writes: > > Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's > > fixed format syntax. I can only think of Python and FORTRAN off the top of > > my head which use whitespace as part of the syntax. > > Definitely NOT. Without addressing the question of HOW Python came by the > idea of using indentation to indicate block structure, it clearly couldn't > have been from Fortran, because what Python does and what Fortran does > are COMPLETELY different. > > In Fortran, starting lines in particular columns is meaningful (as are other > particular characters in particular leading columns). In Python, particular > columns have NO meaning. > Of course, I'm not suggesting that whitespace is *meaningless* in Python > outside of indentation... Python is much like C (and many, many others) in > that regard. After all, in C "y=x+ ++z" and "y=x++ +z" are quite > different things. And in both Python and C "x=abc" is legal, but "x=a bc" > is not. Note that Fortran (at least historic Fortran - not sure about those upstart 9x variants) is *not* among the "many, many others." One can write any of DO 10 I = something DO10I = something D O 1 0 I = something and leave it to the compiler to figure out whether you're starting a DO-loop or assigning a value to the variable DO10I. [Signature from February 1993.] -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Consistently separating words by spaces became a general custom about the tenth century A.D., and lasted until about 1957, when FORTRAN abandoned the practice. - Sun FORTRAN Reference Manual From alanmk at hotmail.com Fri Jul 4 11:37:45 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 04 Jul 2003 16:37:45 +0100 Subject: CGI script is in plain text References: <3F04B0A4.32692.3596CD0@localhost> <3F0590DB.8EE8D7CF@hotmail.com> Message-ID: <3F059F49.BCEACC4F@hotmail.com> BMA TRADING wrote: >>>> When I start CGI script from a web browser, the result is >>>> plain text( the copy of that script) ^^^^^^^^^^^^^^^^^^^^^^^ D'oh! Missed that vitally important piece of the sentence. Sorry for having to follow-up my own post. Obviously, you're script is not being executed. The best way to debug a CGI installation is to place the "cgi.py" script itself in your own CGI directory. "cgi.py" is designed to be used for exactly this purpose, and will render a HTML page with valuable information about your python installation and web server environment. More importantly, "cgi.py" is a script that is *known* to work. Recommended steps: A. Find the installed location of the python on your system B. Copy "cgi.py" from the Lib directory of that installation C. Put it into your cgi-bin, or equivalent, directory. D. Make sure the path on the shebang line matches the path of A. E. Check that the necessary execute bits are set. F: Try this URL http://yourdomain.com/cgi-bin/cgi.py or equivalent. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From peter at engcorp.com Mon Jul 14 15:23:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 15:23:57 -0400 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> <3F0E136A.6222F201@engcorp.com> <2621b014.0307140819.6ec99736@posting.google.com> Message-ID: <3F13034D.19A4C65@engcorp.com> Jon Schull wrote: > > Well, for what its worth, I was thinking about "sniffing, spoofing, or > main-in-the-middle attacks", and I was hoping for something I could > stick into a program for unsophisticated users (e.g, those to whom one > might give a notepad-like application, albeit with a local webserver > interface). > > Everyone who connects to the internet should have a firewall BUT must > all who import httpserver implement or insist on a firewall for all > their users? Realistically? I don't want to think so. Yes, provided they are running code that is not considered inherently safe and provided they have sockets that are listening on all interfaces as opposed to those which bind solely to localhost/127.0.0.1, then I believe they *should* have a firewall. Doing anything else is playing with fire, and a bad habit to get into as well. If this is merely a "local webserver interface", then it should bind to localhost only. If it is intended for local use on a network, and therefore must bind to an external interface, then it's perfectly safe, provided there is no connection to the Internet on that network, or there is a firewall on any such connection. End of story. (Said as black and white to encourage discussion, not necessarily because I truly believe that...) -Peter From vm_usenet at yahoo.com Sat Jul 5 12:56:35 2003 From: vm_usenet at yahoo.com (vm_usenet) Date: 5 Jul 2003 09:56:35 -0700 Subject: A possible bug in python threading/time module? References: Message-ID: "Tim Peters" wrote in message news:... > [Tim] > > Turns out that the Windows implementation of the Python C API function > > PyThread_start_new_thread() contained several "laziness" errors > > > > ... > > > > I'm testing putative fixes on a Win98 box and don't see any hangs any > > more. However, with more than about 3000 threads, > > > > thread.error: can't start new thread > > > > gets raised because MS's _beginthread() fails (with errno == EAGAIN == > > "there are too many threads"). > > FYI, these fixes have been checked in and will be part of 2.3 final (and > 2.2.4, if that's ever released). > > The maximum number of threads you can have alive simultaneously on 32-bit > Windows in an all-default Python build is actually about 2000. This is > because each thread gets a megabyte of stack space by default, and 2048 > threads would entirely exhaust the 31-bit user virtual address space just > for thread stacks. If you want to know more about that, Google on > > CreateThread default stack size > > The top hit is to the current relevant MSDN docs. I'm sorry that this comes immediately after my recent post, and that, of all places, I am forced to put it here. Right after I read Tim's recent post, I went to the python CVS and noted that Tim refered to me as an 'anonymous coward'. Well Tim, I just wanted to say that I appreciate you being part of the community, too. I hope to see more mature people working on the Python project than Tim. vm From duncan at NOSPAMrcp.co.uk Wed Jul 2 04:44:41 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 2 Jul 2003 08:44:41 +0000 (UTC) Subject: function overloading References: Message-ID: "Simon Burton" wrote in news:pan.2003.07.01.19.42.06.202399 at webone.com.au: > class Im: > def __init__(self,x,xx=None): > if xx is not None: > w,h = x,xx > im = Image.new("I",(w,h)) > elif type(x)==str: > filename = x > im = Image.open(filename) > else: > im = x > self.im = im I would probably do it like this: class Im(object): def __init__(self,im): self.im = im def newFromFile(cls, fileName): im = Image.open(filename) return cls(im) newFromFile = classmethod(newFromFile) def newBlank(cls, width=640, height=480): im = Image.new("I",(width,height)) return cls(im) newBlank = classmethod(newBlank) Overloading is a bad idea, explicit is better than implicit. Using class methods as alternate constructors lets you have meaningful parameter names, defaults for each variant (if you want them), and docstrings (here left as an exercise for the reader). -- 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 unendliche at hanmail.net Thu Jul 31 03:18:05 2003 From: unendliche at hanmail.net (Seo Sanghyeon) Date: 31 Jul 2003 00:18:05 -0700 Subject: How to get Windows physical RAM using python? References: Message-ID: <45e6545c.0307302318.451b4ed6@posting.google.com> Mark wrote: > OK, How to check the amount of Windows physical RAM using python? Martin v. Lowis wrote: > You should call the GlobalMemoryStatus(Ex) function. To my knowledge, > there is no Python wrapper for it, yet, so you would need to write one. So let's write one in Python in a minute! ---- winmem.py from ctypes import * from ctypes.wintypes import * class MEMORYSTATUS(Structure): _fields_ = [ ('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('dwTotalPhys', DWORD), ('dwAvailPhys', DWORD), ('dwTotalPageFile', DWORD), ('dwAvailPageFile', DWORD), ('dwTotalVirtual', DWORD), ('dwAvailVirtual', DWORD), ] def winmem(): x = MEMORYSTATUS() windll.kernel32.GlobalMemoryStatus(byref(x)) return x ---- in your code >>> from winmem import winmem >>> m = winmem() >>> print '%d MB physical RAM left.' % (m.dwAvailPhys/1024**2) 90 MB physical RAM left. >>> Hail to ctypes! If you have never heard of ctypes, visit http://starship.python.net/crew/theller/ctypes/ and try it. You will love it. Seo Sanghyeon From danbmil99 at yahoo.com Wed Jul 23 05:12:28 2003 From: danbmil99 at yahoo.com (dan) Date: 23 Jul 2003 02:12:28 -0700 Subject: python assignment References: Message-ID: "Tim Peters" wrote in message news:... >... It would be very > unusual (because bad design) for the __iadd__ method of a mutable type to > return a pre-existing object, though. hmm... >>> a = [1, 2] >>> id(a) 8316112 >>> a += [3] >>> id(a) 8316112 see my prev. post on this. I realize my original assumptions were off base, but frankly the documentation does a poor job (really no job) of describing the state of affairs wrt how Python handles objects, and how this affects what happens when you assign things. A section on names and binding principles would be much appreciated. dbm From kylotan at hotmail.com Tue Jul 8 06:33:53 2003 From: kylotan at hotmail.com (Kylotan) Date: 8 Jul 2003 03:33:53 -0700 Subject: urllib2 for HTTPS/SSL Message-ID: <153fa67.0307080233.2f7abdf5@posting.google.com> The documentation on this module doesn't seem very clear to me... there's an 'HTTPSHandler' object documented, but it just lists the "https_open" function without giving an example of its use. And the urllib2 examples page shows a totally different way to create an HTTPS connection (just by making a Request object). There is a lot of talk about deriving new classes, but is that necessary if I just want to make HTTPS GET requests? I have no idea how (or if) to use the 'HTTPSHandler' object, or what the correct way for me to request an SSL connection is. Does anybody have any hints? And additionally, is there any chance of the official documentation on this useful-looking module being improved? K. From zephyr01 at alltel.net Thu Jul 31 11:44:18 2003 From: zephyr01 at alltel.net (Hans Nowak) Date: Thu, 31 Jul 2003 11:44:18 -0400 Subject: SQL2000 database vs python In-Reply-To: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> References: <55939F05720D954E9602518B77F6127F02F46920@FTWMLVEM01.e2k.ad.ge.com> Message-ID: <3F293952.8020307@alltel.net> Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Ok I was too happy. > > mssqldb doesn't help me to connect my python app on a linux OS to a sql2000 (windows os) database. > I can't even compile the package, I guess it is missing sybase stuff (sybdb.h and sybfront.h), > which is correct because I don't have that database. > Also, mssqldb supports ms sql server 7.0, my hope is that that won't be a problem in using ms sql 2000. > > Pfew, there goes my hope. If anything else fails, you can use SQLXML. I don't have a link handy, but it should be easy to find on Google. What you do is the following: 1. Install SQLXML on Windows machine (if it isn't there already) 2. From Linux, talk to database using XML "updategrams" over HTTP. For example, you can insert a record like this: Not pretty, but it works. You can also issue SQL statements using an URL. Caveats: Creating updategrams is not extremely easy, and you'll probably want to write some custom Python routines to execute SQL, create an updategram, send it, interpret data you get back (this is XML as well), etc. HTH, From gmuller at worldonline.nl Mon Jul 21 13:37:51 2003 From: gmuller at worldonline.nl (GerritM) Date: Mon, 21 Jul 2003 19:37:51 +0200 Subject: Can't Close Word Instance without Save Changes Dlg Box References: Message-ID: schreef in bericht news:mailman.1058804373.21700.python-list at python.org... > I am using COM to manipulate word attachments to emails. Once I use them I > am not concerned with saving the results. I use the following line: > > myWord.ActiveDocument.Close(wc.wdDoNotSaveChanges) > > This closes the document fine but only after I click no on the resulting > "Save Changes" dialog box. Am I missing something really simple? I can > send preceding lines if needed. > > Thanks in advance, > > Loren Poulsen > I have never tried this in Word. However I had the same kind of problem in Visio, which could be solved by setting the document status to saved, something like: myWord.ActiveDocument.saved = 1 regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From Robert at AbilitySys.com Tue Jul 15 18:03:35 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Tue, 15 Jul 2003 15:03:35 -0700 Subject: Stop Python from exiting upon error in Windows References: <3F136BEA.5B56562@engcorp.com> <3F142B51.94C898BC@engcorp.com> Message-ID: The trouble there is that sys.argv[0] is consistently the file name of the script running, whether I do it with python.exe or via IDLE/Run Script. (I actually use it to open the script within itself and copy itself out to an audit log for a record of what code created the script's results) You're right, it's probably not worth it since it just adds a "press enter" to the output when I run my script in IDLE (where I don't actually need the pause). I just thought the cognoscenti out here might have run across a nifty trick for determining if it was python.exe/PythonWin/whatever since I couldn't find such a thing in the books or manuals I have... - Robert "Peter Hansen" wrote in message news:3F142B51.94C898BC at engcorp.com... > Robert at AbilitySys.com wrote: > > > > Ok, I figured out the IDLE block indent (duh - RTFMenu), and now it works > > great in DOS. Again, thanks to all who helped. > > > > However, I'd still like to know how to determine what environment I'm > > running under inside my code. Any suggestions? > > I doubt if there's any particular way to do it consistently. In > principle one could write a cute module which would be able to check > the "signature" of the environment to figure it all out. Check if > certain modules are in __builtins__ to see if you are running inside > an application that uses Python for scripting, check for sys.argv[0] > to learn whether you were launched in a way that suggests running as > a script with python.exe, etc. > > It's probably not a great idea to write anything which depends on this > however, and it sounds like more time than it's worth. > > -Peter From CousinStanley at hotmail.com Wed Jul 30 03:36:34 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 30 Jul 2003 00:36:34 -0700 Subject: graph libraries References: Message-ID: Andrew .... The Java classes provided with the Chemistry Development Kit if interfaced with a bit of Jython might be useful ... http://cdk.sourceforge.net/ -- Cousin Stanley Human Being Phoenix, Arizona From brent.turner at clarisay.com Tue Jul 29 12:28:20 2003 From: brent.turner at clarisay.com (Brent Turner) Date: 29 Jul 2003 09:28:20 -0700 Subject: gridcontrols and list of lists Message-ID: <2f6cf792.0307290828.38d663b4@posting.google.com> It seems that in my code I am often using a grid concept (rectangular list of lists). To access columns of data I am transposing the "grid" and then indexing/deleting/adding rows(which used to be columns) and then transposing the results back. It seems to me that with the abundance of grid controls in applications (and the fact that databases return recordsets/datasets) that many people are doing the same or similar sort of thing. I am wondering if there is a gridData that someone has designed which is fast and has the functionality of a grid control. I want the speed and ease of use of a grid control, but non-gui. Is there anything that anyone has already designed that attempts to do some of these things? If not, then maybe this is something I should attempt... Also, I know Numeric can create arrays of PyObjects, but I am looking for a data_structure where rows or columns can be searched/deleted/added easily. Brent From gh at ghaering.de Thu Jul 24 04:18:53 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 24 Jul 2003 10:18:53 +0200 Subject: How to link a C extension module on Mac OS X? In-Reply-To: References: Message-ID: <3F1F966D.2010305@ghaering.de> Greg Ewing (using news.cis.dfn.de) wrote: > Gerhard H?ring wrote: > >> Two words: Use distutils. > > And it turns out that, rather unintuitively, the way distutils > does it is that it *doesn't* try to create a dynamic library, > just an ordinary object file named with a .so suffix... Does that mean that distutils doesn't work on OS X? -- Gerhard From alanmk at hotmail.com Thu Jul 3 08:23:33 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 03 Jul 2003 13:23:33 +0100 Subject: XML Validation with Python References: Message-ID: <3F042045.C5CB0248@hotmail.com> Will Stuyvesant wrote: > Can you give a commandline example how to do XML Validation (checking > against a DTD) with Python? Not with 4Suite or other 3rd party > libraries, just the Python standard distribution. You can't do it. The base distribution doesn't include a validating XML parser. The only pure python validating parser is Lars Garshol's "xmlproc", which is a part of pyxml (a "third-party" optional extension). You can read the documentation for xmlproc here http://www.garshol.priv.no/download/software/xmlproc/ and the bit about validating on the command line is here http://www.garshol.priv.no/download/software/xmlproc/cmdline.html Is there any reason why it has to be in the base distribution? Assuming that you have a good reason, maybe you can tell us what platform you're running on? There might be a platform specific parser/validator that you can call from python. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From guettler at thomas-guettler.de Tue Jul 15 08:00:45 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 15 Jul 2003 14:00:45 +0200 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: Allison Bailey wrote: > Hi Folks, > > I'm a brand new Python programmer, so please point me in the right > direction if this is not the best forum for this question.... > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. Hi! You can save the spreadsheet in XML format. This can be parsed and modified. This has the advantage that it works on all plattforms. I wrote a small receipe in the python cookbook some months ago. thomas From martin at v.loewis.de Mon Jul 21 01:32:20 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 21 Jul 2003 07:32:20 +0200 Subject: xml processing and sys.setdefaultencoding (more info) References: Message-ID: "christof hoeke" writes: > the original problem with the app was that the Pyana transformation > complained about the string "xml" when it came over as unicode. so i used > str(xml) but that gave the usual "ordinal not in range" error when the xslt > contained e.g. german umlauts. At that point, you should have done xml = xml.encode("utf-8") where you might need to make sure that the string "utf-8" matches the encoding= given in the xml header. > i did not tried that before... setting the default encoding to > utf-8 fixed that. the reason is not entirely clear to me yet though. For any Unicode object X, str(X) is equivalent to X.encode(sys.getdefaultencoding()). Since that defaults to "ascii", str(X) is normally the same as X.encode("ascii"), which fails if you have non-ASCII in your string. > it is my first "bigger" python project, so the code is not the best > i guess and the version which does not work is still online. i need > to put on the version with the changed default encoding. I advise that you get rid of the need to set the default encoding. Many users will have set this to a value different from "utf-8". Regards, Martin From pyth at devel.trillke.net Sun Jul 6 17:58:48 2003 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 6 Jul 2003 23:58:48 +0200 Subject: absolute beginners question about API documentation In-Reply-To: ; from jocsch@phreaker.net on Sun, Jul 06, 2003 at 07:44:13PM +0200 References: Message-ID: <20030706235848.G6906@prim.han.de> Markus Joschko wrote: > Hi all, > I' new to python programming but a longtime java programmer. > Is there an API documentation like the javadoc API from java? Python has this nice interactive command line (others already showed how to get to "method names" and such). As you seem to be using linux you may want to try the "rlcompleter2.py" module which provides bash-like completion on arbitrary python objects ... http://codespeak.net/rlcompleter2 ... this would give you ... >>> {}. * get*(1-2) iteritems*() keys*() update*(1) clear*() has_key*(1) iterkeys*() popitem*() values*() copy*() items*() itervalues*() setdefault*(1-2) and hitting it another time >>> {}. clear*() -> None. Remove all items from D. copy*() -> a shallow copy of D get*(1-2) -> D[k] if D.has_key(k), else d. d defaults to None. has_key*(1) -> 1 if D has a key k, else 0 items*() -> list of D's (key, value) pairs, as 2-tuples iteritems*() -> an iterator over the (key, value) items of D iterkeys*() -> an iterator over the keys of D itervalues*() -> an iterator over the values of D keys*() -> list of D's keys popitem*() -> (k, v), remove and return some (key, value) pair as a. 2-tuple; but raise KeyError if D is empty setdefault*(1-2) -> D.get(k,d), also set D[k]=d if not D.has_key(k) update*(1) -> None. Update D from E: for k in E.keys(): D[k] = E[k] values*() -> list of D's values and going to a specific function >>> {}.get( ------------------------------------------------------------------------------ D.get(k[,d]) -> D[k] if D.has_key(k), else d. d defaults to None. and so on. cheers, holger From FBatista at uniFON.com.ar Fri Jul 4 17:49:25 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 4 Jul 2003 18:49:25 -0300 Subject: print attitude Message-ID: One detail I found, don't now if it's ok: Python 2.1.1 (#4, Mar 8 2002, 12:32:24) [GCC 2.95.3 20010315 (release)] on sunos5 >>> a = '?' >>> a '\xf1' >>> print a ? >>> l = ['?'] >>> l ['\xf1'] >>> print l ['\xf1'] >>> Is this OK? Why this different behaviour? Thank you! . Facundo From sismex01 at hebmex.com Thu Jul 31 13:21:36 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 31 Jul 2003 12:21:36 -0500 Subject: RELEASED Python 2.3 (final) Message-ID: > From: Brian Quinlan [mailto:brian at sweetapp.com] > Sent: Jueves, 31 de Julio de 2003 12:17 p.m. > > > Seems nice enough. You'll only be able to assign to a > > mutable object anyway; > > This statement doesn't make any sense. Assignment to None is a name > binding operating is mutability is not a relevant issue. > > > None is not mutable, and will soon be a keyword. > > None becoming a keyword is a valid reason. > > Cheers, > Brian > Nope; it has to do with making Python faster: if constants such as None, True, False are treated as true constants, then certain optimizations can be enabled with help make it all a bit quicker. So, in order to do so, assignment to builtins is being disallowed; or, only to such singleton instances... I'm not too sure anymore. Anyway, there's a thread in comp.lang.dev about all this. HTH -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From sdfrost at ucsd.edu Wed Jul 23 17:55:23 2003 From: sdfrost at ucsd.edu (Simon Frost) Date: Wed, 23 Jul 2003 14:55:23 -0700 Subject: PyIStream and COM question for WinGraphViz Message-ID: <5.1.0.14.0.20030723145029.028039f0@popmail.ucsd.edu> Dear Python List, I'd like to write a COM interface to WinGraphViz (http://home.so-net.net.tw/oodtsen/wingraphviz/). I would like to dump my image to a PyIStream, but I can't find any documentation on how to do this. Here's the syntax for the COM interface ProgramID: WinGraphviz.BinaryImage Dump(IStream stream) as Boolean I would like to do something like istream=PyIStream(...) myBinaryImage.Dump(istream) and then go on to display the image. Any help would be greatly appreciated. Best Simon Simon D.W. Frost, M.A., D.Phil. Department of Pathology University of California, San Diego Antiviral Research Center 150 W. Washington St., Suite 100 San Diego, CA 92103 USA Tel: +1 619 543 8080 x275 Fax: +1 619 298 0177 Email: sdfrost at ucsd.edu The information transmitted in this e-mail is intended only for the person(s) or entity to which it is addressed and may contain CONFIDENTIAL and/or privileged material. Any review, re-transmission, dissemination or other use of or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this e-mail in error, please contact the sender and delete/destroy the material/information from any computer. From harry.g.george at boeing.com Mon Jul 21 17:32:59 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 21 Jul 2003 21:32:59 GMT Subject: Voting Project Needs Python People References: Message-ID: "Andrew Dalke" writes: > Harry George: > > Is the intent to do opensource all the way to commodity chips? Else a > > proprietary BIOS could be the weak link. > > In which way? There resulting code should be runnable on a wide number > of platforms, so there isn't a single source issue, and the actual vote is > on voter verifiable paper, so corruption of the BIOS won't be able to > affect anything other than the number of "something's wrong - this isn't > what I voted for" complaints. > > Perhaps you were thinking of a pure electronic version? > This is getting a bit off-topic, but is relevant to Python-as-open-source-scripting-tool. Yes, paper audit trail is essential. But I'm pretty sure that conflicts between paper and electronic will result in court cases, with significant chunks of ballots in limbo or thrown out on one pretext or another. By choosing which precincts are thrown in limbo, you can impact the overall results. Here is a possible scenario: 1. Software chooses 1% of votes to change (big enough to have an effect, small enough to maybe go unnoticed). 2. Paper is correct. Visual monitor is correct. Electronic storage is changed. Voter leaves happy. 3. Results are posted based on electronic storage. 4. Only if enough people suspect trouble do we go to the paper trail. At 1%, that may not happen. Yet a 2% swing is pretty big in many settings. > Andrew > dalke at dalkescientific.com > > -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From bgailer at alum.rpi.edu Tue Jul 22 14:02:45 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 22 Jul 2003 12:02:45 -0600 Subject: SAX questions... In-Reply-To: <200307221022.09513.tjg@craigelachie.org> Message-ID: <5.2.1.1.0.20030722115406.04110cd0@66.28.54.253> At 10:22 AM 7/22/2003 -0700, Timothy Grant wrote: >I've worked with DOM before, but never SAX, I have a script that seems to >work >quite well, but every time I look at it I think it's amazingly unweildly and >that I must be doing something wrong. > >def startElement(self, name, attr): > if name == "foo": > do_foo_stuff() > elif name == "bar": > do_bar_stuff() > elif name == "baz": > do_baz_stuff() > >There's similar code in endElement() and characters() and of course, the more >tags that need processing the more unweildly each method becomes. > >I could create a dictionary and dispatch to the correct method based on a >dictionary key. But it seems to me there must be a better way. Please note that this is not a SAX-specific question. I suggest a subject of How To Manage Function Dispatching. Your question comes down to what's the "best" way to dispatch a piece of logic based on some condition. You have already given 2 good alternatives: your example, and using a dictionary. The other approach I sometimes use is defining a class for each condition and then instantiating the class as needed. Class foo: def __init__(self): # do foo stuff etc for each case, then try: x = eval(name+'()') except: raise "Unknown name " + name Which, of course, is just a dictionary lookup in disguise. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From Adrien.DiMascio at logilab.fr Mon Jul 7 03:10:07 2003 From: Adrien.DiMascio at logilab.fr (Adrien Di Mascio) Date: Mon, 7 Jul 2003 09:10:07 +0200 Subject: Newbie question: Strange TypeError In-Reply-To: References: Message-ID: <20030707071007.GA420@logilab.fr> On Mon, Jul 07, 2003 at 04:04:32AM +0000, Tim Isakson wrote: > Howdy, Hi, > > > def HandleInput(self, input): > if self.results.GetValue() == "0": > return input > elif newVal == True: > return input > else: > tmpVal = self.results.GetValue() + input > return tmpVal > > def OnButton1(self,e): > tmpVal = self.HandleInput(self, "1") > self.results.SetValue(tmpVal) > The call to HandleInput is made, but I get the following error: > > Calling HandleInput(self, '1') > Traceback (most recent call last): > File "pycalc.py", line 115, in OnButton1 > tmpVal = self.HandleInput(self, "1") > TypeError: HandleInput() takes exactly 2 arguments (3 given) > So far as I can tell, the offending call *IS* calling HandleInput with 2 > arguments, but the interpreter obviously thinks different, and I'm at a > loss as to why that might be. Well, your script *IS* calling HanlderInput with 3 arguments since there is the 'hidden' object instance as first argument. You must not explicitly pass the 'self' argument, Python will do it for you, so just call : tmpVal = self.HandleInput("1") Hope this helps. Cheers, -- Adrien Di Mascio LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From bokr at oz.net Wed Jul 30 16:06:03 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Jul 2003 20:06:03 GMT Subject: Dict to "flat" list of (key,value) References: Message-ID: On Wed, 30 Jul 2003 21:26:19 +0200, Nicolas Girard wrote: >Hi, > >Forgive me if the answer is trivial, but could you tell me how to achieve >the following: > >{k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] > >The subtle point (at least to me) is to "flatten" values that are lists. > Assuming v3 and others like it can't be references to lists (or how could you tell it from the format of k1's list?): (I quoted your names to avoid haing to define them separately) >>> d = {'k1':['v1','v2'],'k2':'v3'} >>> flat = [] >>> for k,v in d.items(): ... if isinstance(v,list): ... for v2 in v: ... flat.append([k,v2]) ... else: ... flat.append([k,v]) ... >>> flat [['k2', 'v3'], ['k1', 'v1'], ['k1', 'v2']] Or would you prefer an inscrutable one-liner ;-) Note that there is no guarantee of any particular order in d.items(), though you could sort them: >>> d = {'k1':['v1','v2'],'k2':'v3'} >>> flat = [] >>> items = d.items() >>> items.sort() # on keys >>> for k,v in items: ... if isinstance(v,list): # Note that v is a list here, but does have pre-existing order you might want to keep. # If you wanted to guarantee sorted output of the v2's, you could # do v.sort() here, though you might surprise others holding references # to those lists, since they would see the sorting. To avoid that, make a copy first, e.g., # v = v[:]; v.sort() #(untested, but I think it should work ;-) ... for v2 in v: ... flat.append([k,v2]) ... else: ... flat.append([k,v]) ... >>> flat [['k1', 'v1'], ['k1', 'v2'], ['k2', 'v3']] Regards, Bengt Richter From mcherm at mcherm.com Wed Jul 2 18:55:29 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 2 Jul 2003 15:55:29 -0700 Subject: what is self? Message-ID: <1057186529.3f0362e1e348d@mcherm.com> paul h writes: [...] > looking into the code, i see a lot of references to "self" ie > self.window = ... [...] In Python, "self" is nothing special at all... it's just a normal variable like "x" or "y" or "myObject". If you look at the top of the method declaration where you saw self used, you'll see that "self" is the name of the first argument. What's different now is that you're starting to use objects. When you use objects in Python, they have functions that belong to the objects themselves (called "methods"). In Python, the first argument to any method (a function defined within a class) will always be the particular object on which the method is being called. Since that first argument always means "the object this method is called on" Python programmers nearly always use the same name for it... and "self" happens to be the conventional name. Everything would work just fine if you changed "self" to "abc" in the parameter list and also within the body of the method. Everything, that is, except for the fact that people reading your code would find it a bit odd and confusing. -- Michael Chermside From e_fax_t at msn.ZAPME.com Sun Jul 13 05:55:17 2003 From: e_fax_t at msn.ZAPME.com (Justin) Date: Sun, 13 Jul 2003 11:55:17 +0200 Subject: HTML Help (CHM) file for Python 2.2.3 References: Message-ID: <3f112ca1$0$6533$afc38c87@sisyphus.news.be.easynet.net> > Could you send me a download URL of a compiled > HTML Help (CHM) file for Python 2.2.3 ? Try the PYTHLP.PY script available at http://www.orgmf.com.ar/condor/pytstuff.html I just tried it on 2.3b2, and it seems to work even though not explicitly supported. From tdelaney at avaya.com Sun Jul 6 22:44:06 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 7 Jul 2003 12:44:06 +1000 Subject: python scripting game The Temple Of Elemental Evil update Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE844723@au3010avexu1.global.avaya.com> > From: O'Neal Computer Programmer [mailto:cneal92 at lycos.com] > > Anyway, this game also has a forum at > http://ina-community.com/forums/forumdisplay.php?s=&forumid=286 and > also one that you have to pay for at > http://vnboards.ign.com/board.asp?brd=22335 with more info about the > game. Actually, you don't have to pay to use the RPG Vault boards (vnboard), though you do if you want extra features. I've talked to Guido privately about this, and intend to ask Tim Cain (Project Lead) or Steve Moret (Lead Programmer) if they would be willing to write a piece about the use of Python in ToEE. BTW, I'm a long-time inhabitant of the Arcanum Inn and Greyhawk Inn at the RPG Vault boards (magao). Most of the conversation at the Arcanum Inn is off-topic, much of it at the Greyhawk Inn also is (but less so, since the game is in development). Oh - and I have a grave in Arcanum :) Tim Delaney From gml4410 at ggr.co.uk Fri Jul 4 10:21:50 2003 From: gml4410 at ggr.co.uk (Lack Mr G M) Date: Fri, 04 Jul 2003 10:21:50 BST Subject: Building Python - how to set include and lib paths? References: Message-ID: <2003Jul4.102150@ukwit01> In article , Curly Joe writes: |> Lack Mr G M wrote (snipped): |> I'm trying to build (compile and link) Python2.2.3, |> However, I need to indicate where it can find various |> library and header files for other extensions which I |> have already built (things like ssl etc.). |> |> There are two simple ways that I know of: |> 1 - add it to, and export the PYTHONPATH variable - |> mine is in ~/.bash_profile on a Gentoo Linux box. |> Your shell and/or profile file name may be different. |> 2 - probably not what you want, but |> .../python/site_python should be in your PYTHONPATH |> and so you could place you programs there. No - that's not the problem. I know I can set that up for pyhton modules at run time. My problem occurs when I am *building* python itself. There seem to be no way that I can tell it where to look for header files and libraries for other packages/utilities (eg: SSL) that I have previously installed or how to add these to compilation and linking options.. It hard-wires /usr/local/{include,lib} for these. -- --------- Gordon Lack --------------- gml4410 at ggr.co.uk ------------ This message *may* reflect my personal opinion. It is *not* intended to reflect those of my employer, or anyone else. From python at grimes.org.uk Tue Jul 1 11:33:28 2003 From: python at grimes.org.uk (Paul Grimes) Date: Tue, 01 Jul 2003 16:33:28 +0100 Subject: PyQT and Mandrake 9.1 References: Message-ID: MK wrote: > "Paul Grimes" wrote > >> > Be careful. QT is controlled by one company, >> >> Sort of true > > I'd say it's true. What do you mean by "sort of"? > No matter what anybody says, Qt is controlled by > Trolltech, full stop. > The free version is GPLed, so if you don't like the way it's going, you can always fork it. Trolltech only control the _official_ free version (i.e. the one on their website) and the commercial version. If Trolltech should go under, or otherwise stop distributing the GPL version, then the official free version will be BSD licenced (as I understand it, although I find that slightly weird). > >> > and it costs money. >> >> Not true, unless you want to distribute a closed source program > > So this is "sort of true", right? I suppose so. But the free version is free, and always will be. It only costs money if you don't like the license terms of the free version. Paul From tomas at fancy.org Mon Jul 7 12:52:08 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 07 Jul 2003 09:52:08 -0700 Subject: looking for UDP package, network programming guidance Message-ID: Hey all- A friend of mine has built this interesting (to me) bit of hardware that's intended to communicate with a PC over ethernet. The hardware has an OS written in C, and has some PC-side testing software written in Delphi, all of which I have access to. The hardware communicates with the PC via UDP. I've been working on porting the PC "test" software to Python so that 1) I understand the code, 2) don't need to go buy Delphi to help this guy out, and 3) learn enough about network programming to write the actual application interface software for off-the- shelf software to use this hardware. I spent a bunch of hours one night learning everything I needed to about wxPython to get a not-so-fancy but needs-a-lot-of-different-UI-elements test app UI running, but now the stumbling block comes up that Python doesn't seem to have any UDP handling built into its distribution. Searching the web turned up Twisted, although it seems like it might be a bit bigger than I would have hoped (in terms of, "there's a huge package here to figure out"), but as far as I can tell it's the only UDP solution out there. Is this the case? Additionally, the networking protocol is a fixed format packed bytes sort of thing; is it easy enough in Python (with Twisted) to read bytes off of the stream and then decide what to do with them? (I'm a Python newbie but somewhat of a C++ pro.) Finally, I'm also somewhat of a babe in the woods with network programming in general. Any good references for learning about this stuff, something that goes over issues of robustness, error handling strategies, and so forth? It'd be best if anything had "tutorials" written in Python, of course. ;) thanks, -tom! From bdesth.nospam at removeme.free.fr Wed Jul 2 15:27:08 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 02 Jul 2003 19:27:08 +0000 Subject: what is self? References: <6071d159.0307020846.7653afaa@posting.google.com> Message-ID: <3F03320C.8050300@removeme.free.fr> paul h wrote: > hi there, > i've been programming cgi with python for a couple of months now, and > i am now moving into some gui programming, using pygtk2. > looking into the code, i see a lot of references to "self" ie > self.window = ... > however, i have no idea what self is? > can anyone enlighten me... > thanks very much... > self is the current object (read : class instance). I think you should read the part about oop support in the python manual. Bruno From syver-en+usenet at online.no Tue Jul 15 13:20:17 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 15 Jul 2003 19:20:17 +0200 Subject: [OT] sentances with two meanings References: <3F142A58.80426AA4@hotmail.com> Message-ID: Alan Kennedy writes: > Syver Enstad wrote: > > > > Given the biblical meaning of "known", this could have even more > than > > > > two meanings :-) > > > > Does "to know" in english also mean to feel someone? In my own > language > > > the direct translation of the english know also means to feel. I > could > > > say (translated) "I know the cold", meaning I feel the cold > > weather. > > To "know" someone, in the biblical sense, is to have "carnal > knowledge" of them, i.e. "knowledge of the flesh", i.e. to have had > sexual relations with them. Yes, I know that, I think it sounds great. It's just didn't make sense the way I understand the english word "to know". -- Vennlig hilsen Syver Enstad From peter at engcorp.com Sun Jul 20 22:33:19 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Jul 2003 22:33:19 -0400 Subject: sys.setcheckinterval query References: <84fc4588.0307201255.254582df@posting.google.com> Message-ID: <3F1B50EF.9EE3B859@engcorp.com> Anand Pillai wrote: > > """ > setcheckinterval(interval) > Set the interpreter's ``check interval''. This integer value > [...] > """ > I am interested in the last but one statement which says, "Setting it > to a larger value may increase performance for programs using > threads.". So my question is what would that value be? How can I find > out the number of python 'virtual instructions' for every function I have? Do you really want to waste time optimizing at such a level? I suspect it's very unlikely you will notice any difference other than with order-of-magnitude changes. In other words, it's normally every 10 instructions, but if you change it to 100 or 1000 you could notice a difference. (Zope sets the checkinterval to 120 (in the version I checked), but I think I'd be surprised if 100 or 140 turned out much different. Trying to "tune" it to, say 27, or 73, or something would be sheer insanity. If you need better performance than what you are getting, find your bottlenecks by profiling and optimize there, or write a C extension, or use Pyrex, or Psycho or something. (To find the number of bytecode instructions, use module "dis", BTW.) -Peter From simonb at webone.com.au Mon Jul 28 18:25:26 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 29 Jul 2003 08:25:26 +1000 Subject: metaclasses Message-ID: It seems this is a more general way to build classes than inheritance. Is this a reasonable viewpoint? >>> >>> def meth1(self): ... print "i am meth1" ... >>> def meth2(self): ... print "i am meth2" ... >>> Foo = type("Foo",(),{'meth':meth1}) # make a class >>> foo = Foo() # make an instance >>> foo.meth() # call a method i am meth1 >>> Simon. From ricardo.b at zmail.pt Thu Jul 17 12:39:37 2003 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Thu, 17 Jul 2003 17:39:37 +0100 Subject: what u'=' mean??? References: Message-ID: On Thu, 17 Jul 2003 12:24:57 -0300, Luiz Siqueira Neto wrote: > What > ---- > u'=' Its just a unicode string. The string constants in Python can be prefixed with a u. Instead of building a string object for that constant, the interpreter will build a Unicode string object. You can also prefix them with r, to make the interpreter ignore escape codes. For example: >>> print 'a\nb' a b >>> print 'a\\nb' a\nb >>> print r'a\nb' a\nb >>> And you can use the combined ur prefix. -- Ricardo From bokr at oz.net Fri Jul 25 17:57:44 2003 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2003 21:57:44 GMT Subject: file.close() References: <7xhe5b82ip.fsf@ruckus.brouhaha.com> <7xr84e9wey.fsf@ruckus.brouhaha.com> Message-ID: On 25 Jul 2003 13:35:49 -0700, Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: >> >"done" here is a generic method that gets called on exiting a "with" >> >block. >> First reaction == +1, but some questions... >> >> 1) Is f.done() really necessary? I.e., doesn't an explicit del f >> take care of it if the object has been coded with a __del__ >> method? I.e., the idea was to get the effect of CPython's >> immediate effective del on ref count going to zero, right? > >The ref count might not be zero. Something inside the "with" block >might make a new reference and leave it around. > Aha. In that case, is the del just a courtesy default action? >> 2) how about with two files (or other multiple resources)? >> >> with f1,f2 = file('f1'), file('f2'): >> [do stuff with f1 & f2] >> >> What is the canonical expansion? > >I think f1.done and f2.done should both get called. Consistently ;-) > >> Also, what about the attribute version, i.e., >> >> ob.f = file(frob) >> try: >> [do stuff with ob.f] >> finally: >> del ob.f # calls f.__del__, which calls/does f.close() >> >> I.e., ob.f = something could raise an exception (e.g., a read-only property) >> *after* file(frob) has succeeded. So I guess the easiest would be to limit >> the left hand side to plain names... > >The assignment should be inside the try. If I had it on the outside >before, that was an error. Really? Don't you want a failing f = file(frob) exception to skip the finally, since f might not even be bound to anything in that case? The trouble I was pointing to is having two possible causes for exception, and only one of them being of relevance to the file resource. Maybe if you wanted to go to the trouble, it could be split something like with ob.f = file(frob): [do stuff with ob.f] becoming _tmp = file(frob) try: ob.f = _tmp [ do stuff with ob.f ] finally: _tmp.done() del _tmp del ob.f Not sure about the order. Plain ob.f.done() would not guarantee a call to _tmp.done(), since ob could refuse to produce f, and f could be a wrapper produced during ob.f = _tmp, and it might not have a __del__ method etc etc. _tmp is just for some internal temp binding. Regards, Bengt Richter From jjl at pobox.com Fri Jul 4 11:00:41 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Jul 2003 16:00:41 +0100 Subject: Python Code Snippets References: Message-ID: <87y8ze8hgm.fsf@pobox.com> "Aur?lien G?ron" writes: > Does anyone know where I can find a lot of Python code snippets? [...] http://www.uselesspython.com/ They're working on useless 2, with categories. John From simonb at webone.com.au Tue Jul 1 22:47:00 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 02 Jul 2003 12:47:00 +1000 Subject: function overloading References: Message-ID: Yes, it's a good idea; and that's how i started; i just can't remember all the different names. Lazy init is a good idea too... But it adds a level to the class invariant. It seems i am the lazy one: def __init__(self,*args,**kwargs): read_and_dispatch( args, kwargs, (self.init1,self.init2, ... ) ) was what i had in mind, but unless each init has a different signature, it's gonna get more hairy: class Signature: def __init__( self, siglist ): pass class TypeSignature: pass class InstanceSignature: pass blah. Simon Burton. On Tue, 01 Jul 2003 16:03:17 -0400, John Roth wrote: > > I'd subclass it. I see three classes here: > > class Image: > def __init__(self, oldImage) > > class NewImage(Image): > def __init__(self, height, width): > > class ImageFromDisk(Image): > def __init__(self, fileName): > > The subclasses only override the __init__ method > of the base class. > > An alternate method of dealing with the situation > is to do lazy initialization. In other words, don't provide > any parameters on the construction, and provide three > different methods for initializing the resulting object. > > John Roth From uche at ogbuji.net Mon Jul 28 13:55:32 2003 From: uche at ogbuji.net (Uche Ogbuji) Date: 28 Jul 2003 10:55:32 -0700 Subject: XML Validation with Python References: <3F042045.C5CB0248@hotmail.com> <3F0474F5.FD7E57F3@hotmail.com> Message-ID: Alan Kennedy wrote in message news:<3F0474F5.FD7E57F3 at hotmail.com>... > Pytrex is unlikely to be ever completed, because James Clark has > abandoned TREX in favour of RELAX-NG, for which I haven't seen any > python implementation. > > http://www.relaxng.org/ 4Suite provides RELAX NG support. See http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/relaxng You can also just use Eric's XVIF directly: http://www.advogato.org/proj/xvif/ David Mertz also has some tools for working with RNG compact syntax: http://gnosis.cx/download/relax/ http://www-106.ibm.com/developerworks/library/x-matters25.html http://www-106.ibm.com/developerworks/library/x-matters26.html Good luck. --Uche http://uche.ogbuji.net From news at exultants.org Tue Jul 8 05:59:03 2003 From: news at exultants.org (Van Gale) Date: Tue, 08 Jul 2003 09:59:03 GMT Subject: path module In-Reply-To: References: Message-ID: Ian Bicking wrote: > I think Jason Orendorff's path module is really nice: > http://www.jorendorff.com/articles/python/path/ I love it and have been using it in a few personal projects. My only gripe is its monolithic nature :) Van From robin.cull at pace.co.uk Wed Jul 30 08:16:43 2003 From: robin.cull at pace.co.uk (Robin Cull) Date: 30 Jul 2003 05:16:43 -0700 Subject: Is there a standard module library function to access /etc/passwd or /etc/group Message-ID: <16469f07.0307300416.351ba776@posting.google.com> Hi all, I'm writing a script that needs to do lookups on the UNIX passwd and groups file on textual usernames/group names and return numeric UID/GID. Something that gives access to the C standard libarary functions get[pw|group]ent(), for example. I've Googled around on various logical search terms and looked through pydoc and the module reference but haven't found anything up to this point. I'd have thought that the os module would provide this sort of access. I did find something called UserDBM but this appears not to be a standard module. Before I go away and write a couple of functions to do this myself, can anyone tell me if there is a module that provides this sort of interface? I'd really like it to be a standard module as the script will have to run at a lot of different sites and I'm hoping there are no external dependencies past an RPM installation of Python. If not, I'll do my own local functions in the script. Thanks all. Cheers, Robin From rtrocca_SPAM_ME_NOT at libero.it Fri Jul 4 11:24:08 2003 From: rtrocca_SPAM_ME_NOT at libero.it (Riccardo) Date: Fri, 4 Jul 2003 17:24:08 +0200 Subject: Form using HTML on PythonCard References: Message-ID: PythonCard is a wxWindows application, therefore you've got two choices: 1) use a wxHtmlWindow that can display *simple* html. Anyway I used it and I don't think it can handle forms (but maybe I'm wrong). You'd need to extend it a bit (it is a straightforward process see the wxp example in the wxWindows demo) 2)if you are on windows you can use the wxHtmlIEWindow that renders html using th WebBrowser COM component. The problem, then, is how to handle form data. If you want to access them from python that can be troublesome. Riccardo "Luiz Siqueira Neto" wrote in message news:mailman.1057322477.18286.python-list at python.org... > Somebody know how make html forms or python forms inside html to use as gui > application? > > The idea is make a client application like a web site of my interprise for > customers who don't have good connection, in this way the customer can select > the products off line and connect only to execute the shop. The use of HTML > is to have the same paradigm to application and to site. > From glenfant at NOSPAM.bigfoot.com Wed Jul 9 06:52:12 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Wed, 9 Jul 2003 12:52:12 +0200 Subject: Why Python References: <3f0be9ac@news.comindico.com.au> Message-ID: "Tony Steward" a ?crit dans le message de news: 3f0be9ac at news.comindico.com.au... > Hello All, > I am looking for a programming language to use to write a database type > application to run on windows machines. Is python for me or pls suggest what > is. Search (google) for mxODBC. it's a commercial package (free for personal use) that enables to play with any database that provides an ODBC driver (Oracle, MySQL, MS Access, MS SQL*Server, Sybase...) > > Is there a page that explains in simple terms what Python can do on windows? > Is there an IDE? Many 3rd party IDEs are available, free and commercial ones. The standard Python distro comes with IDLE. > Is the windows api pre wrapped? Not in the standard distro, but you can add win32all (google again) that wraps most of the win32 native API. Plus a nice IDE. If you don't want mxODBC, win32all comes with an ODBC module. But it's not as rich as mxODBC. > > Thanks Welcome --Gilles From bgailer at alum.rpi.edu Thu Jul 3 18:27:00 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 03 Jul 2003 16:27:00 -0600 Subject: Python in Excel In-Reply-To: Message-ID: <5.2.1.1.0.20030703162459.07cb0e40@66.28.54.253> At 07:37 PM 7/3/2003 +0000, Afanasiy wrote: >Can I write Excel macros/scripts using Python? > >I mean to actually put Python into an Excel document, not using >Python to access data, for example, from some Excel document. Do you want to use Python as an Excel macro language instead of VBA? If so, the answer is almost guaranteed to be NO. Why do you want to do this? What alternatives can you accept? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From db3l at fitlinxx.com Wed Jul 2 14:36:05 2003 From: db3l at fitlinxx.com (David Bolen) Date: 02 Jul 2003 14:36:05 -0400 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: "Aur?lien G?ron" writes: > There are things that are hard to unit test (I'm talking about automated > unit tests here) and which you just can't do without in some projects. For > instance, the database! I worked in a couple of projects with automatic > unit tests for the DB related components, and having lived through it, I'm > not sure that it was worth it at all! Manual unit tests would have made > much more sense. (...) > (...) > I guess my point is that though you may be right in some specific contexts, > I don't think you can generalize. That's IMHO of course. I'd agree that there are elements that are much more difficult than others to test in an automated fashion - sometimes impractically so given the cost to benefits comparison. Personally, I'd agree that databases, GUIs and asynchronous activities such as network or multi-threading are areas that fall into that category. But I also think that such areas can often be tested far more than some might think within a given development effort. The idea is to strip any layer that can't be (or for a given project can't be justified to be) automatically tested down to its bare minimum, because an automated test will almost always be of more value over time (with repeated use, different developers, etc...) than a manual test. This is where using the tests during development (as opposed to afterwards) can help ensure a test friendly design, and one that is often more modular and structured than a typical developer might have otherwise arrived at without the tests during development. For example, when writing a DB interface layer or component (whether for persistence or direct RDBMS access), if you're trying to construct tests as you develop, you will more than likely arrive at a structure where the final database access layer is isolated enough that you can mock it up for most of your tests of the remainder of your code - if only because without it you find yourself not able to construct tests :-) This might take the form of a specific component used to wrap raw database access. Or, if it's a SQL database, you might find yourself designing business components such that they serve as producers of the actual SQL, for which a separate object consumes it and executes it against a database. That interface (the SQL output) provides a test point for the business logic without involving the database. In the former case, tests would simulate the lowest level database layer to function just as is necessary for the test (accepting and returning appropriate data), thus being able to rapidly and efficiently test the remainder of the code without a live database in an automated and controlled fashion. In the latter case, the tests would execute the business logic and compare the result to expected SQL. A much smaller suite of tests to exercise the database layer would use a test database (or equivalent) but would be focused strictly on the raw database interface, or execution of known SQL test statements, and should be much more containable (in time and development effort), and probably still automatable, although perhaps on a longer cycle time. If the system wasn't designed with testing involved, the actual database I/O might very well be embedded in a higher layer (such as the persistence mechanism which might be tightly coupled to an object layer) and hard to isolate from the rest of the logic. For example, you might find business objects directly calling a persistence or database I/O layer within their implementation, making it hard to test the business logic without a live database. Similar ideas apply to GUIs - keep the actual interface layer as extremely thin as possible, and containing no business logic or application decision processing. Whether you use MVC, MVP or an equivalent approach, ensure that you can test all underlying business logic without actually needing a GUI. This holds for applications and web sites (in many respects, a web site can just be modeled as a different form of view). For example, in MVC/MVP, your automated test can call controller/presenter methods to simulate any aspect of user interaction with the UI, but without the need for a UI, and can mock up a non-UI view to ensure that the model is notified of appropriate changes and that queries to it reflect the new information. At some point you need to verify that performing action X against UI object Y generates the right requests to the other system components, but that's far more constrained testing then trying to test the business logic through that UI. And yes, that could probably involve external UI testing tools, or some manual interaction with an automated test mocking the underlying controller/presenter and model. Of course, this is all easiest if you are designing a system with testability in mind from the get go. Trying to retrofit unit tests onto a GUI for example, where much of the business logic is attached to specific UI elements and not reachable without going through the UI is just plain old difficult. The idea of making up tests as you go (whether TDD or equivalent) and using them as part of the development process helps not only ensure that the final product is as tested, in as automated a fashion, as possible, but that it ends up being designed to be tested. -- David From mwilson at the-wire.com Wed Jul 9 13:01:59 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 09 Jul 2003 13:01:59 -0400 Subject: Collective memory References: <3F09F136.6060000@srv.net> <7rist-gc3.ln1@beastie.ix.netcom.com> Message-ID: In article <7rist-gc3.ln1 at beastie.ix.netcom.com>, Dennis Lee Bieber wrote: >Richard Steiner fed this fish to the penguins on Tuesday 08 July 2003 >01:48 am: >>> Anything in 6 for Continuation >> >> ...except a space. :-) >> > Ah, but on a hollerith card, a space is /nothing/ -- no mark at all No. On a hollerith card a space is something -- amounts of paper occupying volume in twelve particular places. Other characters approach being nothing to different degrees. Regards. Mel. From v.wehren at home.nl Sat Jul 19 16:42:26 2003 From: v.wehren at home.nl (vincent wehren) Date: Sat, 19 Jul 2003 22:42:26 +0200 Subject: List of declared variables in interactive Python session? References: Message-ID: "Fredrik Fornwall" schrieb im Newsbeitrag news:pNdSa.397$Y5.120 at nntpserver.swip.net... > Hello. > > Is there a way to list all the declared variables in an interactive > Python session? use "vars() " HTH, Vincent Wehren > > Thanks, > Fredrik > From tim.one at comcast.net Sat Jul 12 03:26:15 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 12 Jul 2003 03:26:15 -0400 Subject: The "intellectual property" misnomer In-Reply-To: <1057987669.28456.79.camel@lothlorien> Message-ID: [Ian Bicking] > Functionally, though, I think the term intellectual property here > works. Yup. "Copyrights, trademarks, patents, stuff like that" is the common and the intended meaning. > PSF holds (to their knowledge) all intellectual property associated > with Python No, it doesn't. Aahz was correct in clarifying that it's part of the PSF's mission to obtain that stuff. For the most obvious example, stare at your Python license file: copyrights in some of the Python source code prior to the 2.1 release are still held by CWI, CNRI, and BeOpen.com. CNRI also holds several trademarks related to Python, and has applications for others in progress (such as for "Python" itself -- that's been in progress for about 3 years now!). > -- there may be no patents, but with the statement they assert that > either there are no patents or they hold them. The PSF doesn't know of any patents associated with Python. It's possible that the PSF will apply for some, though, and I like using "intellectual property" because it covers (in the common understanding) all stuff of this nature. > We also know (implied from other sources) that PSF does not restrict > its intellectual property. That's an explicit part of the PSF's Mission Statement. For example, if the PSF were to seek algorithmic patents, it would be to protect the free use of algorithms in Python that may be patentable, or perhaps as a deterrent against lawsuits (much as private corporations sometimes build a patent portfolio as protection against patent suits from other companies -- "oh yeah? you sue us for process X, and we'll sue you for process Y, so let's compromise and enter a cross-licensing agreement instead"). Not that there are any current PSF plans to seek patents -- there aren't. It would be within the PSF's mission to do so, though, if we thought that would be in the public interest. > The intent of this statement is that someone using Python need not > worry about "intellectual property" associated with Python, which > includes at least patent, copyright, and trade secrets. Well, the PSF would *like* to say that, but nobody can predict what courts will say, and there's always some element of risk. The PSF exists in part to hold Python's IP in the public interest, but doesn't yet even hold all that currently exists. > I don't know how this applies to trademarks, since they are different > from the others, and obviously PSF does not hold every trademark that > contains Python and relates to computers. The PSF doesn't currently hold any trademarks or service marks. Guido has a strong case (IMO) for a trademark on Python as applied to a computer language, but the US trademark office doesn't make such fine distinctions readily. [Ben Finney] >> If the PSF holds software patents in Python, I imagine many would be >> outraged. I don't believe it does. If it's not the case, why imply >> it with an overbroad term? [Ian] > I would not be outraged. Good -- we've had quite enough outrage in this thread already, and, as above, it is conceivable that the PSF may hold patents someday. > If they enforced those patents, then I might be outraged. Me too. Unless it was just to destroy Perl . From prashsingh at yahoo.com Wed Jul 23 12:03:15 2003 From: prashsingh at yahoo.com (Prashant Singh) Date: Wed, 23 Jul 2003 11:03:15 -0500 Subject: py2exe command line window problem In-Reply-To: References: Message-ID: Klitos Kyriacou wrote: > The fact that the console window shows it's running cmd.exe (the Windows > Command Processor) gives us a good clue. Not all console windows run cmd.exe, > so this is significant. Python's os.system function uses the shell specified > by the ComSpec environment variable (usually C:\WINNT\system32\cmd.exe) to > run the command given as an argument. Check if you are calling system() in > your Python script. If you are, you can be fairly certain that's what's > creating the console window. > > Regards, > Klitos That was it. I replaced the os.system() call with a call to os.spawnl() and now the console window doesn't show up. Thanks a lot, prashant. From skip at pobox.com Fri Jul 11 14:05:05 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Jul 2003 13:05:05 -0500 Subject: Reading a DOS text file and writing out Mac In-Reply-To: <20030711165726.GA29760@dangerousideas.com> References: <20030711165726.GA29760@dangerousideas.com> Message-ID: <16142.64593.775446.454889@montanaro.dyndns.org> Jen> Is there a way to set the EOL character that Python recognizes? Not really. Jen> For example, I'd like to set it to cr/lf (okay, that's eol Jen> characters) when reading a file (DOS text) and set it to just cr Jen> when writing out (Mac). Is there a way to do this? Sure. Open the input file in Universal newline mode (add "U" to the open flags) then write it in binary mode, appending the '\r' character yourself. Universal newline mode is new in 2.3 however. You can always open the input file in binary mode and explicitly strip any trailing \r\n pairs. inf = open("somedosfile", "rb") outf = open("somemacfile", "wb") for line in inf.read().split("\r\n"): outf.write(line+"\r") inf.close() outf.close() or, if you're running 2.3: inf = open("somedosfile", "rU") outf = open("somemacfile", "wb") for line in inf: if line.endswith("\n"): line = line[:-1] outf.write(line+"\r") inf.close() outf.close() Something like that should start you in the right direction. Skip From cidolfas at rpgclassics.com Mon Jul 28 10:09:05 2003 From: cidolfas at rpgclassics.com (Daniel Orner) Date: 28 Jul 2003 07:09:05 -0700 Subject: CGI "download" prompt? References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> <77dd287a.0307250619.7c2ec441@posting.google.com> <3f215bef$0$49107$e4fe514c@news.xs4all.nl> Message-ID: <77dd287a.0307280609.5ebbb1ca@posting.google.com> Gerhard H?ring wrote in message news:... > Irmen de Jong wrote: > > Gerhard H ring wrote: > > > >> Erhm. Let's suppose you want to send an RTF file and have the browser > >> pop up a save dialog with a certain filename preconfigured: > >> > >> Then send these headers: > >> > >> Content-Type: application/rtf > >> Content-Disposition: attachment; filename=mydocument.rtf > > > > I didn't know about Content-Disposition! If this works, > > that's very nice-- especially if the filename part of that > > header is actually used by the web browser. > > That's what it is about. See http://www.faqs.org/rfcs/rfc2183.html for > details :) > > -- Gerhard Great, it works! Thanks very much! From rpgnmets at aol.com Thu Jul 31 14:08:35 2003 From: rpgnmets at aol.com (Rob Renaud) Date: 31 Jul 2003 11:08:35 -0700 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling References: Message-ID: <3759308d.0307311008.2d931ca@posting.google.com> Bram wrote in message news:... > Hi, > Summ: "What is the best way to handle int8,16 and 32 data in python?" > > Im currently working on a class to implement the gui protocol of > mldonkey. (http://mldonkey.lemmster.de/wiki/index.php/GuiProtocol) > However this requires to send int32 and int16 and even int8 integers. > > To create data I'm using the work-around of converting everything to hex > values, and then converting the hex values to a data string wich I put > on the socket (e.g. "\x00\xF0"). > I could do the same on the recieving end: chop it up in bytes and > convert them to numbers (combining the hi and lo bytes of the int16 with > some calculations) > > However, there must be a better way of doing this. > Can anyone help me on this problem? > > Bram This should make it a lot easier for you. http://www.python.org/doc/current/lib/module-struct.html But this will probably be the 4th post containing such a reference. As undoubtedly 3 other people have posted it, but have not yet shown up on google groups. From see at my.signature.com Sat Jul 5 13:31:09 2003 From: see at my.signature.com (Andrei) Date: Sat, 05 Jul 2003 17:31:09 +0000 Subject: Tkinter + Python 2.3b2 on WinXP References: <3068875.1057181763@dbforums.com> Message-ID: <3077839.1057426269@dbforums.com> Originally posted by Martin V. L?Wis > Andrei writes: > > > What should I do to make Tkinter work again? > > Unset TCL_LIBRARY and TK_LIBRARY from your environment. > > Regards, > Martin Thanks, that did the trick. -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From claird at lairds.com Wed Jul 16 12:21:54 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 16 Jul 2003 16:21:54 -0000 Subject: How about using python to write a CMS? References: Message-ID: In article , David McNab wrote: . . . >Twisted or Zope may feel godo to use, but will lock out a lot of users who >only have access to Apache-based hosts. > >mod_python is another option, but not often available in commercial Apache >environments. > >CGI is available on most web hosts, but suffers performance issues. . . . Twisted and Zope are NOT incompatible with Apache. I think you probably had in mind something that was true, but it came out in a misleading way. Yes, there certainly can be issues with, for example, installing Zope usefully on a host where you lack root. It's not impossible, though. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From mis6 at pitt.edu Thu Jul 24 16:44:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Jul 2003 13:44:10 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> <2259b0e2.0307221611.51d6ff27@posting.google.com> Message-ID: <2259b0e2.0307240511.63c8d21@posting.google.com> Oops, sorry for the multiple message, Opera betrayed me :-( From rochkind at basepath.com Mon Jul 14 22:27:54 2003 From: rochkind at basepath.com (Marc Rochkind) Date: Mon, 14 Jul 2003 20:27:54 -0600 Subject: Jtux -- new Java (Jython!) interface to POSIX/SUS Message-ID: Now you can get at POSIX/SUS from Jython. Details at http://basepath.com/aup/jtux. Open Source under the BSD license. --Marc From tzot at sil-tec.gr Tue Jul 22 13:13:06 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 20:13:06 +0300 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: On Mon, 14 Jul 2003 11:06:03 +0100, rumours say that Alan Kennedy might have written: >I'd love to hear of other similar phrases. And somehow I intuit >there's people in this ng who know lots of them :-) No double meaning phrases here, but I recall an urban myth of some american president trying the newest CIA super-secret automatic translator to and fro russian, so whatever he says, gets translated to russian and back to english. He enjoys the machine a lot, and when some assistant comes to remind him that the first lady is waiting for him, he says "out of sight, out of mind...", only for the machine to call him "invisible maniac" :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From mynews44 at yahoo.com Tue Jul 29 14:35:35 2003 From: mynews44 at yahoo.com (google account) Date: 29 Jul 2003 11:35:35 -0700 Subject: newbie needs a little help... trying to write an ftp script. References: Message-ID: Wojtek Walczak posted a simple example: > > import ftplib,sys > > ftp = ftplib.FTP('ftp.python.org') > ftp.login('anonymous','qwe at asd.pl') > print ftp.retrlines('LIST') I think it works the same if I use print or simply ftp.retrlines('list') > ftp.cwd('pub/python') > print ftp.retrlines('LIST') I am interested in reading this into a string so that I can process it. I need to get the name of each file in teh directory so that I can do a loop to retr them all; ie, strip out all directories, and then strip out all the extra information (permissions, dates. I try stuff like SomeString = ftp.retrlines('list') but this only seems to read in the return string: print SomeString 226 Transfer Complete IS there anyway I can read in the whole thing? It is obviously taking the string as being the only part between the single quotes... I don't know how to read the rest into a string. > print ftp.retrbinary('retr README', sys.stdout.write) This is the line I am most interested in! I assume that the callback has something to do with how the program handles the data it is retrieving, and that to save the file it is retrieving I have to open a file, write the file, then close the file... This line would be the writing of the file, I am guessing. something like filename = open(r'd:\downloads\' + file, 'w') ftp.retrbinary('retr README', filename) filename.close And that I can run this thing through a loop for each of the filenames that I get outta the first string. Am I completely way offbase here with what I am attempting? Is this going to actually download the files from the ftp server to the local hardware? Once I can read the output into a string I guess I can get kicked off. This is my current hurdle. Thanks for looking! googleboy. From adechert at earthlink.net Sun Jul 20 19:53:03 2003 From: adechert at earthlink.net (Alan Dechert) Date: Sun, 20 Jul 2003 23:53:03 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: "Andrew Dalke" wrote in message news:bff56e$8iv$1 at slb9.atl.mindspring.net... > Alan Dechert: > > will change. For example, when the voter selects a president/vice > president > > pair, the background will change; the non-selected pairs will be greyed > > while the selected pair will be highlighted (very brightly -- should light > > "greyed" in normal UI parlance means the option is no longer selected. > What happens if someone pressed the wrong button? How is the correct > selection made? > Point (or click on) again to de-select. This is one thing that may require a little voter training. I think it's easy enough, but then we'll find out. You could add a "reset" button but that would make an already busy screen even busier. I'm not sure if that would be easier. > > 3) When "WRITE-IN CANDIDATE" is selected, a large widow (maybe the full > > screen) will pop up with a QWERTY keyboard in the upper half. This > keyboard > > will have only three rows with the alpha keys (no punctuation or numbers > > needed except for perhaps the hyphen... no shift, all CAPS). > > No apostrophe? What if I want to vote for "O'Reilly" > As a matter of fact, we won't let you vote for O'Reilly. On second thought, you're right, I guess. Okay we'll have an apostrophe available. Anything else? > > selected. De-selecting one of the selected candidates reactivates the > > others. > > Ahhh, I think I would have been confused by that. > > Then again, I get confused at time by the machine I use now. :) > as before ... > > 7) The County Commissioner race illustrates how ranked preference voting > > would look. When the voter selects the first one, the button in the "1" > > column is filled and the text "1st" will appear in the space between the > row > > of buttons and the candidate name. When the next selection is made, the > > corresponding button in the "2" column is filled and "2nd" appears, and so > > on. There is a "CLEAR CHOICES" button in case the voter wants to start > > over. > > Heh. I read "CLEAR CHOICES" as a command "the choices are clear". > What about "RESET CHOICES", or an alternate like > point taken. I changed it. http://home.earthlink.net/~adechert/ballot-mockup3.gif > Bill the Cat [1] [2] [3] [4] > Snoopy Dog [1] [2] [3] [4] > Go Fish [1] [2] [3] [4] > Lucy Ricardo [1] [2] [3] [4] > James Kirk [1] [2] [3] [4] > This looks reasonable. There are several ways that ranked preference has been implemented. This on-screen ballot is designed to closely follow paper ballot design. Partly, this makes it easy for a voter to mark a sample ballot and have the on-screen ballot look the same. The design I have there also means that a marksense version could also look the same. The buttons in this case are just for display. The order is set by the order the candidates are selected. > and how are writins added to this? > You would do the write-in as with other races. If you did the write-in before selecting others, then the write-in would be ranked 1st. > *sigh* .. I know just enough to ask questions and be annoying, but not > enough to know the answers.... > > > 8) The printout is intended to come from a personal laser printer located > in > > the voting booth. For the demo, we'll probably use the HP Laserjet 5L. > > I approve of the Mercuri system (I think that's what it's called when a > paper ballot is generated from an electronic ballot - the all-electronic one > I use now is scary). .... > Mercuri (Mercuri-Neumann, more accurately), suggests the paper ballot be inaccessible to the voter -- viewable behind glass. This involves some expensive and proprietary hardware since paper handling must also deal with rejected printouts. My scheme is cheaper and lower tech. It allows the voter to handle the ballot. This involves a minor security issue (then again, since when have we decided we can't trust voters to touch their ballots?). But I think handling the ballot is better psychologically for the voter. This is an issue for our full-blown study to look at in some detail, but we won't worry about this for the demo. > I was just thinking though. Suppose I wanted to rig > the elections by paying for votes. If I know the format of the ballot, I > could generate them myself on specially marked paper then give that > to the people who I've payed for the vote, who go through the process > of voting but use the paper I gave them instead of the printout.. Later, I > or my cronies get access to the ballots (eg, "I'm a reporter and I want to > verify the votes") and can see if my special ballots are included, and > reward/punish as appropriate. > > Not likely to be a problem in real life, but just something I was > thinking about. > It is a real life problem. We've given a lot of thought to this issue. The printout will be designed so that counterfeits can be detected easily. A voting machine will produce special markings particular to that machine and that Election Day which you would have no way of knowing how to duplicate on another machine. There are various other safeguards that will be built into the system so that counterfeits can be detected. Again, this is not something we'll spend any time on for the demo. Vote buying schemes won't be effective against our system because while elections people will know how to spot the counterfeits, crooks (out side the system) won't be able to distinguish counterfeit from real. I don't want to go into this in any depth because I don't have days and days to go over all the possibilities -- we've gone over this stuff before lots and it will be investigated in depth in the full blown study. I just don't have time right now -- just trying to get a simple demo built. > > California ($200 million) and the Help America Vote Act ($3.9 billion) a > lot > > of public funds are being wasted on outrageously expensive hardware that > > will be obsolete in a very few years. > > That's for certain. The tendency to move to higher-tech, more expensive, > and less trustworthy voting machines is scary. > Agreed. > > for conducting elections will be created. We anticipate having quite a > few > > non-academics involved too. For example, Roy Saltman is probably the best > > known voting technology expert and he's not an academic. I'm not an > > academic either. > > The only person I've heard of in this field is Rebecca Mercuri, who > I think is an academic. I've read a lot of RISKS. :) > > > The > > selections will be bar coded in a strip on the left edge. Probably, > > write-in candidate names will be in a separate bar code. The printout > will > > list the voter's selections in text that can be easily read by humans and > > scanners. > > The phrase "bar code" scares me in that the bar code and the human > readable text may differ. Why not just have everything in text? > > > Blind voters will use the system wearing headphones and using a > > hand held device to register selections. > > Isn't that overkill? I seem to recall that already there are provisions > for people with special needs to have someone in the booth to help. > I don't think it's overkill. One of the current [lame] arguments against a "voter-verified paper trail" is that "Mandating Voter-Verified Paper Trails Could Deny Voters With Disabilities the Right to Cast a Secret Ballot." http://www.civilrights.org/issues/voting/details.cfm?id=14878 We have to have a system that allows blind people to maintain a secret ballot. This requirement is pretty much absolute, I would say. > In addition, how does a blind person do a write-in vote? ... > As with current DREs, they use a device with mechanical buttons. It's also likely (the Help America Vote Act pretty much mandates it) that there will be one system set up at each polling place that will be specially outfitted for disabled voters. Generally I don't think the voting machines will have attached keyboards, but the one for disabled voters might include one. > Or someone who is illiterate and hard of hearing? ... > We are not going to do much with this for the demo. These are issues that require a lot of time and effort to study. > > So, please let me know what you think about using Python for this demo. > > Also, if you are a Python expert and would like to help as a volunteer > > (we're all volunteers until the project gets funding), please contact me > > ASAP. We want to have a demo running very soon! -- within a few weeks. > > Python would do this just fine. There are the various GUI projects, but > this sounds like a good place for pygame. > Okay, thanks for your input. > My caution though is that usability testing for this is deeply hard, > and I would advise against "a few weeks" even for demo prototype > code as you suggest. > Darn! Things usually takes longer than we want. We're not going to do a great deal of usability testing for the demo. Mainly, we want to demonstrate that cheap trailing-edge PCs can make great voting machines. It's understood that we will have some lack of functionality and rough edges that will be worked out in the full study. Also worth noting: the PC voting machine software is a very small part of the overall problem. Alan Dechert From jjl at pobox.com Thu Jul 31 13:01:51 2003 From: jjl at pobox.com (John J. Lee) Date: 31 Jul 2003 18:01:51 +0100 Subject: .setdefault() References: Message-ID: <87ispid400.fsf@pobox.com> Tino Lange writes: [...] > This is not what I expected - why evaluate the second argument if it's > not needed? [...] Because that's the way Python always does function calls? > Is this really by design? Yes. > If there's a complicated, expensive to > calculate/build 2nd argument (maybe a function call) then it's also > quite ineffective to evaluate it just to throw away... Don't, then. :-) Use key in dict, or dict.has_key(key). John From alanmk at hotmail.com Wed Jul 23 11:56:38 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 23 Jul 2003 16:56:38 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> <3F1849A0.CB3053D8@hotmail.com> Message-ID: <3F1EB036.E61BE720@hotmail.com> Christos TZOTZIOY Georgiou wrote: > That was my intention: to misspell as 'c?fe' the french word 'caf?', > and then search for it in google groups. This is because the > original greek word --used as an example by Alan, Martin etc-- > was misspelled as 'gi/gnwskw' instead of 'gignw/skw' (accent > 'oxia' in the wrong letter, resulting in an inexistant word), so > it's normal that a google groups search shows up Martin's UTF-8 post > as the only one containing the word. Apologies for the original misspelling. That's purely my fault. I stopped studying ancient Greek 20 years ago (swapped it for the hard-headed practicality of applied mathematics), these days mostly I just remember the alphabet, and a couple of modern Greek words from Greek vacations. But I don't think the misspelling mattered for our exercise. The sole purpose was to find out if travelled correctly through UseNet. Since we know what the misspelling was, I think the search engine exercise we went through was acceptable, because the test was whether our known search term would be correctly found or not. The actual spelling was not important for the purposes of our exercise, although again I apologise for the error. Euxaristw, Christos. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From andreas.kuntzagk at mdc-berlin.de Wed Jul 2 11:11:39 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 02 Jul 2003 17:11:39 +0200 Subject: os.fork() different in cgi-script? References: <85adbxouec.fsf@stowers-institute.org> Message-ID: On Wed, 02 Jul 2003 09:50:03 +0000, Michael Coleman wrote: > Probably because stdout is being buffered here. The pid got written in > the buffer (but not yet actually printed), then the process was forked, > then the buffer got flushed (written out) by each child. > > One solution would be to make sure everything is flushed before you > fork. Thanx, that's it. Is it possible/advisable to make stdout unbuffered? Andreas From phampton at eso.org Thu Jul 3 05:58:51 2003 From: phampton at eso.org (Paul Hampton) Date: Thu, 03 Jul 2003 11:58:51 +0200 Subject: Starting and stopping a background process Message-ID: Hi all I'm new to python so please be gentle :) I'm trying to write a module for my media playing PC which will record input directly from the soundcard using LAME. At the moment I can get it started ok and am about to try and work out the best way to stop the process (which is threaded). I could get the process id of LAME and just kill it, but I think this is a bit messy. Can anyone give me any suggestions on how to make this script determine if lame is already running and then stop it if it is, if not then start it? The following code is run when a certain key is pressed: class main_recording_thread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): self.recording_threaded() def recording_threaded(self): popup_string="Recording Audio Stream" pop = PopupBox(text=popup_string) pop.show() time.sleep(4) pop.destroy() print "Recording" time.sleep(20) recording=1 os.system("sox -t ossdsp -w -s -r 44100 -c 2 /dev/dsp -t raw - | /usr/local/freevo/runtime/apps/lame -x -m s - ./test.mp3") popup_string="Audio Recording Stopped" pop = PopupBox(text=popup_string) pop.show() time.sleep(4) pop.destroy() print "Recording Stopped" recording=0 return [] I expect my coding is really bad as it is my second attempt ever at python. So, what would be the best way to do this start/stop thing? Thanks in advance Paul From martin at v.loewis.de Sat Jul 5 03:58:45 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Jul 2003 09:58:45 +0200 Subject: Tkinter + Python 2.3b2 on WinXP References: <3068875.1057181763@dbforums.com> Message-ID: Andrei writes: > What should I do to make Tkinter work again? Unset TCL_LIBRARY and TK_LIBRARY from your environment. Regards, Martin From staschuk at telusplanet.net Wed Jul 30 17:14:38 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 30 Jul 2003 15:14:38 -0600 Subject: Exceptions as New Style Classes In-Reply-To: <98c4ab9a.0307300830.72dcdc74@posting.google.com>; from zuckuss@apexmail.com on Wed, Jul 30, 2003 at 09:30:45AM -0700 References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: <20030730151438.A1499@tibia.amotlpaa.bogus> Quoth Andrew: > To satisfy my curiosity I was wondering if anyone knew if this > behaviour was intentional? > Is there a specific reason why exceptions are not allowed to be new > style classes? It is intentional. There are two difficulties with allowing new-style classes as exception types. Ideas exist for dealing with them, but at the moment none of them as been implemented. Problem 1: Implicit instantiation. When the interpreter sees raise x it must determine whether x is a class or an instance, so it can determine whether to instantiate it. (E.g., in x = TypeError raise x instantiation will occur during the raise statement, whereas in x = TypeError() raise x it will not.) The problem is that, with new-style classes, there is no clear and strong distinction between classes and instances, so it is not clear how the interpreter can make this decision. Problem 2: It is probably not desirable to allow things like raise 3 raise {'d': 17} since raising such objects as ints and dicts (etc.) is very unlikely to be anything but a bug in practice. (There are cases in which you might want to do such things, but they are rare.) However, there is (or will and should be) no clear and strong distinction between, say, user-defined new-style classes and built-in types, so it is not clear how the interpreter would detect such cases and forbid them. At the moment the dominant idea for solving these problems is to make inheritance from Exception mandatory for exception types; see Guido's 11 June post for details. (I have another idea involving a new special method '__raise__', but haven't worked out the details yet.) -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 15 14:15:24 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 15 Jul 2003 20:15:24 +0200 Subject: A few beginning questions In-Reply-To: References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> Message-ID: <3f1444bc$0$49100$e4fe514c@news.xs4all.nl> Robin Munn wrote: > I'd suggest you try out is Vim (http://www.vim.org/). Its name stands [...] > Cons: It's vi. That means a pretty steep learning curve until you've > gotten used to modal editing, where you go into "insert mode" to type > text and go back into "command mode" (by hitting ESC) to move the > cursor, copy and paste text, do searches, move text around, etc. Many > people try vi and give up in disgust after five minutes. Actually, moving the cursor around, erasing characters (del, bs) and perhaps some other frequent actions *don't* require you to switch to command mode in Vim... So perhaps it is a lot less painful to start using Vim (compared to a 'true' vi). --Irmen From michael at foord.net Wed Jul 9 09:57:44 2003 From: michael at foord.net (Fuzzyman) Date: Wed, 09 Jul 2003 14:57:44 +0100 Subject: Executables under Win32 References: <5vkngvs2epq6rv0a3rodeb839k5ls8bafj@4ax.com> <3F0BE70A.165B5274@engcorp.com> Message-ID: <2q7ogvksccj59kqmmed91u5ohqqvs2hhej@4ax.com> On Wed, 09 Jul 2003 05:57:30 -0400, Peter Hansen wrote: >Fuzzyman wrote: >> >> IS there a tool to make Python Executables (binaries) under Win32... >> or must people have a distribution of Python to use any scripts I >> write ? >> >> I don't need to hide my source code - but would liek to make it easy >> for a newbie to use my scripts. > >(Excellently asked question! We get this one often, but rarely so >clearly. :-) > >There is py2exe and the Macmillan Installer, as well as some lesser >known alternatives. py2exe runs on Windows only, the other on Windows >and Linux (at least). A quick Google for either should get you there... > >-Peter Many thanks :-) Fuzzyman --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera http://www.voidspace.org.uk Where Headspace Meets Cyberspace Cyberpunk and Science Resource Site Exploring the worlds of Psychology, Spirituality, Science and Computing -- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz http://www.learnlandrover.com From mal at lemburg.com Tue Jul 8 15:53:42 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 08 Jul 2003 21:53:42 +0200 Subject: parsing flat file to mssql (odbc) In-Reply-To: <8db020b9.0307081101.23325bd@posting.google.com> References: <8db020b9.0307081101.23325bd@posting.google.com> Message-ID: <3F0B2146.3090803@lemburg.com> .d.hos wrote: > ok, fairly new to python, relatively familiar w/ ms-sql. here's my > issue: > > my .py script parses the contents of a (tab delim.) flat file, then > attempts to insert the information into the db. I've been fighting > this for a day or so, and i'm stuck on the db insertion... > > basically the script uses .readlines() to capture the flat file > contents, and stick the *record* into a container list... > > something to the effect of: > for l in lines: > fields = string.split(l,'\t') > dic.append(fields) > > then, I just want to loop over that container list and do a simple > INSERT statement. I've tried using the .executemany() method to no > avail. .execute(sql, tuple) seems to be working better. > > sql statement (lots of columns): > --------------------------------- > INSERT INTO tbl_pyDev > (COURSE_SECTIONS_0,Term_1,Synonym_2,Section_Name_3,Location_4,Bldg_5,Room_6, > Days_7,Start_Time_8,End_Time_9,Start_Date_10,End_Date_11,Add_Start_Date_12, > Drop_Start_Date_13,Add_End_Date_14,Faculty_15,Short_Title_16,Prerequisite_17, > Required_18,Coreq_Noncourses_19,Course_20,Cred_Type_21,SEC_CRS_DESC_22, > Long_Title_23,Depts_24,Fee_25,Meeting_Days_26,Printed_Comments_27,Subject_28, > Supplies_29,Transfer_Status_30,Course_Cost_31,Status_32,Capacity_33, > COURSE_SECTIONS_34,Corequisite_Sections_35,Section_36,Min_Cred_37, > Instr_Methods_38,SEC_FACULTY_FIRST_NAME_39,SEC_FACULTY_LAST_NAME_40, > Refund_41,CoReq_Name_42,Drop_End_43) values (?,?,?,?,?,?,?,?,?,?,?,?, > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) > > ugly eh? > well, here's an example of what I'm trying to feed this beast: > (the first row of data is col. headers, and thy insert fine. This is > actually the chunk of data the script is choking on (dic[1])) > --------------------------------------------------------------- > ('2475', '03/FA', '25000', 'AAA-010-AS01', 'AS', 'AS', '116', 'TTH', > '05:00PM', '06:50PM', '09/09/03', '10/02/03', '09/09/03', '09/09/03', > '09/26/03', 'Rameil, Lesley J', 'Aca Achieve Pre-College', '', '', '', > '1139', 'UG', "Meets the requirements of the Comprehensive Student > AssessmentSystem and the Secretary's Commission on Achieving Necessary > Sklls, as well as work and postsecondary enrollment skills. Enabes > the student to review and improve in reading, writing, matheatics, > science, and social studies in preparation for the GED tst.", > 'Academic Achievement in Pre-College', 'AAA', '', 'T', '', 'AAA', '', > 'NT', '', 'A', '35', '2475', '', 'AS01', '1.00', 'LEC', 'Lesley', > 'Rameil', '09/12/03', '', '09/26/03') > > I'm executing in this sort of fashion: > -------------------------------------- > for data in dic: > cursor.execute(insertSQL, tuple(data)) > > Error: > --------------------------------------- > Traceback (most recent call last): > File "C:\Python22\parse_flat.py", line 101, in ? > cursor.execute(insertSQL, tuple(data)) > dbi.internal-error: [Microsoft][ODBC SQL Server Driver][SQL > Server]Location: record.cpp:2253 > Expression: m_futureSize == 0 || rec.Size () == m_futureSize > SPID: 58 > Process ID: 1136 in EXEC > > so, if the column headers make into the db, it has to be the > formatting of the following data?!?! single quotes?!?! i'm fried on > this...if anyone has any input I would be very grateful. Strange error message you have there... Have you tried using mxODBC at this ? I'd bet you get much better results. -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Jul 08 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2003-07-01: Released mxODBC.Zope.DA for FreeBSD 1.0.6 beta 1 From intentionally at blank.co.uk Tue Jul 15 01:39:23 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 06:39:23 +0100 Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: <6j47hvk4levl583240qf4noi6nifemdcja@4ax.com> On Tue, 15 Jul 2003 00:40:24 -0400, Jack Diederich wrote: >Prof: No, you will know Him by his heresy, his name 'Stephen', AND his typing. so far... >Prof: And pasties, he will definitely be wearing pasties. Eh? Has this got something to do with a Monty Python sketch? From abcdebl2nonspammy at verizon.net Fri Jul 18 01:20:37 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Fri, 18 Jul 2003 05:20:37 GMT Subject: Regular expression help In-Reply-To: References: Message-ID: Bengt Richter wrote: > On Fri, 18 Jul 2003 04:31:32 GMT, David Lees wrote: > > >>Andrew Bennetts wrote: >> >>>On Thu, Jul 17, 2003 at 04:27:23AM +0000, David Lees wrote: >>> >>> >>>>I forget how to find multiple instances of stuff between tags using >>>>regular expressions. Specifically I want to find all the text between a >>> >>> ^^^^^^^^ >>> >>>How about re.findall? >>> >>>E.g.: >>> >>> >>> re.findall('BEGIN(.*?)END', 'BEGIN foo END BEGIN bar END') >>> [' foo ', ' bar '] >>> >>>-Andrew. >>> >>> >> >>Actually this fails with the multi-line type of file I was asking about. >> >> >>>>>re.findall('BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') >> >>[' bar '] >> > > It works if you include the DOTALL flag (?s) at the beginning, which makes > . also match \n: (BTW, (?si) would make it case-insensitive). > > >>> import re > >>> re.findall('(?s)BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') > [' foo\nmumble ', ' bar '] > > Regards, > Bengt Richter I just tried to benchmark both Fredrik's suggestions along with Bengt's using the same input file. The results (looping 200 times over the 400k file) are: Fredrik, regex = 1.74003930667 Fredrik, no regex = 0.434207978947 Bengt, regex = 1.45420158149 Interesting how much faster the non-regex approach is. Thanks again. David Lees The code (which I have not carefully checked) is: import re, time def timeBengt(s,N): p = 'begin msc(.*?)end msc' rx =re.compile(p,re.DOTALL) t0 = time.clock() for i in xrange(N): x = x = rx.findall(s) t1 = time.clock() return t1-t0 def timeFredrik1(text,N): t0 = time.clock() for i in xrange(N): pos = 0 START = re.compile("begin") END = re.compile("end") while 1: m = START.search(text, pos) if not m: break start = m.end() m = END.search(text, start) if not m: break end = m.start() pass pos = m.end() # move forward t1 = time.clock() return t1-t0 def timeFredrik(text,N): t0 = time.clock() for i in xrange(N): pos = 0 while 1: start = text.find("begin msc", pos) if start < 0: break start += 9 end = text.find("end msc", start) if end < 0: break pass pos = end # move forward t1 = time.clock() return t1-t0 fh = open('scu.cfg','rb') s = fh.read() fh.close() N = 200 print 'Fredrik, regex = ',timeFredrik1(s,N) print 'Fredrik, no regex = ',timeFredrik(s,N) print 'Bengt, regex = ',timeBengt(s,N) From hokiegal99 at hotmail.com Sun Jul 6 18:31:51 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sun, 06 Jul 2003 18:31:51 -0400 Subject: Using Loops to track user input In-Reply-To: References: Message-ID: You guys are great! Thanks for all the examples. Cousin Stanley wrote: > hokiegal ... > > Another way if you also wish to save the input numbers ... > > nLoops = 10 > > list_nums = [] > > for i in range( nLoops ) : > > this_num = int( raw_input( 'Enter an Integer : ' ) ) > > list_nums.append( this_num ) > > total = reduce( int.__add__ , list_nums ) > > print > print list_nums > print > print total > From harry.g.george at boeing.com Thu Jul 10 10:45:57 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 10 Jul 2003 14:45:57 GMT Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> Message-ID: schull at digitalgoods.com (Jon Schull) writes: > PyDoc's author Ka-Ping Yee has suggested that PyDoc be patched to > prevent access from unauthorized IP addresses > (https://sourceforge.net/tracker/?func=detail&atid=305470&aid=672656&group_id=5470), > and that without such a patch, its not " suitable for running on boxes > that aren't behind firewalls" > > It's hard to know how much to worry about such things (Comments?). > > However, even with the patch, IP addresses can be spoofed. Here is an > additional security tactic that might be adopted. > > The port number used by pydoc is currently set by the user at the > command line. Many people probably use the example given in the > python module documentation : "python -p 1234" However, if the port > were chosen at random and printed out, then only pydoc and the user > would know how to access the pydoc server. > > I'm considering a similar strategy for a server based on the > CGIHTTPServer module, so comments would be welcome. "Security through Obscurity" (e.g., random ports) is not the way to go. Instead, use SSL. This can be done through a CGI on Apache through an SSL'd port, or it can be done with stunnel. [Or it might even be done with raw python using pyOpenSSL or M2Crypto (which I haven't done, so I can't tell you anything that direction).] -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From doug.hendricks at tnzi.com Wed Jul 16 21:54:55 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 16 Jul 2003 18:54:55 -0700 Subject: Connecting Oracle8i to Python Message-ID: Hello, I'm a newbie to Python. In order to get much use out of it at my site, I must be able to connect it to Oracle8i databases. I'm running Python 2.2.2 on Tru64 (osf1 V5.1a). First question: What do you recommend? DCOracle2? Note that I am not running Zope or any other web software. cx_Oracle? Other? Second question (important only if you recommend DCOracle2) I can "make" DCOracle2, but I don't see any hints anywhere on how to install it on a non-zope system. If I try any obvious thing, like cp -r to lib/python2.2/site-packages, at BEST I get: > python Python 2.2.2 (#1, May 9 2003, 14:15:51) [C] on osf1V5 Type "help", "copyright", "credits" or "license" for more information. >>> import DCOracle2 Traceback (most recent call last): File "", line 1, in ? File "DCOracle2/__init__.py", line 37, in ? from DCOracle2 import * File "DCOracle2/DCOracle2.py", line 104, in ? import dco2 ImportError: dlopen: DCOracle2/dco2.so: symbol "OCILobIsTemporary" unresolved What is going on here? I think that OCILobIsTemporary is supposed to be in the Oracle8i client shared library, so maybe that library isn't getting loaded. What am I doing wrong? I've tried playing with LD_LIBRARY_PATH=$ORACLE_HOME/lib but nothing seems to work. I've even forced src/Makefile to include -rpath $ORACLE_HOME/lib . I should point out that I have other non-python apps that can use the oracle client library just fine, and > nm libclntsh.so | grep OCILobIsTemporary OCILobIsTemporary | 0004396966856416 | T | 0000000000000008 Doug From anton at vredegoor.doge.nl Wed Jul 16 15:32:41 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 16 Jul 2003 21:32:41 +0200 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: Alan Kennedy wrote: >"Time flies like an arrow, but fruit flies like a banana". > >:-D > >I'd love to hear of other similar phrases. And somehow I intuit >there's people in this ng who know lots of them :-) I don't know about automated translators, but I dare any non Dutch or German native speaker to interprete the following valid Dutch sentence: "Als achter vliegen vliegen vliegen vliegen vliegen vliegen achterna." Anton From bokr at oz.net Fri Jul 25 22:30:01 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 02:30:01 GMT Subject: Why does Python do this? References: Message-ID: On Fri, 25 Jul 2003 15:22:13 -0600, Steven Taschuk wrote: >Quoth Gre7g Luterman: > [...] >> Python 2.2.2 (#3, Jun 16 2003, 19:11:56) > [...] >> >>> class b: >> ... def __str__(self): >> ... print "printed" >> ... return "returned" > [...] >> >>> print y >> printed >> returned >> >> Note the extra space printed when I executed the "print y" command. > >I don't know why this happens in 2.2, but I observe that it >doesn't in 2.3. Presumably some softspace fix has been made. I argued hard that there was something wrong in http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=b952va%24hlt%240%40216.39.172.122&rnum=11 I wonder if those examples work now too ;-) Regards, Bengt Richter From rreagan at attbi.com Wed Jul 2 12:40:39 2003 From: rreagan at attbi.com (Russell Reagan) Date: Wed, 02 Jul 2003 16:40:39 GMT Subject: arbitrary long integer aritmetics References: Message-ID: "Fredrik Lundh" wrote > $ python > Python 2.2 > >>> import sys > >>> sys.maxint > 2147483647 > >>> 2147483647 * 2147483647 * 2147483647 > 4611686014132420609L > > (note the trailing L). Oddly, I get a different answer than you. What's the problem? $ python Python 2.2.3 (#1, Jun 19 2003, 12:10:13) [GCC 3.2 20020927 (prerelease)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.maxint 2147483647 >>> 2147483647 * 2147483647 * 2147483647 9903520300447984150353281023L From usenet_spam at janc.invalid Fri Jul 25 22:10:48 2003 From: usenet_spam at janc.invalid (JanC) Date: Sat, 26 Jul 2003 02:10:48 GMT Subject: Python and VS.Net References: Message-ID: Marc Wilson schreef: > Borland are said to be working on Delphi.NET An "experimental" Delphi.NET compiler is included with Delphi 7. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From h.goebel at crazy-compilers.com Mon Jul 28 06:47:36 2003 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Mon, 28 Jul 2003 12:47:36 +0200 Subject: Tokenize In-Reply-To: References: <8%VTa.133$313.72262@news.uswest.net> <3F203257.AD0A4B30@hotmail.com> Message-ID: <3f24ff48$0$12995$9b4e6d93@newsread4.arcor-online.net> Andrew Dalke schrieb: > Another option is the little-known 'shlex' module, part of the standard > library. ... > As you can see, it treats '-' unexpectedly (compared to the shell). This is why shellword was written (see ) Regards Hartmut Goebel -- | Hartmut Goebel | We build the crazy compilers | | h.goebel at crazy-compilers.com | Compiler Manufacturer | From castong at mathstat.concordia.ca Wed Jul 30 12:46:43 2003 From: castong at mathstat.concordia.ca (Danny Castonguay) Date: Wed, 30 Jul 2003 12:46:43 -0400 Subject: Syntax: pointers versus value Message-ID: <3F27F673.3000801@mathstat.concordia.ca> Simple question but I can't find the answer. Using an example: listA = [1 ,2] listB = listA listB.append(3) #listA now is [1,2,3] I want to avoid listA's value to change. Clearly, "listB = listA" creates the problem. listB and listA become two pointers to the same object. How then, do I duplicate the two objects; ie make a copy of the object that listA is pointing to and have listB point to that object. I'm new to python and I love it. Thank you, From paul at boddie.net Mon Jul 14 12:31:10 2003 From: paul at boddie.net (Paul Boddie) Date: 14 Jul 2003 09:31:10 -0700 Subject: Using xml.xpath question. References: <23891c90.0307110057.bbe91e3@posting.google.com> Message-ID: <23891c90.0307140145.8d9ff70@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > > A very nice and helpful Paul Boddie in action on c.l.p. Glad to be of some help. ;-) > But OMFG! Object Management F Group? > Here we see why we need a good *high* level XML library in > the Python Standard Library. The effbot is doing great work with > elementtree at www.effbot.org, but he is doing that all alone. I > think a good high level XML library should have a very high priority > for Python. This is argued for a lot, but I don't really see total acceptance until the PyXML people get on board. They seem to be managing well enough, and whilst one might argue that the PyXML APIs are too highbrow for the rest of the community, no-one using PyXML for serious XML processing is going to adopt the mythical "Pythonic" API that everyone is talking about unless it does the business for them as well. > It should be a much higher priority for the core Python developers > than the extensions I have seen lately. Booleans, bah! I don't want to get dragged into another debate on core language enhancements. :-) I suppose once Python 2.3 is released, we may well see more focus on the libraries. > And for instance, I hate it to make my code unreadable using list > comprehensions and other syntactic sugar; and then later having to > explain it to a C programmer. "Ha!" she says, "You claimed the Python > language reads like pseudocode!". Geez. Actually, list comprehensions are very readable... to a mathematician. Seriously, though, I'm using them a lot more than map/filter/reduce these days, but I can't see a real need for the language runtime to go beyond generators for the time being, although I'll surely get branded as being "short-sighted" for saying that. Paul From maxm at mxm.dk Wed Jul 2 02:28:28 2003 From: maxm at mxm.dk (Max M) Date: Wed, 02 Jul 2003 08:28:28 +0200 Subject: Good code patterns in Python In-Reply-To: References: Message-ID: <3f027b11$0$97204$edfadb0f@dread12.news.tele.dk> Michael Chermside wrote: > Will Stuyvesant writes: > >>If you know that your source code is going to be used >>later by others, then I feel that code with the pattern: >> >> if some_condition: >> some_name = some_value >> else: >> some_name = other_value >> >>is often a mistake. Much better, safer, would be: >> >> some_name = some_value >> if not some_condition: >> some_name = other_value > > I disagree with you... I think that the first form is superior > to the second. Here are two reasons. > > My number one reason is readability. Seeing "some_name = some_value" > when some_name is ACTUALLY going to take on other_value is very > misleading to the reader. If a programmer has a hard time reading the first version, he really should have another job ;-) You cannot expect to know from any program what value a variable has from a cursory glance. And there are many times where it is the prefered idiom. Like: result = [] if something: result.append(stuff) if something_else: result.append(stuff) return result Another example: url = self.url http = 'http://' if url[:len(http) != http url = http + url return url The "first" form is not an unusual pattern to see in programmes. And I prefer it myself, as it prevents small stupid mistakes better than the "second" form. The first form frequently mutates into nested code like: if some_condition: some_name = some_value else: if some_exotic_condition: some_name = other_value Where it can be pretty obscure what value a variable has, and if it is assigned one at all. And you have to make shure to set the "default" value in all itterations of the code. if some_condition: some_name = some_value else: if some_exotic_condition: some_name = third_value else: some_name = other_value It would have been a simpler and less error prone procedure to change the code if it it had used the first form. some_name = other_value if some_condition: some_name = some_value else: if some_exotic_condition: some_name = third_value regards Max M From abelikov72 at hotmail.com Tue Jul 8 13:11:58 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 08 Jul 2003 17:11:58 GMT Subject: Python vs PHP References: Message-ID: On 8 Jul 2003 16:47:35 GMT, Jon Ribbens wrote: >In article , Afanasiy wrote: >>>Try jonpy (http://jonpy.sf.net/), it solves all of the above. >>>Also you may find FastCGI (which jonpy supports) helps with your >>>"safe mode" problem, although it might require a bit of hackery. >> >> No, CGI is not an option and I tried jonpy. I kept my notes about it... > >The only similarity between FastCGI and CGI is the name. FastCGI is >just as fast, if not faster, than mod_python in my experience. jonpy >lets you use CGI or FastCGI or mod_python interchangeably anyway. CGI, FastCGI, SCGI are not faster than mod_python in my experience and straightforward benchmark. That's all I can really say about it. CGI is not an option for me. From tjreedy at udel.edu Thu Jul 17 14:23:50 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 14:23:50 -0400 Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> <3f156c23$0$166$a1866201@newsreader.visi.com> Message-ID: "Grant Edwards" wrote in message news:3f156c23$0$166$a1866201 at newsreader.visi.com... > Yup. I found a lot of things in FORTRAN surprising. Python is > so much nicer in that respect. Though I was recently surprised > that the remove() method for lists uses "==" and not "is" to > determine what to remove. It's documented that it works that > way. But, it wasn't what I excpected, and it took me a while to > figure out that it was using my class's __cmp__ method rather > than the object ID. Given ints = [9, 99, 999, 9999] would it not surprise you even more if ints.remove(99) worked and ints.remove(999) did not, or even worse, if the behavior of ints.remove(99) depended on the implementation? (Similar examples apply to strings, where the implementation of interning and hence behavior based on identity *has* changed!) Terry From adechert at earthlink.net Mon Jul 21 17:27:15 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 21:27:15 GMT Subject: Voting Project Needs Python People References: Message-ID: "Harry George" wrote in message news:xqxwuebfyym.fsf at cola2.ca.boeing.com... > I was curious why http://www.notablesoftware.com/evote.html wasn't > mentioned. I had the impression that was an early (and continuing) > portal for these issues. > Rebecca Mercuri and Peter Neumann are not part of this project. I spent a lot of time talking with Neumann 12/00 - 1/01 (met him in person 12/17/01 at state Assembly Elections Committee hearings in Sacramento). They have a competing idea that would be much more expensive (dedicated DRE voting machine with printer under glass so the voter can see it but can't touch it). Frankly, I don't see their idea going anywhere. The serious competition we've had has been the Caltech-MIT project. They started with a grand idea but fizzled. At the top of the 12/14/00 Caltech/MIT press release about a "Uniform Voting System," the presidents of MIT and Caltech were announcing "a collaborative project to develop an easy-to-use, reliable, affordable and secure United States voting machine." And they said, "America needs a uniform balloting procedure." They certainly had the right idea, but I had already said the same thing and had gone a step further to say that the machine should be PC based and open source. Part of the reason we had difficulty getting funding in 2001 was because people told us (some important people, that is, holding some big purse strings) that they thought Caltech-MIT were already set to do what we proposed. However, it turns out that while they started with a great idea, the team assigned to carry on the project never embraced the idea of a uniform system! They set about to work with vendors. I don't know about you, but it seems obvious to me that vendors would never really get behind a uniform system. Afterall, the way the make money is with proprietary systems that compete with a bunch of other proprietary systems. They each have their niche. Caltech-MIT underestimated the problem -- especially the political aspect. I don't see their project going anywhere. I mean, people can say I've gotten nowhere in 2.5 years but I never had any money. They had lots of money but bad clues. We don't plan to work with existing election vendors. I see a new crop of election vendors we can cultivate from PC remarketers. 25 million PCs are retired every year in the U.S. and remarketers are always looking for ways to get a few extra dollars for what they get for practically nothing. I have already contacted some remarketers and they like our idea. For example, Jay at Isis Technology would love to become an election vendor. http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=2738670471&category=31502 > Is the intent to do opensource all the way to commodity chips? Else a > proprietary BIOS could be the weak link. > No, we won't go that far. But we will have software to validate the system on bootup. Bennet Yee of UCSD is one of the leading experts on this subject. The Trusted Computing Group is also working on technology that may be applicable: https://www.trustedcomputinggroup.org/home Alan Dechert From bkc at Murkworks.com Tue Jul 29 10:58:00 2003 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 29 Jul 2003 10:58:00 -0400 Subject: Any Software can Python <-> Delphi ? References: <_icVa.1123902$ZC.164425@news.easynews.com> <3F2588C1.8FE0C79B@easystreet.com> Message-ID: "Thomas Heller" wrote in message news:adaxg6gy.fsf at python.net... > achrist at easystreet.com writes: > You could write a small, fake module importing the stuff that the > library needs. If you then run py2exe with the -k (--keep-temp) option, > it doesn't delete its own build tree. You will find there a xxx.zip > file, containing all the modules needed (plus a few scripts which you > can ignore). If you use Python 2.3, just add the zip-file's name to > sys.path, and you are done. That's what I need too, thanks for posting this info. I have an DLL that embeds and extends Python23.dll, but I want to package up all the "standard python .py" as .pyo files in a zip and I'm looking for an easy way to resolve imports. This looks like it will get me most of the way there! From manish.j at gmx.net Fri Jul 25 16:24:48 2003 From: manish.j at gmx.net (Manish Jethani) Date: Sat, 26 Jul 2003 01:54:48 +0530 Subject: How to detect typos in Python programs In-Reply-To: <3F214977.AEB088C8@engcorp.com> References: <3F214977.AEB088C8@engcorp.com> Message-ID: Peter Hansen wrote: > Manish Jethani wrote: > >>Is there a way to detect typos in a Python program, before >>actually having to run it. Let's say I have a function like this: >> >> def server_closed_connection(): >> session.abost() >> >>Here, abort() is actually misspelt. The only time my program >>follows this path is when the server disconnects from its >>end--and that's like once in 100 sessions. So sometimes I >>release the program, people start using it, and then someone >>reports this typo after 4-5 days of the release (though it's >>trivial to fix manually at the user's end, or I can give a patch). >> >>How can we detect these kinds of errors at development time? >>It's not practical for me to have a test script that can make >>the program go through all (most) the possible code paths. > > > You have no good alternative. Why do you say it's impractical > to actually test your software before it's shipped? Isn't it > more impractical to rely on your users to test the software, > thinking it should work? I get your point. But my program is basically open source, so I release early and often, and I expect users to report bugs. BTW a lot of big software houses I know of also do the same thing, but their marketing departments like to put things in a different way ("time to market", "beta release", and stuff like that :-) ). Call my release an alpha, beta or whatever. But I expect users to report "real bugs", not typos. So I thought there should be a better way to catch these things (I saw pylint and pychecker, and they look good). > Unit testing in Python is *really* easy. I can't think of any > reason not to do it as the best way of catching problems like you > show above. If you resist :-), however, you might find PyChecker > will help. I'm not sure if it can do anything in the above case > yet, however. Actually I am writing a client app for a proprietary service. The server is not under my control, so I can't make it behave in a way that will cause every part of my client code to be tested. As I mentioned, for example, I have a function to handle a server-disconnect. But the server rarely ever disconnects of its own, so the function never gets called in reality. Can I unit test this function easily? FYI: The program in question is msnp.py. thanks, -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From P.Schnizer at nospam.gsi.de Fri Jul 4 02:58:25 2003 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 04 Jul 2003 08:58:25 +0200 Subject: how to pass a file descriptor in a swig module References: <871xx82h0t.fsf@smtp.gsi.de> Message-ID: <87k7ay3him.fsf@smtp.gsi.de> Pierre Schnizer writes: > "kj.kjn" writes: > > > My function func(File * des) is embedded in a module swig. > > > > I would to know how to call this function from python script and if it's > > necessay > > > > to declare a typemaps ? > > > > Thank you Sorry I think I misunderstood you. In case you want to pass a file to swig you need a typemap: /* * Type mapping for grabbing a FILE * from Python * Taken from the Swig documentation ... */ %typemap(python,in) FILE * { if (!PyFile_Check($input)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); goto fail; } $1 = PyFile_AsFile($input); } Please note that this typemap is for swig1.3. In case you are using swig1.1 you should replace $1 with $result and "goto fail" with return NULL (which can leak memory ). Pierre From phil at riverbankcomputing.co.uk Tue Jul 29 19:18:32 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 30 Jul 2003 00:18:32 +0100 Subject: PyQt Help and Advice In-Reply-To: References: Message-ID: <200307300018.32770.phil@riverbankcomputing.co.uk> On Tuesday 29 July 2003 4:17 pm, Ilya Knizhnik wrote: > Dear All, > > I am fairly new to Python. I have found it an easy language to learn and > a very usefull one for many tasks. Currently I am working on a python > project that involves a GUI and it was suggested that PyQt is the best way > to design that GUI. > However since PyQt is rather new, I have not found much documentation on > it, or examples in it. The only useful tutorial/book I have found is at > www.opendocspublishing.com/pyqt/ but it is not always clear for someone > with almost no GUI experience. > Does anyone have any suggestions? > > Ilya To correct one misconception... PyQt was first released on November 1st 1998. There have been 34 releases in all. The next release, including support for Qt v3.2.0, will be around August 12th. It isn't new. Phil From bhv1 at psu.edu Tue Jul 15 18:48:09 2003 From: bhv1 at psu.edu (Brian Victor) Date: Tue, 15 Jul 2003 22:48:09 GMT Subject: Distutils gcc error References: Message-ID: Following up to myself for googling purposes. Brian Victor wrote: > wxlibs = commands.getoutput("wx-config --libs") > wxcxxflags = commands.getoutput("wx-config --cxxflags") > > bwaaext = Extension("bwaascalec", ["src/bwaa.cc", "src/bwaascale.cc"], > include_dirs=["src"], > extra_link_args=[wxlibs], > extra_compile_args=[wxcxxflags]) The compiler was taking the chunk of arguments returned by wx-config as one large, nonsensical argument. This is solved by using: extra_link_args=wxlibs.split(), extra_compile_args=wxcxxflags.split()) -- Brian From duncan at NOSPAMrcp.co.uk Wed Jul 16 05:55:16 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 09:55:16 +0000 (UTC) Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: pythonguy at Hotpop.com (Anand Pillai) wrote in news:84fc4588.0307152253.20858619 at posting.google.com: > Hi Pythonistas, > > I have placed a quiz on Python on the trivia site www.funtrivia.com. > Here is the link. > > http://www.funtrivia.com/quizdetails.cfm?id=139672 > > Looks like it is the first quiz on Python on this site. > > Please try it out if you like quizzing. > Let me know if there are any factual errors. > I think that questions 4 and 8 leave something to be desired. At this year's ACCU conference, Guido talked somewhat about the history of Python. He said it was based on ABC, "other influences: Modula-3, C/C++ and even Smalltalk, Icon, Pascal, Algol-68". By my reckoning that makes two of the answers to question 4 correct. On question 8, I'm not aware that Python borrowed anything from Java. Since it predates Java he couldn't have borrowed anything on day one (does anyone remember when Guido first got the time machine working?[1]), although admittedly the language has evolved since then. I suspect the object oriented similarities come more from a common ancestry. At the same talk as above he listed Lisp as an anti-influence, so it isn't clear to me whether lambda &c. were borrowed from CLISP as you claim or from functional programming generally. OTOH I can't exclude Fortran as an (indirect) influence. If the syntax for assignment isn't ultimately borrowed from Fortran, where did it come from? [1] First Python reference to a time machine I can find is Paul Prescod in April 1998 proposing its construction, although it was obviously fully operational by September 1998. -- 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 jcc at ibdosnorte.com Thu Jul 3 07:17:00 2003 From: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) Date: 3 Jul 2003 04:17:00 -0700 Subject: Automation wrapped xmlrpc Server Message-ID: Hello all, I'm trying to create a COM Server with an embedded xmlrpc server. Here is way it must work: - The client application (programmed with a COM capable language) instantiates my COM server (programmed with python). - The COM server must have a connect interface in order to let the client application process the xmlrpc request. - After executing a "serveforever" method on the COM server it begins to listen on a configured port for xmlrpc requests. - When the COM server receives a xmlrpc request it passes this request to the client application event (connect interface) in order to process it. - The client application processes the request and returns a result to the COM server. The COM server returns this result to the xmlrpc requester. So, I must say that I have programmed some COM servers in python with the aid of Mark's book, but in this case I have some problems: - Must I instantiate a new thread for the xmlrpc server? - If the xmlrpc server is a different thread how can this thread call the _BroadcastNotify method from the main thread (the COM server)? - I have successfully called the _BroadcastNotify method from the main thread, but I become a strange behaviuor calling it from other thread. - I tryied to pass the calling object reference to the xmlrpc thread, so the xmlrpc thread has a reference to the _BroadcastNotify method, but it does not work correctly. Here is part of my code (I have deleted some parts): class xmlrpcServer(Thread): def __init__(self, mainthread, host, port): Thread.__init__(self) self.host = host self.port = port self.mainthread = mainthread def run(self): while 1: # the following line simulates the reception # of a xmlrpc request request = xmlrpcRequest('testmethod', [n, 'parameter2']) wrapped = wrap(request, useDispatcher=useDispatcher) self.mainthread._BroadcastNotify(self.mainthread.NotifyCall, (wrapped,)) class COMServer(ConnectableServer): _public_methods_ = ['Serve'] + ConnectableServer._public_methods_ _connect_interfaces_ = [IID_IxmlrpcEvents] def __init__(self): ConnectableServer.__init__(self) self.Host = '' self.Port = None def Serve(self): # method Serve #req = xmlrpcRequest('testmethod', ['parameter1', 23]) #wrapped = wrap(req, useDispatcher=useDispatcher) #self._BroadcastNotify(self.NotifyCall, (wrapped,)) #req = unwrap(wrapped) self._s = xmlrpcServer(self) self._s.start() def NotifyCall(self, interface, arg): interface.Invoke(1000, 0, pythoncom.DISPATCH_METHOD, 1, arg) class xmlrpcRequest: # wraps a xmlrpc request as a COM object in order to pass it to # a client event _public_methods_ = ['Method', 'Parameter', 'Result'] def __init__(self, method, parameters): self.Result = None self._method = method self._parameters = parameters If I call the _BroadcastNotify method directly from the Serve method, it works correctly. Has anybody examples of a similar COM server? Helps will be appreciated. Thank you. From bokr at oz.net Thu Jul 31 18:37:25 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2003 22:37:25 GMT Subject: Python speed vs csharp References: Message-ID: On 31 Jul 2003 08:29:26 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >Mike writes: > >> My first question is, why is the Python code, at 210 seconds, so much >> slower? > >One would have to perform profiling, but in this case, it is likely >because numbers are objects in Python, so each multiplication results >in a memory allocation. In addition, as soon as the parameters of the >multiplication are not needed anymore, you get a deallocation of the >temporaries. > >There is also an overhead for the byte code interpretation, but this >is likely less significant. > >> My second question is, is there anything that can be done to get Python's >> speed close to the speed of C#? > >C# implementations typically do just-in-time compilation to machine >code. They represent numbers as primitive (machine) values, directly >using machine operations for the multiplication. Doing the same for >Python is tricky. > >I recommend that you try out Python 2.3. It has significantly improved >memory allocation mechanisms, so you should see some speed-up. > >You could also try Psyco, which is a just-in-time compiler for >Python. It should give very good results in this case, also. > I just made a C extension out erfc and only got about 5-6 times improvement over the python version, which makes me think that most of the time is in call setup and passing parameters, which as you say involves memory allocation/deallocation. I don't see that csharp could improve on that. The benefit would really only show up fullfledged if the calling loop is using C calling methods, as in numeric array processing that only makes one call from python and many in C, depending on arrary dimensions. I wonder what it would take to have the Python VM do primary allocation of ints and doubles on the stack C-style and only migrate them to heap if/when exported. Then you could bypass exporting when calling a trusted C extension, and in a case like erfc you could just make the raw C call and replace the value on top of the stack, and go on from there until you hit an export trigger. Regards, Bengt Richter From tjreedy at udel.edu Sat Jul 5 16:44:47 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Jul 2003 16:44:47 -0400 Subject: Calculating Year, Month and Day of Life References: Message-ID: > My problem is that localtime is a list of 9 integers while age is a list > of 3 integers. Is it possible to make localtime() only return the first > 3 integers? No, but you can easily slice out what you want -- localtime()[0:3] -- or wrap it with a function that does the same -- def localymd(): return localtime[0:3]. > If so, how would I then do calculations on the two lists' > individual parts? For example, how would I instruct localtime() to > subtract the first integer from age's list from the first intger in its > own list (2003 - 1934)? The mathematical approach is to convert both ymds to Julian days and subtract to get number of days of life. But since 'month' does not have a fixed number of days, it is hard to convert back to get the commonly expected answer for (y,m,d)s of life. So you need to do the subtraction the way it is commonly performed or at least the way you want it to be (The problem is to figure out what to do when you need to 'borrow' a month in order to subtract days.) > Also, I am new to python, but I like it a lot and have picked it up squickly Welcome. Terry J. Reedy From matthias.oberlaender at REMOVE.daimlerchrysler.com Wed Jul 2 07:53:10 2003 From: matthias.oberlaender at REMOVE.daimlerchrysler.com (Matthias Oberlaender) Date: 2 Jul 2003 11:53:10 GMT Subject: cooperation of buitlin methods usingtsuper Message-ID: I would like to adopt the cooperation paradigm in conjunction with builtin methods and operators, such as len, iter, +, * etc. But the direct approach does not work with the current implementation of super. For example, 'len(super(Y, y)' will always result in 'len() of unsized object'. As far as I understand, this is because builtins don't use a dynamic lookup chain, but go directly to the slots for the builtins. However, super returns an instance of class 'super'. Since all super objects share this class, its slots will not be filled as one might hope. My workaround is this: I create a subclass of 'super' on the fly each time I call 'mysuper'. Look at the definition below. It seems to work. But maybe I have overlooked something. Is my understanding correct? Is 'mysuper' a good solution? Possible improvements? (e.g. caching of subclasses) Thanks for comments! import new class X(object): def __len__(self): return 2222 class Y(X): def __len__(self): return 1111 def mysuper(cls, inst): return new.classobj('mysuper', (super,) + cls.__bases__, {})(cls, inst) y = Y() try: print len(super(Y, y)) except Exception, msg: print msg try: print len(mysuper(Y, y)) except Exception, msg: print msg Output: len() of unsized object 2222 -- ____ __ _/_/ . ( / / ( / / / / ===================================================================== Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm RIC/AP (Machine Perception) Wilhelm-Runge-Str. 11, P.O. Box 2360, 89013 Ulm, Germany Phone: +49 731 505 2354 Fax: +49 731 505 4105 Email: matthias.oberlaender at VOID.daimlerchrysler.com ===================================================================== From seberino at spawar.navy.mil Thu Jul 31 18:42:47 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 31 Jul 2003 15:42:47 -0700 Subject: Python+GTK thread question (program freezing)... Message-ID: We have a program that uses threads. If we DON'T run the GTK+ GUI code then multitasking is fine and every thread gets a little CPU time. If we run a GTK+ GUI in the main parent process/thread then program freezes. The PyGTK commands called gtk.threads.thread_enter() and gtk.gdk.threads_leave() are used to avoid conflicts caused by two threads writing to GUI at the same time. The disallow/allow other threads to write to GUI as needed. It would seem that the problem are with these two commands but the guys cannot seem to find the problem. As you know, threads are not the easiest things to debug. I don't want to think Python threads are unstable. Are they?? Any ideas at all how to begin to solve this? Chris From skip at pobox.com Mon Jul 28 08:31:16 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 07:31:16 -0500 Subject: The protection of resources In-Reply-To: References: Message-ID: <16165.6036.893322.744042@montanaro.dyndns.org> Krisztian> So these my questions: Krisztian> - 1. How to use the py mutex object ? Please send an example Krisztian> to me ! Krisztian> - 2. Have the py an signal object ? (platform !!!) Krisztian> - 3. Is any solution is a file locking. Have the py a Krisztian> possibility of exclusive file opening ? Yes. Look at the docs for os.open. There's an EXCLusive flag which should work on Windows as well as Unix I think. This will work across processes as well a threads, but see below if all you're interested in is a single multi-threaded application. I think you'll often find it easier to use the Queue object to protect shared resources. Just create the queue and put() the shared resource on the queue, then get() it when you need it and put() it back when you're done with it. Skip From giles_brown at hotmail.com Thu Jul 10 03:50:53 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 10 Jul 2003 00:50:53 -0700 Subject: Deleting specific characters from a string References: <5ab0af73.0307091044.254f5aab@posting.google.com> Message-ID: <57de9986.0307092350.a373dd0@posting.google.com> Behrang Dadsetan wrote in message news:... > >>> str = 'You are Ben at orange?enter&your&code' > >>> str.translate(string.maketrans('',''), '@&') > and > >>> str.replace('&', '').replace('@', '') > are also ugly... Well beauty is in the eye of the beholder they say. Has anybody mentioned the re module yet? >>> s = 'You are ben at orange?enter&your&code' >>> import re >>> re.sub('[@&]', '', s) 'You are benorange?enteryourcode' Giles From garth at deadlybloodyserious.com Wed Jul 30 20:28:20 2003 From: garth at deadlybloodyserious.com (Garth T Kidd) Date: 30 Jul 2003 17:28:20 -0700 Subject: Ver 2.3 install over 2.2? References: Message-ID: <4c877253.0307301628.7d73a1a6@posting.google.com> > You have to reinstall all of them. Actually, you might need to rebuild > them, as extension modules need to be recompiled. Make sure you have VC6 installed, else you'll be unable to build extensions for Python23. VC7 worked for building Python22 extensions, but no longer (and if anyone can explain why, I'd love to know). error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. I'm reinstalling 2.2.3 so I can keep developing with Reportlab until I can get hold of VC6 or a fix for 2.3. From ulope at gmx.de Tue Jul 22 15:41:57 2003 From: ulope at gmx.de (Ulrich Petri) Date: Tue, 22 Jul 2003 21:41:57 +0200 Subject: Is there a way to access/modify/add variables to caller from a sub function References: <3f5dc178.0307220913.62a7e92f@posting.google.com> Message-ID: "Anand" schrieb im Newsbeitrag news:3f5dc178.0307220913.62a7e92f at posting.google.com... > Is there a way to access/modify variables of a caller function from > within a sub function call? > > Function A: Calls subFuncB: > > var x Add var xx in Function A's name space?? > var y > var z def funcB(foo): return foo*1, foo*2, foo*3 def funcA(): f1,f2,f3 = funcB(1) Ciao Ulrich From ray at rays-web.com Thu Jul 10 19:50:16 2003 From: ray at rays-web.com (Ray Smith) Date: 10 Jul 2003 16:50:16 -0700 Subject: Getting Started with python References: <3f0d2cb9$1@news.comindico.com.au> Message-ID: <5654fff9.0307101550.51012bf1@posting.google.com> "Tony Steward" wrote in message news:<3f0d2cb9$1 at news.comindico.com.au>... > Hello All, > Ok i've decided to try Python can anyone point me at a simple demo of a > windows program operating a database (maybe an address book) so I can see > how it is done. Hi Tony, (From Euphoria fame???) Your question is a good one but the answer probably isn't the one you want to hear!!! First there are many GUI libraries available and many database access techniques and libraries available. I suggest you research each seperately. For GUI the main ones seem to be Tkinter (comes with Python by default), wxPython (at wxPython.org) and PyQT (requires money for commercial use). Everyone has their personal choice - I like wxPython. Pretty well every DB available has a Python lib available to access them. Most use the DB-API specs available at: http://python.org/topics/database/ I persoanlly like pySQLite for the small single user projects. Firebird, MySQL and Postrges(*nix only at this time) all seem like fine choices when more power is required. Searching the news group will find many many discussions in the past about which GUI or DB library is best for different projects / people. I search using google: http://groups.google.com/groups?hl=en&group=comp.lang.python "If" your just learning Python I'd also suggest you look at some basic programming techniques before trying to write a full blown application. I found "How to think like a computer scientiest with Python" as a good freely downloadable book. http://www.greenteapress.com/thinkpython/ To compare Python to Euphoria (assuming your the Tony i think you are!!) ... I found Python a little more difficult to get to grips with as there are many more options available, the biggest hurdle probably is deciding on which GUI you will use, and then which DB you will use. Let me know how you go. Regards, Ray Smith From ianb at colorstudy.com Thu Jul 10 22:07:22 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Jul 2003 21:07:22 -0500 Subject: Securing 'pickle' In-Reply-To: References: Message-ID: <1057889242.9505.1350.camel@lothlorien> On Thu, 2003-07-10 at 20:20, David McNab wrote: > I'm writing a web app framework which stores pickles in client cookies. > > The obvious security risk is that some 5cr1p7 X1ddi35 will inevitably try > tampering with the cookie and malforming it in an attempt to get the > server-side python code to run arbitrary code, or something similarly > undesirable. > > To protect against this, I've subclassed pickle.Unpickler, and added > overrides of the methods load_global, load_inst, load_obj and find_class. A much easier way to secure your pickle is to sign it, like: cookie = dumps(object) secret = 'really secret!' hasher = md5.new() hasher.update(secret) hasher.update(cookie) cookie_signature = md5.digest() You may then wish to base64 encode both (.encode('base64')), pop them into one value, and you're off. Though I suppose at that point you may be hitting the maximum value of a cookie. Hidden fields will work nicely, though. Decoding and verifying is an exercise left to the reader. Ian From usenet_spam at janc.invalid Tue Jul 22 22:56:11 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 23 Jul 2003 02:56:11 GMT Subject: [OT] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) schreef: > ComputerWorld says that SCO is going to charge Linux end users a > license fee for "the opportunity to run Linux legally." This might be interesting "news" for SCO/Caldera: Don't know how they can ask money for stuff one of their employees co-wrote & published under the GPL *with* their permission... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From donn at u.washington.edu Wed Jul 23 15:09:56 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 23 Jul 2003 12:09:56 -0700 Subject: How to disable spawnv's child process output messages References: <1058938603.850678@yasure> Message-ID: In article , nushin2 at yahoo.com (nushin) wrote: > Hi Donn. Thanks for your response. Yes, in this case my parent process > is hello_moon.py that is spwaning the child process, hello_earth.py. I > am simply printing a hello world from each process and do not wish to > see any output messages from the child process, and i *have to* see > the output from the parent process, hello_moon.py > > Could you please elaborate more on how i can use dup2( ) to disable > the output of the child process spawned by spawnv( ) API? It can't be done - as I said, spawnv can't do any kind of redirection, and that is what it would take. Donn Cave, donn at u.washington.edu ----------------------------------- > "Donn Cave" wrote in message > news:<1058938603.850678 at yasure>... > > Quoth nushin2 at yahoo.com (nushin): > > | I have a program called hello_earth.py that is spawned by > > | hello_moon.py, using spawnv( ) API as: > > | > > | os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello_earth.py'),('>/de > > | v/null > > | &')) > > | > > | I do not wish to see any output messages from the hello_earth.py when > > | it is launched by its parent process and i do wish to see *only* the > > | output messages from the parent process in the shell. Is Python > > | capable to so such a thing? > > > > What is the parent process in the shell? You mean the one that calls > > spawnv()? If so - yes, Python can do that. But not so easily. You > > can look at how spawnv is implemented (it's in Python), and read up > > on the dup2 function (man 2 dup2) to see what's needed. spawnv can't > > do any kind of redirection. I think I posted an example here a couple > > weeks ago. > > > > Or you can use the shell, more or less the way you were going but you > > never invoked it - > > os.spawnv(os.P_NOWAIT, '/bin/sh', ['sh', '-c', 'python hello_earth.py > > > /dev/null']) > > > > which is really about the same as > > os.system('python hello_earth.py > /dev/null &') > > > > Donn Cave, donn at drizzle.com From mwh at python.net Mon Jul 14 06:32:01 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Jul 2003 10:32:01 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <5tn2hvgjqlqg1qs7omvugpvm62cuso261k@4ax.com> Message-ID: <7h3smp9o16l.fsf@pc150.maths.bris.ac.uk> Stephen Horne writes: > On Sun, 13 Jul 2003 05:50:46 -0600, Dave Brueck > wrote: > > >But the method for returning more than one thing is not a simple progression > >from this pattern. Instead you learn and shift to a *completely* different > >mechanism. In Python, however, you *can* continue along the original route as > >well: > > > >def foo(a, b, c): > > return a+b, b+c > > You are not directly returning multiple values - you are returning a > tuple. You can return containers in C++ too. The only difference is > that Python makes working with tuples *much* easier - but its no more > a 'simple progression' than in C++. You still need to know about > tuples as well as returning values. Actually, at one stage in Python's development it was almost completely symmetric: you (always) passed in a tuple, and could optionally return a tuple. The syntax made it look a bit like you were passing in multiple arguments, but under the hood a tuple was what you were passing, and there were ways in which this showed up. IIRC, f((a, b)) and f(a, b) were indistinguishable from inside f. This was all long before I came across python, so I may be getting things mixed up... Cheers, M. -- Roll on a game of competetive offence-taking. -- Dan Sheppard, ucam.chat From not.valid at address.org Thu Jul 3 15:16:53 2003 From: not.valid at address.org (YoTuco) Date: Thu, 03 Jul 2003 19:16:53 GMT Subject: Py + CGI or other ? References: Message-ID: Krisztian Kepes wrote: > Hi ! > > I want to substitute/replace my php site to python, 'cause > I fall in love with Python, and not want to continue the work with php. > > A question: > - how to I make the change ? > So, I take an interest in Python+Web. Where I starting this learning ? > > 1. > I use php used in module, not in cgi ? > The python can load to apache in module ? > > 2. > Or I must create an CGI library ? > > 3. > The BaseHTTPServer is good for starting an cgi development ? > > 4. > Can the python handle the session of web browsers ? > > 5. > Can the python access other db servers (not mysql) ? > > Thx: > KK I think www.python.org --> documentation and http://www.python.org/topics/web/ has a lot of your answers. 1. Yes, mod_python. Compile Python with no threads. 2. That is one option. And I think there is a Python fast cgi module, too. 3. If it can do forms as a default, why not. 4. Don't know. 5. Yes From csad7 at yahoo.com Wed Jul 23 05:31:10 2003 From: csad7 at yahoo.com (christof hoeke) Date: Wed, 23 Jul 2003 11:31:10 +0200 Subject: python startup on XP very slow References: Message-ID: Tim Peters wrote: > [christof hoeke] >> for some days now i have problems with python taking a lot of time to >> start up or run programs. > > What did you change on your system some days ago? That is, things > were fine, at some point they got worse, and what changed between > those two times? > >> today i installed the python 2.3rc1 but still the same problem. > > That's just more evidence that it's got nothing in particular to do > with Python. > >> e.g. starting pythonwin 1.53 on winXP (athlon 1200 with 512MB) which >> normally took only a few seconds now takes at least 15-20 seconds. >> >> has anybody had a similar problem or knows where the delay comes >> from? > > I don't, and don't know. Common culprits for things "like this" > include updates to virus scanners and firewall software -- anything > that sticks its nose into other processes' business. So you can try > killing other processes, one at a time, and see how that affects > Python startup time. hi Tim, thanks, i simply did not think... i have a virus scanner and firewall installed which does frequent updates on it own. seems now it is blocking python somehow. if anyone is interested, i have BitDefender and Murphy Shield installed. if Murphy Shield is turned off python is at its normal speed. thanks again chris From gh at ghaering.de Thu Jul 17 11:47:30 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 17 Jul 2003 17:47:30 +0200 Subject: Unicode question Message-ID: <3F16C512.2040503@ghaering.de> >>> u"???" u'\x84\x94\x81' (Python 2.2.3/2.3b2; sys.getdefaultencoding() == "ascii") Why does this work? Does Python guess which encoding I mean? I thought Python should refuse to guess :-) -- Gerhard From jepler at unpythonic.net Sun Jul 13 12:32:39 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 13 Jul 2003 11:32:39 -0500 Subject: installing python library modules (general question) In-Reply-To: <79ad5955.0307122013.6780fc53@posting.google.com> References: <79ad5955.0307122013.6780fc53@posting.google.com> Message-ID: <20030713163239.GC32319@unpythonic.net> Add /usr/local/lib to the list of directories in /etc/ld.so.conf and then execute /sbin/ldconfig to create some needed symlinks in /usr/local/lib. Jeff From john_bradbury at ___cableinet.co.uk Sun Jul 6 16:54:03 2003 From: john_bradbury at ___cableinet.co.uk (John Bradbury) Date: Sun, 6 Jul 2003 20:54:03 +0000 (UTC) Subject: Server Push References: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> Message-ID: Thanks for the info, I will look into it. "Van Gale" wrote in message news:CbtNa.5$Dj1.957478 at newssvr15.news.prodigy.com... > Irmen de Jong wrote: > > John Bradbury wrote: > > > >> I want to send updates from a long running cgi. I have tried copying > >> perl > >> examples of server push and can not get them to work. > >> Does anyone have an idiot proof example of a working server push or > >> sending > >> output in chunks in Python? > > > > to work). The other method is just flushing your output and > > continue to write more data... > > I don't know the details, so this is hearsay, but there's another way > apparently used by KnowNow (www.knownow.com) to implement a 2-way web > interface. Each browser page has 3 frames, one of which is hidden and > is receiving non-ending Javascript from the server (which apparently > modifies a visible frame as it comes it comes in). This lets them do > some slick things like auto-completion in web forms. > > (Apologies to John for not providing any actual help with this post :/) > > Van > From theller at python.net Fri Jul 18 10:56:17 2003 From: theller at python.net (Thomas Heller) Date: Fri, 18 Jul 2003 16:56:17 +0200 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> Message-ID: >>> optparse (a.k.a. optik) is great, whereas I never made my mind up to >>> getopt. To "cure" getopt, I needed to define my own routines for >>> argument parsing; after I started using optparse I had the satisfaction >>> of erasing all of them ;) >> >> I have not yet tried optparse. Is it able to parse Windows' style >> command lines (use '/' instead of '-', ignore case of command line >> options, use long options with a single '-' or '/')? >> >> Thomas > > No. From the optparse documentation: [snip] > Is Windows-style arguments (with slashes) *that* important to you? > Because there's absolutely nothing wrong with following the standard > that's been established for over twenty years... :-) You (or me, at least) have to follow the standard that is used on the system where you work on. Well, sometimes at least. Example: a localserver COM object is started with an /Automate command line flag. And MS requires that the COM object registers itself when the /RegServer or -regserver (case insensitive) options are used. Anyway, I have my own w_getopt for windows now ;-) Thomas From bokr at oz.net Sun Jul 13 18:46:41 2003 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2003 22:46:41 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: On Sun, 13 Jul 2003 16:11:37 +0100, Stephen Horne wrote: >On 13 Jul 2003 10:37:01 -0400, aahz at pythoncraft.com (Aahz) wrote: > >>In article , >>Stephen Horne wrote: >>> >>>One of the few things I hate about Python is that mutable objects are >>>implicitly shared using a reference system whereas immutable objects >>>are not. >> >>Well, that's incorrect. *ALL* Python objects are implicitly shared with >>bindings. The difference is whether updating the value referenced by a >>target requires *re*binding the target or simply updating an object. > >Fine - nit-pick. Well, it *is* a (very) significant nit ;-) > >All you have proven is that it is the distinction between types that >get re-bound and those that don't (rather than the use of references) >that is unnecessarily confusing and error prone. I suspect you are reading some Python statements as if they were C or C++. Python name assignment does not do anything to an object. It just creates an alias name for an object. It may reuse an existing name, but that only changes the meaning of that name as an alias, it does not affect the object that the name was previously an alias for. You can of course have other assignment targets than plain names. In fact, a "plain name" is just the simplest expression for an assignment target. But whatever the target expression evaluates to, what gets put "there" is a reference to an object, not an object itself. The confusion, ISTM, is in what to think of as "there." "There" is definitely not a memory space for a Python object representation or "value". The most accurate (UIAM) C concept would be a "there" of type PyObject* -- i.e., a pointer variable that points to the representation of some kind of Python object. We don't have to know the implementation details to use the idea that the left hand side of a Python assignment is an *expression* (even if a single name) that yields a place to put a reference (effectively a pointer) to the object created by evaluating the expression on the right hand side. A C programmer will tend to think that a symbol on the left is a static expression indicating a specific fixed memory space (static address or stack frame offset). But in Python it is first of all a dynamic expression (though an unqualified target name can only have its "there" be in the local or global namespace, and the choice between those is made statically (at least w.r.t. a given level of compiling/exec-ing). In C terms, the Python assignment target expression always evaluates to a place to put a pointer, never a place to put object representation bits. Of course, "a place to put a pointer" may be *inside* an object. And such inside places are identified by target expressions such as x[2] or x.a or x[2]().b[3] etc. Even a bare name really does identify a place inside an object -- i.e., inside the local or global dict associated with the context. The "place" identified by x= after a global x declaration (or just in global scope) will be the same place as globals()['x']= unless someone has subverted something. Either way, the binding of the name to the object happens by evaluating to a "there" within the global dict object, uniquely associated with the name ('x' here). Evaluated on the right hand side, that name will produce the reference/pointer again for use in accessing the object or copying to another "there" associated with perhaps some other name or a target within a composite object like a list or tuple, or other namespace dict. > >The wart remains, even if my description was wrong. And even that is a >dubious claim. > Every assignment is effectively stores a referential alias for an object, whether associated with a name or not. This is by design, not a wart. >A Python user is interested in how an object behaves - not how it is >internally implemented in the interpreter. Immutable objects don't when you say "immutable objects," are you really speaking of names bound to immutable objects? I.e., the integer 123 is an immutable object represented by the literal 123. You get an immutable object of the same value from the expression int('123'). These are the int *objects* -- how does "behave as references" apply to these actual "immutable objects"? I.e., could you rewrite your sentence (that this is breaking in two) to make it perhaps more understandable for me ?;-) Names are not objects. Nor are left-hand-side assignment target expressions in general, whether bare names or complicated. ISTM what you are discussing is not about objects but about the way names work, and ISTM you are thinking of names as if they were C++ variable references, which they are not, and they couldn't be. For one thing, a C++ reference type has to be initialized once to refer to a specific object. It can't be made to refer to something else during the life of that scope. Pointers are a better model, since you have to distinguish by expression syntax whether you mean to assign a new pointer value or modify the thing pointed to. In python you can only assign pointers, if you want to think in those terms. When you modify a mutable, you are still assigning pointers into some part of the mutable object representation. When you assign to a bare name, you are still assigning a pointer into a place in some dictionary object (or workalike). If you want to modify an object in the usual C sense, you can code it in C and provide a python interface to your C-implemented object. When you pass arguments to the various methods of your mutable, you will get pointers that you can dereference and you can do what you want to your mutable's C data representation. But when you pass the result back to the python world, it will have to be as a standard object reference/pointer, and if you assign that, you will be storing a pointer somewhere. >behave as references - the internal use of references for immutable >objects is basically a lazy copying optimisation and, apart from >performace and a couple of other technicalities (e.g. the 'is' >operator), has no relevance. Certainly it has no relevance to the >point I was making. > The way it works is part of the semantics of the language, not just an optimization issue. Names aren't variables. HTH ;-) I sometimes get things wrong. Corrections welcome. Regards, Bengt Richter From dave at pythonapocrypha.com Thu Jul 17 17:38:35 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 17 Jul 2003 15:38:35 -0600 Subject: wxPython questions In-Reply-To: References: Message-ID: <200307171538.35820.dave@pythonapocrypha.com> On Thursday 17 July 2003 02:52 pm, Edward K. Ream wrote: > How reliable is wxPython? This is the big one. At my company we use it in one of our production applications on Win98/2k/XP and haven't had any crashes reported. We can get it to crash in development pretty easily, but it's usually when we're doing something iffy. YMMV of course, and maybe our users just don't report crashes. :) > How difficult is it in practice to get all the > core dumps out of a medium-sized wxPython app? For us there hasn't been any "special" or additional work in this area - IOW debugging GUI problems and flakiness seems to have been on par with debugging problems and flakiness in the rest of the app. > Presumably many of the wxWindows helper classes aren't needed in wxPython. > Besides the actual widget classes, what other wxWindows classes must a > wxPython app use? Any others besides wxColor, wxIcon and wxFont? What > about strings? I'd much rather use Python strings instead of wxString. I can't think of too many off the top of my head. Generally, if Python has an easier way to do something then the Python way works in wx. For example, you don't have to use the wxSize class since you can always just use an (x,y) tuple (maybe there's an exception to that rule, but I haven't seen it yet). Ditto for strings. Also, if you look in the wxWindows help files there's often a Python-only variation of APIs to make them more Pythonic. > Is it possible to have an app that creates multiple windows without using > wxDoc and allies? You can create as many top-level windows (wxFrames) as you want, if I understand you correctly, and they can be hidden or visible. > My app presently creates a hidden TK root window, and > manages all other Tk windows by hand. Is something like this possible in > wxPython? At least on Windows, yes. I assume it's the same in other OS's too. -Dave P.S. There's a wxPython mailing list you may find more useful - check wxPython.org for details. From fredrik at pythonware.com Fri Jul 4 09:42:29 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Jul 2003 15:42:29 +0200 Subject: bug in Tkinter? invalid literal for int() line 1035 References: Message-ID: Ton K. wrote: > I get subject when binding to a listbox. > The value for h is '??' which triggers the error. > I'm running Python 2.2.2 from SuSE. you're using a version of Tk that's newer than your Tkinter; that "??" you're seeing how really recent versions of Tk represent an "undefined integer value"... this has been fixed in Python 2.3, so you can either upgrade Python or link against an older Tk. (or modify Tkinter.py slightly, adding try/except clauses around the problem spots in Tkinter.py) From tjreedy at udel.edu Sat Jul 12 15:27:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2003 15:27:20 -0400 Subject: Any pure-python relational databases? References: Message-ID: "David McNab" wrote in message news:pan.2003.07.12.14.11.19.428895 at 127.0.0.1... > The server runs Python 1.5.2, > The web host is my client's choice, not mine, and there's very little > prospect of getting them to upgrade their python or install mysql-python. In 1999, Guido posted to c.l.py: "On April 13, the *final* version of Python 1.5.2 was released." [*emphasis* added] How much untouched-in-four-years software does your client depend on for critical business processes, one might wonder ;-) IE4? Win98SE without Y2K + security upgrades? Win95 last updated four years ago? If you want to discuss this with your clients, you can point out that just as IE6 does not run (or even install) on Win95, there are many Python modules that do not run on Python 1.X, and for much the same reason. Good luck. Terry J. Reedy From john_bradbury at ___cableinet.co.uk Thu Jul 3 18:59:58 2003 From: john_bradbury at ___cableinet.co.uk (John Bradbury) Date: Thu, 3 Jul 2003 22:59:58 +0000 (UTC) Subject: Server Push Message-ID: I want to send updates from a long running cgi. I have tried copying perl examples of server push and can not get them to work. Does anyone have an idiot proof example of a working server push or sending output in chunks in Python? Thanks John Bradbury From Nike/FNX at fnx.com Thu Jul 3 15:23:43 2003 From: Nike/FNX at fnx.com (Nike) Date: Thu, 3 Jul 2003 15:23:43 -0400 Subject: Report to Sender Message-ID: Incident Information:- Database: F:/Lotus/Domino/Data/mail3.box Originator: python-list at python.org Recipients: Subject: Re: Movie Date/Time: 07/03/2003 03:23:28 PM The file attachment your_details.zip you sent to the recipients listed above was infected with the W32/Sobig.e at MM virus and was not successfully cleaned. From bokr at oz.net Mon Jul 28 14:06:14 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 18:06:14 GMT Subject: freeze or something else for stand-alone-bins References: Message-ID: On 28 Jul 2003 06:29:23 -0700, ffrederik at gmx.de (Frederik) wrote: >Hello, > >in Python 2.2.2 on Windows I cant find the freeze.py program anymore. >On my Linux-machine it?s still in tools - examples. Where can I find >it? Or can you recommend me anything else for creating >stand-alone-binaries? > It seems to be in the 2.2.2 source distribution for windows. Can't say more, since I haven't used it. Regards, Bengt Richter From skip at pobox.com Mon Jul 28 08:36:43 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 28 Jul 2003 07:36:43 -0500 Subject: List of all python magic numbers? In-Reply-To: <3f24fb20$0$6758$9b4e6d93@newsread2.arcor-online.net> References: <3f24fb20$0$6758$9b4e6d93@newsread2.arcor-online.net> Message-ID: <16165.6363.859595.738777@montanaro.dyndns.org> Hartmut> I'm looking for a list of all Python Magic Numbers and the Hartmut> related Python version -- starting a the last byte-code change Hartmut> towards 1.5. This should make 'decompyle' work with less Hartmut> problems. Take a look at the top of Python/import.c Skip From lists at gregfortune.com Tue Jul 15 20:26:07 2003 From: lists at gregfortune.com (Greg Fortune) Date: Tue, 15 Jul 2003 17:26:07 -0700 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: Message-ID: Are you intended on releasing the source for this? If so, dump something up there so we can play ;o) Greg Fortune Sybren Stuvel wrote: > Tim Gerla enlightened us with: >> Very fun stuff. Someday I hope to have a Zaurus or similar device to >> toy with. > > For those interested: I've put up some screenshots of my jabber client, > Discuss Jabber, at http://zaurus.thirdtower.com/ > > Sybren From skip at pobox.com Thu Jul 24 15:36:45 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Jul 2003 14:36:45 -0500 Subject: [newbie] MySQL : How to check if no row returned? In-Reply-To: <5ua0ivcl3loh45cq6pnoimsoa86nt0q4db@4ax.com> References: <5ua0ivcl3loh45cq6pnoimsoa86nt0q4db@4ax.com> Message-ID: <16160.13645.496975.635058@montanaro.dyndns.org> Jane> I browsed through the archives of this site, but I didn't see how Jane> to check if a SELECT through the MySql module returns an empty set Jane> (whether a row exists or not, the "else" part below is always Jane> called). The return value of the cursor's execute method indicates how many rows were selected: >>> import MySQLdb >>> conn = MySQLdb.Connection(...) >>> curs = conn.cursor() >>> print curs.execute("select * from cities where city like 'San %'") 51 >>> rows = curs.fetchall() >>> print len(rows) 51 Skip From Juha.Autero at iki.fi Wed Jul 2 11:27:46 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Wed, 02 Jul 2003 18:27:46 +0300 Subject: os.fork() different in cgi-script? References: Message-ID: <87fzlpdk3x.fsf@jautero.no-ip.org> "Andreas Kuntzagk" writes: > So it looks the main() is run 2 times. > Is it so? And if yes, why? No, it isn't. The problem is that Python uses C STDIO library that has buffered input and output. The text written in stdout is written in buffer. Since child process created by fork() is almost identical to parent process, it will also have a copy of stdout buffer. When process exits, it closes stdout, which flushes the buffer. So, both buffers are written to stdout and that causes everything to be printed twice. The reason why this doesn happen on command line is that buffers to terminals are flushed after newline. You can see that by redirecting script output to file: $ python script.py >output $ cat output Content-Type: text/plain 4309 Content-Type: text/plain 4309 > I googled for this but only found a similar question from 1997 and no > answer. Which is strange since this common problem and has nothing to do with Python. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From donn at drizzle.com Tue Jul 15 00:18:18 2003 From: donn at drizzle.com (Donn Cave) Date: Tue, 15 Jul 2003 04:18:18 -0000 Subject: cgi-tb after os.chdir References: <2621b014.0307141140.650a234a@posting.google.com> Message-ID: <1058242697.153569@yasure> Quoth schull at digitalgoods.com (Jon Schull): | I find that cgitb fails to show error context if I've changed my | default directory, so I tried to subclass cgitb and get it to save the | directory we were in when the program started. Didn't work. I'd | appreciate your eyes. | | Problem--this apparently fails to find my sourcefile when #os.chdir is | uncommented from this cgi program | ......................... | | #! /usr/local/bin/python | import cgitb | cgitb.enable() | | import os | #os.chdir('../') | 1/0 | ......................... | What I thought would work: | ......................... | from cgitb import Hook | import os | import sys | | class myHook(Hook): | def __init__(self, display=1, logdir=None, context=5, | file=None,wkdir='xx'): | self.wkdir=wkdir | Hook.__init__(self, display=1, logdir=None, context=5, file=None) | | def handle(self, info=None): | os.cwd(self.wkdir) | Hook.handle(self,info) | | handler = myHook().handle | def enable(display=1, logdir=None, context=5): | wkdir=os.getcwd() | sys.excepthook = myHook(display, logdir, context,wkdir=wkdir) | | ......................... | But in fact, my exception handler doesn't even seem to get installed. | (I get python's usual tracebacks) | | I'm probably over my head here, but... Not too badly, I think. | What's wrong with the program where I attempt to subclass myHook? Hm, did you call your enable() function? Looks to me like the handler = ... line is a decoy that doesn't do anything, incidentally. If it were up to me, I might be tempted to make enable() a method of the Hook class, only for convenience though. | Is this a reasonable way to get cgitb to survive directory changes? Yes, it could work. I would use chdir() instead of cwd(), when returning to the original working directory. As you have probably already found out, chdir also can compromise module imports; if your only problem is the quality of tracebacks, you're getting off easy. Donn Cave, donn at drizzle.com From noah at noah.org Sun Jul 13 13:21:56 2003 From: noah at noah.org (Noah) Date: 13 Jul 2003 10:21:56 -0700 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: Tom Plunket wrote in message news:<13t0hvsb7idh0g6ac3upe5k0qd6flc17ah at 4ax.com>... > I want to do something along the lines of the following C++ code: > > void change(int& i) > { > i++; > } > > > Is there any way to do references like this in Python? It'd be > like this, though clearly this doesn't change the thing I want it > to change: > > def change(val): > val += 1 > > v = 0 > change(v) > > # v == 1 now. > > thanks. > > I can see that maybe if I passed in a list of one integer I could > change that, but that seems circuitous to me. > > > -tom! As others have explained, you just return the value. It's just a different point of view. Instead of change (v) you have: v = change (v) I was a C++ programmer in a former life and I remember being annoyed at the lack of references in Python -- I mean, why would something so obvious and cool as a reference variable be excluded, right? Where people usually find themselves wanting references is when they need to modify more than one value at once. For example, consider a function to rotate a 3D point through two angles, where x,y,z get modified by the rotate function: rotate (x,y,z, theta, phi) Here you just have to remember that Python can return more than one value at once as a tuple. So you should expect the code to look like this: x,y,z = rotate (x,y,z, theta, phi) Your rotate() function would return a simple tuple as: return (x,y,z) After I unlearned the C++ idiom I decided I liked the Python idiom better. It's a teensy bit more verbose, but it is far more clear as to what is going on. Your inputs and output are clearly defined. With C++ references you have to look up the function definition to know which variables in modified. Yours, Noah From grante at visi.com Wed Jul 23 15:52:31 2003 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2003 19:52:31 GMT Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> Message-ID: <3f1ee77f$0$160$a1866201@newsreader.visi.com> In article <3f1ed31a$0$181$a1866201 at newsreader.visi.com>, Grant Edwards wrote: > How does one do raw Ethernet under Win32? Ultimately, I want > to do it in a Python program, but if somebody can point me to a > clue on how to do it from C, I could probably figure out the > rest. It looks like I can _almost_ do what I want with the python wrapper around the windows pcap lib. WinPcap has a sendpacket() funcation which doesn't seem to be made visible by the Windows version of pylibpcap, so that's something I'll have to look into. It's probably not the optimal way to receive packets, but I only have to do a few. -- Grant Edwards grante Yow! My DIGITAL WATCH at has an automatic SNOOZE visi.com FEATURE!! From peter at engcorp.com Wed Jul 16 08:47:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jul 2003 08:47:45 -0400 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: <3F154971.470FE84A@engcorp.com> Duncan Booth wrote: > > [1] First Python reference to a time machine I can find is Paul Prescod in > April 1998 proposing its construction, although it was obviously fully > operational by September 1998. Obviously the first thing the PSU did after obtaining the time machine was to travel back to pre-1998 to eliminate records of its actual prior invention, as well as those who knew anyth From frobozz_electric at hotmail.com Wed Jul 9 11:34:51 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 9 Jul 2003 15:34:51 GMT Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: If you find further issues with the code please email me directly, I'd prefer not to clutter this forum any more than I have already. I can be reached at sross at connectmail.carleton.ca until January 2004. From davidcfox at post.harvard.edu Tue Jul 22 11:03:11 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 22 Jul 2003 15:03:11 GMT Subject: detecting containers during object introspection In-Reply-To: References: Message-ID: Steven Taschuk wrote: > Quoth David C. Fox: > [...] > >>However, the real problem occurs if the developer makes a change like >>this (or even just adds a new attribute which is a non-standard >>container), and does increment the version number. Because the version >>number was incremented, the regression test would *expect* some of the >>dictionary elements to change type or structure, and would simply update >>the standard example dictionary. Then, any *subsequent* changes to the >>structure of the values in that container would go undetected (unless >>the developer had also updated the recursive comparison operation to >>take into account that the unknown object was a container). > > > Yes, I see. Thorny. > > What if your recursive comparison operation choked on values of > unknown types rather than falling back on the weak "have same > type" criterion? That way, the developer who changes the > structure by introducing values of (e.g.) a new dict work-alike > type would see tests fail, which would remind her to add to that > comparison operation the necessary knowledge of the new type. > > Fail safe, in other words, where "safe" means "no false positives > from the regression test". > That's one possibility. My original reaction to it was that requiring developers to write comparison operations for every class whose instances are found in the stored dictionary seemed like overkill. Then I started think about what classes actually were found there. Many of them contain lists or dictionaries, and changes to the internal structure of those classes would cause the same problems described above. Therefore, just noting that the old and new versions had an attribute with the same class wouldn't be sufficient. Then, I recalled that any object instance *has* a dictionary of attributes: __dict__. So, instead of writing custom comparison operators for each class, I should be able to define a generic comparison operator cmp_struct(x, y) which returns true iff 1) type(x) == type(y), and 2) one of the following is true: a) type(x) == type({}), and x.keys() and y.keys() match, and for each key, cmp_struct(x[key], y[key]) is true b) type(x) == type([]), and for each pair of items in x and y, cmp_struct returns true c) type(x) == types.InstanceType, and cmp_struct(x.__dict__, y.__dict__) is true d) type(x) is not any of the above Thanks for your advice. It is really nice to have someone to bounce ideas off of. David From pete at shinners.org Thu Jul 3 12:06:25 2003 From: pete at shinners.org (Pete Shinners) Date: Thu, 03 Jul 2003 09:06:25 -0700 Subject: Reading an image file data......... In-Reply-To: <20030703134941.15069.qmail@webmail26.rediffmail.com> References: <20030703134941.15069.qmail@webmail26.rediffmail.com> Message-ID: Suresh Kumar wrote: > I scanned a page of my textbook and stored as a JPEG file. Now i want > to read a text from the JPEG image which is at some location, say from > (100,100) to (300,300). How can i read it? I am using PIL module for > image handling and tkinter. Moreover i am new to PIL module. Is it > possible to read a text from a JPEG file in python/tkinter? what you want is a process called OCR (i think it means optical character recognition, or something like that). it is the process of translating an image into plain text. it looks like on linux you have 'clara', and 'gocr', and probable a few others. you will likely need to call on these other tools to handle the OCR for you. From martin at v.loewis.de Sun Jul 6 15:14:10 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Jul 2003 21:14:10 +0200 Subject: PEP idea. ( removing __slots__ ) References: <3f073594$1_2@news1.vip.uk.com> <3f083043$1_3@news1.vip.uk.com> <3f085fa7_3@news1.vip.uk.com> Message-ID: simon place writes: > i can't think of a point for __slots__ except to save the overhead of > a dict, this is why you DON'T HAVE a __dict__ when __slots__ is > defined. No. Some classes have slots for efficiency, and their subclasses have dictionaries for generality. Likewise, some classes have slots to save the dictionary for most instances, but some instances may need additional attributes, in which case Python creates the dictionary on-the-fly. > The point of the combining is to simplify, you know, based on the idea > that keeping the language simply ( and logical ) aids comprehension. I know. Regards, Martin From hn at nospam.net Fri Jul 25 10:10:32 2003 From: hn at nospam.net (HN) Date: Fri, 25 Jul 2003 16:10:32 +0200 Subject: Python and VS.Net References: Message-ID: > Yes, I was aware of these, too. Despite Microsoft's claims about the .NET > platform being language-independent, it doesn't seem to be a simple task to > get Python going on it. So far, I think there are only VB.NET, C++, C# > and J#. No Python#, Perl# or Ruby#, as of yet... This is probably because .NET is more suitable for statically typed languages than for dynamic ones. However, many statically-typed languages have .NET implementations. For example, Eiffel, which is a very good language, in many aspects far superior to VB, C++, C# and Java. From pascalbarbedor at free.fr Tue Jul 29 03:44:11 2003 From: pascalbarbedor at free.fr (pascal barbedor) Date: Tue, 29 Jul 2003 09:44:11 +0200 Subject: blanks embedded in python 2.3 optparse Message-ID: <3f2625b7$0$24594$626a54ce@news.free.fr> Hi is there a way to pass a param with blank embedded with optparse ? (C:\Python23\Doc\lib\module-optparse.html) for instance prog --name=mr jones and have "mister jones" as a single entry for name ? reading the docs I see nothing about that. the only thing is the nargs to pass nargs at a time, but here you can't tell in advance how many words in the name there is thanks From Chris.Rennert at mdi-oshkosh.com Tue Jul 1 15:27:58 2003 From: Chris.Rennert at mdi-oshkosh.com (Chris Rennert) Date: Tue, 1 Jul 2003 14:27:58 -0500 Subject: remove special characters from line References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Message-ID: <3f01e0b0$0$43854$39cecf19@news.twtelecom.net> I apologize for being vague on what a "special" character is in my context. For me, it would be anything that isn't A..Z , a..z, or 0..9 . My list seems to work, or like it was suggested I could have used a string as well. I thank everyone for the help, and I am really enjoying learning Python. Thanks again, Chris Rennert "Chris Rennert" wrote in message news:3f01a27d$0$43847$39cecf19 at news.twtelecom.net... > Hello all, > > If I have a line like this > > ?blah blah blah blah blah > > I know I could do a slice like this [1:] to pull everything but the special > character, but what if I have several lines in a file. > I am not sure how I would detect a special character like that. I would > just like to pull everything from those lines (and the special character > always appears as the first character, but not on every line) except for the > special characters. > I hope I have enough detail for someone to help me. > > Thanks in advance, > > Chris > > From peter at engcorp.com Sat Jul 19 10:14:44 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jul 2003 10:14:44 -0400 Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> <3F1871A5.3020702@hotmail.com> <3F194969.6020807@hotmail.com> Message-ID: <3F195254.681DF769@engcorp.com> hokiegal99 wrote: > > My scripts aren't long and complex, so I don't really *need* to use > functions. But the idea of using them is appealing to me because it > seems the right thing to do from a design point of view. I can see how > larger, more complex programs would get out of hand if the programmer > did not use functions so they'd be absolutely necessary there. But if > they allow larger programs to have a better overall design that's more > compact and readable (like your examples showed) then one could argue > that they would do the same for smaller, simplier programs too. Uh oh! You're being poisoned with the meme of "right design". Don't use functions because they "seem the right thing to do", use them because *they reduce repetition*, or simplify code by *making it more readable*. If you aren't reducing repetition with them you are losing the primary benefit. If you also aren't making your code more readable, don't use functions. Whatever you do, don't use them just because somebody has convinced you "they're the right thing". -Peter From mike at nospam.com Thu Jul 24 17:56:24 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 24 Jul 2003 14:56:24 -0700 Subject: Standard behaviour of a getSomething method References: Message-ID: Batista, Facundo wrote: > When I want to know about a attribute (e.g.: myAttrib) of an object, I > should use the specific method (e.g.: getMyAttrib). Python don't enforce nor encourage attribute hiding, so don't do it unless you have a good reason. Plain access to attributes is simple: myObject.myAttribute > Considering that this attribute is always another object (everything > is an object in Python), what should getMyAttrib do? > > 1) Return the object > 2) Return a copy of the object Usualy statement x=y creates a new object y referencing to old object y. If y allows modification it can be modified through name 'x' If you want a copy: > How do I return a copy of the object? Do it explicitly: myObject.copy() or import copy copy.copy(myObject) copy.deepcopy(myObject) Mike From mike at nospam.com Wed Jul 16 16:13:45 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 16 Jul 2003 13:13:45 -0700 Subject: c/c++ implementation of python base and derived class References: <521f96c7.0307151943.7d987b2@posting.google.com> Message-ID: Robert Harrison wrote: > in C or C++, to > > 1) implement a new-style Python class, and > 2) derive another new class from it? Take a look to boost.python at http://www.boost.org/libs/python/doc/tutorial/index.html Mike From usenet at fomps.net Tue Jul 15 09:24:53 2003 From: usenet at fomps.net (Stephen VanDahm) Date: Tue, 15 Jul 2003 13:24:53 +0000 (UTC) Subject: Securing the Pyton Interpreter? References: Message-ID: In article , Andrew Koenig wrote: > Stephen> I'm looking for a way to install Python on a UNIX machine in > Stephen> a way such that any user on the system can use it, but only > Stephen> to execute scripts that are located in a certain directory. > > Why? If I were a user on that machine and wanted to execute Python > scripts in a different directory, how would you stop me from installing > Python on my own and using it for those scripts? > Andrew, I'm a member of a Public Access UNIX system. Some users on the system are allowed to use development tools (like Python) and other aren't. Also, some users are allowed to install software that they've written into a publically accessible area so that everyone on the system can use it. The problem is that if the software is written in a language like Python, regular users won't be able to use the Python interpreter to run it, and the Python programs that we write won't be very useful. Some of us want to install a second interpreter that's been secured somewhat so that people can run our programs without being able to execute arbitrary Python programs. You are correct that nothing (in principle) prevents someone from installing another Python interpreter in $HOME/bin and running whatever they want. In fact, that's kind of what *we're* doing. But since I neither make nor enforce the rules, it isn't my problem if other people try to break them. Basically, I need to do this for bureaucratic reasons. I know it's a hack, and that it sounds like a stupid thing to do, but it's the best available option for us.... Thanks for the reply, Steve From mhammond at skippinet.com.au Wed Jul 30 18:37:02 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 31 Jul 2003 08:37:02 +1000 Subject: PyXPCom In-Reply-To: <3f27e5a8$0$13798$4d4ebb8e@news.nl.uu.net> References: <3f27e5a8$0$13798$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > I recently found out about XPCom and it's python bindings and it sounded > very promising. Then I found out that the source of this information was > pretty old. I was wondering what the status is currently. I couldn't find > any documentation or binaries for the python interface. > > > has anyone examples, docs, binaries, urls, etc???? PyXPCOM is in the Mozilla source tree, under extensions/python/xpcom. It is recommented that is you are using a fairly recent Mozilla version, you should use the *trunk* version of pyxpcom, as it has a number of fixes that aren't in the Moz final releases. Mark From logiplex at qwest.net Tue Jul 22 18:20:15 2003 From: logiplex at qwest.net (Cliff Wells) Date: 22 Jul 2003 15:20:15 -0700 Subject: wxpython display jpg in a frame In-Reply-To: <1058908566.1448.42.camel@software1.logiplex.internal> References: <1058908566.1448.42.camel@software1.logiplex.internal> Message-ID: <1058912415.1448.85.camel@software1.logiplex.internal> On Tue, 2003-07-22 at 14:16, Cliff Wells wrote: > On Tue, 2003-07-22 at 12:32, max4 wrote: > > hello > > i would like to know if there is a good tutorial about how to do this > > or if someone could explain > > [ i want to add a jpg to an existing about dialog] Sorry, I misread your question. I was thinking you wanted to add an image as a *background* to a dialog... David's response is correct. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From clifford.wells at comcast.net Sun Jul 13 22:06:33 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 13 Jul 2003 19:06:33 -0700 Subject: How to crash Python in 1 easy step (python 2.2.2) In-Reply-To: <2e363c08.0307130944.4c470bc3@posting.google.com> References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <1058148392.2220.77.camel@devilbox.homelinux.net> On Sun, 2003-07-13 at 10:44, Paul Miller wrote: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. > > This is on a RedHat 9.0 system running on an Athlon 600. Redhat 9, Athlon XP 1700+. Python 2.2.2-26, readline 4.3-5 Not a problem. Regards, Cliff -- There's no light at the end of it all, let's all sit down and cry -This Mortal Coil From fa507874 at skynet.be Thu Jul 31 03:14:38 2003 From: fa507874 at skynet.be (conatic) Date: Thu, 31 Jul 2003 09:14:38 +0200 Subject: Exploring a ftp with python to find pdf Message-ID: I want to make a script that connect to a ftp and get a list of all pdf stored in the ftp with their path to use the list later. I have tried some script with recursion but can't do something good. Could you help ? conatic - http://www.hesit.net From ggg at zzz.it Fri Jul 25 06:46:11 2003 From: ggg at zzz.it (deelan) Date: Fri, 25 Jul 2003 12:46:11 +0200 Subject: (Eclipse/TruStudio) Re: I am so impressed In-Reply-To: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> Message-ID: Guyon Mor?e wrote: > I've been looking for a nice python editor for a while. I was using a great > general purpose editor called EditPlus. It did the job pretty good.... > > I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com > and it's great! after your suggestion i've downloaded both eclispe and trustudio. eclipse starts flawlessy but i cannot see any trace of trustudio python extensions. BTW eclipse runs smoothly on my office P4 1.4GHz, 512MB. there's should be some reference to python support in the IDE, right? something lile "new file --> python", or "new project --> python project", actually i only see java related stuff. following the website instructions i've just unzipped trustudio zip files (2) into eclipse folder (they actually installs under "plug-ins" folder). i've restarted eclipse a couple of times, but nothing changed any thoughts? later, deelan -- goldicus1970 AT yahoo.it http://www.deelan.com/ From anandpillai6 at yahoo.com Mon Jul 21 03:01:34 2003 From: anandpillai6 at yahoo.com (Anand) Date: 21 Jul 2003 00:01:34 -0700 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: <41c203e.0307202301.64022dca@posting.google.com> What if you want to make sure that there are exactly 'n' threads in the queue a given moment ? I had a problem of a similar kind, which I solved by deriving a "Thread monitor" class from Queue. I initialized the Queue with a given size (the number of threads in it a given moment, the number 'n' above). But, I found that this does not happen accurately as I wanted. I solved it by using a non-blocking queue and managing the exception by using an Event and by using my own locks. The code would look something like this ... It uses a polling mechanism with sleeping. # Note: bad indentation! class TrackerMonitor: def __init__(self): ... ... self._event= threading.Event() self._lock = threading.Lock() # Set the event so that threads dont block! self._event.set() def runThreads(self): # Use a non-blocking queue and manage exceptions # on my own. while threading.activeCount()>1: # Run till all threads are exhausted if self._flag: break # flag to signal end of polling time.sleep(1.0) try: t=self.get(0) self._trackers.append(t) # local list for easier management t.start() except Empty: self._event.set() # Wake up all threads waiting for this # event def wait(self): """ Block on the event """ self._event.wait() def addToQueue(self, tracker): """ Add a thread to the thread queue """ # Acquire lock self._lock.acquire() cond = 0 # Use a non-blocking queue and manage exceptions # my own while not cond: try: self.put(tracker, 0) cond = 1 except Full: self._event.clear() # Clear event so that all waiting threads # block, till the queue is empty again # Release lock self._lock.release() And in the thread code... class Tracker(threading.Thread): def __init___(self, monitor): ... ... self._monitor = monitor # Instance of above class def doMyJobInAloop(self): for int in range(0, len(jobs)): ... ... # Wait on the event of the monitor self._monitor.wait() # Do my work ... # This code spawns more thread objects of this # class, all of which call the same loop as this # one. As you can see, I use an event in my queue derived class to signal threads when they can join the queue. The event is set when the queue is empty and cleared when the queue is full. All threads block on this event in their main loop. With this mechanism, I was able to get more control on the queue's handling of threads, which is what I wanted. I am not sure how this affetcs performance theorotically, since I am not using the Queue's internal locking mechanism. But as far as the program goes, I am happy with the way it performs. This might be one way the O.P can use Events in his implementation. ~Anand "Cliff Wells" wrote in message news:... > On Fri, 2003-07-18 at 14:28, Graeme Matthew wrote: > > Aahz > > > > Thanks, ive actually been using your OSCON slides which have helped a lot. > > So it technically correct that all worker threads in a thread pool are > > either doing some work or polling the queue to find out if there is a job > > to process ? > > They don't poll the queue, they block waiting on it until something is > available. > > > eg: (pseudocodish :-)) > > > > def run(self): > > > > while 1: > > > > self.lock.acquire() > > > > if QueueManager.HasJob: > > job = QueueManager.GetFreeJob() > > __processJob(job) > > > > self.lock.release() > > > > def __processJob(self): > > > > blah blah blah ..... > > More like: > > def run(): > while 1: > job = queue.get() # this blocks until something is queue.put() > _processjob(job) > > > Acquiring the locks isn't necessary and ill-advised. The Queue itself > can be thought of as a type of locking mechanism, so you raise the > possibility of a deadlock condition by nesting locks (for instance if > you also put locks around the queue.put()). > > Regards, From KodeKruncherDude at aol.com Sun Jul 20 10:26:40 2003 From: KodeKruncherDude at aol.com (Adam Petrosh) Date: 20 Jul 2003 07:26:40 -0700 Subject: Newbie Questions? Message-ID: <504413fa.0307200626.3fceb85a@posting.google.com> Hail all. Are newbie questions allowed here, or is there a different Newsgroup for that? Thanks. From usenet at kyle.sent.com Thu Jul 3 21:11:09 2003 From: usenet at kyle.sent.com (Kyle Babich) Date: 3 Jul 2003 18:11:09 -0700 Subject: FYI: pyBoards.com Message-ID: <191e20c8.0307031711.42d4e46b@posting.google.com> I have just opened pyBoards.com, a community for Python programmers. Please stop by and check it out. http://www.pyBoards.com Tell me what you think, Kyle From mgerrans at mindspring.com Thu Jul 31 03:35:28 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 31 Jul 2003 00:35:28 -0700 Subject: Portability of Python (VS.Net, Java etc.) References: <221d8dbe.0307272345.63503afd@posting.google.com> <221d8dbe.0307290635.fea912d@posting.google.com> Message-ID: "Dave Kuhlman" wrote: > Of the two frameworks mentioned (MS .Net and Java) we already have > Python in Java. So, before doing Python in/on MS .Net it would be > worthwhile to ask whether Python in Java (Jython) has succeeded. That's overly simplistic, I think. Whether or not Jython was "a success" on the JVM has little to do with whether it is worthwhile on the CLR. In fact, when Guido first began Python proper, I don't think he was too concerned with whether it would be "a success" -- I think he just wanted to create a useful tool. > Ask yourself this question: Would a consultant or contractor who > had no ideological commitment to Python (which I do) choose to work > in Jython over Java, and why? Yes, there are many *pragmatic* reasons to use Python, ideology aside. At the very least, Jython is a great way to experiment with Java APIs and learn them quickly. > One additional consideration is that a consultant/contractor can > bill more hours if Java is used than they can if Python/Jython is > used, because development in Java is slower than development in > Python. So, why would the consultant/contractor choose Python over > Java? This is a silly stereotype. Any consultant/contractor who looks at things this way is a charlatan and should be booted (to the head, no less) at the earliest opportunity. I have only met one consultant who created such bad work that it seemed like he was playing the "job security" game -- and after spending much time trying to disentangle his code, I concluded it was simply incompetence, not intentional malevolence. Having been a consultant/contractor for nearly a decade now, I can tell you that I am always happy to maximize my productivity. There is never any shortage of work to do, even when you get a project done in half the time with better than expected quality. I am working on a .Net project now and if I could do some or all of the code in Python, I would. Instead, I'm using C#, which I like more than Java, but less than Python. There are already a wealth of good libraries available in .Net that would make the Python-on-.Net combination very effective and useful. - Matt From tim.golden at viacom-outdoor.co.uk Thu Jul 31 04:28:25 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 31 Jul 2003 01:28:25 -0700 Subject: How to get Windows physical RAM using python? References: Message-ID: <8360efcd.0307310028.a91343b@posting.google.com> BranimirPetrovic at yahoo.com (Branimir Petrovic) wrote in message news:... > "Martin v. L?wis" wrote in message news:... > > Python can't get you Windows physical RAM. You have to order RAM > > from a manufacturer or reseller if Windows needs more RAM :-) > > > > Regards, > > Martin > > "Easy" way to get to physical RAM on Windows is via WMI objects. > And here's how you'd do it in Python: 1) Get WMI module from http://tgolden.sc.sabren.com/wmi.html 2) Do something like this: import wmi computer = wmi.WMI () for i in computer.Win32_ComputerSystem (): print i.Caption, "has", i.TotalPhysicalMemory, "bytes of memory" Obviously you can fiddle around with Megabytes and Gigabytes and so on if you need to. The loop is a slight hack: you obviously only have one computer system, but this interface to WMI always returns a list (albeit of one value). HTH TJG From barry at python.org Tue Jul 29 20:02:26 2003 From: barry at python.org (Barry A. Warsaw) Date: Tue, 29 Jul 2003 20:02:26 -0400 Subject: RELEASED Python 2.3 (final) Message-ID: <16167.2834.754645.707376@gargle.gargle.HOWL> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3 (final). Nineteen months in the making, Python 2.3 represents a commitment to stability and improved performance, with a minimum of new language features. Countless bugs and memory leaks have been fixed, many new and updated modules have been added, and the new type/class system introduced in Python 2.2 has been significantly improved. Python 2.3 can be up to 30% faster than Python 2.2. For more information on Python 2.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3 Highlights of this new release include: - A brand new version of IDLE, the Python IDE, from the IDLEfork project at SourceForge. - Many new and improved library modules including: sets, heapq, datetime, textwrap, optparse, logging, bsddb, bz2, tarfile, ossaudiodev, itertools, platform, csv, timeit, shelve, DocXMLRPCServer, imaplib, imp, trace, and a new random number generator based on the highly acclaimed Mersenne Twister algorithm (with a period of 2**19937-1). Some obsolete modules have been deprecated. - New and improved built-ins including: o enumerate(): an iterator yielding (index, item) pairs o sum(): a new function to sum a sequence of numbers o basestring: an abstract base string type for str and unicode o bool: a proper type with instances True and False o compile(), eval(), exec: fully support Unicode, and allow input not ending in a newline o range(): support for long arguments (magnitude > sys.maxint) o dict(): new constructor signatures o filter(): returns Unicode when the input is Unicode o int() can now return long o isinstance(), super(): Now support instances whose type() is not equal to their __class__. super() no longer ignores data descriptors, except for __class__. o raw_input(): can now return Unicode objects o slice(), buffer(): are now types rather than functions - Many new doctest extensions, allowing them to be run by unittest. - Extended slices, e.g. "hello"[::-1] returns "olleh". - Universal newlines mode for reading files (converts \r, \n and \r\n all into \n). - Source code encoding declarations. (PEP 263) - Import from zip files. (PEP 273 and PEP 302) - FutureWarning issued for "unsigned" operations on ints. (PEP 237) - Faster list.sort() is now stable. - Unicode filenames on Windows. (PEP 227) - Karatsuba long multiplication (running time O(N**1.58) instead of O(N**2)). - pickle, cPickle, and copy support a new pickling protocol for more efficient pickling of (especially) new-style class instances. - The socket module now supports optional timeouts on all operations. - ssl support has been incorporated into the Windows installer. - Many improvements to Tkinter. Python 2.3 contains many other improvements, including the adoption of many Python Enhancement Proposals (PEPs). For details see: http://www.python.org/2.3/highlights.html Enjoy. happy-50th-birthday-geddy-ly y'rs, -Barry Barry Warsaw barry at python.org Python 2.3 Release Manager (and the PythonLabs team: Tim, Fred, Jeremy, and Guido) From ianb at colorstudy.com Wed Jul 23 12:52:07 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 23 Jul 2003 11:52:07 -0500 Subject: How does Mr. Martelli's Borg recipe work ? In-Reply-To: References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <1058979127.28091.7512.camel@lothlorien> On Wed, 2003-07-23 at 02:45, Robin Becker wrote: > ....can't one do > class TheSomething: > .... > > TheSomething = TheSomething() > > then it's harder to get at the class which presumably is now only > available as TheSomething.__class__ I wouldn't generally name the class and the singleton the same, but just because that is confusing -- if you look briefly at the code you'll initially think that TheSomething is a class, when it is actually an instance. Better would be: class _Something: .... TheSomething = _Something() del _Something Ian From paul.m at speakeasy.net Sat Jul 26 17:29:00 2003 From: paul.m at speakeasy.net (Paul M) Date: Sat, 26 Jul 2003 17:29:00 -0400 Subject: Pythoness In-Reply-To: <3rnav-q64.ln1@beastie.ix.netcom.com> References: <3f2115e6$1@news.012.net.il> <3rnav-q64.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber wrote: > Avner Ben fed this fish to the penguins on Friday 25 July 2003 05:34 am: > > >>The following is from the "A Word A Day" newsletter >>(http://www.wordsmith.org/awad/subscribe.html) of 22 July 2003. I >>thought you'd find it amusing... >> >> >>>pythoness (PIE-thuh-nis) noun >>> >>> 1. A woman with the power of divination. >>> >>> 2. The priestess of Apollo at Delphi in Greek mythology. >>> > > Hmmm, I'd always seen the priestess referred to as "the Pythia" (or > something similar). > For more on Pythia and Delphi see a recent Scientific American article: http://www.sciam.com/article.cfm?articleID=0009BD34-398C-1F0A-97AE80A84189EEDF&pageNumber=1&catID=2 If that URL get's munged, just go the the Scientific American homepage and search on "Delphi" --Paul From imbosol at aerojockey.com Thu Jul 24 00:17:25 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 24 Jul 2003 04:17:25 GMT Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: Ben Finney wrote: > On Wed, 23 Jul 2003 20:29:27 -0700, Erik Max Francis wrote: >> Bryan wrote: >>> is what i'm doing is overkill? >> >> Use of external resources -- which should be released as soon as >> you're done with them -- are best done in try/finally clauses. > > It seems that nesting the 'try' clauses doesn't scale well. What if > fifty files are opened? Must the nesting level of the 'try' clauses be > fifty also, to close them promptly? If you need 50 open files, you almost certainly want to have a way of organizing them. Probably they'll be in a list or dictionary. So, if they're in a list, for example, you can do this: filelist = [] try: filelist.append(open(filename[0])) filelist.append(open(filename[1])) ... do_something(filelist) finally: for f in filelist: f.close() -- CARL BANKS From simonb at webone.com.au Fri Jul 4 08:54:03 2003 From: simonb at webone.com.au (Simon Burton) Date: Fri, 04 Jul 2003 22:54:03 +1000 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: Message-ID: On Fri, 04 Jul 2003 10:59:39 +0000, Francesco Bochicchio wrote: > Did anybody ever attempted to do something like this? > > Ciao > ----- > FB yeah, http://arrowtheory.com/software/python/index.html it's hard :) Simon. From tjreedy at udel.edu Tue Jul 1 12:31:55 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Jul 2003 12:31:55 -0400 Subject: Good code patterns in Python References: Message-ID: "Will Stuyvesant" wrote in message news:cb035744.0307010149.399df2eb at posting.google.com... > If you know that your source code is going to be used > later by others, then I feel that code with the pattern: > > if some_condition: > some_name = some_value > else: > some_name = other_value > > is often a mistake. Much better, safer, would be: > > some_name = some_value > if not some_condition: > some_name = other_value If, bool(some_value) == True, I personally would use the near-ternary idiom some_name = some_condition and some_value or other_value (or equivalent form for bool(other_value)== True or either == False). This is both safe and efficient, avoiding both > Because those people reusing your code might decide to > change or adapt the "if" part of the first example. Or > the "else" part for that matter. And then they could end > up with "some_name" being undefined, crashing other code > maybe 1000's of lines away. and > There is the small overhead of assigning something twice (I acknowledge that some think this ugly and worse and would not be caught dead writing such an 'abomination', so flame repetition is not necessary ;-) Terry J. Reedy From andy47 at halfcooked.com Tue Jul 29 11:23:03 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 29 Jul 2003 16:23:03 +0100 Subject: variable assignment in "while" loop In-Reply-To: References: Message-ID: sismex01 at hebmex.com wrote: >>From: Sybren Stuvel [mailto:sybrenUSE at YOURthirdtower.imagination.com] >>Sent: Martes, 29 de Julio de 2003 07:09 a.m. >> >>Hi there, >> >>Is it possible to use an assignment in a while-loop? I'd like to do >>something like "loop while there is still something to be read, and if >>there is, put it in this variable". I've been a C programmer since I >>was 14, so a construct like: >> >>while info = mydbcursor.fetchone(): >> print "Information: "+str(info) >> >>comes to mind. Unfortunately, this doesn't work. Is there a similar >>construct in python? >> >>Sybren >> > > > Well, you say you've programmed C since 14, but not how old you > are now, so... you could be programming C for six months if you're > 14-and-a-half ;-) > > Assignment, in Python, is not an expression, it's a statement; > it doesn't "return" any value, it binds an object's reference > to a name. Multiple chained assignments in Python don't work > the same way as they do in C, because in Python they're merely > syntactic sugar so you don't have to type them by hand. > > Anyhow... the best way to do what you wanna is simply: > > while 1: > info = mydbcursor.fetchone() > if not info: break > print "Information:", info > > a-ha! you say; yes, the "print" statement ("STATEMENT", not function) > automagically applies str() to the given object, so if you directly > print an object, you don't have to str() it, print does that for > you. > > "But it's so cumbersome" you think, looking upon an inconditional- > turned-conditional loop. Don't worry, it'll become natural with > practice, and after a bit you'll recall your previous C loops > and think "ewww". Why? Because, the C compiler is doing > exactly that, only implicitly, and hiding it from you. > That's bad. > > You could also: > > info = mydbcursor.fetchone() > while info: > print "Information:", info > info = mydbcursor.fetchone() > > and there's nothing wrong with this; the only "anti-aesthetic" > thing here is the duplicated line which assigns to "info", > but that's small potatos, really; don't worry about that. > > Another way, with more modern versions of Python, is to > iterate directly over the cursor: > > for info in mydbcursor: > print "Information:", info > > Why? Because cursors, if I recall correctly, are iterable > objects, so you can iterate through them using for: or any > other similar construct. > > Welcome to programming bliss :-) > > -gustavo > > Spot on, with one (minor) correction. With a for loop you have to iterate over the results of a call to a method on the cursor, e.g.; for info in mydbcursor.fetchall(): print "Information:", info You could replace fetchall() with fetchmany() or, if you are feeling contrary, fetchone() ;-) Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From gh at ghaering.de Thu Jul 31 04:57:57 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 10:57:57 +0200 Subject: Python2.3 and MySQLdb on Windows In-Reply-To: References: Message-ID: <3F28DA15.2090804@ghaering.de> Mike M wrote: > Python2.3 and MySQLdb don't seem to work together on Windows. If I > understand the error message correctly, the problem seems to be that the > _mysql binary expects version 2.2 of the Python dll. Python extension modules with different minor versions are incompatible on Windows. Trying to cheat by copying files around won't change that ;-) > Does anyone know of a > fix for this, or when a Windows version that works with 2.3 will be > available? The more interesting question is when MySQL AB will make their so-called Free Software be able to be compiled with free compilers like mingw. You still need Microsoft Visual Studio to build MySQldb on Windows. Anyway, as usual I've made the binaries and sent them to Andy Dustman. They should show up during the next days at the Sourceforge download page. -- Gerhard From ggg at zzz.it Sat Jul 26 05:47:53 2003 From: ggg at zzz.it (deelan) Date: Sat, 26 Jul 2003 11:47:53 +0200 Subject: (Eclipse/TruStudio) Re: I am so impressed In-Reply-To: <3f211b92$0$8296$4d4ebb8e@news.nl.uu.net> References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> <3f211b92$0$8296$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > did you install both packages from TruStudio? > > you have to download the trustudio framework & the python devtools > be sure you've unzipped the files correctly in th plugin folder of eclipse i cannot check now since i'm at home, but i'm pretty sure i extracted both zip files in the eclipse folder (and they created some sub-folders in the plugin one). i'll check things again the next week. later, deelan -- email: goldicus1970 AT yahoo.it web: http://www.deelan.com From jdhunter at ace.bsd.uchicago.edu Tue Jul 1 21:07:58 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 01 Jul 2003 20:07:58 -0500 Subject: Howto: extract a 'column' from a list of lists into a new list? In-Reply-To: (bokr@oz.net's message of "1 Jul 2003 20:07:43 GMT") References: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Message-ID: >>>>> "Bengt" == Bengt Richter writes: >>>> zip(*fields) That is amazingly helpful. I've often needed to transpose a 2d list, (mainly to get a "column" from an SQL query of a list of rows) and this is just the trick. I recently wrote a function to "deal" out a list of MySQLdb results, where each field was a numeric type, and wanted to fill numeric arrays with each column of results With your trick, eg, for a list of results from three numeric fields, I just have to do: a1, a2, a3 = map(array, zip(*results)) John Hunter From mkc at stowers-institute.org Wed Jul 2 16:04:49 2003 From: mkc at stowers-institute.org (Michael Coleman) Date: 02 Jul 2003 15:04:49 -0500 Subject: os.fork() different in cgi-script? References: <85adbxouec.fsf@stowers-institute.org> Message-ID: <8565mkpue6.fsf@stowers-institute.org> "Andreas Kuntzagk" writes: > Thanx, that's it. Is it possible/advisable to make stdout unbuffered? Probably. I'd be more inclined to just do an explicit flush in the few places where they are specifically needed, though. Mike -- Mike Coleman, Scientific Programmer, +1 816 926 4419 Stowers Institute for Biomedical Research 1000 E. 50th St., Kansas City, MO 64110 From me at home.net Thu Jul 3 15:38:43 2003 From: me at home.net (J-P) Date: Thu, 03 Jul 2003 15:38:43 -0400 Subject: Why so many references to global variables? Message-ID: Hi, I have a Python script interacting with a specialized C numerical library. The whole program does quite a lot of number crunching as should be running for a couple of hours. However, it always seems to run out of memory after maybe 40-45 minutes (I get a MemoryError from the python interpreter). I wanted to see what took that much memory so I printed a reference count (using sys.getrefcount()) and I was suprised to see that a global variable called 'myflag' has litteraly millions of references to it. myflag appears maybe 8 or 10 times in the script, always something like if myflag: #do something else: #do something else It appears that every time the interpreter tests for the value of 'myflag', it keeps a reference to it. I don't know whether this has something to do with the garbage collector not doing its job correctly of me doing something wrong in the code, but I'd really like to fix this thing. Any ideas, suggestions or comments greatly appreciated, as always. Thanks in advance, J-P From bgailer at alum.rpi.edu Thu Jul 17 10:49:29 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 17 Jul 2003 08:49:29 -0600 Subject: Python Quiz In-Reply-To: <87wuehxw45.fsf@emit.demon.co.uk> References: <84fc4588.0307152253.20858619@posting.google.com> <3f152bb4$1@mail.hmgcc.gov.uk> Message-ID: <5.2.1.1.0.20030717084826.0277aa80@66.28.54.253> At 11:53 AM 7/17/2003 +0100, Ian McConnell wrote: >"richardc" writes: > > > 'Question 8' > > Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's > > fixed format syntax. I can only think of Python and FORTRAN off the top of > > my head which use whitespace as part of the syntax. There is also the ISPF Dialog Manager language as used on IBM Mainframes. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From trevor at hotmail.com Sat Jul 5 12:27:29 2003 From: trevor at hotmail.com (Trevor) Date: Sat, 05 Jul 2003 17:27:29 +0100 Subject: CGI script is in plain text References: <3F04B0A4.32692.3596CD0@localhost> Message-ID: On Thu, 03 Jul 2003 19:56:32 -0500, Ian Bicking wrote: > On Thu, 2003-07-03 at 15:39, A wrote: >> I have a webhosting account with one company. >> They have Apache running. >> When I start CGI script from a web browser, the result is plain text( the copy of that script) >> I can not access >> httpd.conf >> file so I changed >> .htaccess >> file. I put into it >> >> Options +ExecCGI >> Sethandler /usr/bin/python.exe .py > > Try renaming the file to .cgi -- as long as the #! line is right, it > doesn't matter the extension. Also, you may have to put the script in > the cgi-bin directory. > > Ian The line Sethandler /usr/bin/python.exe .py This is a Unix/Linux host so it ain't python.exe is it? regards Trevor From newsgroups at jhrothjr.com Mon Jul 28 13:23:43 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 28 Jul 2003 13:23:43 -0400 Subject: Debugging Python ? References: Message-ID: "Michael Sparks" wrote in message news:mailman.1059409013.10134.python-list at python.org... > On Mon, 28 Jul 2003, Shane Hathaway wrote: > > > As a bonus, I find that print statements do not rightfully belong in > > most of the software I write. Therefore I can happily add print > > statements anywhere for debugging purposes, knowing that removing them > > later is perfectly safe. Yup. AFIC, the print statement is only for debugging, and it's quite effective for that purpose. > As an extra bonus, if you do this you can remove them all automatically: > > def print(*args): > for arg in args: > print arg, > return True > > > assert print("Well, well, well", "said", "he") > > To erase all tracks of the debugging statements at runtime, just use the > -O flag. I tend to use a variant of this for debugging systems that have > "complex" concurrency to make it simpler to track "who" "said" what. > > I know you can do the same with just grep if you use print - but you have > to ensure that your debugging statements don't span multiple lines. Which mine do, quite frequently. By the time you get this far, you've pretty much got a logging system. Another interesting arguement for the print statement versus online debuggers is that, if you practice test driven development, you gradually lose your facility with the debugger - you use it so seldom. John Roth > > > Michael. > > From aahz at pythoncraft.com Thu Jul 10 13:31:04 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2003 13:31:04 -0400 Subject: for in sequence problem... possible new operator to add to python References: <3a8fc6c5.0307100816.634c83a3@posting.google.com> <5_gPa.8878$ru2.867718@news20.bellglobal.com> Message-ID: In article <5_gPa.8878$ru2.867718 at news20.bellglobal.com>, Sean Ross wrote: >"Adam Gent" wrote in message >news:3a8fc6c5.0307100816.634c83a3 at posting.google.com... >> >> I was fooling around subclassing a dictionary object and noticed that >> when >> I do the standard "for in :" that I have no >> control on how python gets that sequence. >[snip] >> However I want b to be the values with out doing: >> for b in bl.values() > >You can do it as follows: > >class Blah(dict): > def __iter__(self): > return iter(self.values()) Ick. At the very least, return self.itervalues() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From manish.j at gmx.net Fri Jul 25 20:25:09 2003 From: manish.j at gmx.net (Manish Jethani) Date: Sat, 26 Jul 2003 05:55:09 +0530 Subject: decimal to binary In-Reply-To: References: <200307250653.18754.gherron@islandtraining.com> Message-ID: manuel wrote: >>if listByte[17] & (1 << 3): > > > > Thanks! > > But I don't understand completely the meaning of > & (1 << 3) (1 << 3) will left-shift 1 by 3 bits 00000000 00000000 00000000 00000001 giving you 8 00000000 00000000 00000000 00001000 Then you AND your number (25, for example) with 8 00000000 00000000 00000000 00011001 00000000 00000000 00000000 00001000 ----------------------------------- 00000000 00000000 00000000 00001000 if you get a non-zero value, then the bit is set. If your number is 23 00000000 00000000 00000000 00010111 00000000 00000000 00000000 00001000 ----------------------------------- 00000000 00000000 00000000 00000000 then the result of the AND is 0, and that means the bit is not set. > Can you suggest me a page in python on line manual, > or a tutorial? See the section on bit-wise operations in the Python Reference Manual. -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From bokr at oz.net Wed Jul 9 19:44:02 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Jul 2003 23:44:02 GMT Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: On Wed, 09 Jul 2003 23:36:03 +0200, Behrang Dadsetan wrote: >Walter D?rwald wrote: > >> Behrang Dadsetan wrote: >> >>> Hi all, >>> >>> I would like deleting specific characters from a string. >>> As an example, I would like to delete all of the '@' '&' in the >>> string 'You are ben at orange?enter&your&code' so that it becomes >>> 'benorange?enteryourcode'. >>> >>> So far I have been doing it like: >>> str = 'You are ben at orange?enter&your&code' >>> str = ''.join([ c for c in str if c not in ('@', '&')]) >>> >>> but that looks so ugly.. I am hoping to see nicer examples to acheive >>> the above.. >> >> >> What about the following: >> >> str = 'You are ben at orange?enter&your&code' >> str = filter(lambda c: c not in "@&", str) Aaack! I cringe seeing builtin str name rebound like that ;-/ >> >> Bye, >> Walter D?rwald > >def isAcceptableChar(character): > return charachter in "@&" return character not in "@&" > >str = filter(isAcceptableChar, str) > >is going to finally be what I am going to use. That's not going to be anywhere near as fast as Donn's translate version. >I not feel lambdas are so readable, unless one has serious experience in >using them and python in general. I feel it is acceptable to add a named >method that documents with its name what it is doing there. > >But your example would probably have been my choice if I was more >familiar with that type of use and the potential readers of my code were >also familiar with it. Many thanks! > IMO, if you are going to define a function like isAcceptableChar, only to use it with filter, why not write a function to do the whole job, and whose invocation reads well, while hiding Donn's fast translate version? E.g., substituting the literal value of string.maketrans('',''): ====< removechars.py >======================================================== def removeChars(s, remove=''): return s.translate( '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' ' !"#$%&\'()*+,-./' '0123456789:;<=>?' '@ABCDEFGHIJKLMNO' 'PQRSTUVWXYZ[\\]^_' '`abcdefghijklmno' 'pqrstuvwxyz{|}~\x7f' '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f' '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f' '\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf' '\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf' '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf' '\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf' '\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef' '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' , remove) if __name__ == '__main__': import sys args = sys.argv[1:] fin = sys.stdin; fout=sys.stdout; remove='' # defaults while args: arg = args.pop(0) if arg == '-fi': fin = file(args.pop(0)) elif arg == '-fo': fout = file(args.pop(0)) else: remove = arg for line in fin: fout.write(removeChars(line, remove)) ============================================================================== Not tested beyond what you see here ;-) [16:40] C:\pywk\ut>echo "'You are ben at orange?enter&your&code'" |python removechars.py "@&" "'You are benorange?enteryourcode'" [16:41] C:\pywk\ut>echo "'You are ben at orange?enter&your&code'" |python removechars.py aeiou "'Y r bn at rng?ntr&yr&cd'" Copying a snip above to the clipboard and filtering that with no removes and then (lower case) vowels: [16:41] C:\pywk\ut>getclip |python removechars.py >I not feel lambdas are so readable, unless one has serious experience in >using them and python in general. I feel it is acceptable to add a named >method that documents with its name what it is doing there. > >But your example would probably have been my choice if I was more >familiar with that type of use and the potential readers of my code were >also familiar with it. Many thanks! [16:42] C:\pywk\ut>getclip |python removechars.py aeiou >I nt fl lmbds r s rdbl, nlss n hs srs xprnc n >sng thm nd pythn n gnrl. I fl t s ccptbl t dd nmd >mthd tht dcmnts wth ts nm wht t s dng thr. > >Bt yr xmpl wld prbbly hv bn my chc f I ws mr >fmlr wth tht typ f s nd th ptntl rdrs f my cd wr >ls fmlr wth t. Mny thnks! Regards, Bengt Richter From m at moshez.org Wed Jul 16 13:51:20 2003 From: m at moshez.org (Moshe Zadka) Date: 16 Jul 2003 17:51:20 -0000 Subject: anything like C++ references? In-Reply-To: <1058377188.3f158de4a3a51@mcherm.com> References: <1058377188.3f158de4a3a51@mcherm.com> Message-ID: <20030716175120.17884.qmail@green.zadka.com> On Wed, 16 Jul 2003, Michael Chermside wrote: > stuff[i] = newComplexObject(i++, "name", "fred") I'm not entirely sure that C code is not undefined. I think it is, but it could be that I'm mistaken and that "=" is a "sequence point". It's a variant on the old a[i]=i++ thing. The problem here is that it's not certain what happens first -- the a[i] (evalating to an lvalue) or i++. Since an optimizing compiler might even put both instruction in a single pipeline, it could be that i is neither the old value or the new value at all by the time a[i] is on the stack. In fact, the C standard, if I'm right, gives the C compiler carte blanche to do whatever it feels like doing. In Python, you'd've been forced to write i+=1 stuff[i] = nCO(i) or stuff[i] = nCO(i) i+=1 or j,i=i,i+1 stuff[i] = nCO(j) depending on what you meant. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From adalke at mindspring.com Wed Jul 30 22:14:23 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 30 Jul 2003 20:14:23 -0600 Subject: python in parallel for pattern discovery in genome data References: Message-ID: BalyanM: > I am interested to run python on a sun machine(SunE420R,os=solaris) > with 4 cpu's for a pattern discovery/search program on biological > sequence(genomic sequence).I want to write the python code so that it > utilizes all the 4 cpu's. *oomphh* There's a lot of details buried in your lines. It looks like you will be writing your own pattern matching code. Why? There are plenty of tools for that already. A quick web search finds http://genome.imb-jena.de/seqanal.html and many of those tools are freely available. Okay, suppose you do have the tool or library for it. Do you want to do high throughput searches? Then you can just break your N jobs into N/4 parts, one per machine. Easiest way in Python is to run 4 Python programs, each with a little server going (see the xmlrpc module for an example) and have your code call them (see Aahz's excellent example of master/slave programming using threads). Other options for the communications are Twisted and Pyro. You will not be able to do this with one Python process because Python has what's called the "global interpreter lock" that prevents core Python from effectively using multiple processors. You can write a C extension which does the search and gives up the lock, but I you seem to want to do this in raw Python. (The suggestion to look at POSH won't work - it has some Intel-specific assembly instructions in the C extension.) Depending on the type of pattern search, you instead can assign 1/4 of the genome to each process, with overlap if needed. This will speed up a single search, which is good for interactivity. These work for a single "user" of the code. Might you have many people trying to do pattern searches? If so, you may need some way to throttle how many searches are done per machine. For in-house use this likely isn't a problem - besides, you should get your code working first. There are other approaches. You could use shared memory or CORBA for the communications, or PVM or MPI. Still, given your experience, you should: 1) get your algorithm working on one machine 2) get it working as a client/server using XML-RPC (see the SimpleXMLRPCServer and xmlrpclib modules), 3) get your client to work with multiple servers, using multiple threads in the client (It's a bit of my experience too - I really should try Pyro for this sort of work. Well, I need a break so maybe I'll try it out tonight ;) There are a lot of skills to learn before it all works, so don't get too discouraged too quickly. Andrew dalke at dalkescientific.com From mwh at python.net Fri Jul 18 12:48:03 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Jul 2003 16:48:03 GMT Subject: How to identify the method that has called another method ? References: <764b8294.0307180620.37781a4@posting.google.com> Message-ID: <7h34r1j23g1.fsf@pc150.maths.bris.ac.uk> martin_a_clausen at hotmail.com (Mars) writes: > I am using Python 2.2.3 and new-style classes. I want to implement a > static factory method to build objects for me. My plan is to have > __init__ check that it has been called from said factory method and > not directly. Is there a elegant way of achieving this ? No. sys.getframe(1).f_code.co_name might be a start. > (and is this a silly idea in general ?) I've always disliked trying to disallow this kind of abuse -- it's very hard to make it impossible, and I think you're better off just documenting the restrictions. Note that you might want to investigate __new__() by the sounds of it... Cheers, M. -- 31. Simplicity does not precede complexity, but follows it. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From tim at remove_if_not_spam.digitig.co.uk Wed Jul 16 11:13:11 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Wed, 16 Jul 2003 16:13:11 +0100 Subject: Numarray for Python 2.3 Message-ID: Does numarray-0.5.win32-py2.2.exe work with Python 2.3? If not, is there a version that will? Tia, Tim From ianb at colorstudy.com Sat Jul 5 16:49:26 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 05 Jul 2003 15:49:26 -0500 Subject: Calculating Year, Month and Day of Life In-Reply-To: References: Message-ID: <1057438165.514.161.camel@lothlorien> On Sat, 2003-07-05 at 12:48, hokiegal99 wrote: > Hello, > > I am a funeral director trying to write a small program that calculates > the number of years, months and days a person has lived by entering the > year, month and day of their birth. This is what I have so far: You might want to look at mxDateTime, or Python 2.3's datetime module, which will probably provide functions to make this calculation significantly easier -- counting days in years, adjusting for leap years, etc. Well, that's if you want to be exact, which may not really be important. Ian From rich at mchsi.com Tue Jul 29 23:58:10 2003 From: rich at mchsi.com (Rich) Date: Wed, 30 Jul 2003 03:58:10 GMT Subject: how best to handle httplib timeouts ? Message-ID: Hi all, I'm trying to write an app to monitor an IIS server, by connecting and getting a page via httplib. the problem seems to be when IIS (or ASP) dies httplib does not always return and sometimes I'm left with an app that hangs. what is the best way to handle this ? thanks, rich. the code looks like this: try: res = h.getresponse() dat = res.read() sFlag = sFlag + 1 except: if debug > 0: WriteLog(' Error receiving a response from 2nd mailbox page request') h.close() return sFlag From remi at cherrypy.org Mon Jul 28 05:59:05 2003 From: remi at cherrypy.org (Remi Delon) Date: Mon, 28 Jul 2003 10:59:05 +0100 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> Message-ID: <3f24f3f7@shknews01> > I've read the doc of most of them, I've tested some of them. > But, is there anyone "experienced user" who can give the pro-cons for each > of those solutions ? (or propose an another) The problem is that most people are "experienced users" with only a few of the frameworks. In order to find out all the little caveats of a perticular framework, one has to use it for quite a big project (I'd say at least 6 months). I don't think any of us have developed such big projects with more than, say, 2 or 3 python frameworks. (in my case, I've only used Zope and CherryPy for "real" applications. I've only "played" with the other frameworks). This is why it is hard to have one person make a comparison of all the frameworks ... Having said that, I think that CherryPy definitely meets your requirements... (sorry, I couldn't help saying it :-))) Remi. remi at cherrypy.org ---------------------- Specialized python hosting: http://www.python-hosting.com CherryPy application server: http://www.cherrypy.org Free CherryPy hosting: http://www.freecherrypy.org ---------------------- From gradha at titanium.sabren.com Sat Jul 26 06:15:06 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sat, 26 Jul 2003 12:15:06 +0200 Subject: ANN: mailbox_date_trimmer 1.0.1 -- Correct emails' date headers in a mailbox archive. Message-ID: <20030726101506.GA1467@pedos.es> Changes Improved documentation. Removed stdin pipe detection hack. Many small date parsing errors found and fixed after running the program over 500 MB of mailing list archives. Scenario description You are a mailing list administrator, or you are somebody who keeps mailing list archives for a user group, or you just have a fetish for email archives. Now, don't you always wonder why after running Hypermail or MHonArc on your archives you always have some emails which date back to 1980 or far away in the future like 2011, even though you started collecting emails in the year 2000 and it's still this very same year? While there are many answers to this question, there is a very easy way to fix many, if not all, of these messages, which results in a much more consistent email archive without broken discussion threads. Software requisites This software requires Python (http://www.python.org). It is known to work with versions 1.5.2 or 2.2.3. You also need my mailbox_reader module, which you should be able to get from: http://gradha.sdf-eu.org/program/mailbox_reader.en.html Download http://gradha.sdf-eu.org/program/mailbox_date_trimmer.en.html License GPL -- Please don't send me private copies of your public answers. Thanks. From alex.lapp at bpanet.de Thu Jul 17 04:34:13 2003 From: alex.lapp at bpanet.de (Alex Lapp) Date: Thu, 17 Jul 2003 10:34:13 +0200 Subject: Problems installing cvs / errno? Message-ID: <3F165F85.702@bpanet.de> Hi ng, i have a problem installing cvs module from: http://www.object-craft.com.au/projects/csv/ My Python version is: Python 2.1.3 (Not the latest, but i need this version for running Zope Application Server) I downloaded the package (csv-1.0) and tried to install with python setup.py install. But i got following errormessages: -snip- running install running build running build_ext building 'csv' extension skipping csv.c (build/temp.freebsd-4.8-RELEASE-i386-2.1/csv.o up-to-date) cc -shared -pthread build/temp.freebsd-4.8-RELEASE-i386-2.1/csv.o -o build/lib.freebsd-4.8-RELEASE-i386-2.1/csv.so Traceback (most recent call last): File "setup.py", line 63, in ? license = 'BSD - see file LICENCE', File "/usr/local/lib/python2.1/distutils/core.py", line 138, in setup dist.run_commands() File "/usr/local/lib/python2.1/distutils/dist.py", line 899, in run_commands self.run_command(cmd) File "/usr/local/lib/python2.1/distutils/dist.py", line 919, in run_command cmd_obj.run() File "/usr/local/lib/python2.1/distutils/command/install.py", line 480, in run self.run_command('build') File "/usr/local/lib/python2.1/distutils/cmd.py", line 328, in run_command self.distribution.run_command(command) File "/usr/local/lib/python2.1/distutils/dist.py", line 919, in run_command cmd_obj.run() File "/usr/local/lib/python2.1/distutils/command/build.py", line 106, in run self.run_command(cmd_name) File "/usr/local/lib/python2.1/distutils/cmd.py", line 328, in run_command self.distribution.run_command(command) File "/usr/local/lib/python2.1/distutils/dist.py", line 919, in run_command cmd_obj.run() File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 256, in run self.build_extensions() File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 383, in build_extensions self.build_extension(ext) File "/usr/local/lib/python2.1/distutils/command/build_ext.py", line 475, in build_extension build_temp=self.build_temp) File "/usr/local/lib/python2.1/distutils/ccompiler.py", line 663, in link_shared_object extra_preargs, extra_postargs, build_temp) File "/usr/local/lib/python2.1/distutils/unixccompiler.py", line 235, in link self.spawn(self.linker_so + ld_args) File "/usr/local/lib/python2.1/distutils/ccompiler.py", line 826, in spawn spawn (cmd, verbose=self.verbose, dry_run=self.dry_run) File "/usr/local/lib/python2.1/distutils/spawn.py", line 38, in spawn _spawn_posix(cmd, search_path, verbose, dry_run) File "/usr/local/lib/python2.1/distutils/spawn.py", line 108, in _spawn_posix exec_fn(cmd[0], cmd) File "/usr/local/lib/python2.1/os.py", line 291, in execvp _execvpe(file, args) File "/usr/local/lib/python2.1/os.py", line 305, in _execvpe from errno import ENOENT, ENOTDIR ImportError: No module named errno error: command 'cc' failed with exit status 1 -snip- Is there a problem with the errno module? Can i install the module manually. I can compile the csv.c code manual to a csv.o object. How can i compile the source to a python object? Any other ideas? Thanks and forgive my bad english, ;) Alex From mkc at stowers-institute.org Wed Jul 2 10:50:03 2003 From: mkc at stowers-institute.org (Michael Coleman) Date: 02 Jul 2003 09:50:03 -0500 Subject: os.fork() different in cgi-script? References: Message-ID: <85adbxouec.fsf@stowers-institute.org> "Andreas Kuntzagk" writes: > def main(): > print "Content-Type: text/plain\n\n" > print os.getpid() > > childPID = os.fork() > if childPID == 0: > sys.exit() > else: > os.wait() > > if __name__ == "__main__": > main() > > when run on a shell, gives the result: > --------------------------- > Content-Type: text/plain > > > 20953 > ---------------------------- > > but run as a cgi-script it gives: > --------------------------- > 21039 > Content-Type: text/plain > > > 21039 > --------------------------- > So it looks the main() is run 2 times. > Is it so? And if yes, why? Probably because stdout is being buffered here. The pid got written in the buffer (but not yet actually printed), then the process was forked, then the buffer got flushed (written out) by each child. One solution would be to make sure everything is flushed before you fork. Mike -- Mike Coleman, Scientific Programmer, +1 816 926 4419 Stowers Institute for Biomedical Research 1000 E. 50th St., Kansas City, MO 64110 From ianb at colorstudy.com Sun Jul 13 21:18:25 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2003 20:18:25 -0500 Subject: anything like C++ references? In-Reply-To: References: Message-ID: <1058145504.28467.499.camel@lothlorien> I don't know why I'm participating, but it's feels hard to stay out of this one... On Sun, 2003-07-13 at 17:17, Martin v. L?wis wrote > > 3. Why is there no way to reference an immutable object via a > > pointer, other than stuffing it into a mutable object designed for > > some purpose other than simple pointer behaviour? > > But there is: If I do > > a = 1 > b = a > > then b *refers* the same value that a refers to. That is, the values > associated with a and b have the same identity. I think, then, that Stephen maybe wants to do something like: >>> a = ref(1) >>> b = a >>> b is a True >>> a + 2 3 >>> a = 5 >>> b 5 And so on. This is all quite doable in Python (implementation of ref left to the reader), except for the "a = 5" part. Instead you'd have to do something like "a.set(5)". Even though it is doable, of course, it's by way of clever hacks. The problem that Stephen is not appreciating is that this sort of reference implies that "a" is a typed variable -- of type "pointer", somehow implicitly declared when it was initially assigned a ref object. (He's not alone, because just a little while ago someone proposed a way to overload the meaning of "=", to achieve largely the same functionality) It might not be quite as ugly-seeming if we explicitly declared "a" as a pointer. Besides the disinclination of people to add variable declarations (though "global" already is one), it's more difficult because there's now a new type that has to be usable everywhere, the pointer type. All Python's code that expected, say, integers would have to also be ready to dereference the argument and then use it. It could probably be made seamless at the Python level fairly easily, but the C would be annoying, no doubt. One might think you could just use the references that already exists (since variables are references, and everything is passed by reference). But that's messed up, because that'd mean: >>> b = 2 >>> pointer a >>> a = 2 >>> a is b True >>> a = 5 >>> b 5 The ability to redefine the integers is obviously not a good feature (though I remember someone saying you can accidentally do some stuff like this in C extensions). Anyway, that's my attempt at empathy with Stephen, if not agreement. If he is wanting something other than what I've described, he should give other examples, because code examples are better than words. Ian From jhefferon at smcvt.edu Fri Jul 4 07:25:47 2003 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 4 Jul 2003 04:25:47 -0700 Subject: When is unit-testing bad? References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> <87k7azdber.fsf@titan.staselog.com> Message-ID: <545cb8c2.0307040325.49bcfaf8@posting.google.com> "Jeremy Bowers" wrote > We're using mod_perl, and I'm using Test::Unit, which is a testing > framework for Perl deliberately set up to look like JUnit, as Python's > unittest is. What I'm doing is implementing an Apache Request faked-up > object (which I later found existed in the form of the Perl module > Apache::FakeRequest, but I think my own solution is better suited to our > needs anyhow), and then going ahead and calling the Apache handlers > directly with that object. It's tedious to construct the object if you > can't find one pre-made, but it's easy. > Does anyone know of a place where I could see a sample of doing this under Python? Thanks in advance Jim From scottholmes at sbcglobal.net Tue Jul 29 19:54:01 2003 From: scottholmes at sbcglobal.net (Scott Holmes) Date: Tue, 29 Jul 2003 16:54:01 -0700 Subject: Looking for recommendations Message-ID: <3F270919.9050308@sbcglobal.net> I've yet to write anything worthwhile with Python, but I have been working my way through the O'Reilly books and scanning this list. I am considering porting a legal case management system to python and would like some input as to the best configuration of modules and interfaces for this. I wish to use PostgreSQL for a database engine and tie into OpenOffice as well. I need to be able to develop a suite of GUI programs with a fairly large number of pull down lists, browse screens, header/detail screens and the ability to jump between programs and back again without loosing state. This legal system has been around for many years as an Informix 4GL system on SCO. A few years ago it was ported to a now defunct Windows based language, an Informix and a PostgreSQL version were produced. I need to be able to produce a suite of programs portable to Linux, Windows and Apple if at all possible. Life on multiple learning curves is stressful, so I would appreciate any pointers to similar applications. I've noticed a few but am concerned about commiting to particular optional modules. I'm currently working on a RedHat 7.2 with three versions of Python. The latest being 2.2 that I installed myself. I have tk 8.3 Thanks in advance... -- --------------------------------------------------------------------- Scott Holmes http://sholmes.ws http://pages.sbcglobal.net/scottholmes scottholmes at sbcglobal.net Independent Programmer/Analyst Passport 4GL PHP HTML Composer PostgreSQL Informix 4GL, SQL --------------------------------------------------------------------- There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy --------------------------------------------------------------------- From dkuhlman at rexx.com Fri Jul 18 20:29:59 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 18 Jul 2003 17:29:59 -0700 Subject: ANN: zip-ls -- Zip file listing program Message-ID: I've implemented a Zip file listing program that gives me some of the listing and formatting options that I've wanted from "unzip -l" and "unzip -Z". It's written in Python using the zipfile module from the Python standard library. You can find it here: http://www.rexx.com/~dkuhlman/#zip-ls http://www.rexx.com/~dkuhlman/zip-ls.html http://www.rexx.com/~dkuhlman/zip-ls.zip What is it? *zip-ls* lists the contents of Zip files. It provides controls over which columns are displayed, whether totals are displayed, sorting on various columns, etc. *zip-ls* uses a configuration file (~/.zip-lsrc), which enables the user to specify default settings for command-line flags. *zip-ls* is written in Python, making it very customizable. If you have suggestions or need help with it, please let me know. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From max at alcyone.com Tue Jul 15 20:29:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Jul 2003 17:29:29 -0700 Subject: anything like C++ references? References: Message-ID: <3F149C69.7B990210@alcyone.com> Stephen Horne wrote: > > On 15 Jul 2003 10:19:18 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark > 'Kamikaze' Hughes) wrote: > > >> Really. My computer science lessons were taught in a way that > >> respected the source of most of the theory in mathematics - > >> algorithms, Church's lambda calculus and that kind of stuff. > >> What did your lessons teach? > > > > How computer programming actually works, how to make interpreted and > >compiled languages, how to use them to solve problems, how to analyze > >algorithms, etc.... The usual. > > You say that as if it contradicts the idea of respecting the source of > the theory. It doesn't. > > > Among those were classes in languages > >other than C, which is very broadening, and I highly recommend that to > >you. > > Lets see. > > Probably about a dozen basics, five assembler languages (6502, z80, > 68000 series, 8086 series, 80C196KC microcontroller), forth, lisp, > prolog, miranda, haskell, icon, ada, pascal, modula 2, cobol, > smalltalk. Not all of them very seriously, though, and in many cases > not recently. > > I forget the name of that language designed for transputers, but I > used that a bit at college too - and depending on your inclination you > may want to include SQL. And yes, I have used C, C++ and Java as well. > > That's just off the top of my head, of course. > > But there's no way you can call me C centric. That has been a repeated > accusation, but it is WRONG. > > Python has been an everyday language for me LONGER than C++ has. > > >> Respect the idea of variables binding to values and suddenly the need > >> for pointers becomes more obvious. You cannot abuse mutable objects to > >> fake pointer functionality (another everyday fact of Python > >> programming) if the binding of variables to values (rather than just > >> objects) is respected. > > > > If you're trying to say that the trick I showed you of modifying a > >list to reproduce the effect of reference arguments is not possible in, > >say, C, you're wrong. Trivially proven wrong, even, since Python is > >implemented in C. In fact, the only languages where that won't work are > >those which don't allow passing complex arguments at all; some > >pure-functional toy languages, perhaps. > > Distorting what I said, again. I have already repeatedly said that the > point about C is what happens by default - not what happens when you > explicitly request otherwise. > > Lets take an example from C++ to illustrate the point. > > std::string x = "123"; > std::string y = x; > > // At this point, in most implementations, x and y are bound to the > // same object due to a lazy copy optimisation. However, the > // programmer didn't request this optimisation so this > // implementation detail is expected to be transparent to the user. > // Therefore... > > y [2] = 4; > > // Before doing this operation, a copy was made - the so called > // copy on write. > // The value bound to x is still "123" > // The value bound to y is now "124" > > C++ is using references here just as Python does, but despite being a > crappy low level language it still manages to implement that without > causing remote side-effects through mutability *unless* you explicitly > request that. But (ignoring for the moment Tom's point about this not really being true in modern implementations) that's really an implementation detail and is unimportant. C has copy semantics; whether it's optimizes some away when they're not necessary is an implementation detail that is unimportant from the programmer's perspective. I did something very similar in a stack-based language I designed (and implemented partially in C, and then more extensively in Python). There are no pointers or references, only objects. All objects are distinct; changing one never affects any others. But since this is a stack-based language, there's lots of duplicating things on stack for the purposes of a computation. As an implementation detail (and since I basically got it for free in Python since all Python objects do the reference counting for me), if you duplicate an object, I actually duplicate a reference to it internally. If you mutate an object, then it mutates it if there are no other references to it, but does an actual duplication and then mutates that if there are -- so it implements lazy copying. But the fact this is done at all is completely and utterly and implementation detail. From the programmer's point of view, it makes no difference. Python does _not_ have copy semantics, it has binding semantics. As a reversed example, when multiple bindings exist to the same immutable object, it's an implementation detail whether or not those really are all to the same object. You don't care, because you know its value can't change. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Nine worlds I remember. \__/ Icelandic Edda of Snorri Sturluson From adalke at mindspring.com Mon Jul 7 16:55:35 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 7 Jul 2003 14:55:35 -0600 Subject: anything new on the ternary operator? References: , <3F09252F.9B0F52BD@alcyone.com>, Message-ID: Moshe Zadka: > Well, to be quite honest, there were some "New Europe" attendees. The > most excellent Lithuanians, and yours truly. As well as some of us 'mericans. 6, if I interpreted the stats correctly. Andrew dalke at dalkescientific.com From oren at REMOVETHIS1.hishome.net Mon Jul 21 11:04:59 2003 From: oren at REMOVETHIS1.hishome.net (Oren Tirosh) Date: 21 Jul 2003 08:04:59 -0700 Subject: [OT] On the TimBot References: <62slgvsljos7v5snie6toc4qucv5nt1n15@4ax.com> Message-ID: Christos "TZOTZIOY" Georgiou wrote in message news:<62slgvsljos7v5snie6toc4qucv5nt1n15 at 4ax.com>... ... > 3. To "Tron" fans: yes, you could assign the name TimBit to it, but it's > a broken Bit; what's the use of a Bit that's always true? Henry Spencer is well known around the sci.space.* newsgroups for being very rarely wrong. About as rarely as the TimBot. People that manage to correct Henry get the coveted "I Corrected Henry" virtual T-shirt. May I propose the "I Corrected Timbot" award? From omega at silvreus.eu.org Mon Jul 14 08:34:48 2003 From: omega at silvreus.eu.org (OM) Date: Mon, 14 Jul 2003 14:34:48 +0200 Subject: training for newbies References: Message-ID: U?ytkownik "Jarek Zgoda" napisa? w wiadomo?ci news:betv87$4jq$1 at atlantis.news.tpi.pl... > OM pisze: > > > do you know any sites with free programs for newbies, which will help me in > > progress? i know that only way to develop is writing programs, but in my > > book i don't have programs to write, only questions.. > > Check out http://www.uselesspython.com and Python Cookbook at > http://aspn.activestate.com > > Dzieki:] A polskie ? From peter at engcorp.com Thu Jul 24 19:17:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jul 2003 19:17:02 -0400 Subject: OT, was: Re: needs a logo References: <7fe97cc4.0307230144.9119f89@posting.google.com> <3f205ac9.745241690@news.blueyonder.co.uk> Message-ID: <3F2068EE.8366B14F@engcorp.com> Alan Gauld wrote: > > This is way OT but... > > On 23 Jul 2003 02:44:05 -0700, xah at xahlee.org (Xah Lee) wrote: > > > Better logos should be reminiscent to what it represents. Good > > example's are ... Shell's seashell, > > I remember my grandfather telling me that the Shell logo > originated around WW2 time and it represented a shell exploding > (message => dynamic powerful company) on a building > and was in two colors. After the war it was deemed > a bad marketing image to use warlike logos so they > "re-badged" the company as being around sea shells and > the logo changed to what we know today. > > I've never seen any other reference to this anywhere. > Does anyone know of a source (another grandfather?!) > that can confirm or deny this? Not exactly deny, but at a gallery/museum of design in Rotterdam, which I visited two months ago, there was an exhibit showing various almost iconic products, including the Shell logo, complete with history on their development, and no mention whatsoever was made of this background. Perhaps it was sanitized, but for what it's worth... -Peter From max at alcyone.com Fri Jul 18 00:57:36 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2003 21:57:36 -0700 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <3F177E40.6A5BFBB4@alcyone.com> Ben Finney wrote: > I think it looks like a series of identical question marks. > Presumably > you wrote it using a character set my terminal isn't using, and you > had > no way of instructing my computer to use. When you see the right number of question marks, that usually means whatever's processing it knows it's dealing with Unicode, but can't display the glyphs. So your terminal knows the character set, it just doesn't have the glyphs in the font it's using. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Wretches hang that jurymen may dine. \__/ Alexander Pope From ianb at colorstudy.com Wed Jul 2 15:43:06 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 02 Jul 2003 14:43:06 -0500 Subject: What's the use of module spaces? (was Re: Circular Inheritance) In-Reply-To: References: Message-ID: <1057174986.726.166.camel@lothlorien> On Wed, 2003-07-02 at 10:03, Aahz wrote: > In article , > Ian Bicking wrote: > > > >You might encounter less problems if those classes go together in a > >single module, but module boundaries are just there to help the > >programmer organize code, they have little formal meaning. > > That's not true. Modules define a namespace, and Python's execution > model makes heavy use of the "global" (read, current module's) namespace > for name resolution. Certainly modules have considerable *semantics* and effect execution. But they have little *meaning*. There's all sorts of semantics associated with classes, but that's incidental to the meaning of a class -- a class is a set up behaviors common to a kind of object. A module is just a pile of stuff the programmer likes to keep together. It's essentially a clerical feature. Ian From news at datatailors.xs4all.nl Thu Jul 10 18:07:59 2003 From: news at datatailors.xs4all.nl (Peter van Kampen) Date: Fri, 11 Jul 2003 00:07:59 +0200 Subject: Parsing References: Message-ID: In article , Michael wrote: > I have been assigned a project to parse a webpage for data using > Python. I have finished only basic tutorials. Any suggestions as to > where I should go from here? Thanks in advance. Try to be a little more specific. Parse for what? Links? Images? Tags? Anyway. A good start might be the HTMLParser that comes with the batteries since 2.2 if I remember correctly. See http://www.python.org/doc/current/lib/htmlparser-example.html for a tiny example. PterK -- Peter van Kampen pterk -- at -- datatailors.com From stephen.boulet at motorola.com Mon Jul 21 15:59:43 2003 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Mon, 21 Jul 2003 14:59:43 -0500 Subject: os.spawn[*] help Message-ID: Can someone who understands the os module better than I offer some insight? I want to open some text in xemacs (on Windows) using os.spawn[*], but I want the text to appear in the current xemacs window, as opposed to opening a new xemacs window. Is this doable? Thanks. -- Stephen From alanmk at hotmail.com Mon Jul 14 11:32:57 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 14 Jul 2003 16:32:57 +0100 Subject: Encoding error References: Message-ID: <3F12CD29.E0308BE0@hotmail.com> Casey Kohrt wrote: > I get the following error for the list item below. I know I have to > encode it, but am unsure how or where to write that in. I am new to > python and have had good luck thus far. Any help is greatly > apprecieated. I am not on the list, so a response to me is > appreciated. > > UnicodeError: ASCII encoding error: ordinal not in range(128) > > eainfo = doc.createElement("eainfo") > metadata.appendChild(eainfo) > overview = doc.createElement("overview") > eainfo.appendChild(overview) > eaover = doc.createElement("eaover") > text = doc.createTextNode(str(list[83])) > eaover.appendChild(text) > overview.appendChild(eaover) Hmm, the code that you posted has several errors, and doesn't run. You'll find it much easier to get help if you post instances of running code that is giving you a problem. Also, a description of what you're trying to achieve would be most helpful. Here is a version of your code where I have fixed the errors, which may or may not do something related to what you want. #======================================= import xml.dom.minidom doc = xml.dom.minidom.parseString('') metadata = doc.documentElement eainfo = doc.createElement("eainfo") metadata.appendChild(eainfo) overview = doc.createElement("overview") eainfo.appendChild(overview) eaover = doc.createElement("eaover") text = doc.createTextNode(chr(83)) #text = doc.createTextNode(' '*83) (?) eaover.appendChild(text) overview.appendChild(eaover) print doc.toxml() #======================================= If I haven't even come close, then you really need to post actual running code that you're using, and tell us where it's going wrong for you. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ianb at colorstudy.com Mon Jul 7 17:11:26 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 07 Jul 2003 16:11:26 -0500 Subject: Is there any solution in PYTHON? In-Reply-To: <3F09F032.20821.AC27E76@localhost> References: <3F09F032.20821.AC27E76@localhost> Message-ID: <1057612286.5348.331.camel@lothlorien> On Mon, 2003-07-07 at 15:12, A wrote: > Hi, > I have a program that downloads some web pages. Sometimes there is a poor internet > connection and my script freezes( hangs) and does not download ALL pages. > Is there any solution how to test if the program works and if not re-start it from the point > where it stopped? > Or simply how to download ALL pages eventhough there is a timeout connection( can be > of any value)? Here ya' go: class Timeout(Exception): pass def timeout(time, func, *args): def timeout_handler(signum, frame): raise Timeout signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(time) val = func(*args) signal.alarm(0) return val To use: def try_get_page(url): # get the page, may block def get_page(url): while 1: try: page = timeout(10, try_get_page, url) except Timeout: pass else: return page Note that this will not work in a multithreaded environment due to the nature of the alarm signal. Ian From jepler at unpythonic.net Tue Jul 22 16:48:20 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 22 Jul 2003 15:48:20 -0500 Subject: A challenge to the ASCII proponents. In-Reply-To: <60dfb6f6.0307201951.4eea1930@posting.google.com> References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <60dfb6f6.0307201951.4eea1930@posting.google.com> Message-ID: <20030722204816.GB11779@unpythonic.net> Carl, didn't work in my screen-reading program. "minus minus minus minus (pause) minus minus ..."'ly yours, Jeff From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 24 18:12:43 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 25 Jul 2003 00:12:43 +0200 Subject: Don't want to do the regexp test twice In-Reply-To: References: Message-ID: <3f2059da$0$49114$e4fe514c@news.xs4all.nl> Egbert Bouwman wrote: > While looping over a long list (with file records) > I use an (also long) if..elif sequence. > One of these elif's tests a regular expression, and > if the test succeeds, I want to use a part of the match. I'd do it like this: pat = re.compile(r'...') for line in mylist: if ... : .... elif ... : .... *** insert all the ifs that don't need the regexp *** .... else: mat = pat.search(line) if mat: ....do stuff because pattern does match..... else: ....everything else.... HTH, Irmen de Jong From BPettersen at NAREX.com Fri Jul 25 19:02:44 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 25 Jul 2003 17:02:44 -0600 Subject: Static typing Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE473B@admin56.narex.com> > From: Shane Hathaway [mailto:shane at zope.com] > > Bjorn Pettersen wrote: > >>From: Shane Hathaway [mailto:shane at zope.com] > >>def foo(bar, baz): > >> assert isinstance(bar, int) > >> assert isinstance(baz, str) > > > > [...] > > > > ...which means you can't use foo with unicode strings or > UserStrings, > > That's right, and that's intentional. The function is > designed to work only with byte arrays. This invites > someone who wants to pass a unicode object to first > verify that the function will actually work properly > with unicode. [...] However, the only way said programmer can do that is by looking at _your_ code, and then changing _your_ code. Wouldn't: def foo(bar, baz): """... Expects: bar: integer in the range (0..65535) baz: string (used as binary data) ... """ be much more useful for said programmer? Afterall, we're all adults here. -- bjorn From reply.in.the.newsgroup at my.address.is.invalid Wed Jul 23 11:55:38 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 23 Jul 2003 17:55:38 +0200 Subject: htaccess & urllib References: <52yTa.21249$On.2682411@twister.nyc.rr.com> Message-ID: Max Khesin: >Is there a way to access an htaccess-protected directory with urllib, >password being known? .htaccess is not a protection mechanism, but a configuration file. If this configuration file specifies HTTP Basic Authentication you can use: "class FancyURLopener(...) basic HTTP authentication is performed ... Note: When performing basic authentication, a FancyURLopener instance calls its prompt_user_passwd() method. The default implementation asks the users for the required information on the controlling terminal. A subclass may override this method to support more appropriate behavior if needed." http://www.python.org/doc/current/lib/module-urllib.html -- Ren? Pijlman From c-b-o-o-m-e-r at tiscali.co.uk Tue Jul 29 10:25:12 2003 From: c-b-o-o-m-e-r at tiscali.co.uk (Christopher Boomer (don't dash!)) Date: Tue, 29 Jul 2003 15:25:12 +0100 Subject: DOM as a flat dictionary References: <3f21335a_2@mk-nntp-2.news.uk.tiscali.com> <23891c90.0307290358.554c7ef8@posting.google.com> Message-ID: <3f26c285_2@mk-nntp-2.news.uk.tiscali.com> Paul, Neil, > > there is no way that you can tell whether /spam/eggs comes before > > /spam/bacon in the original XML. I'm not sure that the order is important in any of the documents I am dealing with. They tend to be relational data transmitted as XML, so the ordering is much less important than the structure. > You could make things more complicated: No thanks! My head is pickling enough at the moment. > There are plenty of alternatives, so I hope one of them is useful. :-) I was really hoping that someone would say """Don't be silly, you need to use my module xsl:auto-map""", but I'm actually just grateful that nobody said """that's as barmy an idea as there is.""" Perhaps I am on the right track. If I get something viable, I'll let you know. Many thanks, Christopher. From ianb at colorstudy.com Sun Jul 6 15:56:12 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 06 Jul 2003 14:56:12 -0500 Subject: absolute beginners question about API documentation In-Reply-To: References: Message-ID: <1057521372.517.255.camel@lothlorien> On Sun, 2003-07-06 at 12:44, Markus Joschko wrote: > Hi all, > I' new to python programming but a longtime java programmer. > Is there an API documentation like the javadoc API from java? http://python.org/doc/ , of course. > I'm want to know all methods I can use on dictionaries. Where can I get an > overview about these? You want to look at the Library Reference, in the built-in type section (mapping types). You can also try: >>> dir({}) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'setdefault', 'update', 'values'] >>> help({}.update) Help on built-in function update: update(...) D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k] From jjl at pobox.com Wed Jul 30 14:25:25 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 19:25:25 +0100 Subject: reading in lines from a file -FAST! References: Message-ID: <87fzknx46i.fsf@pobox.com> Rajarshi Guha writes: > I have a file containing 168092 lines (each line a single word) and when > I use > > for line in f: > s = s + line > > it takes for ages to read it all in - so long in fact that it makes the Others have explained better ways to do it, but the *reason* your way is so slow is that Python strings are immutable. Say all your lines have length N. Since strings are immutable, a new one gets created for each + operation -- ie. for each line. So, the number of characters copied for i lines is N + 2N + 3N + 4N + ... + iN, which (to a first approximation) is proportional to i**2. That gets bad quickly as i gets bigger! Illustrative list comprehensions: >>> [sum([j*65 for j in range(1, i+1)]) for i in range(1,20)] [65, 195, 390, 650, 975, 1365, 1820, 2340, 2925, 3575, 4290, 5070, 5915, 6825, 7800, 8840, 9945, 11115, 12350] >>> [65*i*(i+1)/2 for i in range(1, i+1)] [65, 195, 390, 650, 975, 1365, 1820, 2340, 2925, 3575, 4290, 5070, 5915, 6825, 7800, 8840, 9945, 11115, 12350] >>> [(65/2)*(i**2) for i in range(1, i+1)] [32, 128, 288, 512, 800, 1152, 1568, 2048, 2592, 3200, 3872, 4608, 5408, 6272, 7200, 8192, 9248, 10368, 11552] >>> [65*i*(i+1)/2 for i in [168092]] [918290378070L] >>> So, don't do that... John From cce at clarkevans.com Thu Jul 17 11:54:03 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Thu, 17 Jul 2003 15:54:03 +0000 Subject: Co-routines In-Reply-To: References: Message-ID: <20030717155403.GA68289@polya.axista.com> On Thu, Jul 17, 2003 at 11:07:36PM +1000, thewrights at ozemail.com.au wrote: | I have an application in which I want the users to be able to create python | functions: | | def f1(): | print "1-1" | print "1-2" | print "1-3" | | def f2(): | print "2-1" | print "2-2" | print "3-3" | | and when my application runs, I want to execute these functions in | "lock-step", so that the output looks like: | | 1-1 | 2-2 | 1-2 | 2-2 | 1-3 | 2-3 There is a 'Flow' module in Twisted which uses generators to accomplish this sort of thing. Basically, Twisted has a queue of functions that are called, and by yielding "cooperate" object, you re-schedule the given generator for execution on this queue (allowing other code blocks to execute). from __future__ import generators from twisted.flow import flow from twisted.internet import reactor coop = flow.Cooperate() def f1(): print "1-1" yield coop print "1-2" yield coop print "1-3" def f2(): print "2-1" yield coop print "2-2" yield coop print "2-3" d = flow.Deferred(flow.Merge(f1(),f2())) d.addCallback(lambda _: reactor.stop()) reactor.run() I'm working on converting many 'data sources' such as PostreSQL and OpenLDAP so that their async interface works this way. See http://www.twistedmatrix.com/documents/howto/flow.html for more information on the flow module. Best, Clark P.S. If you wished, you could probably use flow without Twisted. You'd have to do three things: (a) create an event queue object, such as twisted.internet.reactor, (b) provide a notification when something scheduled is done, aka twisted.internet.defer, and (c) provide some way to handle exceptions in an async manner, aka twisted.python.fail. Although, once you have all of these things in place... why not just use the rest of Twisted... *grin* In other words, it is easy in theory to implement this correctly, but not that easy if you want to have it work with sockets and properly handle exceptions... So, by the time you do all of this, you will have re-invented the core of Twisted... and then you won't have a built-in http server nor a community to support you. From theller at python.net Tue Jul 22 13:16:42 2003 From: theller at python.net (Thomas Heller) Date: Tue, 22 Jul 2003 19:16:42 +0200 Subject: How do I get info on an exception ? References: Message-ID: >>> >The list of possible socket exceptions is in the docs for sockets. >>> >It also describes the (errno, string) return tuple value of inst.args. >>> . >>> True. >>> >>> But unsatisfying--at least to me. >> >>Submit a patch. > . > . > I deserved that. > > There was more to my post, of course. Part of what I was trying to > express is that exception interfaces are almost always relegated to > a footnote, with only a generalized description, even in the frequent > case that a method's exceptions are more complicated than its invoca- > tions. > > Rather than tilt at the collection of all such windmills, I want to > first understand better why this is, and what response is appropriate. > To summarize: I don't know what patch is the right one. I also > thought it only fair to warn Mr. July that things are indeed more dif- > ficult than we were explaining, even though I didn't feel up to > detailing the difficulties. > > So, Raymond, do you have general guidelines for how you think excep- > tions should be documented? I don't know what Raymond will suggest, but for myself I always (well, nearly always) when I find the docs insufficient, I'll submit a patch which contains what I would like to read there. Works pretty well so far... Thomas From mpnugent at ra.rockwell.com Fri Jul 25 05:10:26 2003 From: mpnugent at ra.rockwell.com (Michael P. Nugent) Date: 25 Jul 2003 02:10:26 -0700 Subject: Getting sub-objects from ADSI References: <3c91a864.0307231744.44a0adbb@posting.google.com> Message-ID: logistix at cathoderaymission.net (logistix at cathoderaymission.net) wrote in message news:<3c91a864.0307231744.44a0adbb at posting.google.com>... > mpnugent at ra.rockwell.com (Michael P. Nugent) wrote in message news:... > > How do I get the underlying values from Win::OLE=Hash(0x...) type > > objects? I can do it in Perl, but not in Python. > > > > For instance, I get > > > > CN=Fred > > > > > > > > > > when running > > > > #! python > > > > import pythoncom > > from win32com.client import GetObject > > > > UserPath = "LDAP://CN=Fred,OU=Two,OU=One,DC=nw,DC=home,DC=here,DC=com" > > > > ldap = GetObject(Userpath) > > > > print ldap.Name > > print ldap.Groups() > > print ldap.LastLogoff > > > > I know that Groups is of the type > >, but that knowledge does not help me much. I have > > fiddled a bit with GetInfo and Dispatch, but it doesn't change the > > results. > > Try: > > for group in ldap.Groups(): > print group.Name #or whatever you really want to do Thank you for that. I had tried that, but must have mistyped something. However, that is only part of the answer I need: what about LastLogoff? I don't know even what type of OLE/COM object it is supposed to be, so I don't know how to intuitively access it. For instance, given: print ldap.LastLogin print ldap.LastLogoff I get: > Thomas Eck in ADSI Scripting Appendix B says that that these should be the same types, so maybe the Python libs are hosed. P.S. I don't like the naming inconsistancy-- logon <=> logoff, login <=> logout-- either. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 25 12:33:52 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 25 Jul 2003 18:33:52 +0200 Subject: CGI "download" prompt? In-Reply-To: References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> <77dd287a.0307250619.7c2ec441@posting.google.com> Message-ID: <3f215bef$0$49107$e4fe514c@news.xs4all.nl> Gerhard H?ring wrote: > Erhm. Let's suppose you want to send an RTF file and have the browser > pop up a save dialog with a certain filename preconfigured: > > Then send these headers: > > Content-Type: application/rtf > Content-Disposition: attachment; filename=mydocument.rtf I didn't know about Content-Disposition! If this works, that's very nice-- especially if the filename part of that header is actually used by the web browser. --Irmen From roo at dark-try-removing-this-boong.demon.co.uk Fri Jul 11 08:20:47 2003 From: roo at dark-try-removing-this-boong.demon.co.uk (Rupert Pigott) Date: Fri, 11 Jul 2003 13:20:47 +0100 Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: <1057926047.339659@saucer.planet.gong> "Abigail" wrote in message news:slrnbgt6ls.ab5.abigail at alexandra.abigail.nl... > Walter Bushell (proto at panix.com) wrote on MMMDC September MCMXCIII in > : > ++ Charles Richmond wrote: > ++ > ++ > int *p, x, y; > ++ > > ++ > then: > ++ > > ++ > y = x/*p; > ++ > > ++ > is quite different from: > ++ > > ++ > y = x / *p; > ++ > > ++ > The first way, "/*" will begin a comment...the second way, > ++ > you get the integer "x" divided by the integer pointed to by "p". > ++ > ++ Ouch!! That is one reason code coloring is *important*. > > Nope. That's a reason why code colouring is evil. If you write code, > and it isn't clear what you mean without the use of code colouring, > you did something wrong. Your code shouldn't rely on a specific code > colouring scheme to be understandable. > > All in my opinion of course. My preference has been to make heavy use of ()'s to make the meaning of expressions clear. Also I have seen people cut & paste expressions from one language to another without checking the precedence rules. You know what happened next ! :) Cheers, Rupert From paul at boddie.net Thu Jul 10 10:22:44 2003 From: paul at boddie.net (Paul Boddie) Date: 10 Jul 2003 07:22:44 -0700 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> <3F0D4728.45284530@hotmail.com> Message-ID: <23891c90.0307100622.8db9814@posting.google.com> Alan Kennedy wrote in message news:<3F0D4728.45284530 at hotmail.com>... > > To those who continue to complain about having to pay for software, > I say: If you don't like paying, fork the software, maintain your > own product and let it be free (both in the free-speech and the > free-beer senses): see how you long *you* last. Or in this case, don't fork the product because the licence won't permit it. Instead, write your own ODBC driver manager package. I've stated before that vocal critics of mxODBC's licensing could relatively easily wrap something like iODBC and release the results under an open source licence, but the fact that it hasn't been done really says a lot about how much the mxODBC licensing is a "problem" for those people. Paul From tjreedy at udel.edu Thu Jul 24 16:30:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2003 16:30:00 -0400 Subject: Associating file types to my Python program References: Message-ID: "John Roth" wrote in message news:vi0dsmks541d25 at news.supernews.com... > Do you really want to do that? I'd advise going a bit > slow, and just get an item on the context menu for > starters. Look at HKCR\SystemFileAssociations\Image\Shell > and put your command in there. It will pop up on > the context menu for all file extensions that have > a "PercievedType" of "Image", at least under Windows XP. As a user, I second this. Too many apps want to be the default 'open'er and too few do the nice thing and *optionaly* add themself as an right-click context menu selection. TJR From somebody at nowhere.com Tue Jul 22 20:04:56 2003 From: somebody at nowhere.com (Sean Richards) Date: Wed, 23 Jul 2003 00:04:56 GMT Subject: How to save web pages for offline reading? References: Message-ID: In article , Paul Rudin wrote: >>>>>> "Will" == Will Stuyvesant writes: > > > There is no "man wget" on Windows :-) And unfortunately the GNU > > Windows port of wget I have (version 1-5-3-1) does not have that > > --page-requisites parameter. > > You need cygwin . That way you get "man wget" > and a wget that has a --page-requisites option on your windows box. There is a windows port of GNU wget 1.8.1 available. You don't need cygwin just to get a decent/recent version of wget. You can get one here.. http://www.weihenstephan.de/~syring/win32/UnxUtils.html Sean From simon at rendermania.com Mon Jul 7 15:21:19 2003 From: simon at rendermania.com (Simon Bunker) Date: Mon, 7 Jul 2003 20:21:19 +0100 Subject: single/double quote escape interpolation Message-ID: I was just wondering why python doesn't make a distinction between single and double quotes - a bit like Perl does. Obviously I realise there are no dollar signs so you can't intrpolate a varaible in a string. This is fine, but having to remember to put an r in front of regex's is really annoying and it would be great if you could jsut use single quotes instead to interpolate slashes properly etc. (ie only escape them once). I could not find this on google, but I guess it has been discussed before. Is there a good reason? thanks Simon -- http://www.rendermania.com/ From max at alcyone.com Tue Jul 1 21:41:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jul 2003 18:41:26 -0700 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> <010720031119590501%pecora@anvil.nrl.navy.mil> Message-ID: <3F023846.68E3F770@alcyone.com> "Louis M. Pecora" wrote: > We write a=b mod m if m divides (a-b) (i.e. no remeinder). > > The defintion does not say how to compute the mod, rather it is an > expression of a relationship between a and b. Hence, writing -2=-7 > mod > 5 appears to be OK. Right. Equivalences modulo m are really alternate numerical spaces in which arithmetic is done; in mathematics, the modulo is not strictly an operator. In those cases, you don't really have to pick a unique residue when doing arithmetic (mod m), since it's all equivalence relation anyway. In computer science, where modulo is an operator that must return a unique value, it's not really specified whether (-n % m) (m, n positive) should be negative or not. Some languages/systems chose negative, some don't. The choice is never "wrong" unless it's done inconsistently within a particular language/system. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ People are taught to be racists. \__/ Jose Abad From gh at ghaering.de Sun Jul 20 09:09:02 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 20 Jul 2003 15:09:02 +0200 Subject: "Pure Python" MySQL module like Net::MySQL In-Reply-To: References: Message-ID: <3F1A946E.7050907@ghaering.de> Ravi wrote: > Hi, > > I did some googling, and found that there doesn't seem to be a pure > python MySQL communication module. There is one for perl however, > Net::MySQL. Does it implement the MySQL wire protocol in pure Perl, without linking to libmysql? Sure that's possible in Python. > I was wondering if there was a specific reason why something > similar hasn't been implemented in Python, Nobody needed it badly enough. > a limitation of the language or libraries perhaps? No. > I briefly scanned through the perl source for > Net::MySQL, and there doesn't seem to be anything that couldn't be done > in Python, but I'm a fresh convert from perl land and I don't much > beyond the basics of Python yet. Is there any particular reason why you'd need such a beast instead of just using MySQLdb? -- Gerhard From ajr at dynacap.com Thu Jul 31 21:13:36 2003 From: ajr at dynacap.com (Arnaldo Riquelme) Date: Thu, 31 Jul 2003 17:13:36 -0800 Subject: A very simple question Message-ID: I'm getting familiar with Python and I have a simple question: class abc: x = 100 y = 200 z = 300 ac = abc() Shouldn't I have a attribute named __dict__ for ac that contains a dictionary of all the variables? Instead when I do: print ac__dict__ I get an empty dictionary {} However: print abc.__dict__ works. I'm missing something somewhere, can anyone please enlight me on this matter. Thanks Arnaldo From bokr at oz.net Fri Jul 18 00:08:32 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 04:08:32 GMT Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> Message-ID: On Thu, 17 Jul 2003 21:33:42 -0400, hokiegal99 wrote: >A few questions about the following code. How would I "wrap" this in a >function, and do I need to? > >Also, how can I make the code smart enough to realize that when a file >has 2 or more bad charcters in it, that the code needs to run until all >bad characters are gone? For example, if a file has the name >"chars out of the file name. > >The passes look like this: > >1. 2. -bad*mac\file becomes -bad-mac\file >3. -bad-mac\file becomes -bad-mac-file > >I think the problem is that once the program finds a bad char in a >filename it replaces it with a dash, which creates a new filename that >wasn't present when the program first ran, thus it has to run again to >see the new filename. Maybe I'm misunderstanding, but in a previous post I suggested combining the name transformations before even going to the file system for renaming. E.g, if you have lessbadfilename = fixup1(badfilename); rename(badfilename,lessbadfilename) evenlessbadfilename = fixup2(lessbadfilename); rename(lessbadfilename,evenlessbadfilename) okfilename = fixup3(evenlessbadfilename); rename(evenlessbadfilename,okfilename) why bother with all the renames, when you could do a single one at the end, i.e., rename(badfilename, okfilename) i.e., why record the intermediate names in the file system, only to change them? > >import os, re, string >bad = re.compile(r'%2f|%25|[*?<>/\|\\]') #search for these. >print " " >setpath = raw_input("Path to the dir that you would like to clean: ") >print " " >print "--- Remove Bad Charaters From Filenames ---" >print " " >for root, dirs, files in os.walk(setpath): > for file in files: > badchars = bad.findall(file) > newfile = '' > for badchar in badchars: > newfile = file.replace(badchar,'-') #replace bad chars. > if newfile: > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,file) > os.rename(oldpath,newpath) > print oldpath > print newpath >print " " >print "--- Done ---" >print " " > This looks like an old post that ignores some responses you got to your original post like this. Did some mail get lost? Or was this an accidental repost of something old? I still see indentation misalignments, probably due to mixing tabs and spaces (bad news in python ;-) Regards, Bengt Richter From mis6 at pitt.edu Mon Jul 7 18:35:18 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 7 Jul 2003 15:35:18 -0700 Subject: Newbie Question: Abstract Class in Python References: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Message-ID: <2259b0e2.0307071435.2c2a3bb4@posting.google.com> "Kevin Bass" wrote in message news:... > I am only looking for an answer about creating an abstract class in Python > and > not a solution to a problem. I am looking for a way to stop class > instantiation > of a class. This should be a generic approach. > > Kevin I may stop instantiation by inheriting from >>> class NonInstantiable(object): def __new__(cls,*args,**kw): raise TypeError("Non-instantiable class") Here is how it works: >>> class C(NonInstantiable):pass >>> c=C() Traceback (most recent call last): File "", line 1, in -toplevel- c=C() File "", line 3, in __new__ raise TypeError("Non-instantiable class") TypeError: Non-instantiable class HTH, Michele From s.nufer at free.fr Wed Jul 30 18:02:26 2003 From: s.nufer at free.fr (=?ISO-8859-1?Q?St=E9phane?= Nufer) Date: Thu, 31 Jul 2003 00:02:26 +0200 Subject: serial, parallel and USB port Message-ID: <3f284386$0$1922$626a54ce@news.free.fr> Hello, Why are there no module to access serial, parallel or USB port in python. This could be great to build front end software to control electronic device or even automaton in industrial process ( or maybe I should ask why the existing third party modules such as pyserial have not been integrated in the official release) Regards, From alanmk at hotmail.com Sun Jul 6 17:32:34 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 06 Jul 2003 22:32:34 +0100 Subject: Search for mapping solution References: <3F087E85.9D8018E9@hotmail.com> Message-ID: <3F089572.C5153FC@hotmail.com> Sean Ross wrote: > Hi. You've left out the accumulating part of the OP's requirements: I know :-( The real temptation I have to resist is deciding to answer someone question without reading the whole question properly. I tried to cancel the post as soon as I realised, but it was obviously too late. No more posting for me for a while. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 29 18:57:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 00:57:19 +0200 Subject: urlretrieve a file whose name has spaces in it In-Reply-To: <10caf2e2.0307291439.33d9fcc3@posting.google.com> References: <10caf2e2.0307291439.33d9fcc3@posting.google.com> Message-ID: <3f26fbce$1$49099$e4fe514c@news.xs4all.nl> HP wrote: > urllib.urlretrieve("http://website.com/path/string string1 foo.doc", > "local_file"); > Try urllib.urlretrieve(urllib.quote("http://website.com/path/string string1 foo.doc"), "local_file") instead. And what is the semicolon doing there? ;-) --Irmen From danb_83 at yahoo.com Fri Jul 25 21:02:40 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 25 Jul 2003 18:02:40 -0700 Subject: The case of the missing modules Message-ID: I installed Python on the HP 3000 at work today. The interpreter itself appears to be working fine, but "import math", "import datetime", etc. fail with "ImportError: No module named [name]". (However, os and system can be imported successfully.) I used help('modules') to print a list of available modules and there were only 14 (__builtin__, _codecs, _sre, _symtable, errno, exceptions, gc, imp, marshal, posix, signal, sys, xxsubtype, zipimport). Any ideas as to why Python can't find most of its modules? ------------------------------------------------------------------------------- $ ./python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /tmp/python/Lib/site.pyc matches /tmp/python/Lib/site.py import site # precompiled from /tmp/python/Lib/site.pyc # /tmp/python/Lib/os.pyc matches /tmp/python/Lib/os.py import os # precompiled from /tmp/python/Lib/os.pyc import posix # builtin # /tmp/python/Lib/posixpath.pyc matches /tmp/python/Lib/posixpath.py import posixpath # precompiled from /tmp/python/Lib/posixpath.pyc # /tmp/python/Lib/stat.pyc matches /tmp/python/Lib/stat.py import stat # precompiled from /tmp/python/Lib/stat.pyc # /tmp/python/Lib/copy_reg.pyc matches /tmp/python/Lib/copy_reg.py import copy_reg # precompiled from /tmp/python/Lib/copy_reg.pyc # /tmp/python/Lib/types.pyc matches /tmp/python/Lib/types.py import types # precompiled from /tmp/python/Lib/types.pyc # /tmp/python/Lib/warnings.pyc matches /tmp/python/Lib/warnings.py import warnings # precompiled from /tmp/python/Lib/warnings.pyc # /tmp/python/Lib/linecache.pyc matches /tmp/python/Lib/linecache.py import linecache # precompiled from /tmp/python/Lib/linecache.pyc Python 2.3c1 (#9, Aug 13 1970, 13:25:05) [GCC 3.2.2] on mpeix70 Type "help", "copyright", "credits" or "license" for more information. >>> raise SystemExit # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] zipimport # cleanup[1] warnings # cleanup[1] signal # cleanup[1] site # cleanup[1] linecache # cleanup[1] posix # cleanup[1] types # cleanup[1] exceptions # cleanup[2] stat # cleanup[2] copy_reg # cleanup[2] posixpath # cleanup[2] os # cleanup[2] os.path # cleanup sys # cleanup __builtin__ # cleanup ints: 4 unfreed ints in 4 out of 105 blocks # cleanup floats $ set | grep "PYTHON" PYTHONHOME="/tmp/python" PYTHONPATH="/tmp/python/Lib" From bokr at oz.net Mon Jul 21 19:22:46 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jul 2003 23:22:46 GMT Subject: pythonic malloc References: Message-ID: On Mon, 21 Jul 2003 10:32:08 GMT, Brad Hards wrote: >Karl Scalet wrote: > >> kjockey schrieb: >>> I have some simple UDP code that does: >>> >s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr) >>> >>> This is OK, except that I'd like to change the text in the middle >>> ("rachel", which is the hostname FWIW), and the NUL padding needs to go >>> out to make the length 25 bytes (so the padding depends on the length of >>> the name). >>> >>> So I could do something like: >>> retpacket = "\xf0\x00\x02\x00"+socket.gethostname() >>> while len(retpacket) < 26: >> >> shouldn't that be 25? >Yes. > >>> retpacket += "\x00" >>> s.sendto(retpacket, addr) >>> >>> But that feels "wrong". And Python in a Nutshell says its a bad idea - >>> "anti-idiom". Well, adding the same character one by one is about as ugly as sum = 14 while sum <25: sum += 1 (Of course, if the original 14 units are also the same, as in integers, sum += 25-sum is not much better ;-) But for small strings, I don't think it should be a big deal to do something like retpacket = "\xf0\x00\x02\x00"+socket.gethostname() retpacket += '\x00'*(25-len(retpacket)) >>> >>> Can anyone show me the true path? >> >> No idea, if it's the true path: >> >> hn = socket.gethostname() >> retpacket = '\xf0\x00\x02\x00%s%s' % (hn, (25-4-len(hn))*chr(0)) >> s.sendto(retpacket, addr) >Probably better for efficiency, but not much for readability.... > >Anyone else? another alternative (untested!): fmt = '\xf0\x00\x02\x00%s'+21*'\x00' # or write it out ;-) ... retpacket = (fmt%socket.gethostname())[:25] s.sendto(retpacket, addr) Regards, Bengt Richter From stuart at bmsi.com Tue Jul 15 13:07:14 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Tue, 15 Jul 2003 13:07:14 -0400 Subject: LyX for Python Documentation Message-ID: Is there a LyX style sheet to help me write simple Python documentation in the standard format without learning to write raw LaTeX? From skip at pobox.com Fri Jul 11 08:18:21 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Jul 2003 07:18:21 -0500 Subject: Is re module thread-safe? In-Reply-To: References: Message-ID: <16142.43789.474127.166801@montanaro.dyndns.org> Jane> As the subject says, is re module thread-safe? Yes. Skip From upandrunning247 at hotmail.com Sat Jul 19 18:13:26 2003 From: upandrunning247 at hotmail.com (George Henry) Date: Sat, 19 Jul 2003 15:13:26 -0700 Subject: Strange(?) list comprehension behavior Message-ID: Never mind, my result was due to a typo. Have you ever typed "<" rather than "," ... and structured your code in such a way that the error escpaed your notice on casual perusal? So ... [ "s1", ... "sj"< "sk", ... "sn"] does indeed produce an int. Debugging python is rather different from debugging languages like C, C++, Java, C# - to say the least. I should have listened to my instincts and done more investigating before troubling the list (y'all) with my stoopid error. Doh! Regards, George _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From aahz at pythoncraft.com Wed Jul 16 14:22:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 Jul 2003 14:22:46 -0400 Subject: Replacing rexec References: Message-ID: In article , Tim Gerla wrote: > >We are looking to use plpython in PostgreSQL, but it's being downgraded >to "untrusted" and/or being completely removed because Python's rexec >went away. Why did rexec go away, specifically? I know it had security >issues, but couldn't these have been fixed? Did the module just have too >many integral flaws in the design to be worth saving? There are two separate issues: * rexec implementation -- it never had a true security audit, and there have never been resources to do it. * rexec vs new-style classes -- the basic mechanism used in rexec fails in the fact of new-style classes, which would require a complete rewrite of rexec. >Is anyone working on a replacement? If not, why not? Even if plpython >isn't very widely used, I think it's still important for advocacy. I'd >much rather write Python than PL. There's been some talk, but it's likely that a secure Python will require forking the code. Note that it's already too easy to write a DoS attack against Python: 100L**100**100 will do it. Conversely, if only trusted code is going into the server, there's no need for rexec. >Anyway, I'm looking for a summary of specific reasons why rexec went >away without a replacement. I understand completely that it had flaws >and was insecure; I'm only confused as to why these flaws were >insurmountable. Take a look at http://www.amk.ca/python/howto/rexec/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From just at xs4all.nl Tue Jul 8 10:16:11 2003 From: just at xs4all.nl (Just van Rossum) Date: Tue, 8 Jul 2003 16:16:11 +0200 Subject: path module In-Reply-To: <16138.53027.356511.290162@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Just> But when the items are variables, what you read is not what you > Just> get. Often you'll want (some) literals, and then you get > > Just> path = basePath/"a"/"b"/"c" > > Just> ...and _that_ I find quite horrible... > > I don't know for sure, but I suspect the above could also be > > path = basePath/"a/b/c" Ooh, it _can_ get worse ;-/ Also: this would not be portable on platforms not using / as os.sep, so is almost equivalent to not using os.path at all and doing path = basePath + "/a/b/c" > Still not perfect, but in any case, the '/' is meant to be > suggestive, not literal. Perhaps you would have preferred he use > ':'? ;-) Heh... > Just> (Did I mention that / usually means divide in Python? ;-) > > Sure, just like '%' means modulo in Python, but it seems to have > found a home in printf-style string expansion. True, but string expansion is quite old (possibly even Python 0.9 or 1.0?), so most people are used to it. (Although, newbies without a C background are usually baffled by it. I know I was, back then...). Just From jdhunter at ace.bsd.uchicago.edu Wed Jul 2 10:24:25 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 02 Jul 2003 09:24:25 -0500 Subject: splitting a string into 2 new strings In-Reply-To: ("Mark Light"'s message of "Wed, 2 Jul 2003 12:02:36 +0100") References: Message-ID: >>>>> "Mark" == Mark Light writes: Mark> Hi, I have a string e.g. 'C6 H12 O6' that I wish to split up Mark> to give 2 strings 'C H O' and '6 12 6'. I have played with Mark> string.split() and the re module - but can't quite get Mark> there. Mark> Any help would be greatly appreciated. Here's an example using re: import re def pairs(l): return [[l[i], l[i+1]] for i in range(0, len(l), 2)] splits = [ t for t in re.split('([A-Z])(\d+) *', 'C6 H12 O6') if len(t)>0] for letter, number in pairs(splits): print letter, number pairs is a function to loop over a list in pairs. John Hunter From martin at v.loewis.de Sun Jul 27 17:36:43 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 27 Jul 2003 23:36:43 +0200 Subject: Checking whether bool is a type References: <3F2442B2.E660E97@jandecaluwe.com> Message-ID: Jan Decaluwe writes: > jand> python2.2 > Python 2.2.2 (#1, Oct 16 2002, 19:59:11) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> type(bool) is type > 0 > > Great isn't it ?! Not sure whether I should consider > this to be completely obvious or very deep ... Very obvious. Python 2.2.1 (#1, Sep 10 2002, 17:49:17) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> bool bool is a function in Python 2.2.1+, not a type. It became a type only in Python 2.3, see PEP 285. Regards, Martin From adechert at earthlink.net Mon Jul 21 12:54:52 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 16:54:52 GMT Subject: Python voting demo discussion References: <3F1BA496.6080305@embeddedsystems.nl> Message-ID: "Gerrit Muller" wrote in message news:3F1BA496.6080305 at embeddedsystems.nl... > In fact the main recommendation is: simply start in Python. .... > I think that's what we'll do. Thank you very much for your input. It will be on sourceforge.net very soon (today). Alan Dechert From abelikov72 at hotmail.com Mon Jul 7 16:39:54 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Mon, 07 Jul 2003 20:39:54 GMT Subject: Python in Excel References: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> <873chm9w7o.fsf@pobox.com> Message-ID: On Sat, 05 Jul 2003 02:48:15 +0100, hannibal wrote: >You can use Microsoft Script Control. If you have the win32 extensions >of python, you can use python in place of vb in this control > >-open the VBA script editor - In menus/Tools/References add Microsoft >Script Control >-Make a new module and declare a new MsScriptControl.ScriptControl > Global sc as new MsScriptControl.ScriptControl >-Initialize the language attibute with python - Note that you and users >of your document must have python and its win32 extensions installed. >Activestate python distribustion include it. >You can put > sc.language="python" >in the routine Workbook_Open() > >Now you can import python modules using ExecuteStatement method of the >control in vba and have results from python functions with eval method. >One interesting thing is that you can pass an object to the control with >AddObject method and have python manipulate it. And so on.. Thanks this is almost what I am looking for, very cool. It would be nice not to have to do so much VB with it. Is there any way around that? From my perspective, every Python function used will be wrapped in a VB function which calls the Python function. -AB From mis6 at pitt.edu Thu Jul 3 11:32:28 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 3 Jul 2003 08:32:28 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <6f03c4a5.0307022119.2b0a4bc1@posting.google.com> Message-ID: <2259b0e2.0307030732.3ec88c84@posting.google.com> rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0307022119.2b0a4bc1 at posting.google.com>... > Everyone! Thanks a lot for the insightful and enlightening discussion. > > I think the suggestion to solve the problem by using the __setattr__ > special method will not work because it intercepts attribute > assignment of the form "self.attr = somthing", and not what I want, > which is "name = something". > > John suggested to look at properties, this is the closest I can get to > the > behavior I am looking for, but from my understanding, that will let me > intercept "name.value = something" instead of intercepting "name = > something". > > Thank you very much everyone. > - Rim Okay, you asked for it ;) class MetaTrick(type): def __init__(cls,name,bases,dic): super(MetaTrick,cls).__init__(name,bases,dic) for (k,v) in dic.iteritems(): if not k.endswith("__"): setattr(cls,k,v) def __setattr__(cls,k,v): print "Intercepting %s = %s" % (k,v) super(MetaTrick,cls).__setattr__(k,v) class C: __metaclass__=MetaTrick name='something' This gives the output "Intercepting name = something". I show you this snippet hoping you will not use it! nothing-is-impossible-with-metaclasses-ly, Michele From theincredibleulk at hotmail.com Wed Jul 2 07:41:11 2003 From: theincredibleulk at hotmail.com (=?ISO-8859-1?Q?=DAlfur_Kristj=E1nsson?=) Date: 2 Jul 2003 04:41:11 -0700 Subject: Embedding Message-ID: Hi, I'm having a bit of trouble trying to script my application using Python. I have created classes that I can use in C++ and I have created Python objects from those classes using SWIG and they're working just perfectly. However, I have no idea on how I can actually pass these back and forth when I call my scripts from C++. Ideas anybody? Please... From ianb at colorstudy.com Thu Jul 24 00:29:28 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 23 Jul 2003 23:29:28 -0500 Subject: Cookbook idea - single-shot __init__ In-Reply-To: References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <1059020967.28066.8311.camel@lothlorien> On Wed, 2003-07-23 at 21:17, Ben Finney wrote: > On Wed, 23 Jul 2003 19:15:23 -0600, Bob Gailer wrote: > > I have at times had the need to initialize some things once at the > > class level > > In Python 2.2 (earlier?) you can define any attribute at the class > level, and it will be shared by all instances: This is true in all versions of Python. However, there are some instances where you can't initialize the attributes at class creation time, and you want to delay initializing those variables until some later time. This usually is a problem of circular dependencies, or where initialization somehow depends on the overall context of the program (like configuration variables that may not be fully read by the time the module is imported). Ian From rdickins at usaor.net Sat Jul 5 16:39:55 2003 From: rdickins at usaor.net (Robert Dickinson) Date: Sat, 5 Jul 2003 16:39:55 -0400 Subject: pyAnt vs SCons Message-ID: Maybe there was a discussion here about these two Python configuration tools. If so, I didn't find it. Anyone who has used both and can compare? -- Rob -- From mfranklin1 at gatwick.westerngeco.slb.com Mon Jul 21 08:23:06 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 21 Jul 2003 13:23:06 +0100 Subject: Python scripting with Paint Shop Pro 8.0 In-Reply-To: References: Message-ID: <200307211323.06752.mfranklin1@gatwick.westerngeco.slb.com> On Monday 21 July 2003 12:29, Marc Wilson wrote: > In comp.lang.python, Martin Franklin > (Martin Franklin) wrote in > > :: > |On Sunday 20 July 2003 13:48, Marc Wilson wrote: > |> Hi, > |> > |> I'm a complete Python newbie, though I know at least one regular in > |> here. > |> > |> :) > |> > |> I've just got Paint Shop Pro 8.0, and the functionality of the old > |> ImageRobot add-on has been replaced with the new Python Scripting. > |> > |> So far, OK. > |> > |> What I'm trying to determine is: can I run these scripts from a > |> command-line invocation? I want to use the scripts to automatically > |> convert files as they arrive, uploaded onto a website, not > |> interactively. > |> > |> Has anyone played with this? > |> -- > |> Marc Wilson > | > |Marc, > | > |This is not an answer to your question... but if you just want to convert > | an image file into another format then upload it to a server you could > | use a pure python solution (well pure python + PIL) > | > |PIL is here:- > | > |http://www.pythonware.com/products/pil/ > | > |In fact a quick browse through the handbook and I found this:- > | > |http://www.pythonware.com/library/pil/handbook/pilconvert.htm > | > |and I quote:- > | > |""" > |Convert an image from one format to another. The output format is > | determined by the target extension, unless explicitly specified with the > | -c option. > | > | $ pilconvert lena.tif lena.png > | $ pilconvert -c JPEG lena.tif lena.tmp > | > | > |""" > > It's a start- actually, we want to convert the file to JPEG (if not > already), sharpen it, fix the size and also derive a thumbnail from it. > > We used something called Image Robot, a helper application from JASC. Now > that they have integrated this functionality into PSP, they no longer > support IR, and we're having odd problems with it, so we're looking to see > if we can do the same thing with a supported level. > > While I'm sure Python is a lovely language, the choice is due to PSP using > the scripting engine: if I have to write something from scratch (or even > from bits'n'bobs), I'll use a language I already know. > > |To upload the image to a server you could use the ftplib module... > > Already got it on the server- the customers upload the files using a web > form. Marc, Point taken... I just can't resist showing you how easy it is in Python..... # PIL IMPORTS import Image, ImageEnhance im = Image.open("gnome-mixer.jpg") enhancer = ImageEnhance.Sharpness(im) eim = enhancer.enhance(2.0) eim.save("gnome-mixer-sharp.jpg", "JPEG") eim.thumbnail((10, 10)) eim.save("gnome-mixer-thumb.jpg", "JPEG") And this is the first time I've used PIL. Cheers, Martin. From dmbkiwi at yahoo.com Sat Jul 12 20:24:32 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sun, 13 Jul 2003 12:24:32 +1200 Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 07:06:33 -0400, John Roth wrote: > Is there anything consistent about either the version of > Python these people are using, or the version of KDE? > The reason I ask is that there are a lot of different > versions out there, and while the Python maintainers > are very good, some of them have subtle bugs. Likewise > for KDE, and for various distributions. I believe that they are using suse8.2, with python 2.2.3. Not sure what version of kde, but it will be either kde-3.1.1, or 3.1.2. > > I also second Bengt's comment about tabs. Outlook > Express, for one, eliminates them so your code example > is simply unreadable. The python standard coding style > is to use 4 spaces for each level of indentation. Python > aware editors supply them automatically when you hit > the tab key. > > John Roth > Thanks for the tip. I'll try to see if the editor I use (kate will do that). Might I also suggest that you use a better newsreader than OE (not wanting to start anything here). But there must be something better for windows than that surely? I know the pan developers have a windows port. Matt From garth at deadlybloodyserious.com Thu Jul 31 08:59:28 2003 From: garth at deadlybloodyserious.com (Garth Kidd) Date: Thu, 31 Jul 2003 22:59:28 +1000 Subject: Ver 2.3 install over 2.2? In-Reply-To: <000001c35727$a3dbd4e0$21795418@dell1700> Message-ID: <000001c35763$96459ff0$8a01010a@gkiddxp2> > The reason that these extensions don't work is that VC7 > introduced incompatibilities in the C runtime library. The > layout for the FILE data type has changed, for example, so > extensions using the FILE returned by PyFile_AsFile may crash. Oh. Fair enough. I've installed VC6, and I still can't build extensions. I don't think distutils is looking hard enough; it can't see VC6 even though I've run VCVARS32.BAT, the environment variables are all there, and I can run CL.EXE with no problems. Digging a little... For whatever reason, I don't have any registry keys named r"Software\Microsoft\Devstudio\6.0\Build System". I do, on the other hand, have a convenient MSVCDIR environment variable once I run VCVARS32.BAT. I've submitted patch 780821: http://sourceforge.net/tracker/?func=detail&aid=780821&group_id=5470&atid=30 5470 Regards, Garth. From drs at ecp.cc Fri Jul 11 20:41:50 2003 From: drs at ecp.cc (drs) Date: Sat, 12 Jul 2003 00:41:50 GMT Subject: More ZEO/ZODB issues Message-ID: I don't seem to be getting any bites on the earlier post ... so here is my problem in a nutshell. I started a ZEO server on one computer (\\camus) using C:\>python C:\Python22\Lib\site-packages\ZEO\start.py -p 9000 C:\db\tmp.fs that is fine on another computer I typed the following from a python prompt: >>> from ZEO import ClientStorage >>> from ZODB import DB >>> addr = ('camus', 9000) >>> storage = ClientStorage.ClientStorage(addr) >>> db = DB(storage) >>> conn = db.open() >>> d = conn.root() I went to a third computer and did the same. from either of the clients, I can manipulate d by doing >>> d[key] = value but the other client can't see the change. I have also tried using >>> get_transaction().begin() >>> d['0'] = 0 >>> get_transaction().commit() and >>> storage.sync() but the other client still does not see changes. If, however, the other client does >>> get_transaction().begin() >>> d[key] = value >>> get_transaction().commit() it will throw an error, but d will contain the changes from the first client. Obviously I am not getting something. The only ZEO examples I can find use BTrees which is not what I want. So, can someone show me how to use a ZEO server as a simple dictionary? Thanks, -doug From skip at pobox.com Mon Jul 14 15:08:40 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 14 Jul 2003 14:08:40 -0500 Subject: www.python.org hacked? In-Reply-To: <3F12FA18.B04B400E@engcorp.com> References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> Message-ID: <16146.65464.856825.821717@montanaro.dyndns.org> Peter> Have we been hacked, or is this human error during maintenance? Human error. We have a full disk situation. One of the webmasters attempted to tweak the home page during that time. Skip From alex_eberts at videotron.ca Mon Jul 14 14:36:31 2003 From: alex_eberts at videotron.ca (Alexander Eberts) Date: Mon, 14 Jul 2003 14:36:31 -0400 Subject: Accessing an instance's __init__ args from outside the class References: Message-ID: Duncan, Thanks for your response - much appreciated. Do you know how the python interpreter handles *args and **kwargs passed to a class's __init__ method? (maybe the better question is "what section in the python docs describes how class args are handled" :) all the best, Alex "Duncan Booth" wrote in message news:Xns93B8AC76381A5duncanrcpcouk at 127.0.0.1... > "Alexander Eberts" wrote in > news:sfAQa.21645$O55.673402 at wagner.videotron.net: > > > Is there any way to find out what arguments an object was called > > with? > > Not in general. > > > Are the args stored with the instance? > > It depends on the object type. Some objects may save some or all of the > arguments to the constructor, but it is up to each object to decide what to > do with its arguments. If you create your own class, and want to be able to > refer to the __init__ arguments after returning from __init__, then you > must save the arguments in the object. > > So, for your original example you could do: > > >>> class Foo: > def __init__(self, *args): > self.args = args > print args # no problem here > > > >>> someobj = Foo('bar', 'bleck') > ('bar', 'bleck') > >>> someobj.args > ('bar', 'bleck') > > -- > 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 Kepes.Krisztian at peto.hu Tue Jul 1 03:48:18 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Tue, 01 Jul 2003 09:48:18 +0200 Subject: Python -> To Exe or/and Elf Message-ID: Hi ! Have the python a compiler what can create native win exe or linux elf from any py program ? Please help me ! KK From mwilson at the-wire.com Fri Jul 25 12:49:53 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 25 Jul 2003 12:49:53 -0400 Subject: How to detect typos in Python programs References: <3F214977.AEB088C8@engcorp.com> Message-ID: In article <3F214977.AEB088C8 at engcorp.com>, Peter Hansen wrote: >Manish Jethani wrote: >> >> Is there a way to detect typos in a Python program, before >> actually having to run it. Let's say I have a function like this: >> >> def server_closed_connection(): >> session.abost() >> >> Here, abort() is actually misspelt. The only time my program >> follows this path is when the server disconnects from its >> end--and that's like once in 100 sessions. [ ... ] > >You have no good alternative. Why do you say it's impractical >to actually test your software before it's shipped? Isn't it >more impractical to rely on your users to test the software, >thinking it should work? The proposed typo catcher would probably catch a typo like sys.edit (5) # finger didn't get off home row but it probably would *NOT* catch sys.exit (56) # wide finger mashed two keys Testing really is a Good Thing. Regards. Mel. From kylotan at hotmail.com Wed Jul 30 07:26:39 2003 From: kylotan at hotmail.com (Kylotan) Date: 30 Jul 2003 04:26:39 -0700 Subject: time, calendar, datetime, etc Message-ID: <153fa67.0307300326.45a29380@posting.google.com> Is there any chance of these modules becoming somewhat combined in the future? Right now it seems a little awkward to find the function you want. The main culprit is 'timegm' which is the only thing I need from the calendar module but which should probably be in the time module. And does datetime.timetuple() actually return something equivalent to a struct_time as used by the time module? At first glance this looks to be true, but it isn't clearly documented as such. Personally I think 2 separate modules (1 high level, 1 low level corresponding to the C api) would suffice, or even to combine it all into one coherent module. Is there any benefit to the status quo that I am missing? PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S %Y')' as a reverse-asctime(), and was surprised that I couldn't find this wrapped in a function in any of the modules. Maybe such a function would be considered for future addition? -- Kylotan From mcherm at mcherm.com Wed Jul 16 09:26:01 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 16 Jul 2003 06:26:01 -0700 Subject: anything like C++ references? Message-ID: <1058361961.3f1552699760a@mcherm.com> Stephen Horne writes: > 'value' is a term which has meaning in mathematics and computer > science. Values are *always* immutable, whatever language you use. > > In Python, assignment takes a name and binds it to an object (or a > pointer to that object). > > In C/C++, assignment takes a name and binds it to a symbolic > representation of a value. > > Objects can be mutable. Representations can be mutable. However, using > that mutability should respect the idea from mathematics of variables > binding to values. The fact that the binding is implemented using > objects or symbolic representations is irrelevant - they are low level > implementation details. You shouldn't have to worry about them in a > 'very high level' language. > > Of course if you explicitly ask to deal with the object (rather than > the value) that is a different thing. But that isn't the case in > Python. It fails to respect the mathematical concept of variables > binding to values BY DEFAULT. This regularly causes confusion and > errors. Stephen: AHA! I think I've got it. Your problem is that you are expecting Python to operate on values -- and it DOESN'T. When I write x = 2 in python, it is NOT binding the variable "x" to the value 2. Instead, it is binding the variable "x" to the OBJECT 2. Of course, since int objects are immutable, this difference is meaningless pedantry. But as soon as you write x = MyObject() the difference quickly becomes meaningful. So there are several ways one could "fix" Python to match your expectations. One would be to introduce "values"... right now, Python has only objects at the language level, and the "values" are a theoretical construct built on top of that. Another would be to make all objects immutable, then the distinction between objects and values could become a mere implementation detail, and the language could be said to contain "values". But as things stand, "values" (as you define them) do not exist in Python. I submit that you may find this be a more useful way to view things -- not that Python's implementation of assignment fails to match your expectation, but that Python provides no true access to "values", only to the more complex construct "objects" (although a strong equivalence exists for immutable types). Do you find this alternate explanation useful? -- Michael Chermside From peter at engcorp.com Fri Jul 4 18:30:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 18:30:22 -0400 Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> <840592e1.0307040900.14e3e668@posting.google.com> <3F05C39D.3F65B89C@engcorp.com> Message-ID: <3F05FFFE.DB98BF44@engcorp.com> Aahz wrote: > > In article <3F05C39D.3F65B89C at engcorp.com>, > Peter Hansen wrote: > > > >Google Groups likely takes its feed directly of a Usenet site, and Usenet > >in general suffers from large propagation delay. It is that delay, caused > >by messages filtering slowly across the Usenet network, which leads to the > >"5 answers" problem, not Google Groups itself. > > Actually, Google uses at least two or three feeds (including > stanford.edu, which has a super-competent news admin), and Usenet > propagation is actually little short of e-mail speeds these days, > depending on where you're located. That might be, but empirically I've seen posts that I've made take hours to get there, and I've seen posts that were made to the mailing list (and copied to me directly) take hours to get there. In both cases, there is an "upwards" propagation delay towards whatever hosts Google is milking before stanford.edu or the others will see it... From peter at engcorp.com Thu Jul 10 12:37:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 12:37:02 -0400 Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> Message-ID: <3F0D962E.23DA9F59@engcorp.com> "Bartolom? Sintes Marco" wrote: > > I have a program that unzip some zip files. After unzipping them, > I want to delete the zip files with os.remove, but I get this error: > OSError: [Errno 13] Permission denied: .... Close the files properly after unzipping them, perhaps? If that doesn't help, please specify operating system, and give details on how you are unzipping. Is it using Python's zipfile module, or some other method, and exactly how do you do it? -Peter From trentm at ActiveState.com Tue Jul 29 14:47:34 2003 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 29 Jul 2003 11:47:34 -0700 Subject: Debugging Python ? In-Reply-To: ; from newsgroups@jhrothjr.com on Mon, Jul 28, 2003 at 01:23:43PM -0400 References: Message-ID: <20030729114734.G1753@ActiveState.com> ... > Which mine do, quite frequently. By the time you get this far, > you've pretty much got a logging system. ... Python's new logging system (standard in the coming Python 2.3 and available for Python versions back to 1.5.2 here http://www.red-dove.com/python_logging.html) is good for not re-inventing the wheel here. Granted there is a learning curve greater than: if __debug__: print "yada yada yada" but it is time well spent. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From wilkSPAM at OUTflibuste.net Fri Jul 4 05:26:21 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: 04 Jul 2003 11:26:21 +0200 Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F04E609.2010500@dadsetan.com> Message-ID: <87llvefxs2.fsf@flibuste.net> Tyler Eaves writes: > On Fri, 04 Jul 2003 03:27:21 +0100, Behrang Dadsetan wrote: > > > A bit a pitty the message board system is php based.. > > > Ben. > > Why? Right tool for the job and all that... It's not the right tool, php board system are very heavy to host. A webserver with in memory persistence data will be ideal for this kind of things. They exists in zope i think, but it's a little bit heavy also... We have a lot of webserver in python, we shall do somethings ! With google i found this one : http://sourceforge.net/projects/tboard "Design Goals (In short: a phpBB clone with various power-ups)" -- William Dode - http://flibuste.net From domma at procoders.net Sun Jul 6 15:36:17 2003 From: domma at procoders.net (Achim Domma) Date: Sun, 6 Jul 2003 21:36:17 +0200 Subject: Search for mapping solution References: Message-ID: "Markus Joschko" wrote in message news:be9t66$2otne$1 at ID-47851.news.dfncis.de... > Name - Number - Costs > > lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > > Now I want to have it in a dictionary(name,costs) Should look like > {'fred':'0,60' , 'sam':'1'} I would do it like this: lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] costs = {} for name,number,price in lines: costs[name] = costs.setdefault(name,0)+float(price) print costs Achim From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 24 18:20:28 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 Jul 2003 08:10:28 +0950 Subject: not able to run References: Message-ID: On Thu, 24 Jul 2003 16:01:18 -0500 (CDT), Joe Kmoch wrote: > # python2.2 > ld.so.1: python2.2: fatal: libstdc++.so.5: open failed: No such file or directory > Killed > [...] > I'm not sure what I should do next. Install all dependencies for any software you want to run. -- \ "I bet one legend that keeps recurring throughout history, in | `\ every culture, is the story of Popeye." -- Jack Handey | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From claird at lairds.com Wed Jul 2 11:21:17 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 02 Jul 2003 15:21:17 -0000 Subject: does lack of type declarations make Python unsafe? References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EEDEC19.CA5786DC@engcorp.com> <3EEE789A.3DD19DA4@engcorp.com> Message-ID: In article <3EEE789A.3DD19DA4 at engcorp.com>, Peter Hansen wrote: . . . >> Automated testing, carefully thought out, can increase this fraction >> significantly; but "run the software before you give it to the customer" >> is a laughably inferior way of finding bugs. > >I agree, that would indeed be a laughable, not to mention ineffective, approach. > >-Peter Yet I must testify that there are plenty of big-budget development operations whose operation doesn't achieve *that* level of sophistication. I note that just for some sort of balance. Please, let's not hold ourselves back to their level of in- competence. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From tim.one at comcast.net Sun Jul 13 14:04:00 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 13 Jul 2003 14:04:00 -0400 Subject: floating point control in extensions In-Reply-To: <92tOKLARvSE$Ewh9@jessikat.fsnet.co.uk> Message-ID: [Robin Becker] > Is there a preferred way to intercept floating point exceptions in > python extensions? I assume one should be careful to restore any > existing error handler. Python itself assumes that no-stop mode is in effect (the IEEE-754 mandated default: all FPU traps are disabled). > Does python have a standard mechanism for setting up fpu control > words etc? See Modules/fpectlmodule.c. Note that the 2.3 NEWS file says: > - The fpectl module is not built by default; it's dangerous or > useless except in the hands of experts. fpectlmodule.c is a cross-platform nightmare, it often doesn't work even on the platforms someone once tried to make it work on (the magic incantations required sometimes even vary across specific releases of specific compilers on specific platforms), and it appeared that nobody used it anyway. If compiler vendors eventually implement the optional IEEE-754 API defined by C99, that would allow a much saner approach. iow-for-now-you're-on-your-own-ly y'rs - tim From gh at ghaering.de Fri Jul 11 11:16:08 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2003 17:16:08 +0200 Subject: Python extension on Windows In-Reply-To: References: Message-ID: <3F0ED4B8.4080401@ghaering.de> David Isal wrote: > hi all, > i'm new to python and i'm trying to build a python extension on win98, > written in c++, with cygwin.^ So we're talking native win32 here, right? You *can* use the Cygwin toolset to compile native win32 executables and DLLs, but I prefer to use MINGW for this. > but i keep having the same error message, and i didnt't find much > resources on the web about it: > >g++ -I/cygdrive/c/python22/include -c demomodule.cpp -o demomodule.o > > In file included from /cygdrive/c/python22/include/Python.h:62, > from demomodule.cpp:1: > /cygdrive/c/python22/include/pyport.h:480:2: #error "LONG_BIT definition > appears wrong for platform (bad gcc/glibc config?)." Yep. Use MINGW, the native GCC for win32. That's what I use and where I could help you with. If you want to continue using Cygwin to build extension modules, be sure to have the win32api Cygwin package installed. > i read that it is mandatory to use Micro$oft visual c++ to build any > extensions on windows beacuse it's the same compiler used to build > python for windows. That's wrong. See http://www.python.org/doc/current/inst/non-ms-compilers.html > does anybody has advices about that? Yes, read the above page :-) I also recommend to use distutils to compile Python extensions instead of trying to find out the correct compiler and linker options yourself. It's the easiest way to compile Python extensions, no matter what the platform. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 for a recipe. Build it using mingw or Cygwin with this command: c:/python22/python setup.py build --compiler=mingw32 I'd recommend you try a minimal C extension first before using C++. IIRC I needed to use something like libraries=["stdc++"] for making a C++ extension with distutils. -- Gerhard From klappnase at freenet.de Thu Jul 17 06:13:23 2003 From: klappnase at freenet.de (klappnase) Date: 17 Jul 2003 03:13:23 -0700 Subject: Problem recording large files with snack Message-ID: <9a410299.0307170213.2f6fb735@posting.google.com> I am trying to develop some little sound applications for linux with python using the Snack toolkit (I am far from being a "professional" programmer, I just do this for fun and I am afraid that I'm still a beginner). Now I have this problem when I want to record large wav-files that every time a screensaver starts up (or other programs are started) there is a loss of audio data in the recording, so for example ten seconds are completely missing. The way I start recording is something like: s = tkSnack.Sound(encoding="Lin16", frequency=44100, channels=2, fileformat="WAV",precision="double", byteteorder="littleEndian", file="xyz.wav") s.record() The "buffersize" option does not seem to have any effect on this problem. Does anyone know how to fix this? From rastm2 at aol.commorespam Sun Jul 27 00:15:39 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 27 Jul 2003 04:15:39 GMT Subject: Del's "except"ional PEP Rejection Message-ID: <20030727001539.05032.00000548@mb-m26.aol.com> Ladieees and Gentilmen and Pyth-O-neers of all ages. Step right up. Don't be shy. Come one come all. Be the first on your block TO GROK *THE* one *THE* only Exception you won't find any where but here! The Exception that's Exceptional! It's the "elif from lamdba except" Exception. (The only Exception that don't need an "except" clause, Because it *IS* one.) It's the story of Del, an intermitantly deaf, intermitantly nauseated importation executive with Print Global Inc. Del's a company man, and the 150 year old, family owned company needs someone to lead them all into the 21'st Century. Having over heard... ( It's amazing how some people who seem deaf at times can hear things from what was supposed to be a closed door meeting between ) ...the VP of Statis talking down to the 85 year old Chief of Data Processing ... ( History Note--that's what they used to call them you know -- worked his way up from crank turner -- but I digress ) ... what was I saying oh yeah Del over heard the VP telling the old guy, "Hell, my 12 year kid stuck *some* kinda snake, wait it was a python, yeah he stuck a python in an old Apple II that was in the attic a week ago Sunday and started typeing like mad and by Thursday he was telling me that he had gone GLOBAL and wouldn't need his allowance anymore. No it's time to upgrade. Shut down the ENIAC." Cut to the "ever butt kissing" Del, half deaf, sitting in Python school. Well, sorta sitting 'cuz' Del's got bowel problems and he needs another pass from the Instructor to go to the lav. Sitting on the pot, like a splash, a thought hits him. ( gosh I hope it was just a thought ) Ya see, Dan didn't just volenteer for this mission, he was holding back from the company. He new a litte "c" code. Just enough to be dangerous, and it made him sick to his stomach. But this Python Language! He truely understood and liked what he was learing. Python was indented so you could read it like a self respecting human being. It was impressive to him, the way you could write your code in the interpreter, and did't have to declare anything or agonize while you waited to see if it worked. He liked the way "elif" statements made case switches easier to code and understand. How "from" this "import" that made code re-usable. How "lamda" could define a function in a function without having to define a function for a function. How exceptions could be used to make programs that worked the first time. He loved the "while loops" and the list comprehensions that had little "for loops" and "if"s in them. He like how any one on the planet, with enough money to maintain a computer and an internet connection, could just be so very proud that they had their PEP rejected by the most intelligent, helpful, thoughtful, and kindest people on Earth. Sitting right there on the throne of inspiration he came up with the only exception that uses all the keywords, types all in one color in the editor, and makes sense to only him, so he sent in a PEP to be rejected... wait for it wait for it Bam! The elif from lambda except: statment elif from lambda except: while del is not def: [import exec for print global] try: continue or else: raise and return break pass in class finally: yeild if assert *PYTHON* *THE*WAY *GUIDO* *INDENTED* *IT*TO*BE* By Raymond St. Marie (Rastm2 at aol.com -- don't laugh, it's been free since I lost my job in January) From newsgroups at jhrothjr.com Sat Jul 12 07:47:55 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 12 Jul 2003 07:47:55 -0400 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> Message-ID: "sebastien.hugues" wrote in message news:3f0e77fc at epflnews.epfl.ch... > Hi > > I would like to retrieve the application data directory path of the > logged user on > windows XP. To achieve this goal i use the environment variable > APPDATA. > > The logged user has this name: s?bastien. The second character is not an > ascii one and when i try to encode the path that contains this name in > utf-8, > i got this error: > > Ascii error: index not in range (128) > > I would like to first decode this string and then re-encode it in utf-8, but > i am not able to find out what encoding is used when i make: > > appdata = os.environ ['APPDATA'] > > Any ideas ? I don't think encoding is an issue. Windows XP stores all character data as unicode internally, so whatever you get back from os.environ() is either going to be unicode, or it's going to be translated back to some single byte code by Python. In the latter case, you may not be able to recover non-ascii values, so Rob Willscroft's workaround to get the unicode version may be your only hope. If you're getting a standard string though, I'd try using Latin-1, or the Windows equivalent first (it's got an additional 32 characters that aren't in Latin-1.) Sorry I don't remember the actual names. Note that Release 2.3 fixes the unicode problems for files under XP. It's currently in late beta, though. I don't know if it fixes the os.environ() interface though, and it's rather late to get anything into 2.3. John Roth > > Thanks in advance > Sebastien > From intentionally at blank.co.uk Tue Jul 15 00:27:05 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 05:27:05 +0100 Subject: anything like C++ references? References: Message-ID: <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com> On Mon, 14 Jul 2003 18:30:15 -0500, sismex01 at hebmex.com wrote: >> From: Tom Plunket [mailto:tomas at fancy.org] >> Sent: Lunes, 14 de Julio de 2003 06:15 p.m. >> >> What I specifically want is a way to have a "second-level >> binding", e.g. a reference to a reference (assuming that the >> terminology is correct by saying that all Python variables are >> references). This is where I see the hole in Python, that there >> actually is a class of object that is different from everything >> else; you can bind to anything at all in the language...except >> references. >> >> -tom! >> > >What for? What would be the practical use for such a thing? >To rebind a name remotely? It's not very consistent with the >rest of the language. > >To have functions which rebind a name in a hidden way seems >to me like a veritable fountain of possible bugs. Explicit >is better than implicit and all that. Absolutely. At present, people fake it by abusing mutable types. Or else they fall over it when they are surprised by the behaviour of mutable types. Wouldn't it be better if it was explicit? Wouldn't it be better if it only happened when you actually asked for it? >A binding can't also be a container, that's a job for an object, >if you truly need to "pull" data from a code segment, then you >should use a dictionary, or a list, or an instance of some >other mutable class, heck, even an empty class: Really. Is that what dictionaries are for? Or lists? Or other mutable classes? Or are you abusing the functionality of types intended for a different purpose in order to fake pointers? From python at grimes.org.uk Tue Jul 1 09:25:53 2003 From: python at grimes.org.uk (Paul Grimes) Date: Tue, 01 Jul 2003 14:25:53 +0100 Subject: PyQT and Mandrake 9.1 References: Message-ID: MK wrote: > "Gilles Lenfant" wrote > >> I've been very excited by PyQT evangelists. > > Be careful. QT is controlled by one company, Sort of true > and it costs money. Not true, unless you want to distribute a closed source program See http://www.kde.org/documentation/faq/misc.html#id2915591 or http://www.kde.org/whatiskde/qt.php and http://www.kde.org/whatiskde/kdefreeqtfoundation.php Paul From roy at panix.com Sun Jul 13 21:36:14 2003 From: roy at panix.com (Roy Smith) Date: Sun, 13 Jul 2003 21:36:14 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien> Message-ID: Jack Diederich wrote: > I was a long time C++ guy and my a-ha moment was when I realized that the > GoF's "Design Patterns" were not all universal -- some are C++ specific. > Trying to force Python semantics into a C++ world view will leave you feeling > empty every time. Thank you for writing this, it makes me feel better! I was having exactly this discussion just a couple of days ago with our local hard-core C++ guy (who also poo-poo's Python, even though he's never actually tried it). I made exactly the point Jack made -- that the Design Pattern book is rather C++-centric, and some of it just doesn't tranlate into Python very well. For example, in the chapter on the Singleton pattern, a lot of time is devoted to (what I consider) esoterica in the C++ access control system (making copy constructors private, and all that stuff) to make sure nobody can cheat and find a way to make a copy of the singleton. None of that makes any sense in Python because (for better or worse), the concept of private members just doesn't exist. From max at alcyone.com Sat Jul 19 22:19:44 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 19 Jul 2003 19:19:44 -0700 Subject: Newbie! I'm a newbie! What's wrong with this program? References: <5da8e4b3.0307191800.48dc0a6d@posting.google.com> Message-ID: <3F19FC40.C082B239@alcyone.com> Id0x wrote: > ##Function for converting minutes to hours## > def minHour(x): > min = 60 > hour = min * x > print hour Your function does the conversion and then _prints_ the result. It doesn't return anything. > print "There are", minHour(x_hours), "minutes in", x_hours, "hours"; Here you're trying to print the return value of minHour, which since you didn't return anything, defaults to None. Fix it by making that last line of minHour return hour instead of print hour > newLine(); > print "Program Terminated."; > newLine(); Note that Python does not require an end of line discriminator, so all these semicolons are redundant (you seem to know this since since you don't use them in some places, but use them in others). (Also, "newLine()" really is a curious abbreviation for "print" :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Love is a hole in the heart. \__/ Ben Hecht From nushin2 at yahoo.com Wed Jul 23 14:30:32 2003 From: nushin2 at yahoo.com (nushin) Date: 23 Jul 2003 11:30:32 -0700 Subject: How to disable spawnv's child process output messages References: None <1058938603.850678@yasure> Message-ID: Hi Donn. Thanks for your response. Yes, in this case my parent process is hello_moon.py that is spwaning the child process, hello_earth.py. I am simply printing a hello world from each process and do not wish to see any output messages from the child process, and i *have to* see the output from the parent process, hello_moon.py Could you please elaborate more on how i can use dup2( ) to disable the output of the child process spawned by spawnv( ) API? Regards, BB (Nushin) "Donn Cave" wrote in message news:<1058938603.850678 at yasure>... > Quoth nushin2 at yahoo.com (nushin): > | I have a program called hello_earth.py that is spawned by > | hello_moon.py, using spawnv( ) API as: > | > | os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello_earth.py'),('>/dev/null > | &')) > | > | I do not wish to see any output messages from the hello_earth.py when > | it is launched by its parent process and i do wish to see *only* the > | output messages from the parent process in the shell. Is Python > | capable to so such a thing? > > What is the parent process in the shell? You mean the one that calls > spawnv()? If so - yes, Python can do that. But not so easily. You > can look at how spawnv is implemented (it's in Python), and read up > on the dup2 function (man 2 dup2) to see what's needed. spawnv can't > do any kind of redirection. I think I posted an example here a couple > weeks ago. > > Or you can use the shell, more or less the way you were going but you > never invoked it - > os.spawnv(os.P_NOWAIT, '/bin/sh', ['sh', '-c', 'python hello_earth.py > /dev/null']) > > which is really about the same as > os.system('python hello_earth.py > /dev/null &') > > Donn Cave, donn at drizzle.com From ianb at colorstudy.com Wed Jul 2 02:03:06 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 02 Jul 2003 01:03:06 -0500 Subject: Haskell distutils-type system In-Reply-To: References: Message-ID: <1057125786.725.146.camel@lothlorien> On Tue, 2003-07-01 at 16:34, Gerhard H?ring wrote: > > Do you / did you find yourself duplicating a lot of what make already > > does, ie dependencies, etc, or do you utilize make? > > AFAIK Python's distutils doesn't know about dependencies. It seems clear to me that distutils would have no use for make's dependencies. distutils is for distribution of modules, not the iterative development of those modules. When you build a C extension, you are always going to compile every file, since you are starting from scratch. Make's dependencies are only for speeding the developer's life as they change individual files, it's not for the extension user or installer. Ian From rreagan at attbi.com Thu Jul 3 19:48:08 2003 From: rreagan at attbi.com (Russell Reagan) Date: Thu, 03 Jul 2003 23:48:08 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: "Dave Brueck" wrote > > I > > mean, is Linux (or Windows) 'not a viable project'?? > > Well, again, neither of those are "applications level" projects. There is a rather large industry which I'll call "computer games" that is rather CPU intensive, and AFAIK the vast majority of those games are written in C/C++. It really depends on the definition of "application level". If we're only including things like word processors and web browsers in the "application level", then there isn't a great need for C++ in the "application level", but there are certainly areas where speed and memory efficiency is important. I will admit that I'm getting tired of writing a lot of the support code, debugging, etc., most of which Python provides for "free". From sismex01 at hebmex.com Thu Jul 24 16:11:46 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 24 Jul 2003 15:11:46 -0500 Subject: easy way to remove nonprintable chars from string Message-ID: > From: Isaac Raway [mailto:isaac at blueapples.org] > Sent: Jueves, 24 de Julio de 2003 03:04 p.m. > > This seems to work. Not sure how fast it'd be, though. > > def stripNoPrint(str): > results = "" > for char in str: > if string.printable.find(char): > results += char > return results > And to make this thread end quickly, the functional version of the above would be like: def StripNoPrint(S): from string import printable return "".join(filter(lambda ch:ch in printable, S)) And converted to use list comprehensions: def StripNoPrint(S): from string import printable return "".join([ ch for ch in S if ch in printable ]) HTH!!! -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From op73418 at mail.telepac.pt Tue Jul 29 09:22:10 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 29 Jul 2003 14:22:10 +0100 Subject: Itertools References: Message-ID: On Tue, 29 Jul 2003 08:32:14 -0400, "Ronald Legere" wrote: >The new itertools stuff is pretty cool. One thing that bothers me though is >that >there seems to be no way to copy an iterator. How does one work around this? >Is >there a trick that I am missing? > >Without being able to 'split' an iterator, I can't >think of how to do some of the cool things you can do with lazy lists in >Haskell. It seems >quite often you want to be able to do this 'splitting', and if I >had more coffee I would post an example :) The ones I >can think of are also defined recursively, which is another kettle of fish. > Iterables can be more far general than lazy lists: think of a socket as an iterable churning out lines of text, for example. How would one go about copying these general iterables? You can take slices of iterables, though - can't remember the name, islice? But since you don't know how to take copies of iterables in general this may not be that useful. > But I hope that someone knows >what I am talking about and has thought of a way... >Cheers! > With my best regards, G. Rodrigues From mertz at gnosis.cx Mon Jul 14 21:57:32 2003 From: mertz at gnosis.cx (David Mertz) Date: Mon, 14 Jul 2003 21:57:32 -0400 Subject: Which Python Book References: <3F134200.8060708@hotmail.com> Message-ID: hokiegal99 wrote previously: |I have an option, I can buy either O'reilly's "Python in a Nutshell" or |"Python Cookbook", but not both. |I've found that I learn better when I look at actual programs written to |solve problems, instead of abstract, theorhetical code that could be |used to solve problems. I guess it would be best if I could take the |abstract, theorhectical code and apply it to real-world problems, but |that's a bit of a leap for me... You might find that my recently released book is somewhere in between the approaches of the above two books. More code samples (and specifically more "real world" code) than _Nutshell_, but a bit more theoretical than _Cookbook_. Both of Alex's books, however, are extremely excellent; you can't go far wrong with those. Of course, my title is _Text Processing in Python_, and the title does not lie about the book's focus. But then, almost everything *I* do is some kind of text processing; YMMV. In any case, you are welcome to read the entire book for free at its website and/or buy a copy printed onto dead trees: http://gnosis.cx/TPiP/ Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From Simon.Wittber at perth.maptek.com.au Wed Jul 9 23:14:47 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Thu, 10 Jul 2003 11:14:47 +0800 Subject: Embedding Python, threading and scalability Message-ID: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> >I asked once and was told it was best fixed by removing the documentation >which mentioned it. Others also stated it was unlikely to be fixed. This can be fixed. Give Guido a SMP machine. I'm sure the threading issue would shortly be resolved. Seriously though, this is an issue, which is a major hurdle Python *has* to cross if it is ever going to be seriously considered for use on large projects, on large SMP hardware. SimonW. From sismex01 at hebmex.com Thu Jul 31 18:33:25 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 31 Jul 2003 17:33:25 -0500 Subject: Python's biggest compromises Message-ID: > From: akhleung at earthlink.net [mailto:akhleung at earthlink.net] > Sent: Jueves, 31 de Julio de 2003 01:41 p.m. > > It seems to me that a big compromise/feature is that all kinds of > namespaces are usually represented by dictionaries, and that Python > exposes this fact to the programmer. This would seem to limit the > possible optimizations that can easily be performed by a compiler. > > BTW, I have only read about Python out of interest, and haven't > actually used it for anything, so I hope my remark isn't ignorant. > > Best regards, > Aaron > Hello Aaron. Actually, this which you call a compromise, is one of Python's biggest strengths: it allows you, as a programmer, to perform many things which in other languages would be simply impossible, or at least would force you to jump through plenty loops and hoops. Take a look at Alex Martelli's Borg pattern, it shows what can be done by having open access to class *and* object namespaces, and being able to manipulate them. In Python it's easy and straightforward (eek), but in other languages, well... you have whole books dedicated to that. We're all adults, and all that. :-) -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From rxs141 at cwru.edu Tue Jul 22 23:34:28 2003 From: rxs141 at cwru.edu (Ravi) Date: Tue, 22 Jul 2003 23:34:28 -0400 Subject: Python and VS.Net Message-ID: Has anyone tried building Python with VC++.NET? Does it work or fail horribly like I think it will. My boss seems to think it is good to have programs that are in managed code because it is more 'portable'. Not that there's another complete .NET runtime besides Microsoft's but he does not understand that. Thanks for the help, Ravi From gh at ghaering.de Fri Jul 11 14:07:33 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2003 20:07:33 +0200 Subject: Why Python In-Reply-To: <3f0edd67.316281478@news.pa.comcast.giganews.com> References: <3f0be9ac@news.comindico.com.au> <3f0edd67.316281478@news.pa.comcast.giganews.com> Message-ID: <3F0EFCE5.503@ghaering.de> Chuck Spears wrote: >>There are, but if you're into thin GUI clients like VB6, there is no >>direct equivalent. > > LOL. Tell our VB guys who have to bundle VB6 runtimes, MDAC, and > other assorted Activex controls with their apps how thin VB6 clients > are. I was mixing terms up. I was really meaning 'fat client' here (full win32 GUI/database access, etc.) in contrast to a 'thin client' (normally a browser-based interface with most processing happening on the backend web-/database server) > If you want a truly thin windows client, use Delphi or C++ > Builder. Executable/runtime size is pretty much irrelevant under most circumstances (read: intranets with scripted installs). -- Gerhard From newsgroups at jhrothjr.com Tue Jul 22 22:50:38 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 22 Jul 2003 22:50:38 -0400 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: "Mars" wrote in message news:764b8294.0307221520.18017b09 at posting.google.com... > I have looked long and hard at Mr. Martelli's Borg recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 > > It is a very useful substitute for a Singleton, but I can't figure out > how it works. _shared_state is never assigned any value, only > self.__dict__ is assigend self._shared_sate's value - or rather > (self.)_shared_state must be assigned a value at some point, otherwise > the code wouldn't work(right ?). I have gone through the code in the > debugger several(many) times, and inserted god knows how many print > statements, but without luck(or skill i guess). > > Just so you don't waste your time, i do understand that _shared_state > is a class field(variable, or what not) and that its state is shared > by all instances. > > Sorry if this question is banal, but I really need to understand this, > even if it means exposing my complete lack of understanding as far as > what is probaly basic Python knowledge. I can kind of understand the justification for the Borg pattern in Python releases before 2.2, because there was no way of creating a true singleton in those releases. However, in 2.2 and later, it's really easy to create one using new style classes. The trick is to use the __new__() method instead of the __init__ method. In the __new__ method, test to see if you've created an instance yet. If you have, just pass it back. If you haven't, call object.__new__ to create an instance, save it, initialize it and pass it back. There are the usual issues with race conditions if you have multiple threads before the first call, but those can be avoided easily. That being the case, I'd like to see the Borg pattern go the way of a fondly remembered hack that is no longer necessary. John Roth > > Regards, > > Martin From Vincent.Raaijmakers at ge.com Thu Jul 31 14:47:06 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 31 Jul 2003 13:47:06 -0500 Subject: SQL2000 database vs python, using mssqldb Message-ID: <55939F05720D954E9602518B77F6127F02F87006@FTWMLVEM01.e2k.ad.ge.com> First of all, thanks for all the help guys! Until now, lots of install problems on all the recommended packages/modules. For now, my best option was to make use of my existing Pyro framework (thanks Irmen!) I already build a MSSQL (Pyro/server)service on the windows box using mssqldb. My linux app will talk to this service. This at least has been installed successful and my service can already connect to the database. So far so good: Now, I can't find the API of MSSQL. Not on the website nor in the installed folders. So, I tried to use the examples and only the connections seems successful. When I try a select on a table, it tells me that the table name is an invalid object name. Just tried a kind of a hello world example... import mssqldb import MSSQL db = MSSQL.connect('my_db_server', 'user', 'password', 'my_database') ## so far, so good c = db.cursor() c.execute('select * from my_table') ## boom, error c.fetchall() c.nextset() The ms sql enterprise manager shows me that the database and table is there. Unfortunately, in python the error tells me: Invalid object name 'my_table' Anyone with experience? Where are the API's? Vincent From furliz at libero.it Fri Jul 25 06:17:24 2003 From: furliz at libero.it (furliz) Date: Fri, 25 Jul 2003 12:17:24 +0200 Subject: newbie: Tkinter and COM objects Message-ID: Is it possible to embed a COM object instance in a Tkinter-based gui program? If I would to use an instance of IExplorer or a Flash movie in a Tkinter window... how can I do it? I hope I don't made a stupid question... From bgailer at alum.rpi.edu Wed Jul 9 15:16:48 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 09 Jul 2003 13:16:48 -0600 Subject: check if dir exists In-Reply-To: Message-ID: <5.2.1.1.0.20030709131556.0267a8a8@66.28.54.253> At 09:01 PM 7/9/2003 +0200, Geiregat Jonas wrote: >How can I check if a dir exists ? os.path.exists(path) # Return true if path refers to an existing path. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From gh at ghaering.de Thu Jul 24 10:54:04 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 24 Jul 2003 16:54:04 +0200 Subject: How to do raw Ethernet under Win32? In-Reply-To: <3f1feeba$0$169$a1866201@newsreader.visi.com> References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> <3f1ee77f$0$160$a1866201@newsreader.visi.com> <3f1feeba$0$169$a1866201@newsreader.visi.com> Message-ID: <3F1FF30C.4030302@ghaering.de> Grant Edwards wrote: > I've never done any SWIG stuff before, but it looks like all I > have to do is add some stuff to the .i file to export the > pcap_sendpacket() function. I haven't done any SWIG work, either (apart from unsuccessful tries at adding something to wxPython once). Instead I directly hacked the SWIG generated C code, so my patch is little but a quick hack. It's also some time ago and I never used the thing myself, so don't ask me about details :-) -- Gerhard From jdhunter at ace.bsd.uchicago.edu Tue Jul 22 10:10:49 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Jul 2003 09:10:49 -0500 Subject: Search for a string in binary files In-Reply-To: (hokieghal99's message of "Tue, 22 Jul 2003 09:45:49 -0400") References: Message-ID: >>>>> "hokieghal99" == hokieghal99 writes: hokieghal99> And, would it be more efficent (faster) to just call hokieghal99> grep from python to do the searching? Depending on how you call grep, probably. If you respawn grep for each file, it might be slower than the python solution. If you first build the file list of all the files you want to search and then call grep on all the files simultaneously, it will likely be a good bit faster. But you will have to deal with issues like quoting spaces in filenames, etc.... JDH From bokr at oz.net Thu Jul 24 15:51:42 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2003 19:51:42 GMT Subject: Mystery Theater New Style Classes References: Message-ID: On Thu, 24 Jul 2003 14:26:20 -0400, "Terry Reedy" wrote: > >"Bob Gailer" wrote in message >news:mailman.1059062857.29503.python-list at python.org... >> Predict the output: >> >> class A(int): >> classval = 99 >> def __init__(self, val = 0): >> if val: >> self = val >> else: >> self = A.classval > >I am not sure what the point is. However, > >1. Rebinding the local variable 'self' (or any other local variable) >only affects further code within the function, which there is not any. >So the above conditional is equivalent to 'pass'. > >2. Because ints are immutable, the value of a new int is set within >int.__new__, which is not overwritten. Thus, the above __init__ is >irrelevant. In particular, the value of an A object has nothing to do >with the defaulted parameter 'val=0'. > >> a=A(3) > >3. This is equivalent to a=int(3). No surprises. > >> b=A() > >4. This is equivalent to b = int(). I thought this might raise an >exception. But after seeing the result (0). I remember Guido's >decision (and a recent PyDev discussion thereof) that callable builtin >types should, if possible, return a null value when getting a null >input. Hence > >>>> int(), long(), float(), tuple(), list(), dict() >(0, 0L, 0.0, (), [], {}) > >> print a,b >3,0 > >5. Result is same if 'val=0' is changed to 'val=9' or anything else. > >> [from OP's self followup] The question this leads to is: how does >one access the value of such a class within a class method? > >Since there is no class method presented, this make not much sense. >Bob: were you aware of 4.) above when you posted this? > Maybe the OP will be helped by >>> class I(int): ... def info(self): print type(self), self, type(int(self)), int(self) ... >>> i=I(123) >>> i.info() 123 123 and the "value" he wants is int(self) ? Regards, Bengt Richter From usenet_spam at janc.invalid Tue Jul 8 23:28:33 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 09 Jul 2003 03:28:33 GMT Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: Fernando Perez schreef: > or even gif (the patents expired recently). Only in the US, not in (some countries in) Europe & Japan. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From postmaster at bag-mail.com Thu Jul 3 03:08:24 2003 From: postmaster at bag-mail.com (postmaster at bag-mail.com) Date: Thu, 3 Jul 2003 09:08:24 +0200 Subject: Undeliverable: Re: Movie Message-ID: Your message To: austria at msdirectservices.com Subject: Re: Movie Sent: Thu, 3 Jul 2003 09:07:16 +0200 did not reach the following recipient(s): austria at msdirectservices.com on Thu, 3 Jul 2003 09:07:57 +0200 The recipient name is not recognized The MTS-ID of the original message is: c=us;a= ;p=bag;l=DEBAGE1430307030707LYSWPK9G MSEXCH:IMS:BAG:EUROPE-SMTP:DEBAGE143 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Movie Date: Thu, 3 Jul 2003 09:07:16 +0200 Size: 941 URL: From db3l at fitlinxx.com Wed Jul 23 12:14:29 2003 From: db3l at fitlinxx.com (David Bolen) Date: 23 Jul 2003 12:14:29 -0400 Subject: python assignment References: Message-ID: danbmil99 at yahoo.com (dan) writes: > see my prev. post on this. I realize my original assumptions were off > base, but frankly the documentation does a poor job (really no job) of > describing the state of affairs wrt how Python handles objects, and > how this affects what happens when you assign things. A section on > names and binding principles would be much appreciated. >From seeing the examples you are using, it seems to me that your issue is much less with Python's object handling, or assignments/name binding, but is really focused on the augmented assignment operators. Perhaps the issue is that the documentation could be clearer that such operators (thus the term "augmented") are not simply assignment operators, but as Tim points out, syntactic sugar for a special method call providing the possibility for differing behavior among different object types (as would be true with any method call). If you think of them that way (as opposed to trying to keep them logically with assignment statements) then perhaps things would seem more consistent. -- David From max at alcyone.com Tue Jul 15 01:01:08 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 22:01:08 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> Message-ID: <3F138A94.A41AFE1B@alcyone.com> Stephen Horne wrote: > The fact that Python has, in this respect, followed the C etc > tradition doesn't mean it is doing the right thing. But in a sense this is tilting at windmills. One could make some high-brow arguments about how these are the wrong choices of symbols for these kinds of operations, but the simple fact is that the computer science community as a whole -- far and wide -- has really grown accustomed to it. Nothing's preventing you from choosing some other choice in your own language (if even those symbols would have relevance! e.g. def/eq vs. =/==), but arguing that Python shouldn't do it because that doesn't match mathematics is an academic (in both senses of the word). It does, there's wide community acceptance of this -- for better or worse -- from a large and exceptionally popular family of languages -- so that isn't going to change. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The actor is not quite a human being -- but then, who is? \__/ George Sanders From jdhunter at ace.bsd.uchicago.edu Tue Jul 22 09:59:19 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Jul 2003 08:59:19 -0500 Subject: Flat file to associative array. In-Reply-To: ("Alex"'s message of "Mon, 21 Jul 2003 01:02:49 -0400") References: Message-ID: >>>>> "Alex" == Alex writes: Alex> Hello, What would be the best way to convert a flat file of Alex> products into a multi-dimensional array? The flat file looks Alex> like this: Alex> Beer|Molson|Dry|4.50 Beer|Molson|Export|4.50 Alex> Shot|Scotch|Macallan18|18.50 Shot|Regular|Jameson|3.00 I work with CSV files a lot, and do something similar. I have written some helper functions and classes that allow you to slice through flat files as a 2D array, where the indices of the slices can either be normal integer indices, or string keys, as in from csvhelpers import getrows, rows_to_array #split the data on the | symbol def splitpipe(x): if len(x.replace('|','').strip())==0: return [] # empty row return x.split('|') rows = getrows( file('beer.flat'), splitpipe) headers=('category', 'brand', 'type', 'price') data = rows_to_array( rows, headers) print data[:,'price'] # prints all the prices (as floats) print data[0] # prints the first row print data # prints everything The getrows function does some extra work: for example it ignores empty rows, tries to convert the individual data cells to int then float, and ignores comments if you pass it an extra comment arg as in rows = getrows( file('beer.flat'), splitpipe, comment='#') With this call, your flat file can look like Beer|Molson|Dry|4.50 Beer|Molson|Export|4.50 # now for some booze Shot|Scotch|Macallan18|18.50 Shot|Regular|Jameson|3.00 For many of the CSV files I work with, there are headers in the first non empty row of the file. If you pass 'headers=1', rows_to_array will get the headers and allow you to index the array with the header strings. Also, I often have a unique key for each row, like a medical ID number. An optional arg rowKeyInd lets you index the data by row key string as well. Here is an example CSV file containing stock quote information. The row keys are in the first column ,,, ticker,date,open,price ADPT,2001-12-13,100.0,20.0 ,,, QQQ,2001-12-13,100.0,103.0 AAA,2001-12-13,100.0,10.2 PPP,2001-12-13,100.0,1.3 Note that the ,,, thing is fairly typical of CSV files that started their life as an Excel spreadsheet. They represent the empty rows. The first nonempty row contains the headers, and the first column the row keys. # use csv module in real life to handle legit commas in fields, etc.. def splitcomma(x): if len(x.replace(',','').strip())==0: return [] # empty row return x.split(',') rows = getrows( file('test.csv'), splitcomma) data = rows_to_array( rows, headers=1, rowKeyInd=0) print data[:,'open'] print data[:,'price'] print data[:,'date'] print data['ADPT',:] I am using Numeric arrays under the hood, and data[:,'open] and data[:,'price'] are Numeric arrays of Floats. Thus you can do things like change = data[:,'price'] / data[:,'open'] You can also use any valid slice, as in data[1:3,3] Hope this helps, John Hunter # csvhelpers.py # Requires Numeric: http://pfdubois.com/numpy/ and python2.2 from __future__ import generators from Numeric import array, Int, Float def iterable(obj): try: iter(obj) except: return 0 return 1 def enumerate(seq): for i in range(len(seq)): yield i, seq[i] def is_string_like(obj): try: obj + '' except (TypeError, ValueError): return 0 return 1 class rows_to_array: def __init__(self, rows, headers, rowKeyInd=None): """ rows is a generator that produces the rows of the flatfile, optionally including the header row. See getrows. If headers is iterable, then it is a list containing the headers. otherwise use the first row for the headers. headers must be unique rowKeyInd, if not None, is the column index of the row key so that rows can be identified by key """ if not iterable(headers): headers = [ h.strip() for h in rows.next()] # make dict from header to col index self.headerd = {} for i,h in enumerate(headers): key = h.strip() if self.headerd.has_key(key): raise RuntimeError, 'Headers must be unique. ' + \ 'Found duplicate: ' + key self.headerd[key] = i data = [row for row in rows] # use the first row to determine types; this should be improved self.types = [] for val in data[0]: if isinstance(val, int): self.types.append(Int) elif isinstance(val, float): self.types.append(Float) else: self.types.append('O') if rowKeyInd is not None: self.rowKeys = {} for i,row in enumerate(data): self.rowKeys[row[rowKeyInd]] = i self.data = array(data, typecode='O') def __getitem__(self, key): try: rowKey, colKey = key except TypeError: # row index only if is_string_like(key): rowSlice = self.rowKeys[key] else: rowSlice = key return self.data[rowSlice] type = None if is_string_like(rowKey): rowSlice = self.rowKeys[rowKey] else: rowSlice = rowKey if is_string_like(colKey): colSlice = self.headerd[colKey] type = self.types[colSlice] else: colSlice = colKey ret = self.data[rowSlice, colSlice] if type is not None: return ret.astype(type) else: return ret def __str__(self): s = str(self.headerd.keys()) + '\n' s += str(self.data) return s def try_to_num(val): try: return int(val) except ValueError: try: return float(val) except ValueError: return val def getrows(fh, parseline, comment=None): """ return the rows of the data in file object fh, converting to int or float if possible parseline returns the row as a list, ie, splits ths row. An empty row should be a list of length 0 if comment is not None, ignore lines starting with comment symbol """ while 1: line = fh.readline() if comment is not None and line.startswith(comment): continue if len(line)==0: return if len(line.strip())==0: continue vals = parseline(line) if len(vals): maxLen = max([len(entry) for entry in vals]) if maxLen==0: continue yield [ try_to_num(val) for val in vals] From gmuller at worldonline.nl Sat Jul 12 15:22:40 2003 From: gmuller at worldonline.nl (GerritM) Date: Sat, 12 Jul 2003 21:22:40 +0200 Subject: Small Python, Java comparison References: Message-ID: "Dave Brueck" schreef in bericht news:mailman.1057953857.30422.python-list at python.org... <...snip...> Java: >From the start of the design to the end of the implementation and initial round of bug fixing took 3 weeks. An additional 2-3 weeks were spent optimizing the code and fixing more bugs. The source code had 4700 lines in 9 files. When running, it would process an average of 1050 records per second (where process = time to parse the file, do calculations, and insert them into the database). <...snip...> Python: Because I wasn't working on this full-time, the development was spread out over the course of two weeks (10 working days) at an average of just over 2 hours per day (for a total of not quite 3 full days of work). The source code was less than 700 lines in 4 files. Most surprising to me was that it processes an average of 1200 records per second! I had assumed that after I got it working I'd need to spend time optimizing things to make up for Java having a JIT compiler to speed things up, but for now I won't bother. Both versions could be improved by splitting the log parsing/summarizing and database work into two separate threads (watching the processes I see periods of high CPU usage followed by near-idle time while the database churns away). Currently the Java version averages 47% CPU utilization and the Python version averages 51%. <...snip...> I recently wrote a short article about bloating of software: "Exploration of the bloating of software" www.extra.research.philips.com/natlab/sysarch/BloatingExploredPaper.pdf (long URL may be broken in two by e-mail reader!). I explain a number of effects I have observed which are caused by bloating, one of them degradation of performance. This degradation is repaired which causes again more bloating.... I think your small sample point is a clear illustration of the fact that appropriate technology is important. Your gain of a factor of 6-7 in loc will translate in comparable gains in maintenance, cost and ease of extending etcetera. thanks for sharing your experience, regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From stuart at bmsi.com Mon Jul 7 10:04:20 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 07 Jul 2003 10:04:20 -0400 Subject: Auto free Buffer objects in C API? References: Message-ID: On Thu, 03 Jul 2003 21:44:27 -0400, David M. Cooke wrote: > This is a bit ugly, as it depends on internal details. Another, cleaner, > method is to define an object which obeys the buffer protocol, and > handles destruction like you want. (This is annoying, as you'll end up > copying all the code in bufferobject.c). So annoying, in fact, that I will continue to make extra copies of the buffer until such time as: a) Python gets a PyBuffer_FromCObject(PyObject *,int len) method. b) Profiling reveals the extra copies to be a major bottle neck. The extra memory allocation is not a problem because the library spends most of its time moving the data between two buffers while processing it. BTW, the application is wrapping DSpam for Python. You can download the dspam module from: http://bmsi.com/python/milter.html From jack at performancedrivers.com Sat Jul 12 05:19:05 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Sat, 12 Jul 2003 05:19:05 -0400 Subject: Python Mystery Theatre -- Episode 1: Exceptions In-Reply-To: ; from vze4rx4y@verizon.net on Sat, Jul 12, 2003 at 06:56:52AM +0000 References: Message-ID: <20030712051904.D3955@localhost.localdomain> On Sat, Jul 12, 2003 at 06:56:52AM +0000, Raymond Hettinger wrote: Since you included the answers I was really unsuprised by what happened, but maybe I'm wrong as to the why (no other posts, docs, or searching read for my explanations). > ACT I --------------------------------------- > >>> s = list('abc') > >>> try: > ... result = s['a'] > ... except IndexError, TypeError: > ... print 'Not found' > ... > > Traceback (most recent call last): > File "", line 2, in -toplevel- > result = s['a'] > TypeError: list indices must be integers A TypeError was thrown, but writing this as except (IndexError,), type_error: explains why it wasn't caught. > ACT II -------------------------------------------- > >>> class MyMistake(Exception): > ... pass > > >>> try: > ... raise MyMistake, 'try, try again' > ... except MyMistake, msg: > ... print type(msg) > ... > > type() of most any (new style?) object will print this > ACT III -------------------------------------------- > >>> class Prohibited(Exception): > ... def __init__(self): > ... print 'This class of should never get initialized' > ... > >>> raise Prohibited() > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited() > Prohibited: > >>> raise Prohibited > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited > Prohibited: This one is new to me, FWIW I write two kinds of exceptions, one that is just defined as MyGuy(Excption):pass and another where I define both __init__ and __repr__ to print what I want. > ACT IV ----------------------------------------------- > >>> module = 'Root' > >>> try: > ... raise module + 'Error' > ... except 'LeafError': > ... print 'Need leaves' > ... except 'RootError': > ... print 'Need soil' > ... except: > ... print 'Not sure what is needed' > ... > > Not sure what is needed There is a reason string exceptions are deprecated ;) the string 'RootError' is not a subclass of the string 'RootError' and thus won't be caught. > > ACT V ----------------------------------------------- > >>> try: > ... raise KeyError('Cannot find key') > ... except LookupError, msg: > ... print 'Lookup:', msg > ... except OverflowError, msg: > ... print 'Overflow:', msg > ... except KeyError, msg: > ... print 'Key:', msg > > > Lookup: 'Cannot find key' > LookupError is the parent of KeyError and IndexError. I generally catch the more specific list/dict exceptions depending on what I'm trying to access. The fact that I'm very certain about my answers increases the likelyhood that I'm in fact wrong ;) -jack [I orignally had a long thing about the weird exceptions thrown by mmap here, but decided A: no one cared, B: a patch would be better than bitching. But really, how can a method with no arguments raise a ValueError?] From griebel at konzept-is.de Mon Jul 21 11:00:43 2003 From: griebel at konzept-is.de (Dr. Peer Griebel) Date: Mon, 21 Jul 2003 17:00:43 +0200 Subject: Stopping a loop with user input in curses In-Reply-To: References: <20030720135329.18124.00000260@mb-m15.aol.com> Message-ID: <3F1C001B.1050306@konzept-is.de> Alex wrote: > Hello Ray, > > Nope. That didn't do it. I got a properly drawn curses box > with nothing inside ... until I hit the 'q' key. Then the clock > popped up and the program quit. > > I have a theory on curses. I could be totally wrong here (and it > would be great if I was, actually). > > Curses cannot multi-task. > > It can't redraw a clock every second and check for a particular > keystroke at the same time -- there is only one cursor after all. > > So I guess I'll forgoe the funky clock in my curses app. However, > if you can completely flush this theory down the toilet, it would > be greatly appreciated... :) It would make my life easier in other > aspects of the program I'm trying to write. > > > Thanks, > > Alex > > Try the appended program. You are right, curses does not multi-task. You even did not create some task... But you don't need to have separate tasks. All you have to do is to check if keypresses are availabe. And only then you should call getch() since it will block until keystrokes are available. See (to understand you probably have to read documentation aboute select()): # Import curses module import curses, time stdscr = curses.initscr() from select import select def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() # If 'q' is pressed, exit finished = 0 while not finished: # finished = 0 until the 'q' key is pressed if select([0], [], [], 1)[0]: c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) From m at moshez.org Mon Jul 14 07:41:44 2003 From: m at moshez.org (Moshe Zadka) Date: 14 Jul 2003 11:41:44 -0000 Subject: Identity inconsistency and unification of types and classes In-Reply-To: <7h3isq5nz5l.fsf@pc150.maths.bris.ac.uk> References: <7h3isq5nz5l.fsf@pc150.maths.bris.ac.uk>, <6f03c4a5.0306301943.d822a6d@posting.google.com> Message-ID: <20030714114144.9423.qmail@green.zadka.com> rimbalaya at yahoo.com (Rim) writes: > With the great unification of types and classes, what will happen to the > following identity inconsistency? > > >>> class myint(int): pass > ... > >>> a=int(1); b=int(1) > >>> a is b > 1 > >>> a=myint(1); b=myint(1) > >>> a is b > 0 On Mon, 14 Jul 2003, Michael Hudson wrote: > Nothing, as is. You can always dick about in myint.__new__ if you > really want to manage that, but as others keep saying, you shouldn't > worry about it too much. Of course, the inconsistency has always been present: >>> int(1) is int(1) 1 >>> int(5000) is int(2500*2) 0 Not so much with the consistency, huh? Here's the deal: if a,b are immutable builtin objects, and a==b, it is undefined if "a is b" is true. Do not rely on it. Assume patch releases of Python will change it to be randomly true or false. Assume flags to Python's compilation will randomly change it to true or false. Assume the fluttering of the wings of a butterfly in Tibet will create a storm... err, sorry, got carried away there. Exercise: Determine for yourself where exactly I got carried away. Discuss. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From duncan at NOSPAMrcp.co.uk Tue Jul 15 05:17:42 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 15 Jul 2003 09:17:42 +0000 (UTC) Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> Message-ID: "richardc" wrote in news:3f13bd77$1 at mail.hmgcc.gov.uk: > 1. How do tyou do enum's in python, infact dose anybody know of a C++ > -> Python crossreference doc out there ? The only way to do enums in Python is to define a bunch of constants. Either put them in a module, or alternatively define them as class attributes. However, you may find there is less call for enums in Python than in C++, for example in C++ you might use enums to tokenise short strings, but in Python you would just use the strings to represent themselves. e.g. You could use any of these: UP, DOWN, LEFT, RIGHT = range(4) move(UP) or: class DIRECTION: UP, DOWN, LEFT, RIGHT = range(4) move(DIRECTION.UP) or: move('up') > 3. How do I reverse iterate through a loop ... is there an easier way > than something like the following > l = ['some', 'text', 'in', 'a', 'list' ] > for i in range( 0, len( l ) ): > do something to l[ i ] The usual way is simply to reverse the list before iterating over it. l = ['some', 'text', 'in', 'a', 'list' ] l_reversed = l.reverse() for item in l_reversed: do something to item > > 4. Is there an easy way to reverse read a file ? I mean like a > 'getline' that works by reading backwards through the file. Im > guessing getting single characters and moving the file pointer back is > going to be slow in python. Its not actally that important... just > wondering > If the file isn't too large you can call the readlines() method and simply reverse the result as above. You may find this incovenient for very large files though. I can't think of many cases where I would want to read a whole file in reverse, if all you want is the last few lines of a massive file then just seek near the end before reading the remainder and reverse the resulting list of lines. If you really do need all of the file in reverse, then you could write a generator to read it backwards in fixed size chunks and split each chunk into lines. -- 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 pinard at iro.umontreal.ca Mon Jul 21 22:15:22 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 21 Jul 2003 22:15:22 -0400 Subject: Search for a string in binary files In-Reply-To: References: Message-ID: [hokieghal99] > How could I use python to search for a string in binary files? From the > command line, I would do something like this on a Linux machine to find > this string: > grep -a "Microsoft Excel" *.xls > How can I do this in Python? Quite easily. To get you started, here is an untested draft, I leave it to you to try and debug. :-) import glob for name in glob.glob('*.xls'): if file(name, 'rb').read().find('Microsoft Excel') >= 0: print "Found in", name -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From clifford.wells at comcast.net Sat Jul 12 19:41:40 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 12 Jul 2003 16:41:40 -0700 Subject: new in town In-Reply-To: References: Message-ID: <1058053300.2220.51.camel@devilbox.homelinux.net> On Sat, 2003-07-12 at 14:19, Elaine Jackson wrote: > That's okay, because I don't want my hand held. What I'd like is a reasonable > assurance that, if I pick up this tool, I'll be able to accomplish what I have > in mind. That is the basic problem: you haven't told anyone what you have in mind. You might think you were being specific, but you weren't. I'm *guessing* you are asking if Python can be compiled in the same sense that C can. That answer is no. If you are asking whether standalone executables can be made, the answer is yes. If you are asking whether Python is fast enough for your application, the answer is maybe (or most likely). > If not then, no offence, but I intend picking up a different tool. As long as it isn't a bloody icepick, I don't think anyone would object to your use of any tool you please. Regards, Cliff -- Take a hollow point revolver, right down the rapids of your heart -Coil From Mike at kordik.net Fri Jul 4 21:25:00 2003 From: Mike at kordik.net (Mike) Date: Sat, 05 Jul 2003 01:25:00 GMT Subject: RTS/CTS and DTR/DTS control References: <3F060F8D.94E47DCD@engcorp.com> Message-ID: On Fri, 04 Jul 2003 19:36:45 -0400, Peter Hansen wrote: > Mike wrote: >> > Is there a library in Python that will give me control over the >> > handshaking lines directly? I actually want to control my X10 firecracker device. I have done it in Java (on Windows) already but now I want to do it in Python on Linux. You control the device by wiggling the control lines with certain patterns. I am looking at the search page you sent to me. Thanks, Mike >> I am running Linux, Python 2.2.2. It would be nice (not mandatory) to >> be cross platform though. > > You call them handshaking lines, so one might infer you want to use them > as such while doing serial communications. Are you in fact actually > planning to control them as discrete inputs and outputs, for some kind > of control application? (If not, I'm curious why you want to control > them directly.) > > There is Chris Liechti's library, which you can find with > http://www.google.com/search?q=python+serial+port but I'm not sure it > supports direct control of the I/Os... if it doesn't you should be able > to get direct control of those lines under Linux using appropriate > fcntl.ioctl() calls, I would think, though I haven't done it myself. > > -Peter From mmoum at woh.rr.com Wed Jul 30 22:10:29 2003 From: mmoum at woh.rr.com (Mike M) Date: Thu, 31 Jul 2003 02:10:29 GMT Subject: Python2.3 and MySQLdb on Windows Message-ID: Python2.3 and MySQLdb don't seem to work together on Windows. If I understand the error message correctly, the problem seems to be that the _mysql binary expects version 2.2 of the Python dll. Does anyone know of a fix for this, or when a Windows version that works with 2.3 will be available? Thanks, Mike -- the Moum's (Mike, Dede, Suzanne, Jeff, Kristen) Tipp City, Ohio, USA e-mail: mmoum at woh.rr.com --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From jarausch at skynet.be Wed Jul 16 10:49:51 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 16 Jul 2003 16:49:51 +0200 Subject: docs html-2.3.0.tar.bz2 - is there anything yet? Message-ID: <3f156610$0$300$ba620e4c@reader1.news.skynet.be> Hi, I am running Python's CVS version and I would like to install the 2.3 version of the html documentation (as requested by Idle, e.g.) Is there already such a file or can it be built from XML? sources contained in the distribution? At least, I haven't found a configure option. Thanks for a pointer, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From llafba at gmx.net Wed Jul 2 10:10:29 2003 From: llafba at gmx.net (Tom) Date: Wed, 02 Jul 2003 16:10:29 +0200 Subject: undo tab Message-ID: <3F02E7D5.4060401@gmx.net> Hi, as we all know we need tabs if we use for, if ... commands. Sometimes I find an easier way to do something and I can get rid of one or more for, if ... loops. Unfortunately I couldn't find a convenient way to get rid of the now unnecessary tabs. I am looking for something as convenient as inserting tabs (mark everything and push the tab key). I tried shift+tab and all other possible variations with alt/shift/ctrl. :-) Thanks for your help. Tom From garabik-news-2002-02 at kassiopeia.juls.savba.sk Tue Jul 1 10:20:21 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 1 Jul 2003 14:20:21 GMT Subject: how to register private python codecs? Message-ID: I am developing and application that makesheavy use of (my own) codecs not distributed with python (i.e. unicode(text, 'kamenicky')) I put the codec into file kamenicky.py, placed the file into /usr/lib/python/encodings, but now I want to distribute my application, and I assume that users won't always have the possibility of copying files into /usr/lib/python/encodings. Is there a (simple) way how to register this encoding so that the file "kamenicky.py" can be in (let's say) current directory? TIA -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From antonxx at gmx.de Wed Jul 30 05:26:19 2003 From: antonxx at gmx.de (stephan) Date: 30 Jul 2003 02:26:19 -0700 Subject: pythonwin and german chars, does anybody use pythonwin in non-us Message-ID: <35b78d97.0307300126.1d99cd2c@posting.google.com> Hi, I have python 2.2.3 + pythonwin 156 on win2k. The problem is that german chars like ??????? are not handled correctly. Just create a test.py file with the content ??????? and edit it with pythonwin. In the editor you will see only ???? . I had the problem in the past, wrote it to mark and he fixed it. The last pythonwin version which works is 148 ! The bug arised again with 150. The versions 150,152,154 and 156 are all the same: they don't work. I wrote it to Mark Hammond but I never got a reply, so it seems he has no, or no more interest or no time or whatever to fix it. So if there is somebody who use pythonwin in germany,france.. ... do you know a workaround?? (or another similar IDE??) I ask because I really like pythonwin, it's small fast and comfortable :-) Thanks stephan From keating at acm.org Mon Jul 14 03:20:30 2003 From: keating at acm.org (Paul Keating) Date: Mon, 14 Jul 2003 08:20:30 +0100 Subject: PyVariant anyone Message-ID: <3f125990$1_2@mk-nntp-2.news.uk.tiscali.com> I need to call a C++ DLL from Python, for which I'm planning to use boost.python. But the DLL has been written to a VBA interface, and this means it expects to get variable length arrays as Windows Variants instead of lists or tuples. Anyone know how to construct a convincing Windows Variant in Python? From hwlgw at hotmail.com Tue Jul 1 05:49:54 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 1 Jul 2003 02:49:54 -0700 Subject: Good code patterns in Python Message-ID: If you know that your source code is going to be used later by others, then I feel that code with the pattern: if some_condition: some_name = some_value else: some_name = other_value is often a mistake. Much better, safer, would be: some_name = some_value if not some_condition: some_name = other_value Why? Because those people reusing your code might decide to change or adapt the "if" part of the first example. Or the "else" part for that matter. And then they could end up with "some_name" being undefined, crashing other code maybe 1000's of lines away. This could happen for example because they use exceptions in the "if" part that jump out of it, etc. There is the small overhead of assigning something twice to some_name in the safer example, so if performance is *that* important then the first example is better, but I feel there should be comments with warnings around it: **CREATING A NEW OBJECT REFERENCE HERE!** Hmm, now that makes code ugly :-) What are your thoughts about this? I am interested in current large scale software development practice, and guidelines that are used there, especially for dynamically typed languages like Python. There must be a lot of advisable code design patterns (I can't find a good name in English) like this for use in software development with many programmers. Perhaps a collection with good documentation would be interesting? Or a tool like pychecker that flags "bad" patterns? -- People who miss goto now use exceptions From max at alcyone.com Thu Jul 3 13:55:06 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 03 Jul 2003 10:55:06 -0700 Subject: zip() or what? References: <3F03AFA8.7030905@ihug.co.nz> <3F03B4DB.545DC6B5@alcyone.com> <3F0401C4.1010306@ihug.co.nz> Message-ID: <3F046DFA.D15034F7@alcyone.com> Ray Tomes wrote: > I can understand the 2nd one, but I don't get the meaning of the * in > the > first. Is this like the opposite of putting [] around something or > what? > Under what circumstances can an * be used like this, and what is it > called? - I don't know how to look for it in the docs :-) f(x) calls the function f with the single argument x. f(*x) calls f with the arguments x, which is expected to be a sequence. The * syntax comes from defining functions, where a formal argument preceded by * means, "All the rest of the arguments as a tuple." So: >>> def f(*x): print x ... >>> s = [1, 2, 3] >>> f(s) ([1, 2, 3],) >>> f(*s) (1, 2, 3) The old way of writing the function call f(*x) was apply(f, x). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ War is like love, it always finds a way. \__/ Bertolt Brecht From martin at v.loewis.de Mon Jul 14 01:25:31 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 07:25:31 +0200 Subject: anything like C++ references? References: Message-ID: Stephen Horne writes: > >>>> a = ref(1) > >>>> b = a [...] > >>>> a = 5 > >>>> b > >5 [...] > Well, during the 'debate', that's the basic idea that involved - > except that I'd use explicit pointer-dereferencing syntax. This is a very bad idea. You want to create a reference to the object 1? Then I assume that assigning to "a" would *change* the value of 1? But 1 is an immutable object, it cannot change! > Imagine, for instance, changing all assignments and other 'copying' to > use a copy-on-write system. That assumes that there is the notion of copying values in the first place. Objects, in general, don't support copying - and assignment has nothing to do with copying. > >>> a = &5 > >>> b = newcopyof a # could be "b = &(*a)" in principle > >>> *b is *a > False Again, objects don't support copying. For immutable objects (like numbers), copying is also a pointless operation: If there where a standard .copy method on objects, numbers would return themselves. There is no way, in the language, to express that you want different copies of the value 5. This is completely different from the notion of values in C or C++, where each occurrence of the literal 5 creates a new value whose state is 5. Regards, Martin From ss3canon at earthlink.net Thu Jul 3 01:18:29 2003 From: ss3canon at earthlink.net (Mike) Date: Thu, 03 Jul 2003 05:18:29 GMT Subject: VERY FUN FREE ADDICTIVE RPG 9168 References: <3f039ec5$0$966$cc9e4d1f@news.dial.pipex.com> Message-ID: I'm sure its a great game but it keeps tellin me I put the security code in wrong. But I know its right, thus I can't play. From jeremiah at facility9.com Sun Jul 20 20:03:06 2003 From: jeremiah at facility9.com (Jeremiah McElroy) Date: Mon, 21 Jul 2003 00:03:06 GMT Subject: .NET Web Services Message-ID: <_4GSa.11522$Vx2.5474184@newssvr28.news.prodigy.com> I am attempting to connect from my local machine to a .NET web service I found on Xmethods.net which provides dictionary lookups. I am running windows XP with Python 2.2.3 and win32all-152. I'm using ZSI 1.2. When I attempt to contact the web serivce, I see the following stack trace: Traceback (most recent call last): File "C:\Python22\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python22\lib\site-packages\Pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python22\lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 591, in run exec cmd in globals, locals File "C:\Documents and Settings\mcelroyj.FACILITY9.000\Desktop\lookup.py", line 39, in ? result_list = b.Send( u, 'GetEEMeaning', DictRequest(word) ) File "C:\Python22\Lib\site-packages\ZSI\client.py", line 175, in Send self.h.connect() File "C:\Python22\lib\httplib.py", line 516, in connect socket.SOCK_STREAM): gaierror: (7, 'getaddrinfo failed') The source follows. I'm fairly new to using web services in Python, and I have only found very limited information on using them, so I'm extrapolating what I can from the docs. Thanks, Jeremiah SOURCE: #!/usr/bin/env python import sys import xml from ZSI import TC from ZSI.client import Binding FULL_DICT_NS = "http://www.xceer.com/trans/dic2.asmx?WSDL" u = '/trans/dic2.asmx?WSDL' h = 'http://www.xceer.com' n = 'http://tempuri.org/' SOAPMethod = 'GetEEMeaning' SoapAction = n + SOAPMethod dict = { 'xmlns:xsi' : 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' : 'http://www.w3.org/2001/XMLSchema', 'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/' } b = Binding( url=u, host=h, port=80, ns=n, nsdict=dict, soapaction=SOAPMethod ) try: word = sys.argv[1] except IndexError: print 'No word given, looking up "curmudgeon"' word = 'curmudgeon' class DictRequest: def __init__( self, word ): self.englishWord = word DictRequest.typecode = TC.Struct(DictRequest, [TC.String('englishWord')], 'GetEEMeaning', inline=1) try: result_list = b.Send( u, 'GetEEMeaning', DictRequest(word) ) print "result_list: ", result_list except: raise print 'reply : ', b.reply_code print 'reply_msg : ', b.reply_msg print 'headers : ', b.reply_headers print 'data : ', b.data From jjl at pobox.com Sun Jul 27 20:52:40 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:52:40 +0100 Subject: emacs python-mode questions: C-c C-c and broken docstring fill References: <87ptjwre0x.fsf@pobox.com> Message-ID: <87brvfa2w7.fsf@pobox.com> Skip Montanaro writes: [...] > John> do that, but the new version also breaks filling text in > John> docstrings (under particular circumstances which I haven't figured > John> out, but which occurs very frequently). I get something like: > John> "The parameter start is not the beginning of a python string". > John> Where does the latest python-mode live, and is this fill bug with > John> docstrings fixed? > > Can you file a bug report with a small failing example? Assign it to me > (montanaro). OK, will try to do tomorrow. John From claird at lairds.com Wed Jul 2 15:20:33 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 02 Jul 2003 19:20:33 -0000 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: In article , Aur?lien G?ron wrote: >> In article <87of0pno5s.fsf at titan.staselog.com>, >> Edvard Majakari wrote: >> > >> >I'm rather interested in (and fond of) unit testing as well as TDD, so I >> >though to share my opinions. I once discussed TDD with my friend in here, >> >and the common agreement seemed to be that TDD is not a silver bullet - >> >often there are types of computational modules that are very hard to unit >> >test, eg. think of graphical user interfaces or complex systems, where >> >forking or threading is concerned. >> . >> . >> . >> While we're all being rational enough to look at bundles of >> costs and benefits, this observation hints at a different >> insight: that it's possible to *design* for testability. >> >> Yes, GUIs and forking and threading are hard to test. SO >> DON'T DO THEM. Or, as I prefer, adopt models of GUI and >> concurrency development that lend themselves to testing. >> >> At this point, I should explain what I mean by that. I >> haven't yet figured out how to say it in less than a book; >> therefore, all I can contribute for today are the slogans >> above. >> >> If you're in a situation where unit-testing is bad, you're >> probably in a bad situation. Change your situation. . . . >I think I sort of understand what you mean, Cameron, but IMHO it looks to me >that you are trying to fit everything into one vision ("Everything looks >like a nail when you have a hammer"). > >There are things that are hard to unit test (I'm talking about automated >unit tests here) and which you just can't do without in some projects. For >instance, the database! I worked in a couple of projects with automatic >unit tests for the DB related components, and having lived through it, I'm >not sure that it was worth it at all! Manual unit tests would have made >much more sense. The same goes for GUIs. I'd be interested to know about >projects where they automate unit tests for GUIs, but I suspect it would be >just as cumbersome. And live without threads? A lot of projects would be >better off not using them, I agree with that, but some projects just can't >do without them! Web sites are also horrible to automatically unit test. >In all those cases, I much prefer having a human being go out and do the >unit tests manually. > >I guess my point is that though you may be right in some specific contexts, >I don't think you can generalize. That's IMHO of course. > >I may not have understood exactly what you meant, though. You may want to >send me a copy of your book? ;-) > >Aur?lien > > David Bolen answers extremely well in his follow-up. I think that, more than trying to hammer everything, I'm saying that, if hammering works for you, then make a point of building things with nails. As everyone else, I'm trying to get at "the big picture". Some organizations accept that A. TDD helps over-all business goals; B. The {GUI,concurrency,...} programming we do now is incompatible with TDD; and conclude C. we must abandon TDD. I propose instead D. Over-all business goals will be best served by a {GUI,concurrency,...} ap- proach that facilitates TDD. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From belred1 at yahoo.com Wed Jul 23 19:55:37 2003 From: belred1 at yahoo.com (Bryan) Date: Wed, 23 Jul 2003 23:55:37 GMT Subject: ndiff Message-ID: i tried using ndiff and Differ.compare today from the difflib module. i have three questions. 1. both ndiff and Differ.compare return all the lines including lines that are the same in both files, not just the diffs. is the convention to take the output and then filter out lines that contain a space as the first character to just get the diffs? it seems strange to me that the output is not just the deltas and a lot of wasted filtering (especially if the file is very large) to get the diff you wanted in the first place. isn't there a better way? 2. i also tried passing IS_LINE_JUNK and IS_CHARACTER_JUNK, but there was no difference in the output even though i changed some whitespace in the file. i then wrote my own junk functions and again, there was no difference in the output even though i returned 1 to filter out some lines. can someone show an example of using IS_LINE_JUNK and IS_CHARACTER_JUNK showing different output than when not using it. 3. is there a simple method that just returns true or false whether two files are different or not? i was hoping that ndiff/compare would return an empty list if there was no difference, but that's not the case. i ended up using a simple: if file1.read() == file2.read(): but there must be a smarter faster way. thanks, bryan From deets_noospaam at web.de Tue Jul 29 19:30:13 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2003 01:30:13 +0200 Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> <6%CVa.59$cI2.38@nwrdny01.gnilink.net> Message-ID: Raymond Hettinger wrote: >> >> In other words, the the inverse of the built-in zip function? >> > >> > When used with the * operator, zip() is its own inverse: > There is no special extension to zip(). > It just happens to be one of those functions > like int.__neg__() that is closely related to > its own inverse. > > * or apply() serve only to break a list into > individual arguments. So, transpose() can > be defined like this: I understand why it works as inverse when * creates a argument list of list element. But don't understand why * works that way in this context. Does ** do this for maps and keywordargs, too? Hey, this is python - lets try: >>> def foo(a=None, b=None): ... pass ... >>> foo(a=10, b=20) >>> foo(**{'a':10, 'b':20}) >>> Coooool. Where is that documented? Never stumbled across it so far! Diez From bbeck at NOSPAM.austin.rr.com Wed Jul 30 16:31:14 2003 From: bbeck at NOSPAM.austin.rr.com (Brandon Beck) Date: Wed, 30 Jul 2003 20:31:14 GMT Subject: Dict to "flat" list of (key,value) References: Message-ID: <1dmlv-qrq.ln1@isomorphism.org> Someone will definitely come up with a better solution than this, but this could work for you at least as a first try import types def flatten(d, iterables=(types.ListType, types.TupleType)): rv = [] for k, v in d.items(): if type(v) in iterables: rv += [[k,x] for x in v] else: rv += [[k,v]] return rv If you want to change the types of things that get iterated over, just pass in a second parameter of your own. Hope that helps, Brandon "Nicolas Girard" wrote in message news:pan.2003.07.30.19.26.18.41642 at removethis.nerim.net... > Hi, > > Forgive me if the answer is trivial, but could you tell me how to achieve > the following: > > {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] > > The subtle point (at least to me) is to "flatten" values that are lists. > > Thanks in advance, > Nicolas > > > > ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From danbmil99 at yahoo.com Sat Jul 19 20:05:28 2003 From: danbmil99 at yahoo.com (dan) Date: 19 Jul 2003 17:05:28 -0700 Subject: Calling tcl from python and viceversa References: <453d10b2.0307190828.3c576f15@posting.google.com> Message-ID: funny -- first look at the board and it's right on subject. I'm trying to write an app that does some cool stuff with sound samples, using tkSnack. But I'm stuck on a simple question -- how do I insert some of my own code into the tkInter mainloop? I need the sequencer to run in the background while the UI is up. Forgetting about snack for the moment, how do I run _any_ non-event-driven code while my Tk widgets are active? (for instance, animation in one window while menus are still available). I can't find any demos that show this sort of behavior. All the Tk examples I've seen set up the widgets and run root.mainloop(). I can't for the life of me figure out what code this call invokes, but it won't return until a quit command or some such action is initiated by the user. TCL docs say that Tk_mainloop calls tcl_DoOneEvent() in a dead loop until a quit flag is set, or something like that. My best guess is that I'm supposed to set up another thread to do my stuff, and send messages to the Tkinter thread that trigger Tk events, or something like that. But the Tkinter docs are so sketchy I can't really get a handle on how to do it. Any help or pointers would be appreciated. thanks in advance - stumped cpitaar at yahoo.com.ar (Carlos P.) wrote in message news:<453d10b2.0307190828.3c576f15 at posting.google.com>... > Hi! > I want to call tcl from python and python from tcl. The big picture is > that I?m writing an application GUI with tcl/tk and application logic > with python, so at least I want to call python events from the tk GUI. > I have read about _tkinter and tkapp.call although I couldn?t find any > detailed documentation. And, anyway, that seems to work in one > direction (python->tcl) but I don?t know how to make it work in the > other (tcl->python). > Thank you, > Carlos From bokr at oz.net Wed Jul 16 11:35:31 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 15:35:31 GMT Subject: String Manipulation References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: On 15 Jul 2003 13:23:09 -0700, lamar_air at hotmail.com (lamar_air) wrote: >I need a piece of code that takes a string like this string1 = >"aaa/bbb/ccc/dd" and extracts a string containting the character after >the last "/" > >So for this example the result would be "dd" > >like this: >for i=0; string1.right(i) != '/'; i++ > >result = string1.mid(i, string1.length()) > >but in python. Others have posted the split() solutions. You could also search backward in Python: >>> s = "aaa/bbb/ccc/dd" >>> s[s.rfind('/')+1:] 'dd' >>> s='no_slashes' >>> s[s.rfind('/')+1:] 'no_slashes' Regards, Bengt Richter From alan.gauld at btinternet.com Wed Jul 9 14:36:15 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jul 2003 18:36:15 GMT Subject: Newbie - No module named stdwin References: Message-ID: <3f0c5faf.172627925@news.blueyonder.co.uk> On Wed, 9 Jul 2003 16:20:47 +0200, "K" wrote: > inport stdwin > stdwin.open ('my window') > > and i have ImportError: No module named stdwin Stdwin is obsolete. For a very brief intro to Tkinter and wxPython visit my tutorial and look at the GUI topic (in the "Advanced" section). Then visit one of the more comprehensive tutorials linked from the Tkinter section of the Python web site. But if you are still just learning Python you might be better keeping clear of GUIs till a little later. They are just one more complication... Alan G. http://www.freenetpages.co.uk/hp/alan.gauld/ From anonymous at coolgroups.com Tue Jul 22 00:21:46 2003 From: anonymous at coolgroups.com (anonymous at coolgroups.com) Date: 22 Jul 2003 00:21:46 -0400 Subject: good python book Message-ID: <3f1cbbda_6@news.athenanews.com> i'm looking to start learning python. could someone recommend a good beginner's book for me? thanks. -------------------------------------------------------------------- For free web access to 50,000+ newsgroups, please visit http://www.coolgroups.com/. Thanks -------------------------------------------------------------------- From peter at engcorp.com Sat Jul 12 05:10:42 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Jul 2003 05:10:42 -0400 Subject: Python - if/else statements References: Message-ID: <3F0FD092.7D452008@engcorp.com> Bengt Richter wrote: > > It could. It depends. A script or a file (extension may vary, .py, .pyc, etc) that's imported > is like a big room with a single cork bulletin board. Think of that bulletin board as > the script's or module's global name space. It's where name tags can be tacked up with names > associated with objects. You can think of the objects themselves as balloons attached to > the name tags by strings (the houses have no roofs, so all the balloons occupy space > someplace high up outside ;-) > [...] > When you leave the playhouse, its inside bulletin board is cleared of name tags (and the > strings detached). When you enter again, you start with a clean inside board with only > name tags matching the formal parameter names (if any). If the last string is detached, > it is grabbed by a balloon collector, who pops it to make sure there is always space in > the sky for new balloons. Kind of ;-) Almost correct. Actually, the balloons are helium-filled and they simply float off into the sky where, after an undefined period of time, but usually instantly, they will POP and cease to exist. ;-) In Jython, the balloons don't usually POP instantly, but instead float up to the stratosphere where a garbage collection airplane flies through and explodes as many as it can find, from time to time. Even in C Python, balloons which are tied together (since balloons can actually have small bulletin board attached too) will actually float around for a while until a garbage collection airplane flies through and does its job. Unfortunately, some balloons have their own automated popping feature attached (__del__) which makes it unsafe for the plane to pop them, so it leaves those alone and it's your job to untie their strings from each other so they can pop on their own, or be popped by the GC airplane on its next pass. > But every eyelet must have a string leading to some balloon, even if it is the None balloon. Note also that the None balloon is filled with "super Helium(tm)" as it must stay aloft even with so many strings attached! No, wait, the strings are actually weightless, right? -Peter P.S.: Very cute, not to mention accurate, way to describe it, if somewhat involved. :-) From aahz at pythoncraft.com Sun Jul 6 20:20:00 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2003 20:20:00 -0400 Subject: Status of Python / Platform-specific support ?? References: Message-ID: In article , Thomas Weholt <2002 at weholt.org> wrote: > >I've been using Python on both Windows 2000 and Linux for some time >now. On Windows I've used PythonWin as editor, Emacs on Linux. This >has been working ok so far. Now as Python will be a part of Mac OS X >Panther will this affect Pythons support for platform-specific modules >in a big way? I'm not a Mac-expert, but OS X is basically a Unix-clone >as base with a Apple-GUI on top, right? So most *nix apps will compile >and run nicely on that platform? With Python as an integrated part of >the system, I'd be seriously thinking about changing platform. > >Can anyone enlighten me as to what the current status is for Python >on Mac, as for support, IDEs etc. ? Is Mac shaping up to be the best >platform for Python development and python lovers in general, or is Mac >just catching up to Linux? That's tough to answer. For starters, Python 2.2 is already part of 10.2, but it's somewhat crippled (no Tkinter, and missing the critical bugfixes of 2.2.1 and 2.2.2). Many Unix apps do compile easily, but I've had trouble with a couple that aren't part of the Fink project (xli and lrz/lsz). There are binary installers available for the Mac (see the download pages on python.org). I've been using Python on a Mac for more than a year now, because I decided to get an iBook as my laptop, but my primary system is still a Linux box, and I'm happier with that. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From gh at ghaering.de Mon Jul 14 11:06:02 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 14 Jul 2003 17:06:02 +0200 Subject: Encoding error In-Reply-To: <60CC7EB7BC00D511B0C80060083FD8F0951EA7@dunleith.igsb.uiowa.edu> References: <60CC7EB7BC00D511B0C80060083FD8F0951EA7@dunleith.igsb.uiowa.edu> Message-ID: <3F12C6DA.1000401@ghaering.de> Welcome to the Python community, But please configure your mailer to send plain text only. Casey Kohrt wrote: > I get the following error for the list item below. I know I have to > encode it, but am unsure how or where to write that in. I am new to > python and have had good luck thus far. Any help is greatly > apprecieated. I am not on the list, so a response to me is appreciated. > > UnicodeError: ASCII encoding error: ordinal not in range(128) The library you're using tries to convert a bytestring you gave it to a Unicode string. If your bytestring is plain ASCII (characters 0 to 127), this works. Outside the world of 7-bit ASCII it's not clear which code means which character, so you'll have to provide the encoding explicitly. > eainfo = doc.createElement("eainfo") > metadata.appendChild(eainfo) > overview = doc.createElement("overview") > eainfo.appendChild(overview) > eaover = doc.createElement("eaover") > text = doc.createTextNode(str(list[83])) list[83] contains non-ASCII characters. Try creating a Unicode string instead and provide an explicit encoding: text = doc.createTextNode(unicode(list[83], "iso-8859-1")) I'm just guessing about your encoding, it might be a different one. Also please next time when asking questions where you got an exception also provide at which line in your code the exception occured. > eaover.appendChild(text) > overview.appendChild(eaover) Cheers, -- Gerhard From gh at ghaering.de Wed Jul 9 17:42:12 2003 From: gh at ghaering.de (=?ISO-8859-2?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Jul 2003 23:42:12 +0200 Subject: format discs. In-Reply-To: References: Message-ID: <3F0C8C34.1050503@ghaering.de> Taka wrote: > On Wed, 09 Jul 2003 15:00:33 +0200, Gerhard H?ring wrote: >>Taka wrote: >>>#!/bin/python >>> >>>import os >>>partition = open ('/dev/hda1', 'w') >>> >>>for x in range(os.path.getsize('/dev/hda1'): >>> partition.write ('0') >>> >>>partition.close() >> [...] >>Your approach is hard to beat in inefficiency. > > Yes, but since file partitions are usualy bigger than your physical RAM, > you cannot do > > import string > partition.write (string.zfill('0', partition.getsize('/dev/hda10')-1) Certainly there are good block sizes between 1 and the size of the partion, right? In my experience, the optimum is somewhere between 2 kb and 8 kb. If I ever needed to overwrite a partition with zeros on Unix from within Python I'd most probably do something like: import os os.system("dd if=/dev/zero of=/dev/myblockdevice bs=8192") -- Gerhard From mis6 at pitt.edu Wed Jul 9 17:44:38 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 9 Jul 2003 14:44:38 -0700 Subject: A story about Python... sort of References: <3F0A0655.99823E25@alcyone.com> <87smphp2in.fsf@pobox.com> Message-ID: <2259b0e2.0307091344.73040406@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87smphp2in.fsf at pobox.com>... > [utterly OT, but couldn't resist replying again] > > Erik Max Francis writes: > > [...] > > Since it's an interpretation, though, it's just an intuitive way of > > looking at the situation. Quantum mechanical interpretations do not > > modify the theory itself; that is, they neither add nor subtract > > anything from the theory which is testable in any way. > > I disagree with all of that. Further discussion taken off-list! > > > John Why do you disagree? I would think Erik is right. BTW, speaking as a physicist, I would say that the many-worlds interpretation is absolutely minoritary in the community: If it was wideaspread, I would have studied it ;) The only thing I know is that there is no relativistic extension and this killed any further interest of mine. Michele From skip at pobox.com Thu Jul 17 15:25:23 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 17 Jul 2003 14:25:23 -0500 Subject: scrollback in macpython In-Reply-To: References: Message-ID: <16150.63523.763013.163150@montanaro.dyndns.org> Chris> Is there any way of getting scrollback to work in MacPython Chris> 2.3b2? At present, when I try and scroll back to re-issue a past Chris> command using the up arrow key, I simply get a series of "^[[A" Chris> symbols. Very annoying, Any tips most appreciated. I think Michael Hudson may have just fixed this in CVS today. If you can wait a few hours, 2.3rc1 should be out later today. Please give that a try. Skip From logistix at cathoderaymission.net Thu Jul 31 10:27:07 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 31 Jul 2003 07:27:07 -0700 Subject: Embedded python: dotted (sub) module name References: <3c91a864.0307301805.7cfea740@posting.google.com> Message-ID: <3c91a864.0307310627.3c6122c6@posting.google.com> Carl Banks wrote in message news:... > logistix at cathoderaymission.net wrote: > > I get the feeling I'm just picking the wrong google search phrase > > here, because I'm finding nothing. I'm trying to namespace out some > > embedded python modules. This works: > > > > Py_InitModule("game", py_game_methods); > > > > but this doesn't: > > > > Py_InitModule("quake.game", py_game_methods); > > > > What am I missing here? Any help would be appreciated. > > > A module's package is defined the importer, not by the module itself. > Move a module file to a different directory, and BAM, it's in a > different package. > > If your only wish is to make it so that someone can import your > extension module using "from quake import game", then it is enough to > just copy the DLL or shared lib into the proper directory. (Well, you > also have to remember to put an __init__.py file in the quake > directory.) Thanks, but I don't have a physical .pyd since this is an embedded interpreter. I'm just calling my 'init_module()' function directly from C, similar to the way array and other modules are statically added to the python dll. From ben at dadsetan.com Wed Jul 2 17:42:58 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 02 Jul 2003 22:42:58 +0100 Subject: Possible fix for Bug 494589 - os.path.expandvars bug References: <3F02015F.3000903@dadsetan.com> <3F032161.7000108@dadsetan.com> <16131.15806.215814.555138@montanaro.dyndns.org> Message-ID: <3F0351E2.2000904@dadsetan.com> Skip Montanaro wrote: > Behrang> I there a way for me to get a SSH CVS access? > Behrang> Or will someone make/submit the patch for me? > >Martin v. L?wis is making nightly snapshots of the CVS tree: > > http://mail.python.org/pipermail/python-dev/2003-June/036609.html > >With that, you could create a "good enough" context diff and submit a patch >on Sourceforge. > >Skip > Thanks Skip, already saw that trick.. but I actually first need some advice from someone whether I should just fix the Lib/dospath.py and Lib/ntpath.py with my version (to fit their actual docstring documentation and comments) or whether I should rather patch them to become just like Lib/posixpath.py so that they fit the "official" documentation (http://www.python.org/doc/current/lib/module-os.path.html) and act the same as the rest of the implementations. a)If I fix the dospath.py and ntpath.py with my version: The developpers reading the docstring/comments from the source code will be happy. Possibly update the main Library Reference documentation on that point explaining a special behaviour of these two implementations. Would have the benefit to theoricaly not break any code and instead fixing magicly some... b)If I copy posixpath.py's implementation over the dospath.py and ntpath.py implementations: The dos and nt implementations would fit the official documentation but I might break some existing code of fellow python developpers c)If I copy my implementation to all underlying platform implementations Could be possible if everyone loves the functionality promised by the dospath docstring, I would need to consult some other platform specialists to see how to adapt their code and then update the main documentation site. I guess b would be the most reasonable to do since the promises of dospath.expandvars docstring never actually delivered what it sayed they would and I feel we need a standard for os.path.expandvars behaviour with breaking the minimum of existing code. This need for advice was the other main reason I did not even risk myself to a patch. If you (knowing well better the procedures and attitudes of python implementors) still believe I would only get advice submitting patches, do you think it is alright submitting two/three different ones? I actually hoped we could first discuss what we want to do. Also the reason why I wrote that I was awaited the BDFL to pronounce a decision. What would be the procedure to get him taking a decision on this? Do I need someone to bring up the question in python-dev? (my mail last week to python-dev got ignored or automaticly classified as spam... not sure ;-) ) Ben. From skip at pobox.com Sat Jul 26 02:25:45 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 26 Jul 2003 01:25:45 -0500 Subject: where is the awk to python translator program In-Reply-To: <87smounf2z.fsf@jidanni.org> References: <87smounf2z.fsf@jidanni.org> Message-ID: <16162.7913.4933.133368@montanaro.dyndns.org> Dan> An old dog can't learn new tricks, so where's the a2py awk to python Dan> translator? Perl has a2p. Sorry, Python doesn't have such a beast. There's never been enough demand. Dan> E.g. today I wonder how to do '{print $1}', well with a2p I know Dan> how to do it in perl, but with python I am supposed to hunker down Dan> with the manuals. Python doesn't have the implicit looping and splitting into fields that awk has, so you need to loop over the input and split the fields yourself: import sys for line in sys.stdin: print line.split()[0] # == '{print $1}' There's also no global field separator variable. Suppose I wanted to print the first field in each row of my passwd file. The split() method, when called as above with no arguments, will split the string on any runs of whitespace. If given a string parameter it will split the string on that string. Here's some input and output pasted from an interactive session: >>> for line in file("/etc/passwd"): ... print line.split(":")[0] ... root bin daemon adm lp ... and so on ... Obviously, Python is not as concise as awk for the sorts of things awk is good at, but then Python is good for a lot more things than awk is. ;-) Skip From essai1 at mci.local Mon Jul 7 07:54:47 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Mon, 7 Jul 2003 13:54:47 +0200 Subject: Python vs PHP References: Message-ID: Hi ! PHP-5 let down MySql, for Sql-Lite (rumor ?) Python has good support for MySql AND Sql-Lite. @+ Michel Claveau From harry.g.george at boeing.com Thu Jul 10 13:23:54 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 10 Jul 2003 17:23:54 GMT Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> Message-ID: Peter Hansen writes: > Jon Schull wrote: > > > > PyDoc's author Ka-Ping Yee has suggested that PyDoc be patched to > > prevent access from unauthorized IP addresses > > (https://sourceforge.net/tracker/?func=detail&atid=305470&aid=672656&group_id=5470), > > and that without such a patch, its not " suitable for running on boxes > > that aren't behind firewalls" > > > > It's hard to know how much to worry about such things (Comments?). > > > > However, even with the patch, IP addresses can be spoofed. Here is an > > additional security tactic that might be adopted. > > > > The port number used by pydoc is currently set by the user at the > > command line. Many people probably use the example given in the > > python module documentation : "python -p 1234" However, if the port > > were chosen at random and printed out, then only pydoc and the user > > would know how to access the pydoc server. > > > > I'm considering a similar strategy for a server based on the > > CGIHTTPServer module, so comments would be welcome. > > My suggestion: don't attempt to mix security into each individual > application in a piecemeal manner. Use the proper tools for the > job, such as firewalls. Setting up a firewall on Linux or WinXP > is nearly trivial at this point, and the learning experience is > worth the effort for those who are new to this, so there's not > much excuse for doing it properly, IMHO. > Here, we have lots of COTS *NIX behind the corporate firewalls, and want to provide internal security. We do this with SSL'd communications. I can see how a firewall denies/allows specific IP addresses (or at least claimed IP addresses), but not how it solves sniffing, spoofing, man-in-the-middle, etc., where encryption protocols are needed. > -Peter -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From m at moshez.org Mon Jul 7 06:47:47 2003 From: m at moshez.org (Moshe Zadka) Date: 7 Jul 2003 10:47:47 -0000 Subject: anything new on the ternary operator? In-Reply-To: <3F09252F.9B0F52BD@alcyone.com> References: <3F09252F.9B0F52BD@alcyone.com>, Message-ID: <20030707104747.14886.qmail@green.zadka.com> On Mon, 07 Jul 2003, Erik Max Francis wrote: > Bob's phrasing of it was obviously overly confrontational, but I do find > it at least a little unfortunate that the final decision on PEP 308 only > came indirectly (meaning not as any form of widespread public > announcement, but rather as a side point in a presentation at a local > conference) I'm sorry, I was going to let this slide by, but this comment made it impossible. How the hell do you figure EuroPython, the biggest Python conference in Europe and largely equivalent to the size of PyCon, is a "local" conference? By and large, I think EuroPython holds half the heritage of the venerable IPCs, being way more international than PyCon. Announcements of new developments are often done at conferences, especially the larger ones. It has been said multiple times that Guido is likely to make an announcement in EuroPython, and it was pretty easy to get the answer out on c.l.py soon afterwards. While the PEP will eventually be updated, I am glad Guido thought it was a higher priority to get 2.3b2 out the door in the little time he had between EP and OSCON. > There isn't a problem that PEPs and such voting processes are worthless > -- obviously the BDFL has the final say -- but perhaps it would have > been a little nicer to get an official position on the subject earlier. Guido said that he wanted to let the discussion simmer down before he made an official pronouncement. He also *did* consider the vote: if you remember, there were a few interpretations. Guido chose the one who enforced Condorset(sp?) semantics on the results, an arguably sane position considering other free software projects use this voting method. According to this interpretation, the vote resulted in "don't change". -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From hwlgw at hotmail.com Fri Jul 11 18:24:58 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 11 Jul 2003 15:24:58 -0700 Subject: XML, xmlproc, MathML and validation References: <3F0EC38B.EBDE74E@hotmail.com> Message-ID: > [Alan Kennedy ] > ...For example, the > public identifier "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" could be > mapped to a local file. An example how to do that would be very welcome! > So you should be able to map DTD identifiers to your local system for > the times when a remote DTD is not available. More info from here > > http://www.garshol.priv.no/download/software/xmlproc/catalog-doco.html Okay, then I will try to find the example there. > Have you supplied a value for the "xml:space" attribute anywhere in > your document? No of course not: as you can see from my stupid questions I am a total XML newbie :-) > If no: I'm not familiar enough with the MathML DTD to know if it has > special requirements for whitespace processing. > > Looking at your error message, and the DTD, might it be that you have > used a value other than "xml:space='preserve'" on a
 section?
> Just a guess.

So what you are saying points to the MathML DTD having peculiar
whitespace handling?  Would not be the first example of a weird
standard.
Thank you.


-- 
Being in the army is like being in the Boy Scouts, except that the Boy
Scouts have adult supervision.
                -- Blake Clark



From glenfant at NOSPAM.bigfoot.com  Tue Jul 22 08:06:10 2003
From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant)
Date: Tue, 22 Jul 2003 14:06:10 +0200
Subject: Pause in a loop
References: <%W7Ta.10360$t92.299097@news1.tin.it>
Message-ID: 

"manuel"  a ?crit dans le message de news:
%W7Ta.10360$t92.299097 at news1.tin.it...
>
> I've two modules: main.py and eval.py
>
> Eval.py is imported in main.py, but I've a loop
> in eval.py that must call a function in main.py...
>
> I can't import main.py in eval.py too, because
> that would create an import loop.
>
> But I'm thinking a different solution:
> a pause in a loop to return periodically an
> output. It's possible?
>
>
> thanks,
>
>           Manuel
>
>

Send that function to the eval as parameter...


...
import eval

def myfunc(...)
  ...
def main():
    ...
   eval.eval(x, y, z, myfunc)
...



...
def eval(x, y, z, afunc):
     ...
    afunc(...)
    ....
    return stuff
...





From stuart_clemons at us.ibm.com  Sun Jul 13 18:30:58 2003
From: stuart_clemons at us.ibm.com (stuartc)
Date: 13 Jul 2003 15:30:58 -0700
Subject: Newbie with sort text file question
References: <86d2ca4.0307121146.3deb854a@posting.google.com> 
Message-ID: <86d2ca4.0307131344.3fb3b9d3@posting.google.com>

Hi Bengt:

Thank you. Your code worked perfectly based on the text file I
provided.

Unfortunately for me, my real text file has one slight variation that
I did not account for.  That is, the fruit name does not always have
an "_" after its name.  For example, apple below does not an an "_"
attached to it.

banana_c \\yellow
apple   \\green
orange_b \\yellow


This variation in my text file caused a problem with the program.
Here's the error.

Traceback (most recent call last):
  File "G:/Python22/Sort_Fruit.py", line 47, in ?
    for fruit, dummyvar in fruitlist: fruitfreq[fruit] =
fruitfreq.get(fruit, 0)+1
ValueError: unpack list of wrong size

I tried to debug and fix this variation, but I wasn't able to.  I did
notice that your split, splits each line in the file into two fields,
as long as there's an "_" with a fruit name.  If the fruit name does
not have an "_", then the split does not occur. I think this is
related to the problem, but I couldn't figure out how to fix it.

Any help will be greatly appreciated. Thanks.

- Stuart



bokr at oz.net (Bengt Richter) wrote in message news:...
> On 12 Jul 2003 12:46:51 -0700, stuart_clemons at us.ibm.com (stuartc) wrote:
> 
> >Hi:
> >
> >I'm not a total newbie, but I'm pretty green.  I need to sort a text
> >file and then get a total for the number of occurances for a part of
> >the string. Hopefully, this will explain it better:
> >
> >Here's the text file: 
> >
> >banana_c \\yellow
> >apple_a \\green
> >orange_b \\yellow
> >banana_d \\green
> >orange_a \\orange
> >apple_w \\yellow
> >banana_e \\green
> >orange_x \\yellow
> >orange_y \\orange
> >
> >I would like two output files:
> >
> >1) Sorted like this, by the fruit name (the name before the dash)
> >
> >apple_a \\green
> >apple_w \\yellow
> >banana_c \\yellow
> >banana_d \\green
> >banana_e \\green
> >orange_a \\orange
> >orange_b \\yellow
> >orange_x \\yellow
> >orange_y \\orange
> >
> >2) Then summarized like this, ordered with the highest occurances
> >first:
> >
> >orange occurs 4
> >banana occurs 3
> >apple occurs 2
> >
> >Total occurances is 9
> >
> >Thanks for any help !
> 
> ===< stuartc.py >========================================================
> import StringIO
> textf = StringIO.StringIO(r"""
> banana_c \\yellow
> apple_a \\green
> orange_b \\yellow
> banana_d \\green
> orange_a \\orange
> apple_w \\yellow
> banana_e \\green
> orange_x \\yellow
> orange_y \\orange
> """)
> 
> # I would like two output files:
> # (actually two files ?? Ok)
> 
> # 1) Sorted like this, by the fruit name (the name before the dash)
> 
> fruitlist = [line.split('_',1) for line in textf if line.strip()]
> fruitlist.sort()
> 
> # apple_a \\green
> # apple_w \\yellow
> # banana_c \\yellow
> # banana_d \\green
> # banana_e \\green
> # orange_a \\orange
> # orange_b \\yellow
> # orange_x \\yellow
> # orange_y \\orange
> 
> outfile_1 = StringIO.StringIO()
> outfile_1.write(''.join(['_'.join(pair) for pair in fruitlist]))
> 
> # 2) Then summarized like this, ordered with the highest occurances
> # first:
> 
> # orange occurs 4
> # banana occurs 3
> # apple occurs 2
> 
> outfile_2 = StringIO.StringIO()
> fruitfreq = {}
> for fruit, dummyvar in fruitlist: fruitfreq[fruit] = fruitfreq.get(fruit, 0)+1
> fruitfreqlist = [(occ,name) for name,occ in fruitfreq.items()]
> fruitfreqlist.sort()
> fruitfreqlist.reverse()
> outfile_2.write('\n'.join(['%s occurs %s'%(name,occ) for occ,name in fruitfreqlist]+['']))
> 
> # Total occurances is 9
> print >> outfile_2,"Total occurances [sic] is [sic] %s" % reduce(int.__add__, fruitfreq.values())
> 
> ## show results
> print '\nFile 1:\n------------\n%s------------' % outfile_1.getvalue()
> print '\nFile 2:\n------------\n%s------------' % outfile_2.getvalue()
> =========================================================================
> executed:
> 
> [15:52] C:\pywk\clp>stuartc.py
> 
> File 1:
> ------------
> apple_a \\green
> apple_w \\yellow
> banana_c \\yellow
> banana_d \\green
> banana_e \\green
> orange_a \\orange
> orange_b \\yellow
> orange_x \\yellow
> orange_y \\orange
> ------------
> 
> File 2:
> ------------
> orange occurs 4
> banana occurs 3
> apple occurs 2
> Total occurances [sic] is [sic] 9
> ------------
> 
> Is that what you wanted?
> 
> Regards,
> Bengt Richter



From sjmachin at lexicon.net  Sun Jul 20 09:47:52 2003
From: sjmachin at lexicon.net (John Machin)
Date: 20 Jul 2003 06:47:52 -0700
Subject: Strings and Unicode
References: 
Message-ID: 

madsurfer2000 at hotmail.com (-) wrote in message news:...
> I have a function that takes a string as an input parameter. This
> function then urlencodes the string and sends it to a server with
> telnetlib.Telnet
> 
> The problem is that the string gets converted into what seems to be
> Unicode. How can I check to see if the input-string is Unicode and
> convert it to a different character set (in this case ISO-Latin1).

You don't/can't urlencode a string. You urlencode a bunch of
(key,value) strings which are represented as "a mapping object or a
sequence of two-element tuples" so sayeth the documentation. See
below. Passing a string attracts a TypeError. See below. If you
provide a simple example of what you are doing, plus the output that
"seems to be Unicode", plus of course the input that cause the strange
output, we may be able to help you further.

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
win32
>>> import urllib
>>> foo = urllib.urlencode({'foo':42,'bar':69})
>>> type(foo)

>>> foo
'foo=42&bar=69'
>>> foo = urllib.urlencode('abcdef')
Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\python22\lib\urllib.py", line 1171, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object
>>>



From davidcfox at post.harvard.edu  Tue Jul 22 00:00:35 2003
From: davidcfox at post.harvard.edu (David C. Fox)
Date: Tue, 22 Jul 2003 04:00:35 GMT
Subject: detecting containers during object introspection
In-Reply-To: 
References:  
Message-ID: 

Steven Taschuk wrote:

> Quoth David C. Fox:
> 
>>Is there a reasonable way to tell whether a variable is a container 
>>(either a mapping or a sequence) and whether it is a mapping or a 
>>sequence?  [...]
> 
> 
> Depends what you mean by "reasonable".
> 
> In the usual scenario, there's a specific facility which you want
> to make use of, and you can either (a) just try to use it, and
> catch the relevant exception (called Easier to Ask Forgiveness
> than Permission, or EAFP), or (b) do some kind of check beforehand
> for whether the facility exists (called Look Before You Leap, or
> LBYL).
> 
> Your example of trying iter(foo) and catching the possible
> TypeError fits into such approaches.
> 
>   [...]
> 
>>Wouldn't it be helpful to have an abstract base class Sequence which 
>>didn't add any actual attributes or methods, but which someone writing a 
>>sequence class could include as a base class, as a sort of unenforced 
>>promise that the sequence operators were supported?
> 
> 
> Consider a DNS name -> address mapping whose __getitem__ actually
> queries the DNS.  (Ignore the fact that this could be better done
> with a function -- assume we have a function which expects a
> dict-like object and we want to use it on the DNS.)  Such an
> object could not reasonably implement __len__.  Should it falsely
> imply that it does (by inheriting from an abstract class Mapping)
> or falsely imply that it's not a mapping (by not inheriting from
> Mapping)?
> 
> Such cases -- those in which for conceptual or pragmatic reasons
> it is infeasible or undesirable to implement all of an interface
> -- are not uncommon.

Thanks, makes sense - I'll just try...catch the actual operations I use.

>>Why am I asking this question?
>>
>>I'm trying to write a regression test for a class which pickles 
>>dictionaries of attributes to store and retrieve instances.  The 
>>dictionary includes a version number, and the class has a system for 
>>updating out-of-date instances to the current version.
>>
>>As part of the test, I need to be able to compare the structure of the 
>>two dictionaries to see if the developer has modified their structure 
>>but forgotten to increment the current version.  Values in the 
>>dictionary may be unknown objects, in which case I just want to compare 
>>their types.  However, the values may also be sequences or mappings 
>>themselves, in which case I want to recursively compare their 
>>elements/values.
> 
> 
> Interesting.  So you have an example of a standard dictionary for
> a given version number, and you want to compare the structure of
> the actual dictionary to the standard example dictionary.  Is that
> right?

Yes.  The particular scenario I'm most worried about is if a developer 
makes a change to the structure of the dictionary, but fails to 
increment the current version number.  In that case, users with existing 
stored dictionaries who update to a new version of the program will end 
up with incorrectly constructed objects, and are likely to have all 
sorts of strange and hard-to-debug problems.

> Are your developers actually using dict-like and list-like objects
> instead of real dicts and lists?  If not, isn't the type-check for
> unknown objects enough?  (If they do start using work-alikes
> instead of the real thing, the test will fail, but YAGNI, right?

Yes to the first*, but yes and good points to the second and third.

[*well, not exactly - I recently replaced a dictionary with a trie data 
structure which effectively maps from sequences of strings to values, 
but it doesn't currently use keys() or __getitem__(self, key).]

However, the real problem occurs if the developer makes a change like 
this (or even just adds a new attribute which is a non-standard 
container), and does increment the version number.  Because the version 
number was incremented, the regression test would *expect* some of the 
dictionary elements to change type or structure, and would simply update 
the standard example dictionary.  Then, any *subsequent* changes to the 
structure of the values in that container would go undetected (unless 
the developer had also updated the recursive comparison operation to 
take into account that the unknown object was a container).

But this scenario requires several mistakes, so YAGNI is probably still 
good advice.  Besides, since there isn't any way to detect containers 
that don't use the standard methods, I guess the automated regression 
testing approach will never be foolproof, and we'll have to fall back on:

(1) giving stern instructions (and good documentation) to our 
developers, and

(2) making sure a developer who is aware of these issues looks over 
their shoulders and their code.  Yet another responsibility - just what 
I need.  Not to mention the sore neck I'm going to get looking over my 
own shoulder ;-)

David




From adechert at earthlink.net  Mon Jul 21 19:04:47 2003
From: adechert at earthlink.net (Alan Dechert)
Date: Mon, 21 Jul 2003 23:04:47 GMT
Subject: Voting Project Needs Python People
References:    
Message-ID: 

"Harry George"  wrote in message
news:xqx7k6b36r8.fsf at cola2.ca.boeing.com...
>
> Here is a possible scenario:
>
> 1. Software chooses 1% of votes to change (big enough to have an
>    effect, small enough to maybe go unnoticed).
>
I don't think this is a possible scenario.  However, it brings up an
interesting test for our full blown study (keep in mind, we're trying to
focus on getting the demo done even though people want to jump ahead to
speculate on every possible detail).

The question you raise here has to do with the chance of x% votes being
recorded differently on paper without y number of voters noticing.  I think
it would also depend on the contest that was changed.  That is, it's
probably more likely that the voter would remember his or her choice for
president than, say, county supervisor.  This also points out some
difficulty with trying to test this with a mock election.  The voter may not
take the selections serious enough to care about remembering exactly how
they voted.

But taking your number, if you changed 1% of the votes in CA, you're talking
about on the order of 100,000 ballots (assuming you're talking about
changing only one contest... if you're talking about all the votes cast on
all races, then that's going to mean many times more ballots altered --
probably over one million).  I think it's likely that some sizable fraction
*would* notice (again, depending somewhat on the contest).  Say it's only
one tenth.  That's 10,000 voters that will be complaining that the computer
changed the vote.  That many complaints would set off fire alarms big time.

> 2. Paper is correct.  Visual monitor is correct.  Electronic storage
>    is changed.  Voter leaves happy.
>
Okay, but now the electronic record doesn't match.  With our system, the
paper is the authentic vote.  There is no crisis because the paper ballots
are available for recount.

> 3. Results are posted based on electronic storage.
>
But it will be caught.  There will be checks in place (in CA we already hand
verify 1% of the ballots at random after the election).  And with
standardized laser printed output, automated scanning should be much faster
and more accurate than scanning hand marked ballots.  Depending on how
elections are administered with this new equipment, it might be possible for
initial results to be posted incorrectly, but virtually impossible that the
tally would stand unchallenged.  A guard against inital bad results would
entail some sampling before the results are announced. We can use some
statistics -- cumulative binomial distribution -- to get a pretty good
confidence level of correctness with a small sample.

> 4. Only if enough people suspect trouble do we go to the paper trail.
>    At 1%, that may not happen.  Yet a 2% swing is pretty big in many
>    settings.
>
I don't think your arguement is very substantial, but certainly these are
some issues a large scale study of new voting technology should investigate.

Still, has nothing to do with the demo I am talking about.

Alan Dechert





From martin at v.loewis.de  Wed Jul  9 01:34:35 2003
From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=)
Date: 09 Jul 2003 07:34:35 +0200
Subject: Possible to install from CD using distutils?
References: 
Message-ID: 

bobsmith327 at hotmail.com (Bob Smith) writes:

> Hi.  I'm trying to distribute a Python package on a CD-ROM that gets
> installed using distutils.  The problem is that distutils attempts to
> write a new 'build' folder on the CD during the installation and fails
> (it of course can't write the to CD).  

You can use the --build-base option to change that directory.

Regards,
Martin



From ruach at chpc.utah.edu  Tue Jul 29 11:02:37 2003
From: ruach at chpc.utah.edu (Matthew)
Date: 29 Jul 2003 08:02:37 -0700
Subject: octet string conversion
References: 
Message-ID: 

Thats great! I really appreciate the help. The F and spaces and ] etc,
are not typos they real output via pysnmp.I used Erik Max Francis'
code and it did exactly  what I needed. Thank you all for
contributing.

-matthew



From mynews44 at yahoo.com  Tue Jul 29 04:01:03 2003
From: mynews44 at yahoo.com (google account)
Date: 29 Jul 2003 01:01:03 -0700
Subject: newbie needs a little help... trying to write an ftp script.
References:  
Message-ID: 

Diez wrote:
> Googleboy wrote:
> > import ftplib
> > 
> > ftp = ftplib.FTP('172.30.30.30')  # This is wrong,  somehow...?
> > ftp.login(user,pass)
> > ftp.retrlines('LIST')  # I believe it might need to be
> > ftp.retrlines('ls -al')
> > ftp.sendcmd('prompt')
> > ftp.cwd('folder')
> > ftp.retrbinary(retr *tgz)
> > ftp.quit()

> Your example worked fine with me for "ftp.suse.com" - at least the first 3
> lines. It didn't understand ls -al and prompt, and a folder "folder" didn't
> exist of course.

A bit of further reading pointed out to me that sendcmd is limited to
rfc959 commands only,  it doens't interpret commands you can type into
an ftp session as I first assumed.  So things like "prompt' (which
turns interactive mode off in ftp clients) won't work.

This introduces extra complexity to my task - I am trying to log into
an ftp site and do a "mget *tgz" and have it download all files ending
in tgz.  I don't think this is a simple thing to accomplish anymore.
 
> The ftp.retrbinary(retr *tgz) is also flawed - what is retr, a variable? I
> think you need to look up that command again. And *tgz can't be right, too.
> You most probably want "*tgz" there (a string literal)

I think I wanted the whole thing to be a string literal.  I have done
a bit more poking and prodding and found that

ftp.retrlines('RETR file')

will work,  so long as file is a text document,  so it can spit the
output to standard out.

retrlines/retrbinary has this thing called a callback.  I am expecting
that is something that allows the script to write the file.  I also
imagine that it will only allow me to have one open callback at a
time.  This further complicates achieving my objectives.

I think I am going to have to figure out some sort of a for loop based
on the output of a list command.

thanks for the help diez.

googleboy.



From mis6 at pitt.edu  Tue Jul 22 22:11:23 2003
From: mis6 at pitt.edu (Michele Simionato)
Date: 22 Jul 2003 19:11:23 -0700
Subject: feature request: a better str.endswith
References: <2259b0e2.0307180401.5dae02f2@posting.google.com>  <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com>  <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> 
Message-ID: <2259b0e2.0307221610.3cc91757@posting.google.com>

bokr at oz.net (Bengt Richter) wrote in message news:...
> I think I'd prefer
> 
>   if any_true(filename.endswith, ('.jpg','.jpeg','.gif','.png')):
>      dosomething()
> 
> I suspect it will more often make sense read aloud in the general
> 
>   if any_true(pred, seq):
> 
> than
> 
>   if the(pred, seq)
> 
> I guess the full set of functions might be
> any_true, any_false, all_true, and all_false.
> 
> or maybe someone can think of better short phrase?
> 
> Regards,
> Bengt Richter

I think in the specific case I was talking about "the" was quite
readable; however I agree that in the general case "any_true" etc.
would be better.
I would not be opposed to add these convenience functions in
itertools. The
advantage is standardization (i.e. I don't have to invent my own name,
different from the name chosen by anybody else), the disadvantage is 
more things to learn; however, with such descriptive names, it would
be
difficult to not grasp what those functions are doing, even without
looking at the documentation. Anyway, I am sure many will be opposed, 
saying that such functions are so simple that they do not deserve to
be
in the library. This would be a sensible opinion, BTW.


          Michele



From theller at python.net  Mon Jul 14 14:05:24 2003
From: theller at python.net (Thomas Heller)
Date: Mon, 14 Jul 2003 20:05:24 +0200
Subject: A few beginning questions
References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com>
Message-ID: 

mis6 at pitt.edu (Michele Simionato) writes:

> "richardc"  wrote in message news:<3f129a8a$1 at mail.hmgcc.gov.uk>...
>> Ive just started playing with Python and have a couple of questions.
>> 
>> Im looking for an agument parsing library (from the command line), Ive come
>> across optik and argtools.  What other ones are there are any of them any
>> good, is there a 'standard' lib for doing this.
>>
>
> optparse (a.k.a. optik) is great, whereas I never made my mind up to
> getopt. To "cure" getopt, I needed to define my own routines for
> argument parsing; after I started using optparse I had the satisfaction
> of erasing all of them ;)

I have not yet tried optparse. Is it able to parse Windows' style
command lines (use '/' instead of '-', ignore case of command line
options, use long options with a single '-' or '/')?

Thomas



From justinjohnson at fastmail.fm  Tue Jul  8 17:08:29 2003
From: justinjohnson at fastmail.fm (Justin Johnson)
Date: Tue, 08 Jul 2003 15:08:29 -0600
Subject: process.py problems
In-Reply-To: <20030708094057.C9520@ActiveState.com>
References: <20030708153117.127C0326C0@www.fastmail.fm> <20030708094057.C9520@ActiveState.com>
Message-ID: <20030708210829.B3BBE3886D@www.fastmail.fm>

Thanks for the reply!

which 1.0.2

Here's the log output with the dir command
-----------------------
process.res: info:[18392288] ProcessOpen._start(): create child stdin:
<_FileWra
pper: file:None fd:3 os_handle:>
process.res: info:[18392288] ProcessOpen._start(): create child stdout:
<_FileWr
apper: file:None fd:4 os_handle:>
process.res: info:[18392288] ProcessOpen._start(): create child stderr:
<_FileWr
apper: file:None fd:5 os_handle:>
process.res: info:[18392288] ProcessOpen.__del__()
process: info:[18392288] ProcessOpen.close()
process: info:[18392288] ProcessOpen: closing stdin (<_FileWrapper:
file:None fd
:3 os_handle:>).
process: debug:[18400496] _FileWrapper.close()
process: debug:[18400496] _FileWrapper.close: close handle
process: debug:[18400496] _FileWrapper.close: closing handle raised
process: debug:[18400496] _FileWrapper.close: done closing handle
process: info:[18392288] ProcessOpen: closing stdout (<_FileWrapper:
file:None f
d:4 os_handle:>).
process: debug:[18400720] _FileWrapper.close()
process: debug:[18400720] _FileWrapper.close: close handle
process: debug:[18400720] _FileWrapper.close: closing handle raised
process: debug:[18400720] _FileWrapper.close: done closing handle
process: info:[18392288] ProcessOpen: closing stderr (<_FileWrapper:
file:None f
d:5 os_handle:>).
process: debug:[18403024] _FileWrapper.close()
process: debug:[18403024] _FileWrapper.close: close handle
process: debug:[18403024] _FileWrapper.close: closing handle raised
process: debug:[18403024] _FileWrapper.close: done closing handle
process: debug:[18400720] _FileWrapper.close()
process: debug:[18400496] _FileWrapper.close()
process: debug:[18403024] _FileWrapper.close()
----------------

I also get the following results running commands that are in my path...
------------------
g`"apper: file:None fd:5 os_handle:>
process: debug:_SaferCreateProcess(appName=None,
                    cmd='C lsview -s',
                    env=None,
                    cwd=None)
    os.getcwd(): 'E:\\ccase\\python\\uhg\\uht'

process.res: info:[18680944] ProcessOpen.__del__()
process: info:[18680944] ProcessOpen.close()
process: info:[18680944] ProcessOpen: closing stdin (<_FileWrapper:
file:None fd
:3 os_handle:>).
process: debug:[18696880] _FileWrapper.close()
process: debug:[18696880] _FileWrapper.close: close handle
process: debug:[18696880] _FileWrapper.close: closing handle raised
process: debug:[18696880] _FileWrapper.close: done closing handle
process: info:[18680944] ProcessOpen: closing stdout (<_FileWrapper:
file:None f
d:4 os_handle:>).
process: debug:[18696832] _FileWrapper.close()
process: debug:[18696832] _FileWrapper.close: close handle
process: debug:[18696832] _FileWrapper.close: closing handle raised
process: debug:[18696832] _FileWrapper.close: done closing handle
process: info:[18680944] ProcessOpen: closing stderr (<_FileWrapper:
file:None f
d:5 os_handle:>).
process: debug:[18699984] _FileWrapper.close()
process: debug:[18699984] _FileWrapper.close: close handle
process: debug:[18699984] _FileWrapper.close: closing handle raised
process: debug:[18699984] _FileWrapper.close: done closing handle
process: debug:[18696832] _FileWrapper.close()
process: debug:[18696880] _FileWrapper.close()
process: debug:[18699984] _FileWrapper.close()
---------


On Tue, 8 Jul 2003 09:40:57 -0700, "Trent Mick" 
said:
> 
> Justin,
> 
> Can you try turning logging on in process.py to perhaps get a better
> picture of what it is trying to do. Look for the "internal logging"
> section. There should be some "if 0"s that you can turn to "if 1"s for
> debugging. (Or vice versa -- my process.py version is a little bit
> different than the public one.)
> 
> My guess: process.py, in some cases, will try to run command via the
> local shell (i.e. cmd.exe or command.com on Windows). This is necessary
> for some commands like "dir" which are not executables themselves but
> just a part of the shell. However, process.py is not as clean as it
> should be on when it does and when it does not use the shell. Perhaps
> process.py is not using the shell when it should here.
> 
> ... note, there may also be a problem with respect to which.py and
> process.py version mismatch. which.py 1.x changed its API from which.py
> 0.x and process.py may not be dealing with that correctly. I may need to
> put up a new process.py to get that right. What is the output of:
>     which --version
> or:
>     >>> import which
>     >>> which._version_
> 
> Cheers,
> Trent
> 
> [Justin Johnson wrote]
> > Hello,
> > 
> > I was wondering if anyone has seen this behavior before for the
> > process.py
> > module available at http://starship.python.net/crew/tmick/.  I've been
> > using it quite well on windows 2000 servers, but when I try to use it on
> > a window nt 4.0 box I get the results posted below.  I have both
> > process.py and which.py installed.
> > 
> > Any help you can provide is greatly appreciated.
> > 
> > >>> import process
> > >>> p = process.ProcessOpen("dir")
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "process.py", line 1108, in __init__
> >     self._startOnWindows()
> >   File "process.py", line 1279, in _startOnWindows
> >     cmd = _fixupCommand(cmd, self._env)
> >   File "process.py", line 506, in _fixupCommand
> >     cmd = _whichFirstArg(cmd, env)
> >   File "process.py", line 315, in _whichFirstArg
> >     candidates = list(which.which(first))
> >   File "which.py", line 251, in which
> >     raise WhichError("Could not find '%s' on the path." % command)
> > which.WhichError: Could not find 'dir' on the path.
> > >>> p = process.ProcessOpen("dir.exe")
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "process.py", line 1108, in __init__
> >     self._startOnWindows()
> >   File "process.py", line 1279, in _startOnWindows
> >     cmd = _fixupCommand(cmd, self._env)
> >   File "process.py", line 506, in _fixupCommand
> >     cmd = _whichFirstArg(cmd, env)
> >   File "process.py", line 315, in _whichFirstArg
> >     candidates = list(which.which(first))
> >   File "which.py", line 251, in which
> >     raise WhichError("Could not find '%s' on the path." % command)
> > which.WhichError: Could not find 'dir.exe' on the path.
> > >>> p = process.ProcessOpen("cmd")
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "process.py", line 1108, in __init__
> >     self._startOnWindows()
> >   File "process.py", line 1295, in _startOnWindows
> >     raise ProcessError(msg=ex.args[2], errno=ex.args[0])
> > process.ProcessError: The system cannot find the file specified.
> > >>> 
> > 
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list
> 
> -- 
> Trent Mick
> TrentM at ActiveState.com
> 




From bignose-hates-spam at and-zip-does-too.com.au  Sun Jul 13 22:56:29 2003
From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney)
Date: 14 Jul 2003 12:46:29 +0950
Subject: How to crash Python in 1 easy step (python 2.2.2)
References: <2e363c08.0307130944.4c470bc3@posting.google.com>
Message-ID: 

On 13 Jul 2003 10:44:41 -0700, Paul Miller wrote:
> Anytime python is accepting keyboard input, whether it's with
> raw_input, or sitting on the command line waiting for the user to type
> code, you can crash python by holding ctrl+shift and then pressing
> enter.

Is this in an xterm, in some other terminal emulator, in a console
session?  I'm guessing you'll see different behaviour if you try all
three of those, which will help narrow down the problem.

Not that a segfault (assuming that's what you mean by "crash") isn't a
bug -- any event that doesn't make the system hardware unreliable should
be handled without a segfault.

-- 
 \          "One time a cop pulled me over for running a stop sign. He |
  `\        said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__)             don't believe everything I read.'"  -- Steven Wright |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B



From max at alcyone.com  Wed Jul  2 19:51:49 2003
From: max at alcyone.com (Erik Max Francis)
Date: Wed, 02 Jul 2003 16:51:49 -0700
Subject: python 2.3b[12]
References: 
Message-ID: <3F037015.3D6D7034@alcyone.com>

Dave Reed wrote:

> ./python
> Python 2.3b1 (#1, Jun 14 2003, 15:08:24)
> [GCC 3.2.3] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
> 
> I thought maybe this was just someone forgetting to update the startup
> message for the new beta, but I've seen other messages that show
> Python 2.3b2.
> 
> Any ideas on what happened?

Hmm, mine doesn't (built from scratch on Linux):

max at oxygen:~% python2.3
Python 2.3b2 (#1, Jun 29 2003, 20:30:58) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Are you sure you're running the version you think you are?

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Love is the true price of love.
\__/  George Herbert



From heikowu at ceosg.de  Wed Jul 16 21:54:58 2003
From: heikowu at ceosg.de (Heiko Wundram)
Date: 17 Jul 2003 03:54:58 +0200
Subject: anything like C++ references?
In-Reply-To: 
References: 
	 <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com>
	 
	 
Message-ID: <1058406898.593.2.camel@d168.stw.stud.uni-saarland.de>

On Wed, 2003-07-16 at 22:02, Stephen Horne wrote:
> The pointer thing was raised in the context of a larger discussion. It
> *would* be necessary if another change was made (don't worry, it won't
> happen).

I know the broader discussion context, but if changes like those (e.g.
copy on write) were to happen at some further point in time, that would
definitely be the moment for me to stop using Python, and switch to
Ruby.

Python's data model is good as it is, I don't really see the need to add
more to it. We've gone a long way with type-class unification, and I
guess there won't be much more need to change for very long...

Heiko.





From jimmy at retzlaff.com  Thu Jul 10 20:36:10 2003
From: jimmy at retzlaff.com (Jimmy Retzlaff)
Date: Thu, 10 Jul 2003 17:36:10 -0700
Subject: Embedding Python, threading and scalability
Message-ID: 

Aahz (aahz at pythoncraft.com) wrote:
>Wenning Qiu  wrote:
>>
>>Has anyone on this list run into the same problem that I have, or does
>>anyone know of any plan of totally insulating multiple embedded Python
>>interpreters?
>
>Sure!  Use multiple processes.

This can have further scalability benefits. The first time I ran up
against the GIL, I grumbled my way through tweaking my code to use
multiple processes and an IPC mechanism (which was surprisingly easy).
After I finished, I realized that nothing about the IPC mechanism I
happened to choose limited my solution to one machine and suddenly my
app was running on 7 CPUs instead of the 2 CPUs I had originally hoped
for. On just 2 CPUs it was probably a little slower than it might have
been because of the IPC overhead, but 7 CPUs put my app in a totally
different league.

Jimmy




From pipen at beast_tu_kielce.pl  Fri Jul 11 03:00:17 2003
From: pipen at beast_tu_kielce.pl (Artur M. Piwko)
Date: Fri, 11 Jul 2003 07:00:17 +0000 (UTC)
Subject: wxPython - question
References:  
Message-ID: 

In the darkest hour on Thu, 10 Jul 2003 18:12:55 -0700,
Tom Plunket  screamed:
> By reading the docs and using the right flags.  :)
> 
> (I've been using wx for two weeks.)
> 

Me - 2 days (-;

> wxFRAME_NO_TASKBAR - Creates an otherwise normal frame but it
> 

Thanks. I was looking for function and this is a style...
I am fighting right now with setting/resetting this flag on live frame.

Artur

-- 
Before the Goat of Mendes... we all must take our turn   |  Artur M. Piwko
Into the magic circle... where still the fire burns      |  mailto:s/_/./
We're spinning round and round... until one takes a fall | -- Mercyful Fate
The fallen one will not return, the fallen one must burn | "Witches' Dance"



From evan at 4-am.com  Tue Jul 29 12:51:17 2003
From: evan at 4-am.com (Evan Simpson)
Date: Tue, 29 Jul 2003 11:51:17 -0500
Subject: variable assignment in "while" loop
In-Reply-To: 
References: 
Message-ID: <3F26A605.8080209@4-am.com>

Sybren Stuvel wrote:
> while info = mydbcursor.fetchone():
> 	print "Information: "+str(info)

Gustavo has already pointed out the classic Pythonic ways of writing 
this.  In the general case, where you don't have an iterator handed to 
you, you can make one as of Python 2.2 like so:

def each(f):
     '''Make a zero-argument function or method iterable.
        It had better have side effects, or this is pointless.'''
     v = f()
     while v:
         yield v
         v = f()

for info in each(mydbcursor.fetchone):
     print "Information:", info

Of course, all this really does is to factor out one of the classic 
Pythonic patterns into a wrapper function.

There's also the Pita pocket solution:

class Pita(object):
     __slots__ = ('pocket',)
     marker = object()
     def __init__(self, v=marker):
         if v is not self.marker:
             self.pocket = v
     def __call__(self, v=marker):
         if v is not self.marker:
             self.pocket = v
         return self.pocket

p = Pita(10)
while p(p() - 1):
     print p()

Cheers,

Evan @ 4-am






From mwilson at the-wire.com  Thu Jul 10 16:59:36 2003
From: mwilson at the-wire.com (Mel Wilson)
Date: Thu, 10 Jul 2003 16:59:36 -0400
Subject: sort() doesn't work on dist.keys() ?
References: <6cd58b6.0307101214.34e99f2a@posting.google.com>
Message-ID: <4OdD/ks/Kn4S089yn@the-wire.com>

In article <6cd58b6.0307101214.34e99f2a at posting.google.com>,
spinard at ra.rockwell.com (Steve Pinard) wrote:
>New to Python, so please bear with me.
>
>>>> import sys
>>>> print sys.modules.keys()          # works fine
>['code', ...snip... ]
>>>> print sys.modules.keys().sort()   # returns None, why?
>None
>
>According to my reference (Nutshell), keys() returns a
>"copy" of the dict keys as a list, so I would expect when
>I aply sort() to that list, I would get an in-place sorted
>version of that list.  Why do I get None?

   Because [ ... what everybody else said ]


   Apparently the designer of sort didn't want anyone to
mistakenly think that

sorted_version = my_list.sort()

would leave them with a sorted list *and* an intact,
unsorted list.


   Lots of people have asked this.  Maybe in the long run
you want to write a module of your own contining something
like


def sorted_copy (a_sequence, *varargs):
    ret = list (a_sequence)
    ret.sort (*varargs)
    return ret


and put it in site_packages, or somewhere where you can
re-use it easily.  *varargs is there to stand for the
optional comparison function in a_list.sort(cmpfunc).

        Regards.        Mel.



From juliagoolia301 at hotmail.com  Sun Jul 13 18:34:36 2003
From: juliagoolia301 at hotmail.com (Julia Goolia)
Date: 13 Jul 2003 15:34:36 -0700
Subject: installing python library modules (general question)
References: <79ad5955.0307122013.6780fc53@posting.google.com> 
Message-ID: <79ad5955.0307131400.696226ce@posting.google.com>

jeff,

you are a gentleman and a scholar.  that worked like a charm.  thank
you so much.  just so i know... adding something to /etc/ld/so/conf is
different than setting LD_LIBRARY_PATH?  what do you do if you don't
have root access?

thanks again,
julia

Jeff Epler  wrote in message news:...
> Add /usr/local/lib to the list of directories in /etc/ld.so.conf and
> then execute /sbin/ldconfig to create some needed symlinks in
> /usr/local/lib.
> 
> Jeff



From domma at procoders.net  Sat Jul 19 04:29:31 2003
From: domma at procoders.net (Achim Domma)
Date: Sat, 19 Jul 2003 10:29:31 +0200
Subject: compiling mysql-python for python 2.3 on windows
Message-ID: 

Hello,

I need mysql-python for python 2.3 on windows. I downloaded the source and
tried to build it myself, but I get linker errors:

mysqlclient.lib(password.obj) : error LNK2001: unresolved external symbol
__ftol2

The problem seems to be, that the mysql lib is build with VC7, but distutils
tries to compile with VC6 (which are both on my machine). Can I force
distutils to use VC7? Or has somebody prebuild binaries for windows? Or has
somebody another hint on how to get it working on windows? I have also mingw
3.2 installed, if it would be helpfull!?

regards,
Achim





From bignose-hates-spam at and-zip-does-too.com.au  Sun Jul  6 22:27:39 2003
From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney)
Date: Mon, 07 Jul 2003 02:27:39 GMT
Subject: A story about Python... sort of
References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk>    
Message-ID: 

On Mon, 07 Jul 2003 02:02:06 GMT, Russell Reagan wrote:
> Anyway, I know of one chess program written in python, and it is
> dreadfully slow compared to *any* program written in C/C++ (that I've
> seen anyway).

Have you looked at the code for it?  Have you profiled it to see where
its bottlenecks are?  It's often the case that a program is low because
of poor design, or simply choosing a slow algorithm.

Until profiling, of course, you can't know which algorithms are too slow
for the program.

> The things that make a chess program fast aren't really python's
> strengths, but hopefully I'm being pessimistic due to my lack of
> python/c knowledge.

My suggestion for those who want to write programs that do something
quickly:

  - Write a program that does the job at all, paying attention to
    simplicity and readability and *no* attention to optimisation.

  - Debug the program so it does everything it's supposed to do, albeit
    slowly.

  - Once the program is correct, and not before, profile it to see where
    it's slow.

  - Pick the biggest bottleneck and make it faster, by one or more of:

      - Choose a faster algorithm, perhaps sacrificing readability or
        simplicity
      - Re-implement in C

  - Iterate the previous step until the program is fast enough or you
    run out of (time|money).

You'll have a program that is quite readable, except in the places where
it needs to be fast.  In my experience, those places are surprisingly
few, and are surprisingly different to where you expected them to be.

> import chess
> chess.run_program_in_c
> print "Thanks for playing! Bye!"

It may well be that all the "real" chess-thinking stuff may be too slow
in Python; you might end up with the move-evaluation routine in C, for
example.

But discover that by profiling a Python implementation first!  If it
turns out to be too slow, at least you've debugged a working algorithm,
and can treat it as pseudocode for the port to C.  If it turns out that
the bottlenecks are somewhere else entirely, you've saved yourself a
huge misguided optimisation effort.

-- 
 \      "My roommate got a pet elephant. Then it got lost. It's in the |
  `\                           apartment somewhere."  -- Steven Wright |
_o__)                                                                  |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B



From lists at gregfortune.com  Tue Jul 22 15:06:16 2003
From: lists at gregfortune.com (Greg Fortune)
Date: Tue, 22 Jul 2003 12:06:16 -0700
Subject: Installing many packages
Message-ID: 

I've got a whole bunch of package dependencies in the programs I develop. 
Mainly, they are generic libraries/utilities I've written that are needed
by most of the programs I write.  The biggest problem I've had with
python's packaging system is that I end up needing to install every library
package on each machine I install my programs on.  It's even worse when I
go through an upgrade...

Is there any way to create something like a "meta-package"?  ie, can bundle
a whole bunch of packages together under a single installer?  I'm working
on both Windows and Mac so the tools need to support both platforms.  Does
anything exist for this purpose?

Thanks,

Greg Fortune
Fortune Solutions



From maoy_REMOVE_IF_NOT_SPAM at cis.upenn.edu  Fri Jul 11 00:54:47 2003
From: maoy_REMOVE_IF_NOT_SPAM at cis.upenn.edu (Yun Mao)
Date: Fri, 11 Jul 2003 00:54:47 -0400
Subject: How to get all IP addresses in python?
Message-ID: 

Hi. I did a little homework on google for this question. The answer was:
>>> import socket
>>> hostname = socket.gethostname()
>>> ip = socket.gethostbyname(hostname)
>>> print ip
192.168.55.101
But what if I have several interfaces, say eth0, eth0:1, eth1, etc. How to
get all of them? It would be a little undesirable if people suggest to parse
the result of ifconfig because I in particular want the code to be cross
platform. Thanks a lot!

Yun





From chrisperkins37 at hotmail.com  Mon Jul 21 09:22:49 2003
From: chrisperkins37 at hotmail.com (Chris Perkins)
Date: 21 Jul 2003 06:22:49 -0700
Subject: feature request: a better str.endswith
References: <2259b0e2.0307180401.5dae02f2@posting.google.com>  <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com>  <2259b0e2.0307200721.16ef2ea1@posting.google.com>
Message-ID: <45228044.0307210522.1ef95144@posting.google.com>

mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307200721.16ef2ea1 at posting.google.com>...
> Oops! My mistake, I forgot the islice; it should be
> 
> the=lambda pred,seq: list(itertools.islice(itertools.ifilter(pred,seq),0,1))
> 
> in such a way that we exit at the first hit, otherwise one could just use
> the standard "filter". 

How about:

def the(pred,seq): return True in itertools.imap(pred,seq)

if you really want to use the name "the" ("any" makes much more sense to me).

Chris



From tl_news at nexgo.de  Wed Jul 30 14:00:24 2003
From: tl_news at nexgo.de (Tino Lange)
Date: Wed, 30 Jul 2003 20:00:24 +0200
Subject: Syntax: pointers versus value
References: <3F27F673.3000801@mathstat.concordia.ca>  <3F280475.3000500@mathstat.concordia.ca>
Message-ID: 

On Wed, 30 Jul 2003 13:46:29 -0400, Danny Castonguay
 wrote:

>new_graph = initial_graph[:]
>	initial_graph is [[2, 3], [1], [1]]
>	initial_graph is [[2, 3], [1], [1]]
>	initial_graph is [[2, 3], [1, 3], [1]]
>	initial_graph is [[2, 3], [1, 3], [1, 2]]

Hi!

Now you have lists in lists. This is another situation.
 
new_graph = initial_graph[:] will really make a copy of the outer list
- but this outer list contains no values but once again pointers to
other objects. 

Use the copy-module for nested copy things like that:
http://www.python.org/doc/current/lib/module-copy.html

Cheers,

Tino




From martin at v.loewis.de  Wed Jul 30 14:15:42 2003
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Wed, 30 Jul 2003 20:15:42 +0200
Subject: How to get Windows physical RAM using python?
In-Reply-To: 
References: 
Message-ID: 

Python can't get you Windows physical RAM. You have to order RAM
from a manufacturer or reseller if Windows needs more RAM :-)

Regards,
Martin




From peter at engcorp.com  Thu Jul 10 18:18:06 2003
From: peter at engcorp.com (Peter Hansen)
Date: Thu, 10 Jul 2003 18:18:06 -0400
Subject: for in sequence problem... possible new operator to add to python
References: 
Message-ID: <3F0DE61E.1F38C291@engcorp.com>

sismex01 at hebmex.com wrote:
> 
> > From: Peter Hansen [mailto:peter at engcorp.com]
> > When you iterate over a dict in recent versions of Python, you
> > are by definition iterating over the keys in the dict.  If you
> > want the values, you use .values(), and if you want both keys
> > and values, you use .items().  See the docs for more.
> 
> Actually, .keys(), .values() and .items() return their respective
> lists, in arbitrary order.

I realize that.  I didn't mean to imply anything different.

> If you wish to use an iterator, use .iterkeys() , .itervalues()
> or .iteritems() ; very helpful in the case of big dictionaries,
> since you don't need to create and then destroy big lists.

Sorry, perhaps I should stop using the term "iterate" for its
more widely known generic meaning of visiting each item in a 
sequence one at a time, and restrict my usage only to those
cases where in Python I'm talking about an actual "iterator"
object.

("Iterate" was a very general term... it would be a shame if
one could no longer use it as such.)

-Peter



From maxm at mxm.dk  Thu Jul 10 05:15:24 2003
From: maxm at mxm.dk (Max M)
Date: Thu, 10 Jul 2003 11:15:24 +0200
Subject: Zope problem:  objectValues('Folder')
In-Reply-To: <3F0D2405.1070606@gmx.de>
References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> <3F0D2405.1070606@gmx.de>
Message-ID: <3F0D2EAC.2010605@mxm.dk>

Jens Riedel wrote:

> Max M schrieb:
> 
>>> 
    >>> >>>

  • >>>
    >>>
> > >> If you have written it exactly like that, it should work. You have no >> folders inside the folder you are running it in then. > > > That's my problem. I followed the instructions of the Zope Book example > exactly and created 3 folders in the folder I use the > objectValues()-method on. hmmm ... it is not a zope problem. objectValues() works! try
  • &dtml-meta_type;
That should give a hint. regards Max M From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 22:39:07 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Aug 2003 12:29:07 +0950 Subject: A very simple question References: Message-ID: On 1 Aug 2003 10:51:22 +0950, Ben Finney wrote: > If you want attributes that are bound to a particular instance, set > them in the class's __init__() method. s/to a particular instance/to each instance/ -- \ "If you ever drop your keys into a river of molten lava, let | `\ 'em go, because, man, they're gone." -- Jack Handey | _o__) | Ben Finney From sismex01 at hebmex.com Fri Jul 4 15:08:04 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 4 Jul 2003 14:08:04 -0500 Subject: Python is a gem, you need to keep pushing it .... Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > Sent: Viernes, 04 de Julio de 2003 01:11 p.m. > > Peter Hansen wrote: > > > > sismex01 at hebmex.com wrote: > > > > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > Sent: Viernes, 04 de Julio de 2003 07:42 a.m. > > > > > > > > delphiro wrote: > > > > > > > > > [attribution removed... don't do that!] > > > > > > Python *is* great but lets not pretend that its a good > > > > > > fit for every problem. > > > > > > > > > > I doubt that (unless you develop hardware drivers). > > > > > > > > Are you saying that you think Python _is_ a good fit > > > > for every problem, excluding only hardware drivers? > > > > > > > > -Peter > > > > > > > > > > Seems like he is; in my experience Python has been flexible > > > enough to fit any problem I've tossed at it. > > > > As it has for me, but neither you nor I have thrown *every* > > problem at it, and the OP appears to be stating that he believes > > we would never find Python inadequate, no matter what we threw > > at it (exception hardware drivers again). > > > > As an example, one could argue that embedded systems are not > > merely "hardware drivers" (one could also argue that they are, > > but I do not), yet we've found Python suitable in only one > > of our embedded system products. > > Thus contradicting myself, of course. :-) What I meant to say > was "I know what you mean, since I've found it highly suitable > as well, but no one with good experience in computing could > reasonably claim it will fit *all* problems except hardware drivers." > > -Peter > Specially since Pypy is going to address some of those problems which make Python not suitable for drivers; they it's going to be *the* right answer for "What language?". ;-) -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From aahz at pythoncraft.com Thu Jul 3 20:31:08 2003 From: aahz at pythoncraft.com (Aahz) Date: 3 Jul 2003 20:31:08 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: In article , Russell Reagan wrote: > >There is a rather large industry which I'll call "computer games" that >is rather CPU intensive, and AFAIK the vast majority of those games are >written in C/C++. It really depends on the definition of "application >level". If we're only including things like word processors and web >browsers in the "application level", then there isn't a great need for >C++ in the "application level", but there are certainly areas where >speed and memory efficiency is important. At the same time, more and more of those games are switching to using C/C++ only for the rendering engine and using a scripting language (Lua or Python) for the gameplay itself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From duncan at NOSPAMrcp.co.uk Wed Jul 16 09:18:18 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 13:18:18 +0000 (UTC) Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: Duncan Booth wrote in news:Xns93BA6E5A0FA08duncanrcpcouk at 127.0.0.1: > On question 8, I'm not aware that Python borrowed anything from Java. Researching beyond Google reveals that the current class syntax dates from Python 0.9.4, December 1991. Since Java was released in 1995 it would definitely seem to be wrong to claim that Python gets "object orientation concepts" from Java. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From lorenb2 at bezeqint.net Sun Jul 27 19:18:18 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Mon, 28 Jul 2003 01:18:18 +0200 Subject: List Question References: <001e01c3548d$bed5a420$6400a8c0@EVOD31> <20030728111954.GA20253@dave@alana.ucc.usyd.edu.au> Message-ID: <005001c35495$5d3f5dc0$6400a8c0@EVOD31> Thanks all, and again, accept my apologizes for the stupid question... *blushed* B ----- Original Message ----- From: "Dave Harrison" To: "Bill Loren" Sent: Monday, July 28, 2003 1:19 PM Subject: Re: List Question > ah ... a perl coder ;-) *chuckle* > > len(heck_of_a_list) > > will give you the length of the list > > Bill Loren (lorenb2 at bezeqint.net): > > Hello, > > > > Forgive my python newbieness. > > Assume I have a list named heck_of_a_list. > > how would I extract the number of elements out of it ? > > (I'm looking for something like perl's $#heck_of_a_list operand) > > > > thanks > > B > > From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jul 13 15:00:23 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 13 Jul 2003 21:00:23 +0200 Subject: How to crash Python in 1 easy step (python 2.2.2) In-Reply-To: <2e363c08.0307130944.4c470bc3@posting.google.com> References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <3f11ac45$0$49101$e4fe514c@news.xs4all.nl> Paul Miller wrote: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > everything about the system is standard except for what's been updated > by RedHat itself. If anyone who has the time and ability to track > down this bug needs more information, please email me. I doubt it is a problem in Python, it works nicely on both my windows and my linux machines (python 2.2.3). Just a gut feeling: reinstall/upgrade your readline library..... --Irmen From anton at vredegoor.doge.nl Tue Jul 29 20:29:43 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 30 Jul 2003 02:29:43 +0200 Subject: spaces on idles last line Message-ID: If editing a script with another editor than Idle (f.e. Scite) sometimes there are spaces left on the last line. If such a script is run from the Scite command line with f.e. "pythonw -u idlespace1.py" the script runs fine. However if next the script is run from Idle, there is the following error: Python 2.3b1 (#40, Apr 25 2003, 19:06:24) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> IndentationError: unindent does not match any outer indentation level (idlespace1.py, line 6) the script: def test(): print "hi" if __name__=='__main__': test() Note that there is no empty last line in this script: the last line contains spaces. A syntaxerror is also possible: >>> File "xxxx\xxxx\idlespace2.py", line 2 ^ SyntaxError: invalid syntax The script that caused the error above: Saving a script with Idle repairs it immediately, because Idle automagically adds an empty last line, however a "check module" from Idle's menu doesn't detect the error. This made it difficult to even write a script to find out what caused it. Is there a reason for Idle being stricter than its own checks? Anton. From ronald at PassTheDairy.net Thu Jul 3 13:00:21 2003 From: ronald at PassTheDairy.net (BearMan) Date: Thu, 03 Jul 2003 17:00:21 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: Not to mention all the time spent recompiling through out the debugging and troubleshooting process. Has Max ever programmed in Python? How about Assembly? The fact of the matter is there is no such thing as one ULTIMATE language. A real programmer will have mastered several languages so as to integrate the best features for any given situation. IMHO "Peter Hansen" wrote in message news:3F043B22.19FE79AE at engcorp.com... > Max Khesin wrote: > > > > import flame.* > > import sorry.* > > Ok, with all my respect to python, the stuff about C++ is a bunch of hooey. > > Compilation time is the problem? Give me a break. > > 1) separate compilation? > > 2) precompiled headers? > > 3) tools that allow cluster compilation? > > 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ > > project. letter-envelope idiom to help compilation...etc. > > Sounds to me that if they've come up with so many and such a wide > range of optimizations to improve compilation time, then it clearly *is* > a problem... > > > Anyway, if you are coding so fast that compilation time becomes a serious > > problem you are either > > a) the smartest and fastest programmer on earth > > b) are not thinking enough > > c) doing test-driven development > > I admit to not having done any C++ code for several years, certainly not > since adopting TDD, but I would guess for a sizable project the compilation > and link times could become a major annoyance > > -Peter From dion_mart at hotmail.com Mon Jul 21 01:48:57 2003 From: dion_mart at hotmail.com (Martin Dion) Date: Mon, 21 Jul 2003 05:48:57 GMT Subject: Needing help with sockets Message-ID: Hi i'm relatively new to python and I need help with a little program i wrote What i want to do: I want to be able to connect on any port on a system and then send and receive commands, by following the protocol rules. If I receive data, it must print on the screen. It asks for data to send in reply to the data received. Once data is sent, it must look if there is data to receive and if not, it must ask the user to send an other string. The problem, is that once data is sent, it goes to the receive data loop and blocks until it gets data. I read a little on non-blocking sockets, but i am not sure if it is what i should look for I heard about timed sockets (maybe it could work, but i am unsure) ========================================================================= import socket remote = raw_input('To wich host:') port = input('To wich port:') #remote = "192.168.0.2" #port = 22 while 1: # entering software main loop s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creating socket print "\nConnecting to:",remote,":",port s.connect((remote, port)) print "\nConnected to:",remote,":",port while 1: #Net main loop while 1: #receiving data data = s.recv(1000) print data if len(data) < 1000: break #no more data to get so break toSend = raw_input("Data to Send:") if toSend == "!QUIT" :break s.sendall(toSend) s.close() del s From mis6 at pitt.edu Mon Jul 7 18:46:05 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 7 Jul 2003 15:46:05 -0700 Subject: Using Loops to track user input References: Message-ID: <2259b0e2.0307071446.4ab54303@posting.google.com> hokiegal99 wrote in message news:... > Perl's motto is "there's more than one way to do it," right? Well, after > reading all of these responses, I think Python could make the same > claim. Thanks again guys! > > > Bob Gailer wrote: > > > Not to neglect the 1-liner: > > > > import operator; reduce(operator.add,[int(raw_input("Number>")) for i in > > range(10)]) > > > > Bob Gailer > > bgailer at alum.rpi.edu > > 303 442 2625 Nowadays even shorter: sum([int(raw_input("Number>")) for i in range(10)]) ;) From torsten.will at epost.de Sat Jul 5 13:46:56 2003 From: torsten.will at epost.de (Torsten Will) Date: Sat, 05 Jul 2003 19:46:56 +0200 Subject: sqlrelay Message-ID: <3f070ec0$0$13370$9b77ed8b@news.comundo.de> http://sqlrelay.sourceforge.net/ From jjl at pobox.com Sat Jul 5 12:32:13 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Jul 2003 17:32:13 +0100 Subject: Bewildered graphs References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: <87vfuhkk8i.fsf@pobox.com> Mark Fenbers writes: > I am investigating Python for the sake of ultimately generating > hydrographs (such as this: > http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) > on-the-fly from a web server cluster. I have not used Python > previously and do not yet know if Python is very useful for this or > if I am wasting my time. I've done a lot of plotting with Python in the past. The issue is really which plotting package(s) you pick rather than anything to do with Python itself (and nobody here is likely to argue with your choice of language, of course!). > Quite frankly, I am a little bewildered. Not only is there Python, > but there are many extention modules which cloud up my view as to > what I will need. Certainly a year or two ago there was no single free plotting package around (Python or no Python) that was everything I needed -- and I was usually plotting pretty straightforward graphs. Things may have improved a bit since then, but I certainly think it's worth considering using a commercial package (from Python). Presumably you already use a package of some kind to plot these things? Most commercial packages seem to have an API of some sort, so try googling for a Python binding for it -- one may well already exist. Otherwise, I'm out of date so can't give you a simple 'use this', but in general: Just to confuse you further, another option is to use a generic plotting library, rather than one designed specifically for graphs. If the format of your graphs isn't going to change, that might be a reasonable choice. You end up with more code, but you avoid having to figure out how to tickle exactly what you want out of a reluctant plotting package. In particular, you can be sure you won't get stuck in the 'so far and no further' situation that graphing packages can leave you in. I'd probably first run though the demos that invariably come with the graphing packages, and if it wasn't fairly obvious that a) all the necessary features were there in one of them and b) reasonably clear the example code / docs c) lightweight enough not to bring your web server to its knees, I'd try a generic plotting library. Ordered by my guess of most appropriate first: PIL, PIDDLE, reportlab (nicer API than PIDDLE; pdf output, but you could probably convert to .png easily enough), plotutils, sketch. Of the graph plotting packages, some that should get the job done: Grace (grace_np.py) API documentation poor last time I looked, but does everything you could want, and has a (rather nasty) GUI interface too, so you can tweak graphs for publication. If load on the web server is high, it might be too heavyweight, though. DISLIN (pxDislin) You probably want the pxDislin binding, not the one distributed with DISLIN itself. Chaco Haven't used this. Probably a nice API, but looks like it's still not very capable. Lots of others too, I'm afraid: PLPLOT, PGPLOT, gnuplot, Qwt, scigraphica... > There's Scientific Python, which sounds promising, but there's also > SciPy which I haven't used the plotting software from either (I don't think Scientific Python had any plotting code when I used it). In general, they do different things. One obvious difference is that Scientific Python is (mostly, at least) new, pure Python code, where SciPy wraps a lot of old, well-tested Fortan, C and C++ code (but no doubt there's a fair amount of pure Python code there too). Both approaches have pros and cons, and the particular codes in SciPy and Scientific Python have different objectives, of course. John From gh at ghaering.de Tue Jul 8 16:40:56 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 08 Jul 2003 22:40:56 +0200 Subject: Newbie - Directory/File Creation In-Reply-To: <68a42404.0307081209.4baafd5@posting.google.com> References: <68a42404.0307081209.4baafd5@posting.google.com> Message-ID: <3F0B2C58.1070405@ghaering.de> Michael J Whitmore wrote: > If I do the following, a file is created in the current working > directory: > TestFile = open("TestTest.out", 'w') > > My question is how to create a file that includes a pathname without > having to mkdir beforehand. > Example: > TestFile = open("TestDir\TestTest.out", 'w') If you want to have a backslash in a string, you have to double it, because the backslash is an escape character in Python strings. So this would be: TestFile = open("TestDir\\TestTest.out", 'w') Alternatively, you can use a raw string: TestFile = open(r"TestDir\TestTest.out", 'w') or just use a forward slash, which works fine on Windows as well: TestFile = open(r"TestDir/TestTest.out", 'w') or, to be politically correct, you can use: import os TestFile = open(os.path.join("TestDir", TestTest.out"), 'w') > Shouldn't open be smart enough to create the TestDir directory before > creating TestTest.out ? No, explicit is better than implicit. [1] > Is there another command that will do this? Sure, os.mkdir. -- Gerhard [1] Try "import this" at an interactive Python prompt for this and more Python Zen :-) From hokiegal99 at hotmail.com Sat Jul 5 14:24:42 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 05 Jul 2003 14:24:42 -0400 Subject: Calculating Year, Month and Day of Life In-Reply-To: References: Message-ID: hokiegal99 wrote: > Hello, > > I am a funeral director trying to write a small program that calculates > the number of years, months and days a person has lived by entering the > year, month and day of their birth. This is what I have so far: > > #--------------------- > from time import * > local = localtime() > > print "Enter the year of birth:"; y = input() > print "Enter the month of birth:"; m = input() > print "Enter the day of birth:"; d = input() > > age = y,m,d > print age > print local > #---------------------- > > The output looks similiar to this: > (1934, 2, 7) > (2003, 7, 5, 13, 20, 0, 5, 186, 1) > > My problem is that localtime is a list of 9 integers while age is a list > of 3 integers. Is it possible to make localtime() only return the first > 3 integers? If so, how would I then do calculations on the two lists' > individual parts? For example, how would I instruct localtime() to > subtract the first integer from age's list from the first intger in its > own list (2003 - 1934)? > > Also, I am new to python, but I like it a lot and have picked it up > quickly. If my approach to this solving this problem is completely > wrong, please point me in the right direction. > > Thanks in advance!!! > Sorry to respond to my own post, but I answered the first part of my question by experimenting a bit. I pulled the first 3 integers from localtime() like this: local = localtime() print local[:3] (2003, 7, 5) From logiplex at qwest.net Mon Jul 21 14:07:45 2003 From: logiplex at qwest.net (Cliff Wells) Date: 21 Jul 2003 11:07:45 -0700 Subject: Threading Pool Event() In-Reply-To: <41c203e.0307202301.64022dca@posting.google.com> References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> <41c203e.0307202301.64022dca@posting.google.com> Message-ID: <1058810865.2717.96.camel@software1.logiplex.internal> On Mon, 2003-07-21 at 00:01, Anand wrote: > What if you want to make sure that there are exactly > 'n' threads in the queue a given moment ? Why not simply start 'n' threads and have them wait on the queue? > I had a problem of a similar kind, which I solved by > deriving a "Thread monitor" class from Queue. I initialized > the Queue with a given size (the number of threads in it > a given moment, the number 'n' above). But, I found that > this does not happen accurately as I wanted. I solved > it by using a non-blocking queue and managing the exception > by using an Event and by using my own locks. You keep saying "threads in the queue". Why are you putting the threads in the queue? Usually the threads run independently and get their *work* from the queue. Part of the reason for having a pool of threads (aside from controlling the number of active threads) is to avoid the overhead of starting new threads. By putting threads on the queue and starting them when there's work to do you lose this benefit. > The code would look something like this ... > It uses a polling mechanism with sleeping. Polling + sleeping seems bad for most applications. Polling when there's nothing to do is a waste of CPU, sleeping when there's work to be done adds latency. Combining the two is the worst of both worlds (again qualifying the statement for the general case). Looking at the code you posted, it isn't clear to me why you would take this approach. It appears to me that your fundamental flaw is thinking that the *threads* must be put on the queue rather than the data the threads will act on and the problems you faced resulted from that misunderstanding. If you disagree, then perhaps you could give an example of an application that would require this type of approach versus the traditional producer/pool-of-consumers setup. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From simonb at webone.com.au Tue Jul 29 18:31:47 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 30 Jul 2003 08:31:47 +1000 Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> Message-ID: On Tue, 29 Jul 2003 22:06:20 +0000, Raymond Hettinger wrote: > "David C. Fox" wrote in message > news:9sBVa.12998$o%2.6289 at sccrnsc02... >> Is there a function which takes a list of tuples and returns a list of >> lists made up of the first element of each tuple, the second element of >> each tuple, etc.? >> >> In other words, the the inverse of the built-in zip function? > > When used with the * operator, zip() is its own inverse: > This (obviously) doesn't work when z has length 0 or 2. I don't quite understand why zip is overloaded ... Oh, hang on, it does work for length 2! that's neat-o, and perhaps that's why zip was extended. Is it a functional programming convention, i wonder. Simon. From vze4rx4y at verizon.net Tue Jul 22 11:47:32 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 22 Jul 2003 15:47:32 GMT Subject: Python Mystery Theatre -- Episode 3: Extend this References: Message-ID: [Steven Taschuk] > > ACT VI ----------------------------------------- > > print "What is the technical name for this algorithm or transformation?" > [...] > > Heh. Nice one. > > The technical name is "the identity transformation". Ding ding! We have a winner. Others thought the i,j swap was suspicious but did not put the finger on left-to-right assignment undermining the whole selection sort to make it do nothing at all. Raymond Hettinger From pw-google at terlkin.org Mon Jul 14 13:06:38 2003 From: pw-google at terlkin.org (Peter Wilkinson) Date: 14 Jul 2003 10:06:38 -0700 Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> <120720032321075007%candiazoo@mac.com> Message-ID: <3344b1fa.0307140325.67be7b8c@posting.google.com> "Michael S. Jessop" wrote in message news:<120720032321075007%candiazoo at mac.com>... > [[ This message was both posted and mailed: see > the "To," "Cc," and "Newsgroups" headers for details. ]] > > I tried supplying host as well, same error. :/ Something is hosed. > I guess I could try reinstalling. I really want to get this to work. > I am trying to write a maintenance program for my wife, so she can > remotely modify the database containing information about her artwork, > distribution lists, etc. > I've just sorted out the problem on my machine and it appeared to be a set of include files from a previous install of MySQL that were sitting in /usr/include, once I removed that and rebuilt with setup.py pointing to the Fink include paths it works fine. Peter. From intentionally at blank.co.uk Sun Jul 13 09:56:18 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 14:56:18 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <5tn2hvgjqlqg1qs7omvugpvm62cuso261k@4ax.com> On Sun, 13 Jul 2003 05:50:46 -0600, Dave Brueck wrote: >On Sunday 13 July 2003 01:41 am, Tom Plunket wrote: >> In C++ it's trivial to return multiple values > >Trivial but non-intuitive until you convince yourself "that's the way it is", >perhaps. :) What I mean is this: when you're just starting out you learn that >functions can return values like this: > >int foo(int a, int b) >{ > return a + b; >} > >But the method for returning more than one thing is not a simple progression >from this pattern. Instead you learn and shift to a *completely* different >mechanism. In Python, however, you *can* continue along the original route as >well: > >def foo(a, b, c): > return a+b, b+c You are not directly returning multiple values - you are returning a tuple. You can return containers in C++ too. The only difference is that Python makes working with tuples *much* easier - but its no more a 'simple progression' than in C++. You still need to know about tuples as well as returning values. >> > IOW, if you could erase the influence of previous languages would >> > this FAQ become "how can I return multiple things from a >> > function" more often than it would become "how can I modify an >> > object from inside a function"? There's more to it than this. Take the Pascal family of languages. These have an explicit distinction between functions and procedures which is hidden in C and Python. In my view, the distinction between a procedure (an imperative tool which may modify parameters in place) and a function (which returns a value but - normally, at least - leaves its parameters unmodified) is a useful one. Writing code to respect these conventions, even when the language doesn't explicitly support it, has considerable benefits - evaluation order in expressions becomes much less of an issue, for instance, effectively eliminating at least one source of subtle hard-to-trace errors. Which suggests a new 'procedure' syntax for Python, either automatically treating all parameters as references or providing a syntax equivalent to the Pascal 'var'. From pyth at devel.trillke.net Tue Jul 8 14:28:52 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 8 Jul 2003 20:28:52 +0200 Subject: path module In-Reply-To: <1057686623.3738.62.camel@lothlorien>; from ianb@colorstudy.com on Tue, Jul 08, 2003 at 12:50:23PM -0500 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <1057686623.3738.62.camel@lothlorien> Message-ID: <20030708202852.J6906@prim.han.de> Ian Bicking wrote: > On Tue, 2003-07-08 at 04:32, holger krekel wrote: > > I agree that something like Jason Orendorff's path module should go into > > the standard library. I've coded a similar module and i think that > > a discussion about certain design decisions would probably improve our > > approaches. > > > > For example Jason lets the "path" object inherit from "str" (or unicode) > > but i think it's better to provide a "__str__" method so that you can say > > > > str(pathinstance).endswith('.py') > > > > and *not* base the path object on str/unicode. > > > > unicode(pathinstance) > > > > would just fail if your platform doesn't support this. First, i tried > > the inheritance approach, btw, but it is ambigous (e.g. for the > > join-method (str.join and os.path.join). > > I'm starting to think the same thing. Not so much because of join, but > because it doesn't actually offer many advantages. Many methods that > look for a filename will be using "type(arg) is type('')", so you'd have > to pass a real string object in anyway -- and people who say "but you > should use isinstance(arg, str)" are obviously forgetting that you > couldn't do this not very long ago, and lots of code uses type > comparison at this point. right. Also i prefer my objects to not have a "polluted" namespace. > > Also, my module provides most of the os.path.* methods as "filters" so > > you can say > > > > dirs = filter(isdir, list_obj_pathobjects) > > fnames = filter(AND(nolink, isfile), list_obj_pathobjects) > > > > in addition to > > > > pathobject.isfile() > > etc. > > That's not necessary with list comprehension, since you can just do: > > [p for p in list_obj_pathobjects if p.isdir()] but i use the same idea (filter-functions) for more advanced walkers: p = path('/music') for i in p.filterwalk(AND(nolink, isfile, isplayable, match(repattern))): play_mp3(i) where filterwalk is a generator because i don't want the playscript to first try to gather *all* files for obvious reasons (as would happen with list comprehension). This has proven to be incredibly useful and easy to read (if you don't engange in list-comprehension <-> functional-style wars). Just because Guido somewhat dislikes "functional support" like lambda, map, filter and friends to be in the __builtin__ module doesn't mean it's bad :-) cheers, holger From jdhunter at ace.bsd.uchicago.edu Wed Jul 30 11:57:48 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 30 Jul 2003 10:57:48 -0500 Subject: funny slashdot quote regarding python 2.3 release In-Reply-To: <3f27b0a9$0$49104$e4fe514c@news.xs4all.nl> (Irmen de Jong's message of "Wed, 30 Jul 2003 13:48:56 +0200") References: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> <3f27b0a9$0$49104$e4fe514c@news.xs4all.nl> Message-ID: >>>>> "Irmen" == Irmen de Jong writes: Irmen> And let's not forget that time-critical code can very well Irmen> be written in a high-performance C extension module. We recently had a physicist visit to show us how to do some calculations and analyses he had developed, and he brought with him a bunch of FORTRAN code he developed to do the calculations. At first I wrapped them with f2py (unbelievably easy!) but then just decided to reimplement them in Numeric since they were amenable to array processing. I found that the Numeric version was about 20% faster than the FORTRAN, in part because there were some inefficiencies in his hand coded FORTRAN routines. Which emphasizes that it's often better to use a well tested, optimized extension than to code it yourself in a compiled language. Why reinvent the wheel when you've got a brand new Michelin tire sitting in the garage? JDH From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jul 13 18:34:48 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 14 Jul 2003 00:34:48 +0200 Subject: =?UTF-8?B?w7HDr8Olw7jDqMOgw6sgw6TDq8O/IMOww67DscOxw6jDqcOxw6o=?= =?UTF-8?B?w6jDtSDDr8Oow7LDrsOtw7nDqMOqw67DoikpKQ==?= In-Reply-To: <3F11BF87.9000208@v.loewis.de> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F11D94A.7050208@removeme.free.fr> <3F11BF87.9000208@v.loewis.de> Message-ID: <3f11de85$0$49112$e4fe514c@news.xs4all.nl> Martin v. Loewis wrote: > That's not what he said. Instead, he said > > "?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? > exe-???? ?????????)." > > To see that, you have to read the message in windows-1251. Wonderful, I can "read" *your* rendition of it... probably because you posted in UTF-8 :-) The original message was posted in regular latin-1... > I think this roughly translates into "Can you please tell me where to > find the proggie freezer (which appears to be needed to create exes)?" Wow, you apparently understand what Garber wrote, too... 'nuff said --Irmen From peter at engcorp.com Mon Jul 14 18:33:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 18:33:23 -0400 Subject: Sio serial module install problem with ActiveState References: Message-ID: <3F132FB3.CF0E6B44@engcorp.com> Conrad wrote: > > Greetings, > > I have a need to print from Win98SE to a little > serial label printer provided by United Parcel, so > based on Mark Hammond's recommendation in > 'Programming on Win32' I decided to try the Sio > module at http://starship.python.net/crew/roger/ > > My problem: Solution to problem (of a sort): don't use SIO module, which relies on a third-party external DLL. Instead, use http://pyserial.sourceforge.net/ or, if that doesn't work use http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html -Peter From oren-py-l at hishome.net Mon Jul 7 06:34:26 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 7 Jul 2003 06:34:26 -0400 Subject: sets.filter? In-Reply-To: <20030625213851.GA4940@nl.linux.org> References: <20030625213851.GA4940@nl.linux.org> Message-ID: <20030707103426.GA25393@hishome.net> On Wed, Jun 25, 2003 at 11:38:51PM +0200, Gerrit Holl wrote: > Hi, > > would it be a good idea to add a .filter() method to a set object, > which behaves like the builtin filter() but resulting in a set? > I often see myself doing sets.Set(filter(f, someset))... Would this > be a good addition to sets.Set? Considering the fact that GvR plans to eventually deprecate map and filter in favor of list comprehensions I doubt this kind of change would be accepted. I suspect his preferred idiom for this would be: Set([x for x in someset if f(x)]) probably-not-very-good-at-channeling-Guido-ly yours, Oren From david.isal at wanadoo.fr Fri Jul 11 10:26:19 2003 From: david.isal at wanadoo.fr (David Isal) Date: Fri, 11 Jul 2003 16:26:19 +0200 Subject: Python extension on Windows In-Reply-To: References: Message-ID: by the way, i'm using python 2.2.3 and g++ 3.2 From belred1 at yahoo.com Thu Jul 24 02:13:43 2003 From: belred1 at yahoo.com (Bryan) Date: Thu, 24 Jul 2003 06:13:43 GMT Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: "Ben Finney" wrote in message news:slrnbhusl6.13c.bignose-hates-spam at iris.polar.local... > On Thu, 24 Jul 2003 05:20:15 GMT, Bryan wrote: > >> filelist = [] > >> try: > >> filelist.append(open(filename[0])) > >> filelist.append(open(filename[1])) > >> ... > >> do_something(filelist) > >> finally: > >> for f in filelist: > >> f.close() > > > > erik, carl... thanks... this is exactly what i was looking for > > The only substantial difference I see between this and what you > originally posted, is that there is only one 'try...finally' block for > all the file open/close operations. Is this what you were wanting > clarified? > well, it wasn't exactly clarification as much as seeing another more scalable solution. i know a lot of people don't explicitly close files in python, but i always do even for small scripts. thanks again, bryan From bokr at oz.net Mon Jul 21 00:03:39 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jul 2003 04:03:39 GMT Subject: A challenge to the ASCII proponents. References: <3F1AAC0A.7A6326B@hotmail.com> Message-ID: On 20 Jul 2003 18:56:51 -0700, steve at cyber.com.au (Steven D'Aprano) wrote: >Alan Kennedy wrote in message news:<3F1AAC0A.7A6326B at hotmail.com>... >> Alan Kennedy: >> >> > The final point I'd like to make [explicit] is: nobody had to ask >> > me how or why my xml snippet worked: there were no tricks. Nobody >> > asked for debugging information, or for reasons why they couldn't >> > see it: > >Sorry Alan, but when I follow your instructions and save your XML to >disk and open it in Opera 6.01 on Win 98, I get this: > >XML parsing failed: not well-formed (1:0) > >At least it renders visibly in my browser, although I don't think its >rendering the way you wished. > >(For the record, this is the contents of the XML file, triple-quoted >for your convenience: >""" >γίγνωσκω""") > > >[snip] >> In summary: >> >> 1. I managed to make a greek word, using the original greek glyphs, >> appear on everyone's "rendering surface", by posting a 7-bit clean XML >> snippet. Another poster widened the software coverage even further by >> posting a 7-bit clean HTML snippet. Both of our 7-bit markup snippets >> travelled safely throughout the entirety of UseNet, including all the >> 7-bit relays and gateways. > >I couldn't see either rendered correctly in either Opera's newsreader >or the Google archive. > >> 2. The only other person who managed it, without using markup, was >> Martin von Loewis, who is so good at this stuff that he confidently >> makes statements like "what I did was right: it was Google that got it >> wrong". Martin used the UTF-8 character set, i.e. a non-ASCII, >> non-7-bit-clean character set, to achieve this. Although I'm sure >> Martin could have managed it with UTF-7 as well. > >Martin's effort did work for me in Opera's newsreader, but not in the >Google Groups archive. But we already knew that Google broke it. > >> 3. If anybody else was willing to give it a try, they don't seem to >> have had enough confidence in their knowledge of encodings, MIME, >> transports, NNTP, etc, etc, to have actually hit the "send" button, in >> case it didn't work. Which doesn't bode well for the average person in >> the street: if the technology specialists in this newsgroup don't feel >> in command of the issue, what hope for everyone else? > >Exactly. Which brings us back to Ben's suggestion: when writing for a >general audience using unknown systems, stick to ASCII, or at least >follow your rich text with a description of what your reader should >see: > >"""And I can use Umlauts (???) -- you should see a, o and u all in >lowercase with two dots on top.""" > >It's a mess and I despair. It would be nice if everyone used bug-free >XML-aware newsreaders, browsers and mail clients, but the majority >don't. That's why I always practice defensive writing whenever I use >any character I can't see on my keyboard, and spell it out in ASCII. >That's not very satisfactory, but its better than some random >percentage of your audience seeing "?????". > Here's a way that's been around a while (you have ghostscript, right?) ====< gignooskoo.ps >==================================== gsave 72 72 scale /Symbol findfont 1.0 scalefont setfont 1.0 10.0 moveto (\147\151\147\156\167\163\153\167) show showpage grestore ========================================================= Of course, if you use tools (ms word, pdfwriter) to get that done, you'll wind up with 24,655 bytes of resources and font info and privacy compromise instead of 135 bytes of native PS level 1 ;-) Or a 102-byte one-liner that may not be multipage context friendly, but should show in ghostscript: /Symbol findfont 72 scalefont setfont 72 720 moveto (\147\151\147\156\167\163\153\167) show showpage Regards, Bengt Richter From jjl at pobox.com Wed Jul 30 13:52:01 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 18:52:01 +0100 Subject: how best to handle httplib timeouts ? References: Message-ID: <87k79zx5q6.fsf@pobox.com> "Rich" writes: [...] > outage. The script I have so far connects to the server (using HTTPS) then > passes a login request for a mailbox and retrieves the Inbox page. It does 5 > different requests in all and sometimes gets stuck on the third or fourth > request. Running the source code version seems a little better than the one > compiled with py2exe, and it will often return after what seems like a 2 > minute socket timeout. I've also tried playing with different settings for > the default socket timeout value but that doesn't seem to help either. (I'm > running 2.3b2) 1. Get 2.3final (I don't know whether there was a bug fix, but I have a vague recollection there was some sort of problem with timeouts -- see the python-dev summaries and/or SF bug archive). 2. Check with a tool like ethereal to see exactly where it's getting stuck. If it's DNS, maybe you can do the name lookup(s) once, then just use the IP address for subsequent requests. If not, at least you'll know where the problem is. John From db3l at fitlinxx.com Tue Jul 15 11:18:05 2003 From: db3l at fitlinxx.com (David Bolen) Date: 15 Jul 2003 11:18:05 -0400 Subject: mx.DateTime.Parser.DateFromString('crap') References: <451fb248.0307140616.3584c85f@posting.google.com> Message-ID: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) writes: > Exactly. Found this out after posting, of course, except that I > overlooked the "_date_formats" and typed in everything myself. I debated doing that myself. Using _date_formats is sort of cheating since by being named with the leading underscore it's been marked as an internal use only variable. But in the scheme of things I'd probably accept the risk of needing to track it changing over time, versus keeping a current list of parsers up to date. -- David From syver at inout.no Tue Jul 1 05:51:42 2003 From: syver at inout.no (Syver Enstad) Date: 01 Jul 2003 11:51:42 +0200 Subject: experience with emacs and python-mode References: Message-ID: "Leo" writes: > hi all > > i'm new to python and new to the group and i want to develop python with > emacs :-) i try to use python-mode.el version 4.6. > does somebody else uses this? Yes, been using it for years now. Very nice, but has its quirks, the most annoying being perhaps that triple quoted strings are not supported. Well in trivial cases it looks like they are supported because "" is treated as one string and then the final " is the beginning of a new string and then " is the end and then "" is an empty string again. From pinard at iro.umontreal.ca Sat Jul 19 09:23:42 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 19 Jul 2003 09:23:42 -0400 Subject: __getitem__ and arguments In-Reply-To: <10eb079f.0307190110.30deb5b9@posting.google.com> References: <10eb079f.0307190110.30deb5b9@posting.google.com> Message-ID: [KanZen] > >>> class A(object): > def __getitem__(self, *args): > print len(args) > >>> a=A() > >>> a[1, 2, 3] > 1 > For __getitem__() the arguments become a tuple. I can't seem to find this > in the language spec. Can anybody explain this to me? Hello, KanZen. When you write an argument list as `*args', you _always_ get a tuple of all arguments. Normally, one writes: def __getitem__(self, argument): ... as `__getitem__' only accepts one argument besides `self'. Of course, you may well write: def __getitem__(self, *arguments): ... but then, `arguments' will always be a 1-tuple in practice, and `arguments[0]' will contain the actual argument. This being said, consider the call `a[1, 2, 3]' (it does not look like a call, but we both know that under the scene, this is calling `__getitem__'). We may be tempted to think that it works a bit the same as an explicit function call would work, like if it was written `a(1, 2, 3)', and the confusion might come from there. Indeed, in `a(1, 2, 3)', there are three arguments. `a[1, 2, 3]' is not the same, it calls the `__getattr__' of `a' with a _single_ argument `1, 2, 3'. That single argument is really a tuple itself. Many Python users like to write tuples as `(1, 2, 3)', using superfluous parentheses for strange reasons. :-) They would likely write `a[(1, 2, 3)]' as a way to over-stress that `a[]' accepts only one value within the brackets. The writing `a[1, 2, 3]' is very legible because it is less noisy, and you are right in preferring it. Yet you have to remember that `1', `2' and `3' are not to become separate arguments for `__getitem__'. The single argument will be what was within brackets, that is, a tuple. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From adalke at mindspring.com Wed Jul 2 15:17:13 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 2 Jul 2003 13:17:13 -0600 Subject: splitting a string into 2 new strings References: Message-ID: trp: > I'm, assuming that these are chemical compounds, so you're not limited to > one-character symbols. The problem is underspecified. Usually 2-character (or 3-character for some elements with high atomic number, and not assuming the newer IUPAC names like "Dubnium", which was also called Unnilpentium (Unp) or, depending on your political persuasion, Joliotium (Jl) or Hahnium (Ha)) have the first letter capitalized and the rest in lower case. > re_pat = re.compile('([A-Z]+)(\d+)') So this should be written ([A-Z][A-Za-z]*)(\d+), where I explicitly allow both lower and upper case trailing letters to be more accepting. (In some systems, "CU" is "1 carbon + 1 uranium" and in others it's an alternate way to write "1 copper". Though I suspect it's not allowed in the OP's problem.) Andrew dalke at dalkescientific.com From jjl at pobox.com Sat Jul 5 16:47:02 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Jul 2003 21:47:02 +0100 Subject: Bewildered graphs References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: <87k7awk8ft.fsf@pobox.com> hwlgw at hotmail.com (Will Stuyvesant) writes: [...] > You are thinking about generating a .PNG or .JPG or .GIF or something > like that? > > I have an idea: if your app is running on a web server cluster > already, how about generating dynamic web pages displaying the graph. > You could for example display this whole picture with SVG [...] > this. Note the BIG advantage of such a web application: everybody can > use it with their browser; no installations, compilations, I just tried Mozilla Firebird 0.6 and Konqueror 3.1, and neither has built-in SVG support. [...] > I *know* they plan to deprecate the string library. But most web > hosting Pythons are still 1.5.2 :-! They are? There's still stuff in string that isn't duplicated as string methods, so that seems unlikely to happen for a long while yet, if ever. John From david.abrahams at rcn.com Fri Jul 4 02:07:05 2003 From: david.abrahams at rcn.com (David Abrahams) Date: 3 Jul 2003 23:07:05 -0700 Subject: does lack of type declarations make Python unsafe? References: <3EEE3036.1080105@removeme.free.fr> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:... > david.abrahams at rcn.com (David Abrahams) wrote: > <700+ LOP> > >I love a nice jestful debate. Maybe your whole post is jestful and I > >failed to recognize it. It certainly seems to have a derisive tone > >which makes it hard to see the love. Where's the love, people? > >Anyway, if you tell me you didn't mean it that way I'll take your word > >for it. > > Perhaps not love, to me both you guys are discussing trifles. TDD and > the source of it, static typing, are both about being satisfied with > just passing tests, while the really important discussion -for me at > least- is about aligning the code with ones thoughts, and how to > accomplish that. I think that's *exactly* what I was talking about. Type declarations on function parameters help me to align the code with the thoughts I have about the implicit contract with the function's callers. In the process, it makes that contract more explicit. -Dave From thomas.nuecker at web.de Wed Jul 2 08:35:12 2003 From: thomas.nuecker at web.de (=?ISO-8859-1?Q?Thomas_N=FCcker?=) Date: 2 Jul 2003 05:35:12 -0700 Subject: How to keep a Tkinter-Dialog on top of all other windows? Message-ID: <4b66f6d2.0307020435.345ff4f1@posting.google.com> Hi! I am creating a dialog-box within my application, using tkinter. The problem is the following: After the dialogbox is started, the main application window comes again to top and the dialogbox is covered by the window of the main application and must be "fetched" again via the taskbar to continue. Is there a way to "force" the dialogbox on top of all other windows? (I'm using MSWindows and Python22) The source of my dialogbox-class is the following: class NumberEntry: def __init__(self): import Tkinter from Tkconstants import RIDGE from Tkconstants import BOTH from Tkconstants import BOTTOM from Tkconstants import ACTIVE from Tkconstants import LEFT from Tkconstants import W from Tkconstants import E self.tk = Tkinter.Tk() self.tk.title("My Dialog") frame = Tkinter.Frame(self.tk, borderwidth=2) frame.pack(fill=BOTH,expand=1) label=Tkinter.Label(frame, text="Telefonnummer:") label.pack(fill=BOTH,expand=1) self.entry = Tkinter.Entry(frame, name="entry") self.entry.pack(fill=BOTH,expand=1) box = Tkinter.Frame() w = Tkinter.Button(box, text="OK", width = 10, command=self.OnOk, default = ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Tkinter.Button(box, text="Cancel", width=10, command=self.OnCancel) w.pack(side=LEFT, padx=5, pady=5) box.pack() # try to keep focus on current dialog box self.tk.focus_set() self.tk.mainloop() def OnOk(self): self.result = self.entry.get() self.tk.destroy() def OnCancel(self): self.tk.destroy() result = "" From tjreedy at udel.edu Thu Jul 31 15:19:01 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2003 15:19:01 -0400 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <1-ScnVtGQNEx9rSiXTWJkQ@comcast.com> "Anthony_Barker" wrote in message news:899f842.0307310555.56134f71 at posting.google.com... > What to you think python largest compromises are? A compromise is an in-between position or decision. Example: wife wants to go to a horse show, husband to an auto race, so they compromise and go to a horse race. > The three that come to my mind are significant whitespace, dynamic > typing, and that it is interpreted - not compiled. The first two are end-point positions, not in-between compromises. The third is a matter of definition and implementation. CPython compiles to version-dependent but otherwise portable PyCode. PyRex, Weave, and Psyco all compile to C or machine code. > These three put python under fire Anything can bo put under fire by anyone who wants to shoot. > and cause some large projects to move off python or This sort of statement remains an opinion or impression until backed by evidence. > relegate it to prototyping. This is one of its intended uses. > Whitespace is an esthetic preference that make Andrew Hunt and David > Thomas (of Pragmatic Programmer fame) prefer Ruby. Evidence? And I mean evidence that whitespace is *the* reason and not just a convenient summary of an overall esthetic preference. In any case, so what? Different strokes for different folks. Do they also use indentation for human readers? If so, they have assigned themselves the task of keeping brackets and indents in sync so that human and machine 'see' the same structure. I see two good uses for brackets: 1. machine-generated code never intended for human eyes 2. redundancy for transmission error detection by a processor that compares brackets and indents and raises a flag on mismatches. A compromise in the area of structure indication would be accepting either brackets or indents or both. > Yahoo groups moved from python to C due to dynamic typing. Evidence? Evidence as to what exactly happened (it is not common knowledge that I know of) and that any such change was a reasoned technical decision and not politics. If memory serves me right, Guido has tried a couple of compromises to slightly limit dynamicity that he could not see much use for and has backed off at least partly when current users presented use cases that the change would break. > Non-compiled - obviously there are times when performance matters more > than other things. Google I believe uses python to prototype (or used) > and then turns to c++ for heavy lifting. This is a simple matter of economic tradeoff. A week of programmer time costs roughly the same as, say, a year of pc time. A roaring success like Google has hundreds (thousands?) of servers around the world running the same relatively stable code. Faster code means machines not bought, installed, and maintained. But I imagine that their main production code is pretty far out on the frequency-of-use curve. Terry J. Reedy From klapotec at chello.at Thu Jul 31 10:13:33 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 31 Jul 2003 14:13:33 GMT Subject: [Newbie] FAQ? References: Message-ID: On Thu, 31 Jul 2003 15:08:07 +0200, psycho_78 at libero.libero.it (Simone Finotti) wrote: >hi all, >is there a FAQ for this NG? > http://www.faqs.org/faqs/by-newsgroup/comp/comp.lang.python.html Have you heard of Google? --Christopher From mwh at python.net Tue Jul 29 07:58:23 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jul 2003 11:58:23 GMT Subject: Documenting properties created by property() properly References: Message-ID: <7h3brvdk0je.fsf@pc150.maths.bris.ac.uk> Brian Dam Pedersen writes: > Hi Group > > I'm trying to figure out the proper way to document object properties > created with property() using the LaTeX styles coming with python. The > closest thing seems to be \begin{memberdesc}, but that seems like a > clumsy way to express it. Is there any "official" way to do this ? I doubt it. What is the problem with memberdesc? Cheers, mwh -- LINTILLA: You could take some evening classes. ARTHUR: What, here? LINTILLA: Yes, I've got a bottle of them. Little pink ones. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From Simon.Wittber at perth.maptek.com.au Wed Jul 9 02:06:00 2003 From: Simon.Wittber at perth.maptek.com.au (Simon Wittber (Maptek)) Date: Wed, 9 Jul 2003 14:06:00 +0800 Subject: Possible to install from CD using distutils? Message-ID: <20E0F651F8B82F45ABCBACC58A2D995B032AEC@mexper1> Try this command. It will let you write to a CD drive. mount -o rw /dev/cdrom /mnt/cdrom Regards, Sw. From grante at visi.com Wed Jul 23 10:14:14 2003 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2003 14:14:14 GMT Subject: python assignment References: <3f1e92bc$0$161$a1866201@newsreader.visi.com> <3F1E964E.BFD7513F@engcorp.com> Message-ID: <3f1e9836$0$171$a1866201@newsreader.visi.com> In article <3F1E964E.BFD7513F at engcorp.com>, Peter Hansen wrote: > Grant Edwards wrote: > >>> The examples you gave showed that integers share identity with >>> other integers of the same value, while floats do not. >> >> I believe that's only true for small integers, isn't it? > > Google finds "LOADI - a fast load instruction for small positive integers > (those referenced by the small_ints array in intobject.c)" and checking > that file is left as an exercise to the reader. I'm going to blindly > assume this is directly related to the issue in question... ;-) I think so. As others have pointed out, it's an implementation detail, and the language definition doesn't require equal-valued integer objects to share identity (nor is it prohibited). Programs that rely on that behavior are broken. Python 2.2.2 (#1, Jan 30 2003, 21:26:22) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=2 >>> b=2 >>> print id(a), id(b) 135297000 135297000 >>> a=123456789 >>> b=123456789 >>> print id(a), id(b) 135449020 135449032 -- Grant Edwards grante Yow! I invented skydiving at in 1989! visi.com From bogal2 at comcast.net Sun Jul 13 16:33:32 2003 From: bogal2 at comcast.net (BogAl) Date: Sun, 13 Jul 2003 15:33:32 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: Thanks for the reply, Bernard.... > Mmh...works for me - ActivePython 2.2.2 > Are you sure you downloaded the pyd file corresponding to > your python version? Yes, Python 2.2.2 here. > Running the MS "depends" utility on > csv.pyd reveals that it only needs python22.dll, msvcrt.dll > and kernel32.dll. Are these all on your PATH? > I think they are now.... "...C:\WINDOWS\SYSTEM\python22.dll;C:\WINDOWS\SYSTEM\KERNEL32.dll;\C: \WINDOWS\SYSTEM\MSVCRT.dll;..." > > Traceback (most recent call last): > > File "", line 1, in ? > > import csv > > What's pyshell? did you try from good ole trusty python.exe > in a DOS box? No difference. Still the same error message. Any further help is greatly appreciated. From jdhunter at ace.bsd.uchicago.edu Thu Jul 17 17:55:42 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 17 Jul 2003 16:55:42 -0500 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? In-Reply-To: <5.2.1.1.0.20030717104805.028516c0@66.28.54.253> (Bob Gailer's message of "Thu, 17 Jul 2003 10:51:41 -0600") References: <3f15ca92@shknews01> <5.2.1.1.0.20030717104805.028516c0@66.28.54.253> Message-ID: >>>>> "Bob" == Bob Gailer writes: Bob> [snip] I sure hope you are not writing "yet another winning Bob> lottery number predictor". It is a sad commentary on Bob> mathematics education when individuals belive that one can Bob> predict the outcome of a truly random process based on any Bob> history. I for one certainly won't support any effort to Bob> further mislead people. Granted, but this reminds me of the excellent story when 2 chaos mathematicians went to the Montreal Casino to try and figure out the pattern of the random number generator for the Keno game. After some time, they noticed that the numbers were simply repeating. Apparently there was a defect in the hardware, and when the machines were rebooted, they started with the same random seed. he won $600,000 in three consecutive jackpots. So looking for patterns in the outputs of RNGs is not total folly. Of course RNGs are not "truly random"..... JDH From tl_news at nexgo.de Tue Jul 29 18:03:06 2003 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 30 Jul 2003 00:03:06 +0200 Subject: Bottleneck: easy obscurity "encryption" via xor Message-ID: Hi! I identified a bottleneck in my programs. I just want to "encrypt" data by easy xoring. Ok - that's no encryption at all - I know. But it's hardly readable - and that's enough :-) Just some quick obscurity. It turns out not to be quick at all. I really didn't expect this to be a bottleneck, but it takes quite some time. Here's the code: >$ cat python/EasyCrypt.py >#! /usr/bin/env python >import operator >def xorcrypt(str, salt = 255): > if salt > 255: > raise "Invalid salt! Must be < 255!" > return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, _salt = salt: operator.xor(ord(char), _salt), str), "") xor'ing medium sized-files takes long time. For example a 360 kByte-File takes: >$ time ./just_crypt.py Userdatan/ScanImage01.jpg > bert >real 1m52.138s >user 0m40.320s >sys 1m6.030s on my 2.66 GHz P4 machine! Hmmm, do you have some better implementation ideas? Some optimizing tricks? (Besides coding in C to avoid immutable string problems) I already took the operator module to speed up a bit - but it seems that's not enough... Thanks Tino From max at alcyone.com Tue Jul 15 03:31:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Jul 2003 00:31:41 -0700 Subject: anything like C++ references? References: <3f67hvgi36s7rmtn59rajj2gpir8hhfiph@4ax.com> Message-ID: <3F13ADDD.57BF2969@alcyone.com> Stephen Horne wrote: > The whole point of 'self' is to act as a name for the object (not the > value) so there is no problem in having it behave that way. Its > already special because its implicit, so making it special in this way > too wouldn't be a big issue. > > Implementation detail. Not a fundamental problem. I don't understand what distinction you're making between "object" and "value" in this context. In a dynamically, strongly typed language, I don't see what value -- or, rather, merit -- there is in making the distinction. The value is the object. The object is the value. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Heaven and Hell / Is on Earth \__/ Salt-n-Pepa From davidb at mcs.st-and.ac.uk Tue Jul 29 18:36:39 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 29 Jul 2003 15:36:39 -0700 Subject: PyQt Help and Advice References: Message-ID: <4de76ee2.0307291436.229faecb@posting.google.com> "Keith Jones" wrote in message news:... > Also. as Sybren mentioned, the Qt > tutorial itself should be useful.. Finally, I'll say that the book you > mentioned is excellent, and a wonder source of example code. I liked it > enough that I bought it, and I'm happy I did. There's also a mailing list for PyQt and PyKDE: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde > Good luck with PyQt! The only issues I've had were related to QCanvas not > deleting canvas items (and therefore my program leaking them) if I don't > reuse them. I still haven't figured that out, so I just keep track of the > ones I create and reuse them, in order to prevent memory leaks. This sounds familiar. I wonder if you've tried this solution: http://www.mail-archive.com/pykde at mats.gmd.de/msg02890.html -- http://www.boddie.org.uk/david/Projects/ From drs at ecp.cc Wed Jul 9 16:15:32 2003 From: drs at ecp.cc (drs) Date: Wed, 09 Jul 2003 20:15:32 GMT Subject: .join() question References: Message-ID: "Terry Reedy" wrote in message news:Q4KcnQcI8sgt65GiXTWJiA at comcast.com... > > "drs" wrote in message > news:eo_Oa.14415$BM.4645038 at newssrv26.news.prodigy.com... > > why does > > > > >>> ''.join(lst) > > > > not automatically do > > > > >>> ''.join([str(i) for i in lst]) > > > > ? That is, is there ever a time when one does not want .join to > make > > everything into a string? This seems like reasonable default > behavior, but > > maybe I'm missing something? > > If the members of lst are already str strings, this would be a waste > of time. If they are unicode strings, this would be the wrong thing > to do. Auto conversions are not Python's style. >>> l = [u'abcde', 'fghij'] >>> ''.join(l) u'abcdefghij' this seems to be auto converting the non-unicode to unicode? -d From bhv1 at psu.edu Tue Jul 29 16:54:32 2003 From: bhv1 at psu.edu (Brian Victor) Date: Tue, 29 Jul 2003 20:54:32 GMT Subject: curses and use_default_colors() Message-ID: I am attempting to write a curses-based program. I would like to use the default terminal background rather than a black one (a significant difference with transluscent terminals, regardless of one's opinion of them). It appears that in the C ncurses interface, this is accomplished via use_default_colors() and assume_default_colors(). However, these functions don't seem to have parallels in the python binding. Is there some way to accomplish what I want? Thanks, -- Brian From adalke at mindspring.com Tue Jul 8 18:17:04 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 8 Jul 2003 16:17:04 -0600 Subject: Embedding Python, threading and scalability References: Message-ID: Wenning Qiu: > I am researching issues related to emdedding Python in C++ for a > project. > Has anyone on this list run into the same problem that I have, or does > anyone know of any plan of totally insulating multiple embedded Python > interpreters? Ahh, the Global Interpreter Lock (GIL). Years ago, Greg Stein had a version of Python 1.4 running with no GIL. http://www.python.org/ftp/python/contrib-09-Dec-1999/System/threading.README Search for "free threading" to get more hits on this topic. As I recalled, it slowed down the performance on single-processor/single-threaded machines, so the general take was to keep the GIL. In addition, see http://groups.google.com/groups?selm=mailman.1008992607.2279.python-list%40p ython.org&oe=UTF-8&output=gplain Tim Peters: ] The prospects for another version of that grow dimmer. Everyone (incl. ] Greg) has noticed that CPython internals, over time, increase their reliance ] on the thread-safety guarantees of the global interpreter lock. The only solutions I know of are explicit multi-process solutions: - a generic system, like XML-RPC/SOAP/PVM/MPI/CORBA, on which you build your own messaging system - use systems like Pyro or Twisted, which understand Python objects and implement 'transparent' proxying via network communications - use POSH, which does the proxying through shared memory (but this uses Intel-specific assembly) Andrew dalke at dalkescientific.com From gerrit.muller at embeddedsystems.nl Wed Jul 16 03:16:51 2003 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Wed, 16 Jul 2003 09:16:51 +0200 Subject: link collection References: <3F140634.2010201@embeddedsystems.nl> Message-ID: <3F14FBE3.5020509@embeddedsystems.nl> Steven Taschuk wrote: > Quoth Gerrit Muller: > [...] > >>This link collection is bootstrapped by proudly stealing the links >>mentioned in Dr Dobbs Python URL by Steven Taschuk. Many thanks to Steven. > > > Though I appreciate the comment, I should point out that the > author of Python-URL changes from time to time -- at present it's > Irmen de Jong, not me. The editor and general overseer of the > various authors is Cameron Laird, who surely deserves those thanks > more than I do. > Steven, thank you for this addition. I have updated the page: this particular text is extended and moved to a new section "Acknowledgements". A short search with Google provided indeed many more authors: Grant Edwards, Gordon McMillan, David Ascher, Paul Boddie, Quinn Dunkan, Moshe Zadka, Oleg Broytmann, Emile van Sebille, Cameron Laird, Fredrik Lundh, Steve Holden, Skip Montanaro, Paul Prescod, Andrew M. Kuchling Even this list might be incomplete. Kind regards, Gerrit -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From bokr at oz.net Wed Jul 30 11:18:00 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Jul 2003 15:18:00 GMT Subject: while (assignment): References: <840592e1.0307291501.42b1156e@posting.google.com> <2259b0e2.0307300419.124c040b@posting.google.com> Message-ID: On 30 Jul 2003 05:19:07 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >Sybren Stuvel wrote in message news:... >> Hannu Kankaanp?? enlightened us with: >> > Typically this is done by breaking out of the loop: >> > >> > while True: >> > info = mydbcursor.fetchone() >> > if not info: >> > break >> > print "Information: "+str(info) >> >> This was my first solution as well. Kinda ugly, though. >> >> Sybren > >When I started using Python I though the "while 1" idiom was horrible. >Now I think it is quite Pythonic. Few months can change your mind! ;) > >You may also use this form, which you may find more readable: > >while 'info': > info = mydbcursor.fetchone() > if not info: break > print "Information: "+str(info) > >Remember, 'info' is another spelling of True! >This is a trick anyway, and I always use "while 1" in my code, it is >the idiomatic way at the end. > > Michele Using a one-line class definition and instantiation (and silly aliasing) >>> keeping = info = type('',(),{'__call__':lambda o,*a:a and setattr(o,'v',a[0]) or o.v})() >>> fun = iter((1,5,0,9)).next >>> while keeping(fun()): print info() ... 1 5 which would let you spell it while keeping(mydbcursor.fetchone()): print "Information: %s" % info() ;-) Regards, Bengt Richter From bignose-hates-spam at and-zip-does-too.com.au Tue Jul 22 07:27:24 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 22 Jul 2003 21:17:24 +0950 Subject: How to save web pages for offline reading? References: Message-ID: On 21 Jul 2003 23:38:12 -0700, Will Stuyvesant wrote: >> [Sybren Stuvel] >> do "man wget" > There is no "man wget" on Windows :-) Another good reason to use Cygwin: which comes with man pages and a 'man' command. -- \ "As I bit into the nectarine, it had a crisp juiciness about it | `\ that was very pleasurable - until I realized it wasn't a | _o__) nectarine at all, but A HUMAN HEAD!!" -- Jack Handey | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ianb at colorstudy.com Wed Jul 30 11:16:53 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2003 10:16:53 -0500 Subject: Web tool kit : pro - cons ? In-Reply-To: <240b1020.0307292228.35cc8d08@posting.google.com> References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f24f3f7@shknews01> <240b1020.0307292228.35cc8d08@posting.google.com> Message-ID: <1059578213.12751.94.camel@lothlorien> On Wed, 2003-07-30 at 01:28, Jeffrey P Shell wrote: > Database Abstraction is another key issue. Zope gets points here not > only for the built in ZODB database, but for SQL Methods / Database > Adapters. There is nothing in Zope that is tied to Postgres, MySQL, > Oracle, Sybase, SQLite, etc. Yet it's always been able to use any of > them since before it was Zope. There's just a nice simple abstraction > layer that one seldom has to think about. Praising SQL Methods? Maybe I've been missing something, but SQL Methods seem really primitive to me, certainly worse than the DB API (though I suppose they preceded the DB API). The transaction stuff is convenient -- if sometimes mysterious (like so many Zope things). But it's not solving a terribly difficult problem. > Other tools try the O-R > mapping route for abstraction with varying degrees of success. > SkunkWeb has PyDO, Webware has one (I can't remember its name right > now). Zope's model is nice because it's not intrinsic to Zope that > you use SQL - it's just a nice model to plug into if you need it, when > you need it. I don't know how other toolkits stack up here. Some may > just say "go find a Python adapter that works for you and do what you > want with it", which seems to be as good of a way to go as any. PyDO and MiddleKit (Webware's) are both independent of their frameworks (it's kind of unfortunate that they appear to be tied, though), as are the other ORMs (like my SQLObject). All three provide something approximating business objects built around database rows. My impression of Zope's SQL Methods is that they encourage distinctly un-OO style of programming, and instead everything is done through a heap of ad hoc queries and eclectic query results. At least, that's the code I've encountered, and it's taken discipline to avoid doing the same thing -- maybe there are better ways to use SQL Methods than what I've been exposed to. (If so, it would be better if Good Zope Style was documented, not just learned through wisdom born of failure -- but I haven't found that sort of documentation for Zope yet). Ian From sNO_SPAMpinard at zoominternet.net Sat Jul 12 13:04:03 2003 From: sNO_SPAMpinard at zoominternet.net (Steve Pinard) Date: Sat, 12 Jul 2003 13:04:03 -0400 Subject: [OFF TOPIC] Re: The "intellectual property" misnomer References: Message-ID: <3f103fa7_6@corp.newsgroups.com> This newsgroup is for postings related to the computer language Python. Your discussion about the meaning of intellectual property may best be served in a newsgroup for topics related to the law. (In other words, you all should know better. Take it outside.) -----= 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 Kepes.Krisztian at peto.hu Thu Jul 17 04:01:47 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Thu, 17 Jul 2003 10:01:47 +0200 Subject: Linux - python vs sh Message-ID: Hi ! I want to list my rpm database to file with this: #!/bin/sh file="./allrpm.txt" nr=1 for rpmname in `rpm -qa` do echo '>>>>>>>>>>>>>>>' >>$file echo "$nr." >>$file echo "Name: $rpmname" >>$file echo "" >>$file info=`rpm -qi $rpmname` echo "$info" >>$file echo "" >>$file nr=`expr $nr + 1` done But it have two error: 1. the $nr is not incremented 2. the rpm detailed info is not writed to the file I want to change it to py code. I see an perl code: @rpmlist= rpm -qa It is get the rpm's output. But how I get the rpm's output in my py program ? list= rpm -qa ???? Please send me an simple example ! Thx: KK From klappnase at freenet.de Sat Jul 19 21:41:25 2003 From: klappnase at freenet.de (klappnase) Date: 19 Jul 2003 18:41:25 -0700 Subject: tkFileDialog without a parent window References: Message-ID: <9a410299.0307191741.501e42@posting.google.com> Stephen Boulet wrote in message news:... > I'm using the following code to get a file name: > > import tkFileDialog > tkFileDialog.askopenfilename(filetypes=[("HDF Files", ".hdf")]) > > How can I do this without an empty tk window popping up and hanging around > after the dialog is closed? Thanks. > > -- Stephen Hi, you may use the withdraw() method on the root window: root = Tk() root.withdraw() somefile = tkFileDialog.askopenfilename(filetypes=[("HDF Files", ".hdf")]) ... Cheers michael From tebeka at cs.bgu.ac.il Wed Jul 2 08:07:43 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 2 Jul 2003 05:07:43 -0700 Subject: arbitrary long integer aritmetics References: Message-ID: <33803989.0307020407.1ad80a38@posting.google.com> Hello Leo, > is there a python module around allow using arbitrary long integers? > > i.e. the result of an integer operation is as long as necessary, so that a*b > never produces an overflow error. (but rather an out of memory error ;-) ) It's built in: >>> from operator import mul >>> def fact(x): return reduce(mul, range(2, x + 1), 1) >>> fact(100L) 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L HTH. Miki From peter at engcorp.com Sun Jul 6 22:48:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Jul 2003 22:48:26 -0400 Subject: help! - cmd line interpreter gone "dumb" References: Message-ID: <3F08DF7A.99CC11F@engcorp.com> Tim wrote: > > For the record... > > if I don't define any paths for Python, it naturally knows were to go for > the core + libraries. > but, if you define the PYTHONPATH in the environment--only those directories > are searched. It was probably the late night that had me forget when I > changed things (funny--its seemed to work for a long while, but the changes > may not have been reflected if I had the same command window open the entire > evening (this was the case, I think). This wasn't likely the cause of all your problems. Try defining that environment variable again, and check whether "import sys" really does give a syntax error. If it does, it's something else, because all PYTHONPATH should do is let you add more stuff to the standard search path. (If you can get import sys to work, type "sys.path" to see what is defined, and you'll see that the stuff in PYTHONPATH merely goes at the front, just after the '' item which means the directory from which the script runs.) If you are really getting a syntax error, paste the full traceback into another posting so we can see what it is. Maybe you were typing with CAPSLOCK on? Or you had a module of your own in the current directory, called sys.py, and it contained a syntax error, so when you imported it you got confused? Definitely something other than PYTHONPATH, I think. -Peter From mcherm at mcherm.com Wed Jul 16 08:47:53 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 16 Jul 2003 05:47:53 -0700 Subject: Python Quiz Message-ID: <1058359673.3f154979ded2a@mcherm.com> richardc writes: > Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's > fixed format syntax. I can only think of Python and FORTRAN off the top of > my head which use whitespace as part of the syntax. Definitely NOT. Without addressing the question of HOW Python came by the idea of using indentation to indicate block structure, it clearly couldn't have been from Fortran, because what Python does and what Fortran does are COMPLETELY different. In Fortran, starting lines in particular columns is meaningful (as are other particular characters in particular leading columns). In Python, particular columns have NO meaning. In fact, I would venture to say that it is NOT whitespace that is "significant" in Python... it's INDENTATION. The distinction is significant, because humans are very poor at reading whitespace (the presense or absence of it yes, but the amount is something we're not good at reading), but we find indentation to be a *very* readable way to mark block structure (in practically every language which doesn't (like Fortran) prohibit indentation, it is a convention adhered to universally ). There's also the fact that "lines" (statements) are defined by line breaks in Python -- but I rarely hear complaints about this, since most programmers mentally chunk up code into "lines" anyway. Of course, I'm not suggesting that whitespace is *meaningless* in Python outside of indentation... Python is much like C (and many, many others) in that regard. After all, in C "y=x+ ++z" and "y=x++ +z" are quite different things. And in both Python and C "x=abc" is legal, but "x=a bc" is not. So I would say MOST languages make the presence or absence of whitespace significant... and that's a good idea, since it helps humans "tokenize" the code they read. Python uses newlines to indicate where new "lines" (statements) begin... not usually a controversial convention. Finally, most PROGRAMMERS use indentation to indicate block structure, but Python differs from most languages in that the Python parser uses the indentation level as syntax for blocks, while most languages don't. And Python doesn't[1] care about the AMOUNT of white space (independent of indentation level) which is a good thing, because humans find that difficult to read. -- Michael Chermside [1] Unless you mix tabs and spaces. Don't do that. Use tabnanny if you need to. From cfunk at pantechnica.com Thu Jul 10 21:42:57 2003 From: cfunk at pantechnica.com (Craig Funk) Date: Thu, 10 Jul 2003 20:42:57 -0500 Subject: Zope problem: objectValues('Folder') In-Reply-To: <3F0D5479.6090401@gmx.de> Message-ID: The objectValues() will only return a list of the folders if it is called from with a DTML Method. If you are calling it from within the context of a Document it will not work. The method is called within the context of the folder so everything is fine. That is why it would work in standard_html_header. However a Document has it's own context. Craig On 7/10/03 6:56 AM, "Jens Riedel" wrote: > Max M schrieb: > >>> I used the objectValues('Folder')-method in a DTML-method named >>> 'navigation'. I include in a >>> 'standard_html_header' DTML method, and this standard_html_header is >>> used in the index_html document. > >> Does it work if you render only the navigation method? > > Yes, that's what confuses me. The navigation works completely if I call > it with http://localhost:8080/ZopeZoo/navigation, also the > standard_html_header does. But when I include it in the index_html, the > list of folders vanishes, the rest of navigation works. > > >> Also, you will find it much easier to find replies to Zope questions on >> the zope mailing list. > > thanx for the hint, I'll try it. > > regards, > Jens > > -- Craig Funk PanTechnica Corporation 952-368-3079 From webmaster at watchtow3rDOTorg.pl Tue Jul 8 05:14:10 2003 From: webmaster at watchtow3rDOTorg.pl (Jaroslaw Zabiello (3->e & DOT->.)) Date: Tue, 08 Jul 2003 11:14:10 +0200 Subject: Python vs PHP References: Message-ID: On Mon, 07 Jul 2003 13:47:00 +0300, Catalin wrote: >Can Python replace PHP? Sure. Look at http://spyce.sourceforge.net >Can I use a python program to make an interface to a mysql 4.X database? Of course, you can. http://www.python.org/sigs/db-sig/ E.g. http://dustman.net/andy/python/MySQLdb_obsolete >If that's possible where can I find a tutorial? http://www.python.org/doc/Newbies.html http://www.python.org/doc/current/ http://www.python.org/cgi-bin/faqw.py -- JZ From trentm at ActiveState.com Wed Jul 23 15:37:49 2003 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 23 Jul 2003 12:37:49 -0700 Subject: Getting started with win32pdh... In-Reply-To: ; from fmeehan@ctbr.com on Wed, Jul 23, 2003 at 01:19:26PM -0400 References: Message-ID: <20030723123749.C356@ActiveState.com> [Francois Meehan wrote] > Hi all, > > Can someone give me an example on how to use win32pdh module (that > access windows performance counters)? For example, how to retreive the > number of processes running on a win2k server, with the > Objects-Processes counter? > > Any ideas? There are a few examples installed with PyWin32 (or with ActivePython if you got PyWin32 that way): ...\Lib\site-packages\win32\Lib: win32pdhquery.py win32pdhutil.py Trent -- Trent Mick TrentM at ActiveState.com From http Fri Jul 11 11:54:55 2003 From: http (Paul Rubin) Date: 11 Jul 2003 08:54:55 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <87k7apyuor.fsf@pobox.com> Message-ID: <7xr84x83e8.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > Security isn't a big deal -- or rather, securing cookies isn't a big > > deal. > > I don't understand. The problem is that pickles can be constructed > that can damage systems when unpickled, is that right? If that's > true, then surely unpickling cookie data is unsafe, because stuff > coming in from the network has to be regarded as malevolent. Are you > saying that web server environments are sufficiently-well bolted down > that no pickle attack will work? But belt-and-braces is the best > policy, isn't it? The point is that you can use cryptographic signatures to make sure any cookie you receive is one that the server actually sent, before deciding to unpickle it. That means if the attacker constructs a malicious cookie, you never unpickle it. From duncan at NOSPAMrcp.co.uk Wed Jul 23 04:26:48 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 23 Jul 2003 08:26:48 +0000 (UTC) Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88) References: Message-ID: "Ulrich Petri" wrote in news:bfk2cd$ctqfr$1 at ID- 67890.news.uni-berlin.de: >> x = y >> x = z # <-- >> >> is y's reference count decremented (and therefore its __del__ possibly >> called) *before* x is bound to z (or is z bound to x, I don't know the >> correct wording) or *afterwards*? > > No. > 1. its not y's reference count that gets (possibly) decremented but > the-object-y-points-to Correct > 2. in this example noting will be decremented since y never goes out of > scope. Just by assining y to x you dont "invalidate" y. > In this example the reference count of the-object-known-as-y is incremented by the assigment 'x=y' and decremented during the assignment 'x=z'. In answer to the original question, is the reference count decremented before or after the assignment, the answer is 'after'. It has to be after the assignment has completed otherwise there would be a window, accessible during the call to __del__ where 'x' still referred to the original object, but the original object had a reference count of 0. It is usually fairly safe to assume that Python gets elementary things like reference counts right. (Unlike Microsoft whose reference counting on COM objects goes to 0 more than once during their lifetime which can cause pain in free threaded programs.) -- 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 allisonb at terralogicgis.com Mon Jul 14 20:31:47 2003 From: allisonb at terralogicgis.com (Allison Bailey) Date: Mon, 14 Jul 2003 17:31:47 -0700 Subject: Open MS Excel Spreadsheet with Python Message-ID: <000c01c34a68$79b9cda0$0c00a8c0@RHODY> Hi Folks, I'm a brand new Python programmer, so please point me in the right direction if this is not the best forum for this question.... I would like to open an existing MS Excel spreadsheet and extract information from specific worksheets and cells. I'm not really sure how to get started with this process. I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), using Microsoft Excel 10.0 Object Library, then import win32com.client xl = win32com.client.Dispatch("Excel.Application") wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") Then, I get errors when I try the following: sh = wb.worksheets(1) I think I'm missing something fairly fundamental, but I've googled all over the place and can't seem to find anything very introductory about opening and using data from MS Excel using Python. Any suggestions, including places to get more information are welcome. Also, do I need to run the makepy utility every time I run my script? If so, how would I do it from within my Python program, rather than with the GUI in the IDE? Thanks for your help, Allison ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Allison Bailey TerraLogic GIS, Inc. allisonb at terralogicgis.com 425-673-4495 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From claird at lairds.com Tue Jul 1 17:57:30 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 01 Jul 2003 21:57:30 -0000 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: In article <87of0pno5s.fsf at titan.staselog.com>, Edvard Majakari wrote: > >I'm rather interested in (and fond of) unit testing as well as TDD, so I >though to share my opinions. I once discussed TDD with my friend in here, >and the common agreement seemed to be that TDD is not a silver bullet - >often there are types of computational modules that are very hard to unit >test, eg. think of graphical user interfaces or complex systems, where >forking or threading is concerned. . . . While we're all being rational enough to look at bundles of costs and benefits, this observation hints at a different insight: that it's possible to *design* for testability. Yes, GUIs and forking and threading are hard to test. SO DON'T DO THEM. Or, as I prefer, adopt models of GUI and concurrency development that lend themselves to testing. At this point, I should explain what I mean by that. I haven't yet figured out how to say it in less than a book; therefore, all I can contribute for today are the slogans above. If you're in a situation where unit-testing is bad, you're probably in a bad situation. Change your situation. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ianb at colorstudy.com Wed Jul 9 13:34:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 09 Jul 2003 12:34:46 -0500 Subject: Sample Web application (Re: Python vs PHP) In-Reply-To: References: Message-ID: <1057772086.3738.1136.camel@lothlorien> On Wed, 2003-07-09 at 10:26, Daniel Dittmar wrote: > Ian Bicking did something like this with > http://colorstudy.com/docs/shootout.html with a Wiki as the example > application. If there is interest, I would volunteer to copy this into the > Wiki so that it can be more easily extended. I already got Ian's > permissionto do so, but was so far too lazy for it. It might be preferable to do this in CVS somewhere -- it would handle the source files better, and most of the commentary can go in comments. One of the big problems I also had was installation. Many of the frameworks require non-trivial Apache configuration, which hinders experimentation. Actually solving this is significant work, though -- but also something which very much deserves solving. A SourceForge (or equivalent) project might be a good place to start. Ian From vincent_delft at yahoo.com Sun Jul 13 14:07:26 2003 From: vincent_delft at yahoo.com (vincent_delft) Date: Sun, 13 Jul 2003 20:07:26 +0200 Subject: CGIHTTPserver looze PYTHONPATH References: <5c184570.0307130722.2c74879c@posting.google.com> Message-ID: <3f119feb$0$265$ba620e4c@reader0.news.skynet.be> vincent delft wrote: I've found the problem by analysing the CGIHTTPServer.py code. The exec command send the LOCAL env variable instead of the full environemnts. + os.execve(scriptfile, args, os.environ) - os.execve(scriptfile, args, env) > I'm using Python 2.2.2 > the standard cgihttpserver (example given in the python doc). > All HTML and CGI work. > > BUT > > by writing a simple python-cgi script like this : > " > #!/usr/bin/env python > import os > print "%s" % os.environ > " > I've discover that the environement variable are lost. > For example PYTHONPATH is no more present. > > Can you explain me why ? > Does this is a bug ? > How can I keep my PYTHONPATH variable across my python-cgi ? > (I don't want to add os.putenv on top of each python-cgi script) > > Thanks From peter at engcorp.com Tue Jul 29 09:23:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jul 2003 09:23:17 -0400 Subject: variable assignment in "while" loop References: Message-ID: <3F267545.65B41378@engcorp.com> Sybren Stuvel wrote: > > Is it possible to use an assignment in a while-loop? I'd like to do > something like "loop while there is still something to be read, and if > there is, put it in this variable". I've been a C programmer since I > was 14, so a construct like: > > while info = mydbcursor.fetchone(): > print "Information: "+str(info) > > comes to mind. Unfortunately, this doesn't work. Is there a similar > construct in python? Yes: while 1: info = mydbcursor.fetchone() if not info: break print "Information: " + str(info) -Peter From intentionally at blank.co.uk Sun Jul 13 23:51:10 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 04:51:10 +0100 Subject: anything like C++ references? References: Message-ID: On Sun, 13 Jul 2003 22:42:21 GMT, "Bryan" wrote: > >> 3. Why is there no way to reference an immutable object via a >> pointer, other than stuffing it into a mutable object designed for >> some purpose other than simple pointer behaviour? >> > >>>> a = (1, 2, 3) >>>> b = a >>>> id(a) >15471760 >>>> id(b) >15471760 >>>> print b[1] >2 >>>> > > >i just referenced an immutable object via a "pointer" and i __did_not__ >stuff it into a mutable object as you say. >a and b "point" to the same object. Technically, but what is the point? You can't do pointer-style things with it. You can't change the object in any way without changing the id, and you can't use the mechanism to, for instance, allow 'var' parameters. In short, you are showing evidence of the use of pointers internally within Python, but that is not the same as providing pointer-like semantics. From amk at amk.ca Sun Jul 20 20:12:49 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 20 Jul 2003 19:12:49 -0500 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xllus94t8.fsf@ruckus.brouhaha.com> Message-ID: On 20 Jul 2003 16:06:11 -0700, Paul Rubin <> wrote: > one another. Otherwise the ballot would be a voting receipt, > something that a good voting system should not provide. Search for > "receipt-free voting" in Google to see what a big problem this is for > computerized systems. On the other hand, given the ready availability of cellphones with digital cameras, even in a paper-based system you can now make your own voting receipt while you're still in the voting booth. Not clear what can be done about this... perhaps you'll have to hand in your cellphone when voting, and go through an X-ray system to prove you don't have it. --amk From jjl at pobox.com Tue Jul 8 09:16:31 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Jul 2003 14:16:31 +0100 Subject: A story about Python... sort of References: Message-ID: <87wuetp39s.fsf@pobox.com> "Russell Reagan" writes: > "John J Lee" wrote: > > > A Google result (appropriately enough, given the origin of > > the name Google) suggested 10**120 > > 10**120 is the estimate of "paths", or "games", not "positions". The > estimate of unique positions is 10**40, give or take. I don't recall whether [...] Yeah. The previous couple of lines you snipped from my post: | attempting to work out the number of chess games is that my undergrad ^^^^^^^^^^^^^^^^^^^^^ | maths books are currently propping up the monitor I'm using to write this | <0.5 wink>. A Google result (appropriately enough, given the origin of | the name Google) suggested 10**120, and I seem to have a number in my head John From whisper at oz.net Mon Jul 21 12:45:29 2003 From: whisper at oz.net (David LeBlanc) Date: Mon, 21 Jul 2003 09:45:29 -0700 Subject: COM interface to the Python interpreter In-Reply-To: Message-ID: Does \Python22\Lib\site-packages\win32com\HTML\PythonCOM.html help? You might also want to look at \Python22\Lib\site-packages\win32comext\axscript\server\axsite.py David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Christian Knoblauch > Sent: Monday, July 21, 2003 7:14 > To: python-list at python.org > Subject: COM interface to the Python interpreter > > > Hello all, > > under Win32 it is possible to use Python as a scripting language > inside ASP > pages (win32lib package), so there must be a COM interface to the Python > interpreter. > > I like to use this interface instead of writing my own COM server > to invoke > Python scripts from COM aware languages, unfortunately i can not find the > type-library for this interface. > > Can one provide this information (perhaps with an litle example) ? > > Thanks in advance ! > > By, > Christian > > > -- > http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Wed Jul 30 10:05:51 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Jul 2003 10:05:51 -0400 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: <67fdivk9iu0q1p7nc8smfj1miip3cbvobf@4ax.com> Message-ID: In article , Jeff Epler wrote: >On Tue, Jul 29, 2003 at 07:29:19PM +0100, Marc Wilson wrote: >> In comp.lang.python, aahz at pythoncraft.com (Aahz) (Aahz) wrote in >> :: >> >> |Fair enough. Note carefully that I said "submit a patch" -- that >> |doesn't guarantee that the patch will be accepted, and it's quite likely >> |that it won't be. But "submit a patch" is usually a good way to get >> |people to shut up. ;-) >> >> Shame it doesn't work in *all* newsgroups, eh? > >I'll have you know that I've submitted a number of Python patches that >were clearly bad ideas. In fact, I'm a little hurt that Aahz doesn't >think of me as "that guy who often posts or submits horrible patches >and won't shut up". I'm not sufficiently involved with the actual development process to hold such an opinion. ;-) (Despite my regular comments on python-dev, I don't contribute code because SF refuses to make changes to allow Lynx to work correctly.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From sross at connectmail.carleton.ca Thu Jul 31 17:15:26 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 31 Jul 2003 17:15:26 -0400 Subject: list indexing References: Message-ID: "Matthew" wrote in message news:ec1162c7.0307311153.26d1b999 at posting.google.com... > Hello, I am rather new to python and I have come across a problem that > I can not find an answer to any where I my books. What I would like to > know is if there is a way to get the index number of a list element by > name. Sort of the inverse of the .index() method. Perhaps I've misunderstood, but it looks like you want: >>> words = ['this', 'is', 'a', 'list'] >>> words.index('list') 3 which is, of course, not the inverse of .index() (but .index() itself). In general, if you use this, you'll either need to be certain that the item is indeed in the list, or nest the call in a try/except like so: >>> try: ... index = words.index('list') ... except ValueError: ... pass # or whatever you want to do when the look-up fails ... >>> index 3 HTH Sean From Robert at AbilitySys.com Tue Jul 15 12:21:40 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Tue, 15 Jul 2003 09:21:40 -0700 Subject: Stop Python from exiting upon error in Windows References: <3F136BEA.5B56562@engcorp.com> Message-ID: Ok, I figured out the IDLE block indent (duh - RTFMenu), and now it works great in DOS. Again, thanks to all who helped. However, I'd still like to know how to determine what environment I'm running under inside my code. Any suggestions? - Robert wrote in message news:vh6v443q2fjab3 at corp.supernews.com... > Thanks! I'm getting closer to what I want, but it raises two questions: > > 1. Is there an IDLE keystroke to indent a block of code? (just putting try: > at the start of my program causes an error, expecting an indented block to > follow which is my entire program!) > > 2. Is there a way to tell the environment I'm running under (python > interpreter, IDLE window, or other)? I'd like to put a pause at the end of > my program if and only if I'm running under the python.exe DOS-like > program... > > - Robert > > "Peter Hansen" wrote in message > news:3F136BEA.5B56562 at engcorp.com... > > Tom Plunket wrote: > > > > > > Or- catch the error in your mainline, and do a sys.raw_input() > > > call on exception. > > > > Tom meant just "raw_input()", which is a builtin, rather than > > sys.raw_input which does not exist, of course. > > > > To answer your question in the other reply, yes, you can > > nest exceptions. If you have a try/except and the raw_input > > in the except, however, you won't see any exception traceback > > printed at the console so you'll need something like the > > traceback module and one of the functions from it, like > > traceback.print_exc(). > > > > -Peter > > From selwyn at home.net.nz Mon Jul 14 02:58:46 2003 From: selwyn at home.net.nz (selwyn) Date: Mon, 14 Jul 2003 18:58:46 +1200 Subject: timeout on os.popen3? In-Reply-To: <1058116964.113730@yasure> References: <1058116964.113730@yasure> Message-ID: <4wsQa.4778$9f7.548299@news02.tsnz.net> > On the other hand, if you don't mind writing to disk files instead, that > will completely eliminate this aspect of your problem. thanks worked perfectly - classic case of not seeing the forest for the trees! From tim.one at comcast.net Thu Jul 17 14:28:09 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 17 Jul 2003 14:28:09 -0400 Subject: anything like C++ references? In-Reply-To: Message-ID: [Stephen Horne] >> Anyway, Algol and Fortran apparently (I didn't know this until today) >> *always* used call-by-reference. [Terry Reedy] > Not true (about Fortran). I vaguely remember (about 1980) when IBM > Fortran switched from one calling convention to another. I initially > missed the one-line change in the manual update sheets. A working > program started giving strange results until I finally figured out > what was going on and then found the one line 'announcement'. Yes, many Fortran implementations used call-by-value/result, and that's fine by Fortran's rules. The primary difference lies in whether assigning to formal argument X appeared to change the value of formal argument Y too, while you were still in the subroutine with those formal arguments, when the caller passed the same variable as actual argument in both the X and Y positions. In CBR, changes are instantly visible via aliases; in CBVR, they're not. The Fortran standard finessed this simply by declaring programs which relied on either specific behavior to be non-conforming programs ("undefined"). Algol's history is a lot more complicated too, and, indeed, the infamous "call by name" came out of what was probably a mistake in the Algol 60 specification. From staschuk at telusplanet.net Tue Jul 1 14:26:35 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 12:26:35 -0600 Subject: Good code patterns in Python In-Reply-To: ; from hwlgw@hotmail.com on Tue, Jul 01, 2003 at 02:49:54AM -0700 References: Message-ID: <20030701122635.A15807@tibia.amotlpaa.bogus> Quoth Will Stuyvesant: > If you know that your source code is going to be used > later by others, then I feel that code with the pattern: > > if some_condition: > some_name = some_value > else: > some_name = other_value > > is often a mistake. Much better, safer, would be: > > some_name = some_value > if not some_condition: > some_name = other_value I join the Ms in disagreeing strongly. The visual parallelism of the first reflects the conceptual parallelism of the two cases, while the second obscures it. > Because those people reusing your code might decide to > change or adapt the "if" part of the first example. Or > the "else" part for that matter. And then they could end > up with "some_name" being undefined, crashing other code > maybe 1000's of lines away. This could happen for example > because they use exceptions in the "if" part that jump out > of it, etc. I assume you're not speaking of local variables here -- a function thousands of lines long would be unconscionable. Presumably you're speaking of attributes, and the danger is that an exception in one branch would cause the object's invariants be broken. But I don't see how this would happen in practice, in a way which would (a) leave the attribute undefined and (b) imply to the caller that everything was fine. Do you have an example? (Much more serious and more common is the danger that after an exception is raised, the function has done half its work and left the object in a broken state. But this has nothing to do with what you're talking about.) > There is the small overhead of assigning something twice Too minor to worry about: $ timeit -s'def foo(): global a; a = 1' 'foo()' 100000 loops, best of 3: 5.51 usec per loop $ timeit -s'def foo(): global a; a = 1; a = 1' 'foo()' 100000 loops, best of 3: 6.1 usec per loop If I'm running the code a million times, and everything else in the loop takes less than a microsecond, this might be worth thinking about. -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From davidcfox at post.harvard.edu Tue Jul 22 17:13:28 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 22 Jul 2003 21:13:28 GMT Subject: How do I get more events from a wxListCtrl in a panel? In-Reply-To: References: Message-ID: bmoore at integrian.com wrote: > Hello. > > I am working on an application using wxPython that includes a panel > with a wxListCtrl populated with data received from a LAN attached > database. > > I want the wxListCtrl panel to be loaded with a small amount of data > initially. When the user moves the vertical scrollbar or press PageUp > or PageDown, I want to load the list view with new data from the > database. I only want to load the wxListCtrl with a subset of the > database data at a time so the list view is responsive and will allow > for handling large databases. > > The problem I am having is how to get events from the scrollbars or > the PageUp/PageDown keys, etc. I can get events from selecting items, > etc. Use a virtual list control (style wxLC_VIRTUAL) which doesn't contain any data, but invokes callbacks to retrieve only those records which are currently visible. See the example in the demo. David P.S. for wxPython specific questions, you will probably find a bigger audience on the wxPython-users list (see http://www.wxpython.org/maillist.php) From smoret-google at genocide.net Sat Jul 12 20:46:26 2003 From: smoret-google at genocide.net (Steve Moret) Date: 12 Jul 2003 17:46:26 -0700 Subject: python scripting game The Temple Of Elemental Evil update References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:... > Actually, you don't have to pay to use the RPG Vault boards (vnboard), > though you do if you want extra features. > > I've talked to Guido privately about this, and intend to ask Tim Cain > (Project Lead) or Steve Moret (Lead Programmer) if they would be willing > to write a piece about the use of Python in ToEE. I'd be overjoyed to write up a little article on our use of Python in ToEE. I believe Vampire: The Masquerade: Bloodlines is also using Python for scripting. We both are taking slightly different approaches to its use, and in retrospect I'd love to rip out our current implementation and redo it a little better. I'll try and remember to send you or Guido an e-mail when we finish the project to get the ball rolling on this. Right now we're deep into crunch mode and if thats not bad enough, have people pulled away frequently for PR related issues. I'm thinking (more hoping really) we should be done and relaxed around September 1st. From heikowu at ceosg.de Fri Jul 18 02:43:11 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 18 Jul 2003 08:43:11 +0200 Subject: How do I get info on an exception ? In-Reply-To: References: Message-ID: <1058510591.593.5.camel@d168.stw.stud.uni-saarland.de> > How do I get the "(11004, 'host not found')" part? > More importantly, where is the answer documented that I should > have looked? Look at the traceback module from the Python standard library. If you just wish to print the exception, do the following: import traceback try: nosuchobject except: traceback.print_exc() HTH! Heiko. From steve at ferg.org Tue Jul 22 08:04:59 2003 From: steve at ferg.org (Stephen Ferg) Date: 22 Jul 2003 05:04:59 -0700 Subject: Python & Perl in Wall Street Journal Message-ID: Seen in the Wall Street Journal, Monday, July 21, 2003, page B1. Lee Gomes' "Portals" technology column: "Two Men, Two Ways to Speak Computerese and Two Big Successes". This is a brief, non-technical story on Guido von Rossum, inventor of Python, and Larry Wall, inventor of Perl. I don't think this is available online unless you are a paid subscriber to the WSJ online edition. So here are a few quick quotes and a mini-review. "They live a few dozen miles from each other, have strikingly different backgrounds and world views, but in their own separate ways they have created computer languages among the most important in the world." "Over the past decade, ... scripting languages have come to rival full-blown languages such as C and Java in power and performance. But they've kept the ease of use that was their main attraction in the first place. Hence their popularity." "As the most popular of all the scripting languages, Perl and Python compete with each other for mind share among the same communities of programmers. The competition is good-natured, like the fake-Buddhist Python Web site that tells how 'the origin of suffering lies in the use of non-Python.'" Mr. Gomes is right on the mark when he notes that "computer languages have distinct personalities", but I think he misses the mark when attempting to capture and contrast the personalities Perl and Python. "Perl is famous for being permissive, with no right or wrong way of accomplishing a task. Python by contrast, is considered more rigid an exacting." I think it would have been more accurate to contrast an eclectic grab-bag approach to language design with a clear, consistent design philosophy. The article goes on to contrast the characteristics of the languages with the personalities of their developers. Larry Wall "gatekeeper of the undogmatic Perl is a devout Christian." In contrast, Guido, "started working on the my-way-or-the-highway Python as a typical resident of the famously freewheeling city of Amsterdam." It would have been just as easy to paint the languages as being highly consistent with the personalities of their inventors. One might observe, for instance, that Perl is extremely conservative. It is unwilling to abandon any of the features of its multiple forebears. Like Genesis with its E and Y sources, Perl is composed of pieces of its predecessors, stitched together even when they offer differing approaches to the same subject. Python, in contrast, is genuinely innovative. How many other languages use indentation as a control structure? In any case, Mr. Gomes has written a very readable column that raises the name-brand awareness of Perl and Python for a non-technical audience, and for that he deserves a big round of applause from the Python, Perl, and open-source communities. -- Steve Ferg (steve at ferg.org) From 2002 at weholt.org Thu Jul 3 13:17:55 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 3 Jul 2003 19:17:55 +0200 Subject: Python is a gem, you need to keep pushing it .... References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: I've been a hardcore python evangelist for 4-5 years, but in my experience most developers are conservative when it comes to programming languages. They tend to stick to what they know and avoid everything else. Especially coders using compiled languages like Delphi/Pascal. They know some VB or Perl and laugh when I bring up Python. But don't loose faith. Thomas "delphiro" wrote in message news:mailman.1057242668.12614.python-list at python.org... > Same story here, > > My company primarily uses Delphi (Object Pascal) which is actualy a nice development language / IDE but with linux as a rising star and Kylix as a nasty and not-so-friendly-and-platform-indepandent Delphi-clone we have decided to use Python for a number of small projects. As a python addict I really hope this works out! No offence, but I'd rather be using Emacs and Python than the Delphi IDE. It is so much more fun and it runs on Linux *and* Windows (ok and more.. but those are our target OS'es). > > We now have a team of 4 Python addicts trying to convince our bosses and the 30+ Delphi developers. I realy hope this works out :-) > > Regards, > Rob > > -- > [-------------delphiro-------------] > [-- http://pyciv.sourceforge.net --] > [----------------------------------] > From johnroth at ameritech.net Sat Jul 5 16:38:53 2003 From: johnroth at ameritech.net (John Roth) Date: Sat, 5 Jul 2003 16:38:53 -0400 Subject: Least used builtins? References: Message-ID: Reducing the number of builtins doesn't seem like the right direction. I'd prefer to see something in the official documentation that tries to bring some conceptual order to the builtins. While my mind *likes* to read down a list of dispariate things and try to bring some order out of the mess, I know that others are put off by the task. For example: Functional Programming: map() reduce() filter() itertools module zip() Mathematics and similar: abs() complex() complex math module divmod() float() int() long() max() min() pow() round() Reflection and meta-programming apply() *depreciated* callable() compile() delattr() eval() execfile() getattr() hasattr() input() isinstance() issubclass() setattr() vars() Maybe with a one line (no more!) explanation of what the function or module does. John Roth From peter at engcorp.com Wed Jul 16 19:35:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Jul 2003 19:35:00 -0400 Subject: Choosing the right framework References: Message-ID: <3F15E124.A737D1E4@engcorp.com> David McNab wrote: > > I've been working on an HTML generation framework called 'pyWeb'. Just > posted to this ng yesterday, calling for testers. > > You might like to visit http://www.freenet.org.nz/python/pyweb and have a > look. David, I had to post instead of reply, since you of course have hidden your email address. I hope you get this. You are using the refuse.com domain for your fake address. This is very inappropriate, as that is a real domain for a real company. Please switch to the proper approach: append ".invalid" to your address. This is the *defined* way to form a domain name which is guaranteed to be invalid. -Peter From max at alcyone.com Tue Jul 1 21:48:15 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jul 2003 18:48:15 -0700 Subject: whitespace and ?asc()? References: <3F02086D.9010300@ihug.co.nz> Message-ID: <3F0239DF.C24C269E@alcyone.com> Ray Tomes wrote: > I was trying to find out the exact definition of whitespace so I went > to > look at strings.whitespace to find out which chars were whitespace, > and > found 9, 10, 11, 12, 13, 32 which according to my ancient ascii chart > are > TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? ASCII 12 decimal is FF, or form feed. NP is not an official control character in ASCII, and TAB and SPACE are written HT (horizontal tab) and SP, respectively. http://www.alcyone.com/max/reference/compsci/ascii.html > Also, in trying to find the ASCII (or is it ANSI) values ... It's ASCII. > ... for > characters I > could not find the reverse function for chr() [in BASIC it is asc()]- > can > someone please tell me what reverses chr()? ord. >>> ord('\n') 10 >>> chr(10) '\n' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ People are taught to be racists. \__/ Jose Abad From carel.fellinger at chello.nl Sun Jul 27 14:13:49 2003 From: carel.fellinger at chello.nl (Carel Fellinger) Date: Sun, 27 Jul 2003 20:13:49 +0200 Subject: Tools for reading Dr Dobb's Python-URL In-Reply-To: <3f23f845$0$49109$e4fe514c@news.xs4all.nl> References: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> <3f23f845$0$49109$e4fe514c@news.xs4all.nl> Message-ID: <20030727181349.GA5534@mail.felnet> On Sun, Jul 27, 2003 at 06:05:31PM +0200, Irmen de Jong wrote: > Egbert Bouwman wrote: > >My mail reader is the text-based Mutt, which: ... > I cannot help you with a better alternative > to mutt if you want to use a text-based mail reader, well, he could use a real:) news/mail reader like gnus (inside emacs), still text based, but calls to viewers are a tad more integrated. on the other hand, mutt is fine, reliable and trust worthy, so why change. -- groetjes, carel From gh at ghaering.de Sat Jul 12 11:46:42 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 12 Jul 2003 17:46:42 +0200 Subject: new in town In-Reply-To: References: Message-ID: <3F102D62.7060804@ghaering.de> Elaine Jackson wrote: > Can Python be compiled? [...] That depends on your definition of "compiled". If you mean that machine language can be constructed without any interpreter involved, then the answer is no. If you want a way to make a Python application not depend on an installed interpreter, then there are several ways to do this. This and many more of your questions to come will be answered by the Python FAQ, btw: http://www.python.org/cgi-bin/faqw.py -- Gerhard From dortmann at lsil.com Tue Jul 1 19:01:55 2003 From: dortmann at lsil.com (Daniel Ortmann) Date: 01 Jul 2003 18:01:55 -0500 Subject: Python-2.3b1 bugs on Windows2000 with: the new csv module, string replace, and the re module Message-ID: These problems only happen on Windows. On Linux everything works fine. Has anyone else run into these bugs? Any suggestions? Where do I find out the proper bug reporting process? Problem #1: While using the csv module's DictWriter on MSDOS (a.k.a. Windows2000), the output files get newlines like \x0d\x0d\x0a instead of \x0d\x0a. csvwriter = csv.DictWriter( file( out1filename, 'w' ), infieldnames, extrasaction='ignore' ) csvwriter.writerow( dict( zip( infieldnames, infieldnames ) ) ) Problem #2: While trying to fix up the first problem I run into another problem. The following string replace code works until right around the boundary at 2^7 * 1024, i.e. near 131072 (around line 1224), and then inserts a bunch of \x00's in the string! Before the \x00's, all of the \x0d's were correctly replaced. After the \x00's, NONE of them were replaced. content = file( fname, 'rb' ).read().replace( '\x0d', '' ) file( fname, 'wb' ).write( content ) Problem #3: The same problem also happens with the re module. content = re.sub( '\x0d', '', file( fname, 'rb' ).read() ) file( fname, 'wb' ).write( content ) -- Daniel Ortmann, LSI Logic, 3425 40th Av NW, Suite 200, Rochester MN 55901 work: Daniel.Ortmann at lsil.com / 507.535.3861 / 63861 int / 8012.3861 gdds home: ortmann at isl.net / 507.288.7732, 2414 30Av NW #D, Rochester MN 55901 From staschuk at telusplanet.net Mon Jul 28 16:21:29 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 28 Jul 2003 14:21:29 -0600 Subject: looping through a file In-Reply-To: <87u197a495.fsf@pobox.com>; from jjl@pobox.com on Mon, Jul 28, 2003 at 01:23:18AM +0100 References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> <3f21903c$0$27898$626a54ce@news.free.fr> <87llukrdow.fsf@pobox.com> <87u197a495.fsf@pobox.com> Message-ID: <20030728142129.A1276@tibia.amotlpaa.bogus> Quoth John J. Lee: > bokr at oz.net (Bengt Richter) writes: [woes with file iterators reading ahead] > > >I gathered from a recent thread that this has changed -- the file is > > >its own iterator now. Was the old behaviour ever released in 2.2, or > > >was it just part of a 2.3 beta? > > > > > Curious what was changed ... > > I'm not certain it has changed -- haven't tested. 2.3 has the change, 2.2.2 does not: Python 2.2.2 (#1, Jun 19 2003, 11:01:48) >>> fp = file('foo') >>> iter(fp) is fp 0 Python 2.3b1 (#1, Apr 30 2003, 22:25:58) >>> fp = file('foo') >>> iter(fp) is fp True (I don't know about 2.2.3.) -- Steven Taschuk staschuk at telusplanet.net "Please don't damage the horticulturalist." -- _Little Shop of Horrors_ (1960) From aahz at pythoncraft.com Mon Jul 28 21:53:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2003 21:53:58 -0400 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> <7b454334.0307281742.10274598@posting.google.com> Message-ID: In article <7b454334.0307281742.10274598 at posting.google.com>, Fazer wrote: > >This is a little off-topic, but I wish to know how would you turn a >string (or data from a text-file) into an array? For example, maybe >turn each \n into an array. > >So a string like: > >"This is line 1 >This is line 2 >This is line 3" > >And so when you read that into a list called text text[0] would the >"This is line 1". s.split('\n') -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From tl_news at nexgo.de Wed Jul 30 06:36:18 2003 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 30 Jul 2003 10:36:18 GMT Subject: Bottleneck: easy obscurity "encryption" via xor References: <7xwue0pzcl.fsf@ruckus.brouhaha.com> Message-ID: <1d45gb.cjp.ln@217.11.196.167> Hi Irmen, Bengt and Paul! Thanks a lot for your answer. Indeed it seems that I chose the slowest possible implementation :-) I tested all your recepies and I would like to give a short summary of what I found: > def xorcrypt_old(str, salt = 255): > if salt > 255: > raise "Invalid salt! Must be < 255!" > return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, _salt = salt: operator.xor(ord(char), _salt), str), "") > > def xorcrypt_irmen1(str, salt = 255): > if salt > 255: > raise "Invalid salt! Must be < 255!" > return ''.join(map(lambda char, _salt = salt: chr(operator.xor(ord(char), _salt)), str)) > > def xorcrypt_irmen2(str, salt = 255): > if salt <0 or salt> 255: > raise "Invalid salt! Must be 0<=salt<=255!" > return ''.join( [ chr(ord(c) ^ salt) for c in str ] ) > > def xorcrypt_bengt(str, salt = 255): > if salt <0 or salt> 255: > raise "Invalid salt! Must be 0<=salt<=255!" > translation_table = ''.join( [ chr(c ^ salt) for c in range(255) ]) > return str.translate(translation_table) > > def xorcrypt_paul(str, salt = 255): > if salt <0 or salt> 255: > raise "Invalid salt! Must be 0<=salt<=255!" > n = len(str) > stream = array.array('B', str) > for i in xrange(n): > stream[i] = stream[i] ^ salt > return stream.tostring() And it seems that Bengt's reciepe is the fastest. For very small strings (<255 chars) the method irmen2 should be the best choice - it doesn' have to pre-create the translation-table and does everything on-the-fly. Have a look at some results: File with 380303 Bytes > Old Version ... 511 seconds -> 744 Bytes/second > Irmen's 1st Version ... 4 seconds -> 95075 Bytes/second > Irmen's 2nd Version ... 3 seconds -> 126767 Bytes/second > Bengt's Version ... 1 seconds -> 380303 Bytes/second > Paul's Version ... 1 seconds -> 380303 Bytes/second File with 6587435 Bytes > Old Version ... not tested > Irmen's 1st Version ... 71 seconds -> 92780 Bytes/second > Irmen's 2nd Version ... 39 seconds -> 168908 Bytes/second > Bengt's Version ... 1 seconds -> 6587435 Bytes/second > Paul's Version ... 16 seconds -> 411714 Bytes/second Once again - thanks for your help! Cheers, Tino From donn at drizzle.com Thu Jul 10 23:42:18 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 11 Jul 2003 03:42:18 -0000 Subject: Embedding Python, threading and scalability References: Message-ID: <1057894937.226792@yasure> Quoth "Simon Wittber (Maptek)" : | [snip] | >...the way to scale Python in a threaded environment is to call out to | a C >extension that releases the GIL. | [snip] | | To write scalable applications in Python, one must write the | 'scalabilty-required' parts n C. | | Does anyone else see this as a problem? Is it a problem? I don't know all the reasons why an application might want to compute in parallel on multiple CPUs, but I am guessing that ordinarily it's about processor intensive computations. That isn't really Python's strongest point - you want to write the heavy duty computing in C if you want speed. If it's any consolation, I believe the ocaml Objective CAML thread implementation has the same kind of global lock, even though it does compile to efficient native code and would otherwise be an attractive candidate for compute intensive applications. Don't take my word for it, but that's how it looks to me. Regardless of how grave the problem may be, if there's no practical fix, we live with it. Donn Cave, donn at drizzle.com From intentionally at blank.co.uk Sun Jul 13 17:52:46 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 22:52:46 +0100 Subject: anything like C++ references? References: Message-ID: On Sun, 13 Jul 2003 16:57:18 -0400, "Tim Peters" wrote: >[Stephen Horne] >> ... >> The fact is that 'assignment' has a common meaning separate from the >> choice of programming language, > >Well, that's not a fact, although there may be much commonality among the >(necessarily few, if you believe this) programming languages you've used. >Python's assignment semantics are in fact common among languages >higher-level than those of the Fortran/COBOL/Algol/C ilk. For examples, >Lisp, SNOBOL4, Scheme, Smalltalk and Icon are (very) much like Python in >this respect. So is Java in the end, although the underlying machinery is >more complicated there. > >> and that the way Python handles name binding means that meaning is not >> respected by Python for mutable objects. > >Python's assignment semantics don't vary according to object type. OK then. With reference to another of my posts... 1. Why are dictionarys called dictionaries (rather than references to dictionarys or whatever)? Similar for lists and class instances. 2. Why are the values of mutable objects always forced to be accessed via a pointer (or reference or whatever)? Note - whether it makes sense to allow in-place changes to part or all of a value is not the same as whether it makes sense to reference that value indirectly. 3. Why is there no way to reference an immutable object via a pointer, other than stuffing it into a mutable object designed for some purpose other than simple pointer behaviour? This excuse is, as I already said, invalid. >Well, I can assure you Guido wouldn't change anything about Python's >assignment semantics if were able to do it all over from scratch. That's a >puzzle for you to work out, then: is Guido unique, or are all Dutch people >that stupid ? Your words, not mine. I simply point out that no-one, BDFL or otherwise, can be perfect. From reply.in.the.newsgroup at my.address.is.invalid Thu Jul 17 14:43:35 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 17 Jul 2003 20:43:35 +0200 Subject: html tags and webpages References: Message-ID: <1grdhvg02eg644i0lqb436vf626r05h7m0@4ax.com> jeff: >Basically what i want to do is create a script in python that will >look at a website and pull off a certain type of html tag and anything >contained within them tags, This is what you need: http://www.python.org/doc/2.2.3/lib/module-urllib.html http://www.python.org/doc/2.2.3/lib/module-HTMLParser.html -- Ren? Pijlman From other at cazabon.com Mon Jul 7 01:37:01 2003 From: other at cazabon.com (Kevin) Date: Mon, 07 Jul 2003 05:37:01 GMT Subject: Threading issue: [Error 9]: bad file descriptor References: Message-ID: <1G7Oa.376746$ro6.9153831@news2.calgary.shaw.ca> My oversight, thanks! I'm testing on Windows 2000 Professional, but have had other users report the same problem on other Windows flavours (NT, 98). Kevin. "Andrew MacIntyre" wrote in message news:mailman.1057519510.8812.python-list at python.org... > On Sun, 6 Jul 2003, Kevin wrote: > > > Has anyone else run into random IOErrors ([Error 9] bad file descriptor) in > > multi-threaded Python apps? > > Not indicating which of the platforms with Python supported threads you're > experiencing this on doesn't give much scope for others to help... > > -- > Andrew I MacIntyre "These thoughts are mine alone..." > E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 > andymac at pcug.org.au (alt) | Belconnen ACT 2616 > Web: http://www.andymac.org/ | Australia > From fredrik at pythonware.com Thu Jul 3 03:14:10 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Jul 2003 09:14:10 +0200 Subject: arbitrary long integer aritmetics References: <3F035958.FADD276E@alcyone.com> Message-ID: Erik Max Francis wrote: > Probably because he pasted in an incomplete transcript. I pasted in an overly complete transcript, and decided to trim it down before posting. bad idea. From zneptune321 at zexcite.zcom Mon Jul 14 23:19:40 2003 From: zneptune321 at zexcite.zcom (Conrad) Date: Tue, 15 Jul 2003 03:19:40 GMT Subject: Stop Python from exiting upon error in Windows References: Message-ID: Years ago, Nostradamus predicted that on Mon, 14 Jul 2003 20:06:14 -0700, Tom Plunket would write, saying: > Robert wrote: > >> How can I stop the Python interpreter from exiting when an error occurs? > > create a batchfile, tell Windows that the association of Python > files is to that batch file, and put this in the file: > > python.exe %1 > pause > > > Or- catch the error in your mainline, and do a sys.raw_input() > call on exception. > > -tom! Or the third, and admittedly brute force solution I use is to fire up the DOS shell, (click on START, then RUN, then type "command"). Depending on which Win you're running, you may want to run DOSKEY, which lets you cursor back up to previous commands. Once you've got the command window up (and doskeyed), cd to your python source directory, and type in something like *C:\python22\python.exe mypythonfile.py* (leave out the *s and be sure python is in the same place on your machine.) This doesn't keep the python interpreter from exiting, but it does keep the DOS window open to let you see your error messages. I admit it's ugly, but hey, I mostly develop in FreeBSD and Linux, where the CLI is your buddy ;-) Conrad From aahz at pythoncraft.com Mon Jul 14 10:21:12 2003 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2003 10:21:12 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: In article , Ian Bicking wrote: >On Sun, 2003-07-13 at 20:32, Aahz wrote: >> In article , >> Ian Bicking wrote: >>> >>>(Admittedly, some confusion may occur because these very different >>>operations use the same syntax: >>> >>> x = 10 >>> x[0] = 10 >>> obj.x = 10 >>> >>>The second and third are entirely different from the first.) >> >> No, they aren't. They are precisely the same; they just have different >> assignment targets. > >Sure they are different. The first is a primitive operation binding the >variable x. The second gets x, and calls x.__setitem__(0, 10), and the >third is equivalent to setattr(obj, 'x', 10). > >The first is primitive syntax. I suppose you could say that it could be >reduced to operations on locals() and globals(), but I feel like that's >a detail that is best not brought up ;) The local and global scope are >not as flexible as other objects The other two are really just syntactic >sugar. You've got a good point, but I think my point is just as valid. Which viewpoint is more appropriate depends on the circumstance. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From peter at engcorp.com Thu Jul 24 11:39:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jul 2003 11:39:37 -0400 Subject: Associating file types to my Python program References: Message-ID: <3F1FFDB9.4AAF1092@engcorp.com> Psymaster wrote: > > How could I do that? I'm writing an image viewer and I would > want to associate all images to be opened with my proggie when > they are double-clicked. Not really a Python question, but if you specify your OS we can probably help better. Assuming you mean Windows, just open Explorer, find the File Types tab on the Folder Options submenu, and create New Type or Edit the existing type. For more information, Google can help you, or you can look at how the Windows installer already set up .py and .pyw files in that File Type list, and copy that. -Peter From tjg at craigelachie.org Wed Jul 23 23:35:03 2003 From: tjg at craigelachie.org (Timothy Grant) Date: Wed, 23 Jul 2003 20:35:03 -0700 Subject: SAX questions... In-Reply-To: <5.2.1.1.0.20030722115406.04110cd0@66.28.54.253> References: <5.2.1.1.0.20030722115406.04110cd0@66.28.54.253> Message-ID: <200307232035.04750.tjg@craigelachie.org> Thanks to everyone who replied to this request. I'm going to try each method suggested just for the fun of it and see which fits my thinking patterns the best. I appreciate your input! On Tuesday 22 July 2003 11:02 am, Bob Gailer wrote: > At 10:22 AM 7/22/2003 -0700, Timothy Grant wrote: > >I've worked with DOM before, but never SAX, I have a script that seems to > >work > >quite well, but every time I look at it I think it's amazingly unweildly > > and that I must be doing something wrong. > > > >def startElement(self, name, attr): > > if name == "foo": > > do_foo_stuff() > > elif name == "bar": > > do_bar_stuff() > > elif name == "baz": > > do_baz_stuff() > > > >There's similar code in endElement() and characters() and of course, the > > more tags that need processing the more unweildly each method becomes. -- Stand Fast, tjg. Timothy Grant www.craigelachie.org From dkuhlman at rexx.com Wed Jul 30 14:57:46 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 30 Jul 2003 11:57:46 -0700 Subject: Python debugger References: Message-ID: Andrew Chalk wrote: > I am sure that it has been asked before but could someone tell a > newbie whether there is a Python debugger out there? > See: http://www.python.org/doc/current/lib/module-pdb.html - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From tjreedy at udel.edu Thu Jul 17 13:41:57 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 13:41:57 -0400 Subject: anything like C++ references? References: Message-ID: "Bengt Richter" wrote in message news:bf21le$5gu$0 at 216.39.172.122... > Python's name bindings just aren't your variable bindings, > and Python's names aren't variable names. They're aliases. Exactly. When Oswald shot JFK, JohnJKennedy, TheNNthUSPresident, PT109.putative_author, and Daddy (in Caroline's namespace), being one and the same person, all died. Terry J. Reedy From bgailer at alum.rpi.edu Tue Jul 1 14:20:42 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 01 Jul 2003 12:20:42 -0600 Subject: Good code patterns in Python In-Reply-To: <1057079630.3f01c14ed962a@mcherm.com> Message-ID: <5.2.1.1.0.20030701121604.01aa9318@66.28.54.253> >Will Stuyvesant writes: > > If you know that your source code is going to be used > > later by others, then I feel that code with the pattern: > > > > if some_condition: > > some_name = some_value > > else: > > some_name = other_value > > > > is often a mistake. Much better, safer, would be: > > > > some_name = some_value > > if not some_condition: > > some_name = other_value This brings back the good old days of FORTRAN IV which had a single-statement IF and no ELSE. Thus: C = VALUE1 IF ( A .EQ. B) C = VALUE2 Notice the indentation. Cols 1-5 were reserved for line # and col 6 for the continuation code. So Python is not the only indentation dependent language. Nor is it the first to use indentation to convey structure. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From kent at NOSPAMspringfed.com Sun Jul 20 06:56:00 2003 From: kent at NOSPAMspringfed.com (Kent Tenney) Date: Sun, 20 Jul 2003 05:56:00 -0500 Subject: distutils.core not in Debian python2.2 package In-Reply-To: References: Message-ID: Thanks It surprises me to find distutils in a package described as: "Header files and a static library for Python (v2.2)" Kent David M. Cooke wrote: > At some point, Kent Tenney wrote: > > >>Howdy, >> >>I did; >># apt-get install python2.2 >> >># python >>Python 2.2.1 >>... >> >>> >> >>then checked docutils out of CVS >>and did; >> >>docutils# python ./setup.py install >> >>ImportError: No module named distutils.core >> >>How do I install distutils? > > > Install the python2.2-dev package. > From intentionally at blank.co.uk Mon Jul 14 23:52:34 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 04:52:34 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> Message-ID: On Mon, 14 Jul 2003 20:48:54 -0700, Tom Plunket wrote: >Stephen Horne wrote: > >> True enough. And if someone creates a language in which '+' does >> subtraction, I'm sure people could get used to that to. Doesn't mean >> it's the right thing, though. > >It's often more useful to do what users want than it is to >blindly adhere to what's right and correct. True enough. The issue of how assignment is represented is trivial and unimportant in the scheme of things. From whisper at oz.net Thu Jul 24 15:21:45 2003 From: whisper at oz.net (David LeBlanc) Date: Thu, 24 Jul 2003 12:21:45 -0700 Subject: running python In-Reply-To: Message-ID: > > How do you run files written with python if you don't have the > compiler and > stuff on your computer? > You need to expand your question a bit. Python is an interpreted language, so the interpreter must be available to run Python scripts. There are ways to bundle the interpreter with a script so that it will run stand-alone though. See: http://www.mcmillan-inc.com/install1.html Dave LeBlanc Seattle, WA USA From gh at ghaering.de Sun Jul 6 22:16:03 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Jul 2003 04:16:03 +0200 Subject: mod_python/good documentation? In-Reply-To: References: Message-ID: <3F08D7E3.6000301@ghaering.de> Tim wrote: > ...just starting to work with mod_python. There are a number of details and > pitfalls: any suggestions on where to get some decent tips and tricks. I can > comprehend the provided docs but...they are not that great. :-( mod_python questions are obviously best asked on the mod_python mailing list :-) > Feel free to comment/recommend any other Apache modules for py. It seems among the three (mod_python, mod_snake, PyApache), mod_python is the one to go. There's still mod_scgi and FastCGI as alternatives. But these, just like mod_python are just for connecting your app to the webserver, not a complete web framework yet. -- Gerhard From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Fri Jul 11 02:12:28 2003 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Koczian) Date: Fri, 11 Jul 2003 08:12:28 +0200 Subject: Calling Excel module functions from python [repost] In-Reply-To: References: Message-ID: Mark Carter schrieb: > A further tip: > For a function taking arguments, use > xlApp.Run("func", "arg1", "arg2", ...) > Thank you! That was something I tried to get right some weeks ago but gave up on. Moral: don't give up, ask around. 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 peter at engcorp.com Thu Jul 10 10:30:31 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 10:30:31 -0400 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> Message-ID: <3F0D7887.9D069ED0@engcorp.com> Jon Schull wrote: > > PyDoc's author Ka-Ping Yee has suggested that PyDoc be patched to > prevent access from unauthorized IP addresses > (https://sourceforge.net/tracker/?func=detail&atid=305470&aid=672656&group_id=5470), > and that without such a patch, its not " suitable for running on boxes > that aren't behind firewalls" > > It's hard to know how much to worry about such things (Comments?). > > However, even with the patch, IP addresses can be spoofed. Here is an > additional security tactic that might be adopted. > > The port number used by pydoc is currently set by the user at the > command line. Many people probably use the example given in the > python module documentation : "python -p 1234" However, if the port > were chosen at random and printed out, then only pydoc and the user > would know how to access the pydoc server. > > I'm considering a similar strategy for a server based on the > CGIHTTPServer module, so comments would be welcome. My suggestion: don't attempt to mix security into each individual application in a piecemeal manner. Use the proper tools for the job, such as firewalls. Setting up a firewall on Linux or WinXP is nearly trivial at this point, and the learning experience is worth the effort for those who are new to this, so there's not much excuse for doing it properly, IMHO. -Peter From ianb at colorstudy.com Sun Jul 20 21:38:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 20:38:46 -0500 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: References: Message-ID: <1058751526.28094.2506.camel@lothlorien> On Sun, 2003-07-20 at 18:53, Alan Dechert wrote: > "Andrew Dalke" wrote in message > news:bff56e$8iv$1 at slb9.atl.mindspring.net... > > Alan Dechert: > > > will change. For example, when the voter selects a president/vice > > president > > > pair, the background will change; the non-selected pairs will be greyed > > > while the selected pair will be highlighted (very brightly -- should > light > > > > "greyed" in normal UI parlance means the option is no longer selected. > > What happens if someone pressed the wrong button? How is the correct > > selection made? > > > Point (or click on) again to de-select. This is one thing that may require > a little voter training. I think it's easy enough, but then we'll find out. > You could add a "reset" button but that would make an already busy screen > even busier. I'm not sure if that would be easier. I think it would make more sense not to change the display of the unselected candidates, but only to highlight the selected candidate. The more you reduce the amount of color used elsewhere in the display, the more color in a selection will stand out. At least for people who aren't completely color-blind -- but those people will just have to pay slightly more attention. I think font changes might confuse people. Thickening the border of the selected candidate would not. If you have a dense ballot like you are proposing I would expect even an experienced user would be likely to make one mistake somewhere, so it should be clear how to fix it. > > > 3) When "WRITE-IN CANDIDATE" is selected, a large widow (maybe the full > > > screen) will pop up with a QWERTY keyboard in the upper half. This > > keyboard > > > will have only three rows with the alpha keys (no punctuation or numbers > > > needed except for perhaps the hyphen... no shift, all CAPS). > > > > No apostrophe? What if I want to vote for "O'Reilly" > > > As a matter of fact, we won't let you vote for O'Reilly. On second thought, > you're right, I guess. Okay we'll have an apostrophe available. Anything > else? Also a hyphen, like for Mercuri-Neumann. I assume it would be acceptable to simply leave off any accent marks, umlauts, tildes, etc. from a candidate's name (at least in the US), even though strictly speaking an "n~" (excuse my uninternationalized keyboard) isn't the same letter as an "n"... but no one will be confused by that, which is more important than correctness. However, whether Mercuri-Neumann becomes MERCURINEUMANN or MERCURI NEUMANN would confuse and distress people (even if those were likely to be counted as the same by the system). Ian From furliz at libero.it Tue Jul 8 06:12:48 2003 From: furliz at libero.it (furliz) Date: Tue, 08 Jul 2003 12:12:48 +0200 Subject: Tkinter window Message-ID: Learning Python, I'm making some exercise of little GUI application with Tkinter. I'd like to know if is it possible to customize the little 'Tk' icon on the top-left corner of the main window ( Tkinter.Tk() ). Thanks to evryone who will resolve me this 'big' doubt :)) From e_fax_t at msn.ZAPME.com Sun Jul 13 11:19:57 2003 From: e_fax_t at msn.ZAPME.com (Justin) Date: Sun, 13 Jul 2003 17:19:57 +0200 Subject: Any pure-python relational databases? References: <2a897f11.0307121143.4a37113b@posting.google.com> Message-ID: <3f1178ba$0$6533$afc38c87@sisyphus.news.be.easynet.net> >> While not relational, have you looked at Metakit? > Thank YOU, Wayne!!! :))) Be careful, though: the metakit page states that "There is no multi-user support", so I am not sure this is the ideal choice for a web-app. Unless the web clients just fetch dynamic pages and don't need to _write_ to the db... I have been intrigued by the library myself, but always thought this warning must be there for a reason... From mmuller at enduden.spam.filter.com Sun Jul 27 14:11:02 2003 From: mmuller at enduden.spam.filter.com (Michael Muller) Date: Sun, 27 Jul 2003 18:11:02 GMT Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> Message-ID: <20030727.141111.1139901474.9957@demon.mindhog.net> In article <3f23ae06$0$21093$626a54ce at news.free.fr>, "Bruno Desthuilliers" wrote: > Michael Muller wrote: > Interface documentation may be obtained in others ways (docstring for > exemple). Yes, and that's the way that I do it now. But the problem with this is that it's "non-binding": it doesn't impose any programmatic constraints. Because of this: - it's hard to enforce automatically (if you want to make sure that all programmers in your team are using the prescribed argument definition conventions, you have to parse all the docstrings) - there is no global standard (I might use "name: type info" in my docstring, you might use "type name") - it is hard to guarantee that the documentation is in sync with the code (if you change the type expectations of a function, you can do so without changing the documented expectations) - it makes type errors less obvious (you end up getting an attribute error when you perform an operation on the value instead of a type error when you initially abuse the interface) Although, I must say that this is surprisingly less of a problem in Python than one might expect. > And I'm not sure static typing would optimize anything, but not being a > Python (nor anything else) guru, I would not bet my hand on this... my 2 > cents... In and of itself, static typing does not optimize anything. In fact, it could slow things down because you suddenly have to do typechecks all over the place. Static typing can be /used/ for optimizations because it allows for optimized forms of attribute access - without it you must do dynamic name resolution at runtime. For example, if you want to resolve a method name, you currently have to look up the method name in the object and its classes. With static typing, since you know the type of the object at compile time, you can just reference it in a "vtable" (a virtual function table) associated with the object. In short, static typing brings us one step closer to "python compiled to machine code". -- Remove the spam and filter components to get my e-mail address. From heikowu at ceosg.de Tue Jul 15 21:08:46 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 16 Jul 2003 03:08:46 +0200 Subject: Solaris 9, problem building Python 2.1.1 In-Reply-To: <20030716003454.GA2860@dave@alana.ucc.usyd.edu.au> References: <20030716003454.GA2860@dave@alana.ucc.usyd.edu.au> Message-ID: <1058317726.622.90.camel@d168.stw.stud.uni-saarland.de> On Wed, 2003-07-16 at 02:34, Dave Harrison wrote: > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.1/socket.py", line 41, in ? > from _socket import * > ImportError: ld.so.1: python2.1: fatal: libssl.so.0.9.6: open failed: No such file or directory Seems like your lib(open)ssl is missing, or invalid. I think there is some command-line option to configure which states whether to try to link with SSL support (just turn it off), but maybe you'll have to change the setup/Modules file to leave out SSL-support for the socket module. Or try installing openssl 0.9.6j (is the latest, I think). HTH! Heiko. PS: I remember someone else experienced some problem like yours about three months ago, linking Python with OpenSSL on AIX (iirc) wouldn't work correctly. Maybe you could just look there. PPS: I don't know too much about Solaris, so this is all just a guess... From mail at heikokoehler.de Sun Jul 27 10:56:23 2003 From: mail at heikokoehler.de (Heiko =?ISO-8859-15?Q?K=F6hler?=) Date: Sun, 27 Jul 2003 16:56:23 +0200 Subject: ANN: scintilla based, scriptable code editor CUTE 0.1.6 released Message-ID: <3f23e794$0$6774$9b4e6d93@newsread2.arcor-online.net> CUTE is a Qt and Scintilla based text editor which can be easily extended using python . It 's main purpose is to be an user-friendly source code editor with a common graphical user interface. The editor is in an early stage and its use is limited yet. Homepage http://cute.sf.net regards Heiko K?hler From bogus at antispam.com Mon Jul 21 01:02:49 2003 From: bogus at antispam.com (Alex) Date: Mon, 21 Jul 2003 01:02:49 -0400 Subject: Flat file to associative array. Message-ID: Hello, What would be the best way to convert a flat file of products into a multi-dimensional array? The flat file looks like this: Beer|Molson|Dry|4.50 Beer|Molson|Export|4.50 Shot|Scotch|Macallan18|18.50 Shot|Regular|Jameson|3.00 I've managed to read the file properly and get the individual lines into a list, but I've got to turn this list into something that can be stored in memory like a dictionary / associative array so I can properly display the data. Here's the code I have so far: [Code] #! /usr/bin/python import string file = open("definitions", "r") while 1: line = file.readline() if not line: break else: data = string.split(line, '|') item = dict([('product', data[0])]) print "You want a " + item['product'] + ". What kind? " + data[1] + " for $" + data[3] + " ... right?" file.close() [/Code] Thanks in advance, Alex From postmaster at 127.0.0.1 Wed Jul 16 09:33:44 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Thu, 17 Jul 2003 01:33:44 +1200 Subject: How about using python to write a CMS? References: Message-ID: On Wed, 16 Jul 2003 18:21:38 +0800, ?????? paused, took a deep breath, then came out with: > To write a CMS, everyone is thinking about PHP, but, what do you think if I > am using python to write a Content Management System? If you want to minimise damage to your sanity, don't touch PHP with a barge-pole. It's a nice easy language to learn, but once your code grows, the built-in irritations of PHP will likely cause you much pain. IMO, Python is the natural choice for most software when writing from scratch. Deficiencies in performance are easily corrected via C layers at the bottom-end. Given the glut of PHP-based CMSs and the paucity of those in Python, I think you'd be doing a great thing to build yours in Python. Please think carefully about the environment you choose. Twisted or Zope may feel godo to use, but will lock out a lot of users who only have access to Apache-based hosts. mod_python is another option, but not often available in commercial Apache environments. CGI is available on most web hosts, but suffers performance issues. Lastly (forgive me those who are sick of me saying this), many web hosts only offer Python 1.5.2, with no MySQL interface library. So you might want to look at another database engine which can be installed without requiring root access to the server. Cheers David From tchur at optushome.com.au Mon Jul 28 21:39:21 2003 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 29 Jul 2003 11:39:21 +1000 Subject: pretty printing graphs Message-ID: <200307290139.h6T1dLo12893@mail012.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tomas at fancy.org Thu Jul 3 01:55:03 2003 From: tomas at fancy.org (Tom Plunket) Date: Wed, 02 Jul 2003 22:55:03 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: Mirko Zeibig wrote: > You don't need lambda here, just give the Countdown class a reference to your > callback-method by specifying it's name *without* parentheses :-). Heh oh yeah. The "instance-bound methods" I guess this is called is what was really throwing me. :) Thanks- this is the solution that I was looking for. Dunno why I got stuck in the needing a lambda routine, but oh well. ;) -tom! From tjreedy at udel.edu Thu Jul 10 11:13:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2003 11:13:48 -0400 Subject: PYTHON TO ANSYS References: Message-ID: "satish k.chimakurthi" wrote in message news:mailman.1057796495.19578.python-list at python.org... Suggestion: DON'T SHOUT WITH ALL CAPS >can someone throw light on the interfacing stuff in general and cite There is an essay entitled something like Extending and Embedding with Python which might help you and which should be available on www.python.org. TJR From Aaron.Buhr at campuscommgroup.com Wed Jul 30 16:18:08 2003 From: Aaron.Buhr at campuscommgroup.com (Aaron Buhr) Date: Wed, 30 Jul 2003 20:18:08 GMT Subject: Webware application question References: <2LTVa.13085$Oz4.4738@rwcrnsc54> Message-ID: <4KVVa.14886$It4.10267@rwcrnsc51.ops.asp.att.net> Gotcha, that thread is perfect. I believe I understand now. Thanks for the help. "deelan" wrote in message news:kd89gb.2c9.ln at news1.interplanet.it... > Aaron Buhr wrote: > > > Hello all. I am looking to rebuild our corporate website from Cold > > Fusion to Python/WebWare/Cheetah. I am new to all three, so I apologize in > > advance if my questions are ignorant. I do not understand how one would > > cache database connections using WebWare. At this point I do not want to > > use Middlekit, but I would like to compartmentalize all my database > > connection code and cache it for performance. > > there's a module in webware called dbpool > that caches DB connection. > > you may want to check this thread on the > webware mailing list archive: > http://tinyurl.com/ijhc > > i strongly suggest you subscribe both to webware anc > cheetah lists. being a newbie too i've found very > supportive people on both ML :) > > bye > -- > email: goldicus1970 AT yahoo.it > web: http://www.deelan.com > From 2002 at weholt.org Sun Jul 6 18:59:11 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 7 Jul 2003 00:59:11 +0200 Subject: Status of Python / Platform-specific support ?? Message-ID: Hi, I've been using Python on both Windows 2000 and Linux for some time now. On Windows I've used PythonWin as editor, Emacs on Linux. This has been working ok so far. Now as Python will be a part of Mac OS X Panther will this affect Pythons support for platform-specific modules in a big way? I'm not a Mac-expert, but OS X is basically a Unix-clone as base with a Apple-GUI on top, right? So most *nix apps will compile and run nicely on that platform? With Python as an integrated part of the system, I'd be seriously thinking about changing platform. Can anyone enlighten me as to what the current status is for Python on Mac, as for support, IDEs etc. ? Is Mac shaping up to be the best platform for Python development and python lovers in general, or is Mac just catching up to Linux? Any thoughts on platform benefits for python developers; Win32 vs. Linux vs. Mac? Drawbacks? Best regards, Thomas W From manish.j at gmx.net Fri Jul 25 16:10:19 2003 From: manish.j at gmx.net (Manish Jethani) Date: Sat, 26 Jul 2003 01:40:19 +0530 Subject: How to detect typos in Python programs In-Reply-To: References: <3F214977.AEB088C8@engcorp.com> Message-ID: Mel Wilson wrote: > In article <3F214977.AEB088C8 at engcorp.com>, > Peter Hansen wrote: > >>Manish Jethani wrote: >> >>>Is there a way to detect typos in a Python program, before >>>actually having to run it. Let's say I have a function like this: >>> >>> def server_closed_connection(): >>> session.abost() >>> >>>Here, abort() is actually misspelt. The only time my program >>>follows this path is when the server disconnects from its >>>end--and that's like once in 100 sessions. [ ... ] >> >>You have no good alternative. Why do you say it's impractical >>to actually test your software before it's shipped? Isn't it >>more impractical to rely on your users to test the software, >>thinking it should work? > > > The proposed typo catcher would probably catch a typo like > > sys.edit (5) # finger didn't get off home row > > but it probably would *NOT* catch > > sys.exit (56) # wide finger mashed two keys 1) That's in a different class of typos. Such things can't be auto-detected in any language. It will probably require close examination by the human who wrote it in the first place, or someone who has been debugging it. 2) No on calls sys.exit() like that. 5, or 56, is probably a constant defined somewhere (where such typos are easier to spot). -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From robin at jessikat.fsnet.co.uk Wed Jul 30 07:55:48 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 30 Jul 2003 12:55:48 +0100 Subject: PIL & TIFF transparency? Message-ID: Has anyone done transparency with PIL & TIFF? I'm using PIL to generate a preview TIFF for embedding into an eps file and am being asked for the TIFF to support transparency. -- Robin Becker From paoloinvernizzi at dmsware.com Tue Jul 15 09:05:59 2003 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Tue, 15 Jul 2003 15:05:59 +0200 Subject: path module In-Reply-To: References: <1057651068.5348.386.camel@lothlorien> <182bcf76.0307141319.7b6fed7a@posting.google.com> <20030715090753.M6906@prim.han.de> Message-ID: Florian Schulze wrote: > Try google with "cache:http://..." this worked for me. Done. Thanks for the advice. --- Paolo From staschuk at telusplanet.net Thu Jul 17 20:04:10 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 17 Jul 2003 18:04:10 -0600 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? In-Reply-To: <3f16bb84@shknews01>; from lol@lolmc.com on Thu, Jul 17, 2003 at 04:05:15PM +0100 References: <3f15ca92@shknews01> <3f16bb84@shknews01> Message-ID: <20030717180409.A931@tibia.amotlpaa.bogus> Quoth Rogue9: > After reviewing my question I realised that I should have posted the short > piece of real code I'm working on and not tried to write some pseudo-code > to illustrate the problem I'm having.Therefore I have printed the listing > below which is quite short and hopefully won't annoy too many peopleabout > the length of my post. Excellent! I'd also like to see a trimmed-down example of the input data which causes the unexpected output. If you don't mind, extract from your pickle files sublists of, say, five or ten elements, change the code to set masterList and skipFreqList directly to those sublists and verify that the problem still occurs, and post that, along with what output you see and what output you expect. -- Steven Taschuk "[W]e must be very careful when we give advice staschuk at telusplanet.net to younger people: sometimes they follow it!" -- "The Humble Programmer", Edsger Dijkstra From jjl at pobox.com Sun Jul 6 15:55:18 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Jul 2003 20:55:18 +0100 Subject: Search for mapping solution References: Message-ID: <87adbrzazd.fsf@pobox.com> Markus Joschko writes: [...] > I have a List: > > nName - Number - Costs [...] > > lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] [...] Note that tuples were designed for that sort of 'mini-object' use (and were not intended primarily as immutable lists). lines = [('fred','333','0,10'), ('sam','444','1'), ('fred','333','0,50')] though of course it's no disaster if you end up with a list of 3-element lists instead of 3-tuples, if it's convenient to build the list with zip or whatever. John From xah at xahlee.org Wed Jul 23 05:44:05 2003 From: xah at xahlee.org (Xah Lee) Date: 23 Jul 2003 02:44:05 -0700 Subject: needs a logo Message-ID: <7fe97cc4.0307230144.9119f89@posting.google.com> it would be good if Bash and Python have a decent logo. the current logos of simplistic font http://cnswww.cns.cwru.edu/~chet/img/bash-org.jpg http://python.org/pics/pythonHi.gif are homely. -- some quick tips for good logos: Good logo is not something generic, even if it is beautifully rendered. Example of bad or not very good logos with this problem: old gnu hurd logo of just a generic sphere http://www.gnu.org/graphics/hurd-logo-sm.jpg Fresco Window system of triangles (fresco.org) bash of simplistic font http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html python of simplistic font (python.org) Better logos should be reminiscent to what it represents. Good example's are SGI's computer rendered tube cube illusion, Sun Micro's 8Us that spells out Sun in 4 directions, Apple's bitten apple, Be media company's eye-ear logo, NeXT's geometrical cube, X-Window's sharp X, Redhat's redhat, GNU's gnu head, BSD's deamon tyke, MS Windows's window, Perl's ugly camel, nVidia's eye, GNU Hurd OS' recursive arrows, Shell's seashell, McDonnald's M, Taco Bell's bell, Honda's H ... Good logo should be distinct, an impression lock, even if it isn't reminiscent of what it represents. For example, AT&T's death star (globe connotation), Apache feather (Native American, panache), Linux's penguine tux (connotes glut with food and sex), Qmail's arrow distribution, Yamaha's tuning forks, General Electric's curlicue. Even font alone can do very good if in distinctive style: IBM stripped blue, coke drink's cursives, ATI's high-tech font, ebay and google's colorful fonts. Note that successful company's logo are not necessaily good. Examples are: SONY, JVC, TOSHIBA, RCA, Microsoft. These are just unremarkable. Good logo should not be overly complex. It shouldn't be photographic or complex drawings, for examples. Here's a related essay on the logo used by functional languages: http://xahlee.org/UnixResource_dir/lambda_logo.html Thanks. Xah xahlee.org http://xahlee.org/PageTwo_dir/more.html From zsolt+public5274 at mailblocks.com Mon Jul 14 14:17:29 2003 From: zsolt+public5274 at mailblocks.com (zman) Date: 14 Jul 2003 11:17:29 -0700 Subject: Any news on www.python.org being offline? Message-ID: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> Website has been offline for more than an hour 11:18 PT. From mike at nospam.com Mon Jul 14 14:37:11 2003 From: mike at nospam.com (Mike Rovner) Date: Mon, 14 Jul 2003 11:37:11 -0700 Subject: niaoeae aey ?inneeneeo ieoiiueeia))) References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F11D94A.7050208@removeme.free.fr> <3F11BF87.9000208@v.loewis.de> Message-ID: Martin v. Loewis wrote: > "?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? > ? exe-???? ?????????)." > > To see that, you have to read the message in windows-1251. > > I think this roughly translates into "Can you please tell me where to > find the proggie freezer (which appears to be needed to create exes)?" You are absolutely right. > The program is called freeze, and it is located in the Tools > directory, atleast of the source distribution. See the FAQ for other > options to create exes. I'm afraid he is not fluent in English, so I'd repeat you answer in Russian: ????????? ?????????? freeze ? ????? ? ???????? Tools ? ????????????. FAQ ????????? ? ?????? ??????? ???????? exe-??????. Mike From belred1 at yahoo.com Wed Jul 23 10:13:55 2003 From: belred1 at yahoo.com (Bryan) Date: Wed, 23 Jul 2003 14:13:55 GMT Subject: [OnTopic] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: what's to prevent this from happening to python? all those c modules? couldn't they have been copied from microsoft, sco, etc? how is python protected from others claiming the modules are copied works? bryan "Daniel Dittmar" wrote in message news:bflr29$7q2$1 at news1.wdf.sap-ag.de... > Ville Vainio wrote: > > It might be slightly on topic in that the future versions of Python > > could theoretically (and developers willing), shall we say, not pay as > > much attention for unixware as the target platform... perhaps even > > drift so far as not being able to compile at all >;-). > > SCO doesn't want you to actually use unixware. You should only pay them as > if you do. > > Daniel > > > From johnroth at ameritech.net Tue Jul 1 20:40:56 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 1 Jul 2003 20:40:56 -0400 Subject: Circular Inheritance References: Message-ID: "jinal jhaveri" wrote in message news:mailman.1057099023.14043.python-list at python.org... > Hi All, > > I have one question regarding circular inheritance > > I have 3 files > > 1) A.py , having module A and some other modules > 2) B.py having module B and some other modules > 3) C.py having module C and some other modules > > Now I want to import Module C in B.py > > but C requires A.py > and A requires B.py > > so > > B requires C > C requires A > A requires B > > and when I try to do this using > > from ...import.... > it tells me that you cannot import this. > > So any suggestions on this? You've run into one one of those things that is only understandable if you remember that Python *executes* the module during the import process. When you say "import" something, Python suspends importing the first module, and begins importing the second. Then if the second one tries to import the first, it sees that it's in the module table, and tries to find what you requested; but it's incomplete since it's stalled at the first "import" statement so it probably won't find whatever it was looking for. The best way around this is to eliminate the circular dependency. The result is clearer and easier to maintain. Otherwise, you have to be very specific about what goes where in each module so that any resources that one wants have actually been loaded when the other executes. In particular, "from foo import *" simply doesn't work with a circular import. If it's not in the incomplete module, it won't get imported. John Roth > > thank you > Jinal > > > From sholden at holdenweb.com Sun Jul 6 17:17:58 2003 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 06 Jul 2003 21:17:58 GMT Subject: Python is a gem ,another successful day .... References: Message-ID: Graeme: Congratulations! I'd be interested in knowing some of the arguments you used to win over VB, as I've been asked to put a couple of articles together suggesting why VB users might consider switching to Python. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ "Graeme Matthew" wrote in message news:ECUNa.628$kY2.37591 at nnrp1.ozemail.com.au... > Hi all I previously made a post ( > Python is a gem, you need to keep pushing it ....) > > about how impressed I was with python and how im suign it in a proposed > commercial app. > > Got a call on Friday a company with a very succesfull product in Visual > Basic (Front End) SQL (Backend) wanted to move from Microsoft products due > to all the problems with MDAC (ADO etc), XP networking issues .... and > concerns with microsofts control /// > > Well after three hours looks like Python (and linux and mysql) may have won > again, explained perl (semantic nightmare but a great language) , ruby > (great language but lack of libraries) etc, Vb's weaknesses and the need for > vendor neutrality anyway, as things move ill put some updates on here ... > and tell you ho it goes, .... > > Hey, im trying very hard to promote it :-) > > Cheers > > > > From jepler at unpythonic.net Thu Jul 31 11:46:59 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 31 Jul 2003 10:46:59 -0500 Subject: regular expression In-Reply-To: References: Message-ID: <20030731154653.GB30928@unpythonic.net> These are all untested, because I don't have Mk4py or your datafile to try it on. I might write this: import re pattern = re.compile("^Ge") def func(row): try: nachname = row.Nachname except AttributeError: return 0 return pattern.search(nachname) is not None vf = vw.filter(func) If you're using a Python version with nested scopes, you could use them in this case: import re def make_func(pattern): pattern = re.compile(pattern) def func(row): try: nachname = row.Nachname except AttributeError: return 0 return pattern.search(nachname) is not None return func vf = vw.filter(make_func("^Ge")) or you can make a callable filter object by using classes: import re class PatternFilter: def __init__(self, pattern): self.pattern = re.compile(pattern) def __call__(self, row): try: nachname = row.Nachname except AttributeError: return 0 return self.pattern.search(Nachname) is not None vf = vw.filter(PatternFilter("^Ge")) Jeff From news at manuelmgarcia.com Tue Jul 8 14:48:15 2003 From: news at manuelmgarcia.com (Manuel Garcia) Date: Tue, 08 Jul 2003 18:48:15 GMT Subject: single/double quote escape interpolation References: Message-ID: On 8 Jul 2003 02:15:38 GMT, bokr at oz.net (Bengt Richter) wrote: >Might want to mention that somedict only has to act like a dict, not necessarily *be* >a dict. I.e., supporting __getitem__ suffices, so you can synthesize anything you like >from the key passed. E.g., > > >>> class AsIs(object): > ... def __getitem__(self, key): return '%(' + key + ')s' > ... > >>> somedict = AsIs() > >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict > "why don't we drop by the %(where)s and %(dowhat)s a few?" > >Maybe that was a little weird ;-) How about, > > >>> class RU(object): > ... def __getitem__(self, key): > ... res = list(key.upper()) > ... res.reverse() > ... return ''.join(res) > ... > >>> somedict = RU() > >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict > "why don't we drop by the EREHW and TAHWOD a few?" This is a really great trick! When I am debugging I always have a lot of code like this: print 'variable_name: %r' % (variable_name,) And it bugs me that I have to type in the variable name twice. But using your trick, I might do: ################## import sys class VarReport(object): def __getitem__(self, key): f = sys._getframe(1) if f.f_locals.has_key(key): v = f.f_locals[key] elif f.f_globals.has_key(key): v = f.f_globals[key] else: raise NameError('name %r is not defined') % (key,) return '%s: %r' % (key, v) VarReport = VarReport() longname_a = 7 longname_b = 12 print '%(longname_a)s; %(longname_b)s' % VarReport ################## Manuel From syver-en+usenet at online.no Tue Jul 15 11:51:55 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 15 Jul 2003 17:51:55 +0200 Subject: [OT] sentances with two meanings References: Message-ID: roy at panix.com (Roy Smith) writes: > Harvey Thomas wrote: > > Also 'I was unknown to you and you deceived me'. Slightly colloquial > > > Given the biblical meaning of "known", this could have even more than > two meanings :-) Does "to know" in english also mean to feel someone? In my own language the direct translation of the english know also means to feel. I could say (translated) "I know the cold", meaning I feel the cold weather. From bit_bucket5 at hotmail.com Tue Jul 15 10:20:00 2003 From: bit_bucket5 at hotmail.com (Chris) Date: 15 Jul 2003 07:20:00 -0700 Subject: MySql autocommit off? Message-ID: Is there some way to turn off mysql autocommit when connecting? I see no reference to "autocommit" in the db api doc. I'm trying to use transactions with mysql (using innodb tables), and it looks like I can use "begin", but am wondering if there is some other way to just turn off autocommit. Thanks, Chris From peter at engcorp.com Wed Jul 23 11:27:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jul 2003 11:27:24 -0400 Subject: The global statement References: Message-ID: <3F1EA95C.E1623298@engcorp.com> Thomas G?ttler wrote: > > global BAD > BAD=1 > > def foo(): > global BAD > print BAD Note: the first use of global above, outside a function, is redundant. -Peter From bgailer at alum.rpi.edu Fri Jul 4 15:11:14 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 04 Jul 2003 13:11:14 -0600 Subject: strings problem In-Reply-To: Message-ID: <5.2.1.1.0.20030704130521.01a53c40@66.28.54.253> At 11:11 PM 7/4/2003 +0530, Jimmy verma wrote: >Hello *.* > >Can you please tell me how can i have the output in no's, instead of >string from this program: > >#/usr/bin/python >import re >import string > >def csNumEncode(num): > if(num>=-107 and num<=107): > return chr(num+139) > elif(num>=108 and num<=1131): > return chr(((num-108)/256)+247) + chr((num-108)%256) > else: > print 'do nothing' > >re_num = re.compile("\-?[0-9]+(\.[0-9]+)?") > > >def CompileCS(source): > result='' > for tkn in re.split('[ \n\t]+', source): > print "Token: %s"%tkn > if re_num.match(tkn): > result = result + csNumEncode(string.atoi(tkn)) > else: > raise SyntaxError, "%s is invalid operator"%tkn > return result > >src1 = '50 800' > >t = CompileCS(src1) > >print t > > > >The output is > >Token: 50 >Token: 800 >\275\371\264 > > >Instead of this i want the output should be in no's like this: >bdF9B4 When I run this I get: Token: 50 Token: 800 some graphical characters that don't even copy into the e-mail (whose ord values are 189, 249, 180). I have stared at the desired result bdF9B4 but see no relationship between that and '50 800'. What is the relationship (what are you wanting to accomplish)? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From cubop at tin.it Fri Jul 25 11:59:38 2003 From: cubop at tin.it (cubop) Date: Fri, 25 Jul 2003 15:59:38 GMT Subject: about select.poll Message-ID: A very short question: how the poll call is supposed to behave if a new file descriptor is registered in another thread while polling? thanks massimo From user at domain.invalid Tue Jul 1 03:57:25 2003 From: user at domain.invalid (user at domain.invalid) Date: Tue, 01 Jul 2003 09:57:25 +0200 Subject: I have a list... In-Reply-To: <20030701113915.226ae9bd.agg@astranet.ru> References: <20030701113915.226ae9bd.agg@astranet.ru> Message-ID: Damir Hakimov wrote: > Hi, All! > > say, i have a function: > > def f(*b): > print b > return > > then i do: > f(3,4,5) > (3, 4, 5) > > but i have list f=(3,4,5) > f(l) > ((3, 4, 5),) > > how can i call f function to result > f(???(b)) > (3, 4, 5) > > Thanks! > > > You can use the keyword 'type' to check the type of your arguments and return the appropriate 'format' according to the their types Regards Salvatore From postmaster at pcexpert.ee Fri Jul 11 18:35:15 2003 From: postmaster at pcexpert.ee (postmaster at pcexpert.ee) Date: Sat, 12 Jul 2003 01:35:15 +0300 Subject: Undeliverable: Re: Application Message-ID: <318DD801337CD3119FEB009027CCDD78FCCC33@trantor.pcexpert.ee> Your message To: rar at pcexpert.ee Subject: Re: Application Sent: Sat, 12 Jul 2003 01:33:10 +0300 did not reach the following recipient(s): rar at pcexpert.ee on Sat, 12 Jul 2003 01:35:06 +0300 The recipient name is not recognized The MTS-ID of the original message is: c=us;a= ;p=ay;l=TRANTOR03071122353GL6JAHC MSEXCH:IMS:AY:PCEXPERT:TRANTOR 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Application Date: Sat, 12 Jul 2003 01:33:10 +0300 Size: 836 URL: From logiplex at qwest.net Wed Jul 30 17:50:56 2003 From: logiplex at qwest.net (Cliff Wells) Date: 30 Jul 2003 14:50:56 -0700 Subject: Misuse of In-Reply-To: References: <3f27f0e3$1@news.broadpark.no> Message-ID: <1059601855.8920.4237.camel@software1.logiplex.internal> On Wed, 2003-07-30 at 10:25, max wrote: > The problem with spaces is that you need to do 5 times the work of a tab > to get decent-looking indentation :). Or you get a decent editor that inserts 4 spaces when you hit tab and erases 4 spaces when you hit backspace. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From donn at u.washington.edu Tue Jul 15 12:44:54 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 15 Jul 2003 09:44:54 -0700 Subject: PyErr_SetString() != raise ? References: Message-ID: In article , David Eger wrote: > When I use PyErr_SetString() in an extension, python just keeps on > chugging instead of acting as though a Python exception had been > 'raise'd. Why is this, and do I really have to write the Python code > to raise an exception manually after I've used PyErr_SetString()? > > Most recently, writing an iterator -- I write: > > if (nextEl == NULL) { > PyErr_SetString(PyExc_StopIteration, "Array index out of bounds"); > return NULL; > } > > in my iterator extension, but when I use my extension, I get an infinite loop: ... > (and so on, and so on...) The thing is, even though I *set* the > exception with PyErr_SetString, to the interpreter, it doesn't get > raised. Am I just misinterpretting how PyErr_SetString is supposed > to work? Sounds like it. PyErr_SetString installs the exception, but it doesn't raise it. The most common way a C function causes an exception to be raised is to return 0 (or NULL, if you prefer) where a non-zero (PyObject *) is expected. So you are doing that, but I don't know if it's effective in that particular context. Some functions have other conventions, for example type initialization returns 0 for success. More research required. At any rate, don't worry about whether the exception has been initialized, at the moment that is not your problem. Donn Cave, donn at u.washington.edu From mcfletch at rogers.com Tue Jul 22 00:11:14 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 22 Jul 2003 00:11:14 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: Message-ID: <3F1CB962.7020508@rogers.com> Bengt Richter wrote: >On 20 Jul 2003 09:39:51 -0400, aahz at pythoncraft.com (Aahz) wrote: > > ... >I was wondering if Mike was wanting to have class C(...) with property p >(meaning the property object is an attribute of class C or a base), and >wanting also to have the instance dict contain the data as c.p rather >than, say, c._p. > Well, that's a regular property. I have lots of those. I'm looking for a meta-property here. >IOW, does he want a sneaky way to avoid seeing the underscored or otherwise >modified names in the object, so as to have a clean dir(c)? > Yes, that's part of it. >Other than the problem of getting the class defined in a dynamically configurable way >via metaclasses or other machinery, c.__dict__['p'] = value_from_property_fset should >work, IWT. The code below does that, though a little more parameterized ;-) > Yup, it all works fine for regular instances, the question is, how to do it for classes in a way which as closely as possible mimics what is done with instances. Michael's code is, AFAICS so far, the only stuff that yet addresses this. >What I'm not getting is why a dict proxy is getting in the way, unless there is an >attempt to use the property mechanism to store properties-as-values in a class-as-instance. > Precisely that. Using the same general mechanism, properties of a class modifying instances of that class, in this case, the class is a meta-class and the instances are regular classes. The problem is that the dict-proxy of classes gets in the way of this rather straightforward combination of the two concepts of "property" and "metaclass". >If so, does he (continuing 3rd person since I'm replying to AAhz. Hi Mike ;-) > Hi! :) >really want >all that dynamic meta-stuff to happen every time a class is instatiated, or should the >classes-to-use be created once at some configuration time (maybe system start or other >special times), and thereafter appear to be equivalent to plain valnilla manually written >classes with properties? > I think you're imagining much simpler usage patterns than I am. The basicproperty hierarchy includes such things as lazy calculation/retrieval of values from database, default-value calculation in the abscence of explicit settings, logging/change notification, etceteras. I want to make those services available for the dynamically loaded plug-in classes (as distinct from instances of those classes) in such a way that it seamlessly integrates with the rest of the system and doesn't warp the code too horribly. The only thing blocking that from happening is a low-level way to set/get attributes in a class' __dict__ without triggering the __setattr__ machinery. This is a deficiency in the Python descriptors API that I'd like to see fixed. The plug-in classes do tend to have large numbers of regular (non-meta) properties as well, BTW, but that's not interfering with anything. >If the latter, some kind of factory module that manufactures configured classes with >configured properties and puts them in its global name space to be used in apparently >normal "import m; inst=m.C()" fashion would seem better than metaclass inheritance magic behind C. >If there are other configuration times than first-import, the module could have a special >factory functions for that, IWT (as in cpc.py below). The properties of the final >configured/manufactured classes could of course act with any degree of dynamism desired >when accessed as attributes of the final class instances. > Not what I'm trying to do. I have lots of mechanisms for dynamically creating instance properties from a database, creating them from data-structures, or creating them as names in class namespaces as per normal. That stuff all works fine, it's the meta-properties which cause problems. >BTW, do I recall somewhere seeing that defining __dict__ as a slot induces creation of >a writable dict, and could that be used to get a dict in place of proxy for the trouble spot? > Nope, __slots__ doesn't work with type objects. >For Mike: > >What does the following not address (I assume you can rearrange things to your taste ;-) >that you want to do? (InfoSource is my placeholder as an example for whatever dynamic >configuration of the ultimate class you want to do). > It doesn't create active properties on the class instances (meta-properties) (as far as I can see, anyway). See my response to Michael's post for an example of what's being attempted. BTW, sorry for not responding immediately, it often takes me a while to sit down and work through large posts with lots of code to work through to understand the point of the post. Michael's code was short enough that I could dash off a response before dinner, while yours was considerably more involved and required me to set aside time to work through what you were doing and asking. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From nav+posts at bandersnatch.org Fri Jul 25 15:29:19 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 25 Jul 2003 15:29:19 -0400 Subject: The global statement References: Message-ID: "David Hitillambeau" writes: > I want to enable some sharing between the two functions (foo and bar) > using one global variable in such a way that each function can have read > and write access over it. Using the "global" statement seems unpythonic to me, for reasons I'm too lazy to come up with good ways to express. :^) This is what I do, if I need something like this: ----------------------------- class Global: """Generic container for shared variables.""" pass def foo(): Global.somevar = 'set in foo' def bar(): print Global.somevar foo() bar() ----------------------------- HTH, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From jjl at pobox.com Fri Jul 4 11:30:38 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Jul 2003 16:30:38 +0100 Subject: Python is a gem, you need to keep pushing it .... References: <41A1CBC76FDECC42B67946519C6677A9A20BBA@pippin.int.etrials.com> Message-ID: <87u1a28g2p.fsf@pobox.com> delphiro writes: [...] > > For Windows GUI apps Delphi has a great screen-builder and a > > collection of 3rd party component (many freeware) that puts > > Tk/Swing/wxWindows/QT/GTK/everything else available to Python to > > shame. > > Well, part of that is true.. you can drag and drop almost any > possible component on a form and start working. This takes more time > in Pyhton (in my case with wxPython) but I don't think Python should [...] > useful. Easy does it, though I must admit that the GUI part will > develop faster with the Delphi IDE (rough guess, about 2-3 times in > development speed). [...] Have you tried PyQt and Qt designer (with Qt 3)? Interested to know how it compares to Delphi / Kylix. Probably there are many fewer 3rd-party (commercial or otherwise) Qt components than there are Delphi components. Of course, Qt 3 itself has a lot of stuff there already (including database stuff, a very good table widget, and a good rich text widget). http://www.trolltech.com/company/third_party.html?cr=1 John From calderano at sgaspa.it Thu Jul 31 09:10:49 2003 From: calderano at sgaspa.it (Luca Calderano) Date: Thu, 31 Jul 2003 15:10:49 +0200 Subject: handle
tags Message-ID: <002e01c35765$2a2b73b0$410100a4@utente65> Hi guys... I've done a subclass of SGMLParser to handle the contents of a web page, but i'm not able to handle the
tag can someone help me??? S.G.A S.p.A. Nucleo Sistemi Informativi Luca Calderano From drlinux at columbus.rr.com Thu Jul 3 13:16:21 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Thu, 3 Jul 2003 13:16:21 -0400 Subject: python 2.3b[12] In-Reply-To: <200307031200.25633.drlinux@columbus.rr.com> References: <3F037015.3D6D7034@alcyone.com> <200307031200.25633.drlinux@columbus.rr.com> Message-ID: <200307031316.21192.drlinux@columbus.rr.com> On Thursday 03 July 2003 12:00, Dave Reed wrote: > On Wednesday 02 July 2003 19:51, Erik Max Francis wrote: > > Dave Reed wrote: > > > > > ./python > > > Python 2.3b1 (#1, Jun 14 2003, 15:08:24) > > > [GCC 3.2.3] on sunos5 > > > Type "help", "copyright", "credits" or "license" for more > information. > > > >>> > > > > > > I thought maybe this was just someone forgetting to update the > startup > > > message for the new beta, but I've seen other messages that show > > > Python 2.3b2. > > > > > > Any ideas on what happened? > > > > Hmm, mine doesn't (built from scratch on Linux): > > > > max at oxygen:~% python2.3 > > Python 2.3b2 (#1, Jun 29 2003, 20:30:58) > > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > > > Are you sure you're running the version you think you are? > > > I even ran it directly from the build directory and it still reports > b1. > > I do have b1 installed in another directory (that was in the path when > I compiled b2). Maybe I need to remove that version of python before > compiling the new one. I used different --prefix= values when > compiling each one, but since the other one was still in the path, it > may have messed up. > > Dave Still get 2.3b1. Here's the file size of the Python-2.3b2.tgz file: 8421285 Is that correct? Dave From jjl at pobox.com Thu Jul 17 08:17:54 2003 From: jjl at pobox.com (John J. Lee) Date: 17 Jul 2003 13:17:54 +0100 Subject: Replacing rexec References: Message-ID: <87adbd73f1.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: [...] > There's been some talk, but it's likely that a secure Python will > require forking the code. Note that it's already too easy to write a > DoS attack against Python: 100L**100**100 will do it. Conversely, if > only trusted code is going into the server, there's no need for rexec. [...] I don't see how it's possible to prevent that, whatever language you're using. http://www.securingjava.com/chapter-four/chapter-four-3.html | It is ironic that some of the most Java-heavy Web pages almost go as | far as denial of service in doing what their programmers intended <0.3 wink> Isn't it true that the only solution to a program taking up too much of a system's resources is to cap its resource usage, or stop it running? Usually, it's the OSs job to do that (which you might view as almost the definition of an OS, perhaps) -- is that a bad thing? John From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Jul 14 14:21:45 2003 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: 14 Jul 2003 11:21:45 -0700 Subject: mx.DateTime.Parser.DateFromString('crap') References: Message-ID: <451fb248.0307140616.3584c85f@posting.google.com> David Bolen wrote in message news:... > Koczian writes: > > Double check that you're using a recent version of the egenix base > package (probably 2.0.3 or later). The parser module functions such > as DateFromString were augmented to accept an optional list of parsers > to try, which allows you to override the default. The default does > include an "unknown" parser which will default to the current date as > in prior versions, but if you exclude that you'll get a ValueError > exception if none of the other parsers match. > > For example: > > >>> import mx.DateTime > >>> print mx.DateTime.Parser._date_formats > ('euro', 'us', 'altus', 'iso', 'altiso', 'lit', 'altlit', 'eurlit', 'unknown') > >>> print mx.DateTime.Parser.DateFromString('crap') > 2003-07-10 00:00:00.00 > >>> myformats=mx.DateTime.Parser._date_formats[:-1] > >>> print myformats > ('euro', 'us', 'altus', 'iso', 'altiso', 'lit', 'altlit', 'eurlit') > >>> print mx.DateTime.Parser.DateFromString('crap',formats=myformats) > Traceback (most recent call last): > File "", line 1, in ? > <...snip...> > ValueError: unknown date format: "crap" > Exactly. Found this out after posting, of course, except that I overlooked the "_date_formats" and typed in everything myself. Thank you for not pointing out that it's all in the doc ... next time I'll look more carefully. Koczian From mwilson at the-wire.com Thu Jul 31 16:11:49 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 31 Jul 2003 16:11:49 -0400 Subject: .setdefault() References: Message-ID: In article , Tino Lange wrote: >Hi! > >I just realized that .setdefault *always* executes the second >argument - even if it's not necessary, because the requested item in >the first argument exists. >[ ... ] >Is this really by design? If there's a complicated, expensive to >calculate/build 2nd argument (maybe a function call) then it's also >quite ineffective to evaluate it just to throw away... Like they say, it's the way all functions, like setdefault, work. Arguments have to be evaluated before the function is called. Maybe you want try: some_var = some_dict[key] except KeyError: some_var = some_dict[key] = default_expression_value in code where `default_expression_value` isn't ready to hand. Lazy evaluation is easy, as long as you don't mind using statements. Regards. Mel. From not.valid at address.org Wed Jul 2 15:10:09 2003 From: not.valid at address.org (not your business) Date: Wed, 02 Jul 2003 19:10:09 GMT Subject: How Do You Get Redirected Input? Message-ID: I have a shell tool that accepts arguments on the command line. I would like to check if the input is being piped in. That is, $ mytool.py < cmdlst.txt In this case sys.argv is empty. So I added pipein = os.read(sys.stdin.fileno(),256) if (pipein): input_args = pipein.split() else: input_args = sys.argv[1:] Problem is that if nothing is redirected in, the script waits for a Enter pressed on the the keyboard. Anyone know a solution to this? Thanx in advance for any help. From adalke at mindspring.com Tue Jul 29 20:29:59 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 29 Jul 2003 18:29:59 -0600 Subject: while (assignment): References: <2259b0e2.0307290844.6cbcad85@posting.google.com> Message-ID: Michele Simionato > Second answer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234 I just added this alternative >>> a = [1, 2, 9, 0] >>> n = iter(a).next >>> while [x for x in [n()] if x]: ... print "I have", x ... I have 1 I have 2 I have 9 >>> Again, don't this in real code. Evil. But cute. Andrew dalke at dalkescientific.com From manuelbastioniNOSPAM at tin.it Fri Jul 25 18:54:34 2003 From: manuelbastioniNOSPAM at tin.it (manuel) Date: Fri, 25 Jul 2003 22:54:34 GMT Subject: decimal to binary References: <200307250653.18754.gherron@islandtraining.com> Message-ID: > if listByte[17] & (1 << 3): Thanks! But I don't understand completely the meaning of & (1 << 3) Can you suggest me a page in python on line manual, or a tutorial? From h.b.furuseth at usit.uio.no Fri Jul 18 03:30:32 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 18 Jul 2003 09:30:32 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: Oren Tirosh wrote: >On Fri, Jul 18, 2003 at 03:11:56AM +0000, Bengt Richter wrote: >> Needs to be charset=utf-8. iso-8859-7 has no character number 947. >>

γ(...) > Actually, you don't need the "CHARSET=iso-8859-7". It would be > required if you used the bytes 227, 223, 227, 237, 249, 243, 234, 249 > to represent the characters. With numeric character references you can > embed any character from the UCS repertoire regardless of the charset > used. &#; seems to mean character number NUM in the current character set, not in UCS. At least on NS 4.79. -- Hallvard From torh at operamail.com Tue Jul 8 10:30:42 2003 From: torh at operamail.com (Tor) Date: Tue, 8 Jul 2003 16:30:42 +0200 Subject: anything new on the ternary operator? References: Message-ID: (if C: x else: z) Was this the winning syntax? I think I saw it somewhere without the parentheses, in something written by GvR. This syntax would have been great without the parentheses. A bit messy with them, especially when they really don't add any readability, like this return if C1: x elif C2: y else: z Why are the parentheses neccessary (and are they really)? From sysop at qwest.net Fri Jul 4 04:47:50 2003 From: sysop at qwest.net (System Operator) Date: Fri, 4 Jul 2003 03:47:50 -0500 Subject: Movie In-Reply-To: <200307040847.DAA45846@mail.oss.uswest.net> References: <200307040847.DAA45846@mail.oss.uswest.net> Message-ID: <200307040847.h648loiN000498@blackmagic.oss.uswest.net> *** THIS IS AN AUTOMATED RECEIPT NOTIFICATION *** ** THE RETURN ADDRESS ON THIS MESSAGE HAS BEEN SET TO PREVENT MAIL ** ** LOOPS IN THE EVENT THAT YOU ARE RUNNING SOFTWARE WHICH AUTO-REPLIES ** ** TO INBOUND MAIL. QWEST WILL NOT SEE ANY REPLY SENT TO THIS MESSAGE. ** This message is a response to your report of an Acceptable Use Policy (AUP) violation involving a Qwest customer, entitled: < Re: Movie > If you do not wish to receive this automatic response, send future reports to . "Pop-Up" Spam If you are receiving "pop-up" spam advertisements, please see the following web page for information on how to disable the Microsoft Messenger service. http://support.microsoft.com/default.aspx?scid=kb;en-us;Q330904 Thank you for reporting this incident to Qwest. We are have received your report and are investigating the situation. Once we have completed our investigation, we will take appropriate action against the offending customer account. Due to the current high volume of abuse mail we handle, this may be the only response you receive, unless we need further information to complete the investigation. If you are reporting an email abuse issue such as UBE or spam, please include the following information so that we can complete a full investigation of your report: 1) Original subject line- When you forward email, please forward it with a subject header the same as when you received it. 2) Complete headers- Most email programs only display abbreviated headers. Please check your email program's documentation for assistance in how to display the full headers. Full headers will include a "RECEIVED:" line with a set of four numbers divided by periods (ex. 123.45.67.89) We cannot complete an investigation without this information. 3) Complete message body- Please include the complete, unedited body of the message as you received it. If you are reporting unauthorized access attempts, please be sure to include logs of the incident, including the IP address of the offender, as well as the date, time and time zone when the incident occurred. ** Please note: Submissions must be in plain text format. ** ** All attachments are removed upon receipt and discarded. ** -- Qwest Internet Solutions sysop at qwest.net, abuse at qwest.net (A)cceptable (U)se (P)olicy (AUP) http://www.qwest.com/legal/usagePolicy.html From shalehperry at comcast.net Fri Jul 4 14:04:50 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Fri, 4 Jul 2003 11:04:50 -0700 Subject: Least used builtins? In-Reply-To: References: Message-ID: <200307041104.50261.shalehperry@comcast.net> On Friday 04 July 2003 10:27, Dan Bishop wrote: > sandskyfly at hotmail.com (Sandy Norton) wrote in message > news:... [snip] > > > I know there some plans to reduce the number of builtins in some > > future version of python (Python 3.0?): So which builtins do you least > > use? > > > > Pesonally, I don't think I've ever used the following: intern, buffer, > > coerce > > I haven't used: apply, buffer, coerce, globals, intern, iter, locals, > oct, slice, super, unichr, unicode. apply isn't as useful as it used to be. locals and globals is useful in some interesting ways. iter is really new so no surprise you haven't used it yet. most people don't play with octal so I doubt oct() gets a lot of mileage. The unicode stuff is new and most English only coders don't use it. But the rest of the world does. From http Sun Jul 20 20:44:34 2003 From: http (Paul Rubin) Date: 20 Jul 2003 17:44:34 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> Message-ID: <7x7k6cu2rx.fsf@ruckus.brouhaha.com> "Ulrich Petri" writes: > Here in germany we also have elections where more than one thing is voted > upon but if that is the case we have a seperate ballot for each of those > descisions and they all go into different "boxes" and are counted by > different people. What is a typical number of such boxes? In a US election, the number of "boxes" that would be needed is usually more than 20 and can be as many as 50. Not just politicians but also judges, sheriffs, and ballot questions like whether to build a new school in a given location, all get voted on. Do you really want to fill out 50 separate pieces of paper in a voting booth, and then make sure to deposit each one in its own correct separate box? From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 18:26:05 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Aug 2003 08:16:05 +0950 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> <9rehivsavhereijf36nhla96krct4s1fmn@4ax.com> Message-ID: On Thu, 31 Jul 2003 13:03:15 +0200, Gerhard H?ring wrote: > Christopher Koppler wrote: >> [tab settings] >> And, as others have said, DON'T use 5. > > I'd still like to hear a reason for this. -- \ "During the Middle Ages, probably one of the biggest mistakes | `\ was not putting on your armor because you were 'just going down | _o__) to the corner.'" -- Jack Handey | Ben Finney From p-abel at t-online.de Sat Jul 19 06:41:36 2003 From: p-abel at t-online.de (Peter Abel) Date: 19 Jul 2003 03:41:36 -0700 Subject: Python dictionary syntax, need help References: <56ba0aea.0307181142.7401aa02@posting.google.com> Message-ID: <13a533e8.0307190241.69252b08@posting.google.com> crewr at daydots.com (Crew Reynolds) wrote in message news:<56ba0aea.0307181142.7401aa02 at posting.google.com>... > I want to create a dictionary of note on/off timings and access it by > the name of the object. The following code works for one row. > > a = "Hammer1" > b = [5,45,45,45,45,50,55,57,59,61,60,59] > > notes = {a:b} > print notes["Hammer1"][3] > >>> 45 > > The problem is, I want to load the data from a file to populate > variables a and b and build a dictionary for "Hammer1" thru > "Hammer10". That way, I can stick the name of the object in the array > index and receive a list of note timings that I can index with an > ordinal as in the above example. > > This is straight Python syntax but I'm hoping someone has done this or > understands the syntax better than I. > > Thanks! Alternative solutions to this concept would be greatly > appreciated. >>> # Reading the note_txt from file and splitting it by lines >>> # by split('\n') and not by realines to avoid '\n' at the end of line >>> note_lines=file('notesfile.txt').read().split('\n') >>> # If the last line had a '\n' at the end you'll get >>> # an empty list for the last line. We'll get rid of it. >>> if not len(note_lines[-1].strip()):del note_lines[-1] ... >>> # Splitting the lines by comma to get a list for each line >>> # It's supposed that the first item is the key >>> note_lists=map(lambda line:line.split(','),note_lines) >>> # Making a dict from tuples(key,list), where the key is the >>> # 1st item of note_list[i] and list is the rest of note_list[i] >>> notes=dict( map(lambda l: (l[0],l[1:]) , note_lists) ) >>> # The result: >>> for (k,v) in notes.items(): ... print '%-10s: %s'%(k,v) ... hammer1 : [' 5', ' 45', ' 45', ' 45', ' 45', ' 50', ' 55', ' 57', ' 59', ' 61', ' 60', ' 59'] hammer3 : [' 35', ' 345', ' 345', ' 345', ' 345', ' 350', ' 355', ' 357', ' 359', ' 361', ' 360', ' 359'] hammer2 : [' 25', ' 245', ' 245', ' 245', ' 245', ' 250', ' 255', ' 257', ' 259', ' 261', ' 260', ' 259'] hammer4 : [' 45', ' 445', ' 445', ' 445', ' 445', ' 450', ' 455', ' 457', ' 459', ' 461', ' 460', ' 459'] >>> Regards Peter From kylotan at hotmail.com Wed Jul 9 05:29:13 2003 From: kylotan at hotmail.com (Kylotan) Date: 9 Jul 2003 02:29:13 -0700 Subject: urllib2 for HTTPS/SSL References: <153fa67.0307080233.2f7abdf5@posting.google.com> Message-ID: <153fa67.0307090129.2d6bef57@posting.google.com> Jeremy Hylton wrote in message news:... > On Tue, 2003-07-08 at 06:33, Kylotan wrote: > > I have no idea how (or if) to use the 'HTTPSHandler' object, or what > > the correct way for me to request an SSL connection is. Does anybody > > have any hints? And additionally, is there any chance of the official > > documentation on this useful-looking module being improved? > > Unless I misunderstand your intent, you don't need to use the Handler > object directly. HTTPS support is provided automatically, so long as > your local Python has SSL support. (It should.) Ok, so what you're saying is that the stuff documented in: "Python Library Reference - 11.5.14 HTTPSHandler Objects" is purely an implementational detail? In other words, they're specifying examples of Handler classes in case you wanted to see how to write one yourself, but to use the urllib2 library normally you'd never need to really know this? I'm guessing the OpenerDirector object tries the URL with each BaseHandler-derived object to see which one should handle it. Thanks, K. From bgailer at alum.rpi.edu Sun Jul 6 19:19:19 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 06 Jul 2003 17:19:19 -0600 Subject: anything new on the ternary operator? In-Reply-To: Message-ID: <5.2.1.1.0.20030706171559.02597288@66.28.54.253> At 10:59 PM 7/6/2003 +0200, Tor wrote: >What's the current status on the ternary operator that may or may not be >added to python. Haven't heard much about that since the vote was announced >for a couple of months ago. What's the best way to follow that dicussion? >Or are we just waiting for the developers to make their decision? Last I heard it was killed by Guido, which makes me wonder why we spent so much time discussing and voting. If he did not want it I wish he had killed it at the start. I thought the vote was to determine the best choice, and I was looking forward to having it. Makes me wonder about the whole PEP process. Why bother! Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From peter at engcorp.com Mon Jul 14 08:04:29 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 08:04:29 -0400 Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> Message-ID: <3F129C4D.F4CF0BB8@engcorp.com> richardc wrote: > > Ive just started playing with Python and have a couple of questions. > > Im looking for an agument parsing library (from the command line), Ive come > across optik and argtools. What other ones are there are any of them any > good, is there a 'standard' lib for doing this. getopt is a long-standing standard module for this, and I find it very simple and functional for small utilities, while Optik has been assimilated in the latest release as standard module optparse, as you can see from this page: http://www.python.org/dev/doc/devel/whatsnew/node18.html#SECTION0001820000000000000000 > Also how should I '#define' magic numbers in Python. I spent ages looking > around for a 'define' statement or anything that will allow me to create a > constant value 'object'. Am I missing something very obvious ? Python has no "constants" per se, but you shouldn't need them either. Just define variables, following the convention of using ALLCAPS to name them: MY_CONSTANT = 5 -Peter From skip at pobox.com Wed Jul 2 18:43:20 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 17:43:20 -0500 Subject: Remote db connections possible with DCOracle2? In-Reply-To: <200307021518.22410.dave@pythonapocrypha.com> References: <16131.19186.190625.679324@montanaro.dyndns.org> <200307021518.22410.dave@pythonapocrypha.com> Message-ID: <16131.24584.242446.711276@montanaro.dyndns.org> Dave> Use this style of connection string (all one line if it wraps): Dave> user/password@(description=(address=(host=10.20.30.40)(protocol=tcp)(port=1521))(connect_data=(sid=dbsid))) Thanks. The example or two I saw indicated something like user/password at dbname where I presume "dbname" is looked up in tnsnames.ora. Skip From mfranklin1 at gatwick.westerngeco.slb.com Mon Jul 21 04:01:24 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 21 Jul 2003 09:01:24 +0100 Subject: Python scripting with Paint Shop Pro 8.0 In-Reply-To: References: Message-ID: <200307210901.24335.mfranklin1@gatwick.westerngeco.slb.com> On Sunday 20 July 2003 13:48, Marc Wilson wrote: > Hi, > > I'm a complete Python newbie, though I know at least one regular in here. > :) > > I've just got Paint Shop Pro 8.0, and the functionality of the old > ImageRobot add-on has been replaced with the new Python Scripting. > > So far, OK. > > What I'm trying to determine is: can I run these scripts from a > command-line invocation? I want to use the scripts to automatically > convert files as they arrive, uploaded onto a website, not interactively. > > Has anyone played with this? > -- > Marc Wilson > Marc, This is not an answer to your question... but if you just want to convert an image file into another format then upload it to a server you could use a pure python solution (well pure python + PIL) PIL is here:- http://www.pythonware.com/products/pil/ In fact a quick browse through the handbook and I found this:- http://www.pythonware.com/library/pil/handbook/pilconvert.htm and I quote:- """ Convert an image from one format to another. The output format is determined by the target extension, unless explicitly specified with the -c option. $ pilconvert lena.tif lena.png $ pilconvert -c JPEG lena.tif lena.tmp """ To upload the image to a server you could use the ftplib module... Regards Martin From ta-meyer at ihug.co.nz Fri Jul 11 02:14:07 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 11 Jul 2003 18:14:07 +1200 Subject: IMAP BODYSTRUCTURE format & the email.Messages In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13025656A5@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AAFE@its-xchg4.massey.ac.nz> [Apologies for the cross-post]. Does anyone know of existing code to convert/format/flatten an email.Message into the correct format for IMAP's BODYSTRUCTURE request? (it basically breaks down all the MIME parts of the message). It can use twisted or imaplib, or neither, I don't care. Thanks, Tony Meyer From robin at jessikat.fsnet.co.uk Wed Jul 23 03:45:32 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 23 Jul 2003 08:45:32 +0100 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: In article , Ian Bicking writes > >class _Something: > ... > >TheSomething = _Something() > > >Then just never refer to _Something again. Import TheSomething (calling >it whatever you want), and use it, not its class. It's a singleton >because there's only one of them. Simplicity! > > Ian > ....can't one do class TheSomething: .... TheSomething = TheSomething() then it's harder to get at the class which presumably is now only available as TheSomething.__class__ -- Robin Becker From icebeing1 at dslextreme.com Fri Jul 25 14:53:03 2003 From: icebeing1 at dslextreme.com (C. Martin) Date: 25 Jul 2003 11:53:03 -0700 Subject: win32com exception when trying to invoke IE 6.0 Message-ID: <2e873c65.0307251053.c9b32ce@posting.google.com> Hi all, I have a script where it goes around opening 30 Internet Exploder windows and uses one of them to browse 20 websites (and some of those sites have nasty pop-ups too, but what can you do?) Anyway, I'm running into the following exception: refreshing website: http://www.quicktime.com/ refreshing website: http://www.hightimes.com/ refreshing website: http://www.anonymizer.com/ refreshing website: http://www.term-papers-4u.com/ refreshing website: http://www.careerbuilder.com/ refreshing website: http://www.ew.com/ refreshing website: http://www.moviefone.com/ refreshing website: http://www.tvguide.com/ refreshing website: http://www.gambling.com/ refreshing website: http://www.rotten.com/ refreshing website: http://www.humorlinks.com/ Traceback (most recent call last): File "D:\pyscripts\urlbrowse2.py", line 86, in ? b.Navigate(string.rstrip(url_list[u])) File "win32com\gen_py\EAB22AC0-30C1-11CF-A7EB-0000C05BAE0Bx0x1x1.py", line 112 4, in Navigate pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024726), None) I have seen similar posts on this issue in the past, and I recall Mark H. mentioning the script can wait for IE to finish loading a page before terminating the browser. I'm wondering if anyone out there has found a solution to this problem? Cheers, Charles M. From tjenista at ball.com Tue Jul 1 08:20:10 2003 From: tjenista at ball.com (Todd Jenista) Date: 1 Jul 2003 05:20:10 -0700 Subject: Unicode problem.... as always Message-ID: <631aeedc.0307010420.685500e9@posting.google.com> I have a parser I am building with python and, unfortunately, people have decided to put unicode characters in the files I am parsing. The parser seems to have a fit when I search for one \uXXXX symbol, and there is another unicode symbol in the file. In this case, a search and replace for ? with a ? in the file causes the infamous ordinal error. My quick-fix, because they have good context, is to change them both to "UTF8", and then attempt to replace the UTF8 at the end with the original ?. The problem is that I am getting a ?? when I try to re-insert using \u00b5 which is the UTF8 code. Words of wisdom would be greatly appreciated. From adechert at earthlink.net Sun Jul 20 21:03:59 2003 From: adechert at earthlink.net (Alan Dechert) Date: Sun, 20 Jul 2003 18:03:59 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <1ED4ECF91CDED24C8D012BCF2B034F130212AB6B@its-xchg4.massey.ac.nz> Message-ID: <006201c34f23$f8a63e40$960277d8@alandech> ----- Original Message ----- From: "Tony Meyer" To: "'Alan Dechert'" ; Sent: Sunday, July 20, 2003 5:18 PM Subject: RE: Possible use of Python for a voting machine demo project -- your feedback requested > > > > 3) When "WRITE-IN CANDIDATE" is selected, a large widow > > > > (maybe the full screen) will pop up with a QWERTY keyboard > > > > in the upper half. This keyboard > > > > will have only three rows with the alpha keys (no punctuation or > > > > numbers needed except for perhaps the hyphen... no shift, all CAPS). > > > > > > No apostrophe? What if I want to vote for "O'Reilly" > > > > > As a matter of fact, we won't let you vote for O'Reilly. On > > second thought, you're right, I guess. Okay we'll have an > > apostrophe available. Anything else? > > What about non-English names? Names with umlauts, accents, Asian > characters, and so on? > Good question. Eventually, our on-screen keyboard would enable the voter to choose accented characters. I'm thinking there would be an "ACCENTED CHARACTER" button that you'd select such that when you select "E" on the keyboard after pushing the button you'd get a drop down list of accented Es from which you could select the desired one. I'm not sure if we'll implement that in the demo (probably not, actually). Probably, Asian characters will only be available if and when the voter has chosen the Asian language at the outset (as it is, the non-English languages available varies from county to county and state to state... it may even vary from city-to-city within counties. Many, if not most, jurisdictions only offer English language ballots). Then, the keyboard would behave the way Asian language keyboards normally behave. For the demo, I think we will have at most one other language (probably Spanish) to select. When the printout of choices is given when a non-English language has been selected, I think the English equivalent will be printed along with the translation. When it comes to write-in votes, we probably won't be able to do that. This only becomes an issue where enough write-in votes are recorded such that it could affect the outcome. Right now, election law varies a great deal on how to deal with write-ins. In some cases (e.g., Florida) write-ins have to meet some sort of qualifications (no. of signatures) before they can be written in. Again, this is something to look at in some depth when our full blown voting study is underway. Alan Dechert From ben at dadsetan.com Sun Jul 13 16:57:05 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Sun, 13 Jul 2003 22:57:05 +0200 Subject: Newbie with sort text file question In-Reply-To: <86d2ca4.0307121146.3deb854a@posting.google.com> References: <86d2ca4.0307121146.3deb854a@posting.google.com> Message-ID: <3F11C7A1.8010406@dadsetan.com> stuartc wrote: > Hi: > > Here's the text file: > > banana_c \\yellow > apple_a \\green > orange_b \\yellow > banana_d \\green > orange_a \\orange > apple_w \\yellow > banana_e \\green > orange_x \\yellow > orange_y \\orange > > I would like two output files: > > 1) Sorted like this, by the fruit name (the name before the dash) > > 2) Then summarized like this, ordered with the highest occurances > first: Here is some mostly tested code ;) import re file = open ("textfile.txt") # your file name instead of textfile.txt alllines = list(file.readlines()) file.close() alllines.sort() fruitre = re.compile('^[a-z]+') fruits = {} for line in alllines: fruitresult = fruitre.search(line) print line if fruitresult: fruit = fruitresult.group(0) fruits.setdefault(fruit, 0) fruits[fruit] += 1 totalamount = 0 for fruit, amount in fruits.items(): print fruit, " occurs ", amount totalamount += amount print "Total amount of fruits ", totalamount Regards, Ben. PS: It looks a little unoptimized to me but it works. Hopefully others will reply to you as well so I can learn how to make the above better. From mpeuser at web.de Tue Jul 22 06:40:21 2003 From: mpeuser at web.de (Michael Peuser) Date: Tue, 22 Jul 2003 12:40:21 +0200 Subject: Pause in a loop References: <%W7Ta.10360$t92.299097@news1.tin.it> Message-ID: "manuel" schrieb im Newsbeitrag news:%W7Ta.10360$t92.299097 at news1.tin.it... > > I've two modules: main.py and eval.py > > Eval.py is imported in main.py, but I've a loop > in eval.py that must call a function in main.py... ..... How is that loop activated in the first place? If you activate it by a call just provide your main-proc as a callback parameter in that call... Kindly Michael From gml4410 at ggr.co.uk Wed Jul 9 11:05:53 2003 From: gml4410 at ggr.co.uk (Lack Mr G M) Date: Wed, 09 Jul 2003 11:05:53 BST Subject: Building Python - how to set include and lib paths? References: <2003Jul4.102150@ukwit01> <2lcqt-p45.ln1@newsgate.kjn.lan> Message-ID: <2003Jul9.110553@ukwit01> In article <2lcqt-p45.ln1 at newsgate.kjn.lan>, Theodor Rash writes: |> Lack Mr G M wrote: |> |> > ... My problem occurs when I am *building* python |> > itself. There seem to be no way that I can tell it where to look for |> > header files and libraries for other packages/utilities (eg: SSL) that I |> > have previously installed or how to add these to compilation and linking |> > options.. It hard-wires /usr/local/{include,lib} for these. |> > |> That's right. I had to patch setup.py to make it find Tcl/Tk which resides |> under /opt in my system. Well, I have a fudge for it... Whereas the configure stage does not allow you to specify where you have things, and neither setup.py nor build.py seem to have any way of changing things either, the even lower level build_ext.py script *does* allow you to specify libdirs. incdirs and rpath info. So, the low-level ability is there (well, some of it is - read on) but no higher-level ability to actualy use it :-( So, after running a standard make (where some things fail). I then run a script which: a) sets environment variables CC, LDSHARED and OPT to the values set in the Makefile. b) Run build_ext directly using ./python -E ./setup.py build_ext \ --include-dirs=${_incdir} \ --library-dirs=${_libdir} \ --rpath=${_libdir} where ${_incdir} and ${_libdir} are set to the :-separated lists I need. Mind you, this fails if your linker uses -rpath rather than -R. Then you also need to edit ccompiler.py and unixccompiler.py in Lib/distutils to: 1) Make runtime_library_dir_option use -rpath as required. 2) Make runtime_library_dir_option return a list, rather than a string, since -rpath requires you to pass back 2 parameters (-R allows catenation as a string). 3) Make the call to runtime_library_dir_option be a loop, to handle the returned list. All very messy.... -- --------- Gordon Lack --------------- gml4410 at ggr.co.uk ------------ This message *may* reflect my personal opinion. It is *not* intended to reflect those of my employer, or anyone else. From Juha.Autero at iki.fi Wed Jul 23 04:28:22 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Wed, 23 Jul 2003 11:28:22 +0300 Subject: python assignment References: Message-ID: <874r1d3avt.fsf@jautero.no-ip.org> "Tim Peters" writes: > It would be very unusual (because bad design) for the __iadd__ > method of a mutable type to return a pre-existing object, though. I'm confused. I thought that the idea of __iadd__ is that for *mutable* types it modifies existing object instead of returning new one. So, was that a typo or are Python lists just bad desing: >>> l=[] >>> f=l >>> f+=[1] >>> f [1] >>> l [1] -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 15 18:35:58 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 22:35:58 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: Message-ID: Tim Gerla enlightened us with: > Very fun stuff. Someday I hope to have a Zaurus or similar device to > toy with. For those interested: I've put up some screenshots of my jabber client, Discuss Jabber, at http://zaurus.thirdtower.com/ Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From fabsk+news at free.fr Mon Jul 28 04:59:12 2003 From: fabsk+news at free.fr (Fabien SK) Date: Mon, 28 Jul 2003 10:59:12 +0200 Subject: default import path In-Reply-To: <3f24c37e@news.maxnet.co.nz> References: <3f24c37e@news.maxnet.co.nz> Message-ID: <3f24e61d$0$24786$626a54ce@news.free.fr> Peter wrote: > > How can I edit the default import path for Python under Windows? > > I want to use the piddle module. So far, I've copied the unzipped contents > of the zip file to c:\prog~1\python\lib\site-packages, but how do I set it > so this is automatically on the python path? > > (I don't want to have to manually add that directory every time.) Hi, I added this key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.2\PythonPath\Some_name and I set the default value for this key to the new Path Have a nice day Fabien From paul_rudin at scientia.com Mon Jul 21 10:40:25 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 21 Jul 2003 15:40:25 +0100 Subject: COM interface to the Python interpreter References: Message-ID: >>>>> "Christian" == Christian Knoblauch writes: > Hello all, under Win32 it is possible to use Python as a > scripting language inside ASP pages (win32lib package), so there > must be a COM interface to the Python interpreter. > I like to use this interface instead of writing my own COM > server to invoke Python scripts from COM aware languages, > unfortunately i can not find the type-library for this > interface. I think there's a possible misconception floating around here... the libary code to support the implementation of com servers in python is not of itself a com server and hence has no type library. > Can one provide this information (perhaps with an litle example) > ? There is code for a "hello world" com server in the win32com documentation - see . There are a couple of other examples in site-packages/win32com/demos (assuming you've installed the win32com stuff). From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 21 15:48:10 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 21 Jul 2003 21:48:10 +0200 Subject: Needing help with sockets In-Reply-To: References: Message-ID: <3f1c4378$0$49110$e4fe514c@news.xs4all.nl> Martin Dion wrote: > I want to be able to connect on any port on a system and then send and > receive commands, by following the protocol rules. > > If I receive data, it must print on the screen. > > It asks for data to send in reply to the data received. > > Once data is sent, it must look if there is data to receive and if not, > it must ask the user to send an other string. > > > The problem, is that once data is sent, it goes to the receive data loop > and blocks until it gets data. Try the select module. This allows you to react to things happening on both IO channels at the same time (user input to send, and data to receive). --Irmen From stuart at bmsi.com Thu Jul 17 18:51:02 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Thu, 17 Jul 2003 18:51:02 -0400 Subject: Documentation examples needed References: Message-ID: On Thu, 17 Jul 2003 00:44:44 -0400, Dave Cole wrote: > Stuart> Is there a small project with documentation in the Python > Stuart> standard that I can use as an example? > > We have some: > > http://www.object-craft.com.au/projects/albatross/ > http://www.object-craft.com.au/projects/sybase/sybase/ Thank you. Your Makefile is much less confusing than the one that comes with Python! It also points out a shortcoming of the RPM packaging. The python2-devel package includes everything you need to compile python extension modules, but does not include what is needed to "compile" python documentation! Are third party module writers not supposed to document anything? :-) It looks like I'll have to download the Python sources and create my own RPMs. Presumably, I do not need *everything* in the Doc directory to compile my own docs. Probably just the tools directory, and maybe texinputs and templates. Is the list of what is needed for 3rd party docs documented somewhere? I can create a python2-doc rpm for it. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From bogus at antispam.com Thu Jul 17 03:25:57 2003 From: bogus at antispam.com (Alex) Date: Thu, 17 Jul 2003 03:25:57 -0400 Subject: Curses module. References: Message-ID: You were both correct. I simply had to get rid on the curses.py program (my first test program) and everything worked fine. Thanks again for the help. I can get down to some serious learning/hair-pulling frustration :) Alex From staschuk at telusplanet.net Tue Jul 22 07:45:24 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 22 Jul 2003 05:45:24 -0600 Subject: Python Mystery Theatre -- Episode 3: Extend this In-Reply-To: ; from vze4rx4y@verizon.net on Tue, Jul 22, 2003 at 07:27:21AM +0000 References: Message-ID: <20030722054524.A835@tibia.amotlpaa.bogus> Quoth Raymond Hettinger: [...] > Let me know if you learned something new along the way. [...] > ACT IV --------------------- > pets = list('cat ') > pets += 'dog ' > pets.extend('fish ') > print pets + 'python' This one was new to me -- I was shocked and amazed to learn that list.__iadd__, unlike list.__add__, accepts arbitrary iterables. [...] > ACT VI ----------------------------------------- > print "What is the technical name for this algorithm or transformation?" [...] Heh. Nice one. The technical name is "the identity transformation". -- Steven Taschuk staschuk at telusplanet.net "What I find most baffling about that song is that it was not a hit." -- Tony Dylan Davis (CKUA) From stuart at bmsi.com Wed Jul 16 22:31:36 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Wed, 16 Jul 2003 22:31:36 -0400 Subject: Documentation examples needed Message-ID: I am still wanting to produce Python standard format documentation for Python extensions I have written. I have looked at the docs that come with Python itself, but I am new to Latex, and don't know how to add the document classes and styles from texinput for a new project. Is there a small project with documentation in the Python standard that I can use as an example? -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From kbass1 at nc.rr.com Sun Jul 6 20:42:27 2003 From: kbass1 at nc.rr.com (Kevin Bass) Date: Mon, 07 Jul 2003 00:42:27 GMT Subject: Newbie Question: Abstract Class in Python References: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Message-ID: "Aahz" wrote in message news:beaed6$e71$1 at panix2.panix.com... > In article <5U2Oa.239646$jp.6482027 at twister.southeast.rr.com>, > Kevin Bass wrote: > > > >I am new to Python and want to know how to implement an abstract > >class? I have read through different books and I have no found this > >information. Thanks! > > Simple answer: you don't. Python doesn't really have that concept. If > you tell us what you're trying to do, we can explain how to do that in > Python. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "Not everything in life has a clue in front of it...." --JMS I am only looking for an answer about creating an abstract class in Python and not a solution to a problem. I am looking for a way to stop class instantiation of a class. This should be a generic approach. Kevin From CousinStanley at hotmail.com Sun Jul 6 00:12:10 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 5 Jul 2003 21:12:10 -0700 Subject: Calculating Year, Month and Day of Life References: Message-ID: hokiegal ... I spent 1971-1978 as a graduate student at VPI chained to a lab bench over in Davidson Hall, so I actually know what a Hokie is ... Best of luck with your Python endeavors ... -- Cousin Stanley Human Being Phoenix, Arizona From alanmk at hotmail.com Fri Jul 18 15:25:20 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 18 Jul 2003 20:25:20 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> Message-ID: <3F1849A0.CB3053D8@hotmail.com> Alan Kennedy >> More worrying however is the failure of modern browsers to display >> the characters when accessed through Google Groups. Martin v. L?wis: > It's not the browsers that display it incorrectly; it is Google > rendering it incorrectly. Fortunately, they keep the original data > at > http://groups.google.com/groups?selm=3F172442.2040907%40v.loewis.de&oe=UTF-8&output=gplain Thanks Martin, a virtuoso demonstration. It is also worth noting that your message and messages quoting it are the only hits that turn up in a Google Groups search using the original greek text as a search term: i.e. I go to Google Groups and paste in the greek letters. This is true of both "global" Google Groups and the Greek version as well: groups.google.com: http://tinyurl.com/hd58 groups.google.com.gr: http://tinyurl.com/hd5l Bravo! (These kudos exchangable for food+beers should you ever decide to visit Dublin :-) To everyone else: Why does this stuff get so complicated? Why does it take a multi-lingual + encoding-guru + protocol-guru + markup-guru + python-bot like Martin von L to get stuff like this done? Does it have to require somebot who writes better quality software (i.e. less defective) than the world's leading search engine, Google, who got it slightly wrong? The idea of raising this came to me when that Russian individual posted a message a few days ago that got very garbled in the transmission, both subject and content. Again, it was only Martin who was able to figure out its content: I, being an ordinary mortal, was left saying "?Qu??" Computers should be about making it easier for people to communicate with each other. And yes I fully realise python's excellence in that regard, thanks in large part to Martin. To me, the "structure data using ASCII" argument seems very similar to the human language position: "English is now universal, therefore all people must learn and speak it if they want to communicate." What if I want to have an irish gaelic word in the subject line of my emails or usenet posts? sl?n libh, -- al?in ? cinn?ide ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From BPettersen at NAREX.com Tue Jul 8 16:13:52 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 8 Jul 2003 14:13:52 -0600 Subject: mx odbc Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE44FC@admin56.narex.com> > From: Kim Petersen [mailto:kp at kyborg.dk] > > Regarding ODBC usage in Python... > > it seems to me that there is a couple of ways to use odbc from python, > one of these is the MX version - now that one has a pretty > steep licence cost (imho). Well, you pay for what you get . If you're interested in a no-cost alternative the adodb module from Henrik Ekelund is a db api layer over ADO which should get you the connectivity you need but may or may not solve your real problem :-) -- bjorn From jjl at pobox.com Tue Jul 29 16:00:47 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 21:00:47 +0100 Subject: emacs python-mode questions: C-c C-c and broken docstring fill References: <87ptjwre0x.fsf@pobox.com> <6qy8yjj5gw.fsf@salmakis.intevation.de> Message-ID: <874r156r2o.fsf@pobox.com> Bernhard Herzog writes: [...about failure to fill...] > One situation where this can happen is if point is the at the @ in the > following triple quoted string: > > """nobody expects the "spanish" @inquision""" > > The following patch should fix this I think (I haven't tested this very > well though): [...] Works for me. Thanks. I'll post this with the bug report I'm just about to file. John From manish.j at gmx.net Sun Jul 27 16:14:21 2003 From: manish.j at gmx.net (Manish Jethani) Date: Mon, 28 Jul 2003 01:44:21 +0530 Subject: multithreading-problem In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Hi, > > I expirienced strange problems when using the module threading: > > class Bar: > def __init__(_, arg): > _.arg = arg > def work(_): > while 1: > print _.arg > > def foo(arg): > b = Bar(arg) > b.work() > > for i in xrange(4): > thread = threading.Thread(target=lambda : foo(i)) > thread.start() > > What I'd expect would be a sequence of prints like this > 1 > 2 > 3 > 4 > 1 > 3 > 4 > 2 > > What I actualy get is this: > 1 > 4 > 4 > 4 > 4 > 1 > 4 > 4 > 4 > > Placing a time.sleep(3) after the thread.start() fixed things. So it appears > that the curried lambda passed as target is somehow a reference equal for > all four invocations. No, I don't believe it to be true. It's probably just that the other threads aren't getting a chance to run. Consider time.sleep(0) in the while loop in work() -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From kjones9 at rochester.rr.com Sat Jul 26 23:13:43 2003 From: kjones9 at rochester.rr.com (Keith Jones) Date: Sun, 27 Jul 2003 03:13:43 GMT Subject: Beginners help with password program! References: Message-ID: For starters, I suggest you install pychecker and use it on any programs you create. Second, every error in python should give you some information as to what line it occurred on. For example: : a = b :Traceback (most recent call last): : File "", line 1, in ? : a = b :NameError: name 'b' is not defined Here it says line 1, because this occurred in Idle. Start by going to that line... 90% of the time, your error will be right there. As for your file... well the line if "login == no:" looks wrong, unless you have a variable named 'no'.. you probably want the string 'no' there. As was mentioned, you probably won't get much help if you ask people to debug for you. Debugging is a major part of programming, and you can't avoid it. So get used to it and get good at it. :D (and learn to test your code thoroughly). Finally, I recommend you use raw_input(...), rather than input(...), and then convert the return value from a string to whatever you need it to be. From altis at semi-retired.com Mon Jul 28 13:27:35 2003 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 28 Jul 2003 10:27:35 -0700 Subject: Python on a USB storage device? Message-ID: Does anyone have experience running Python from a USB storage device? Whether it is the need for doing a demo of your application, doing a bit of consulting, or just showing off Python, it would be handy to be able to run Python on machines that don't already have Python installed. I'm thinking about giving this a try, but wondered if anyone is already doing it and the downsides, if any? CD-ROM is not very effective because the media is read-only and too big to carry in your pocket. I think USB 2.0 is supposed to be roughly 20x faster than USB for storage devices, but I'm guessing that if you can live with the load times for machines that don't have USB 2.0, plain USB should still be effective. HP Windows desktops, Linux, and Mac OS X already have Python installed and Mac OS X (Panther) will have Python 2.3. But even so, you generally have to install additional packages to get the functionality you want. Having all you need on a USB storage device and not needing to install anything on the host machine seems like it would be very convenient. ka From john_bradbury at ___cableinet.co.uk Sun Jul 6 17:03:28 2003 From: john_bradbury at ___cableinet.co.uk (John Bradbury) Date: Sun, 6 Jul 2003 21:03:28 +0000 (UTC) Subject: Server Push References: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> Message-ID: I have used the Netscape examples and can not get them work. I am using Windows and have tried Omnicron and XITAMI servers. What is frustraing me is that I can achieve the desired result in Delphi by simply using : response.sendresponse; request.writestring('progress line'); I was hoping to find similar functionality in Python. John "Irmen de Jong" wrote in message news:3f05b7ab$0$49103$e4fe514c at news.xs4all.nl... > John Bradbury wrote: > > I want to send updates from a long running cgi. I have tried copying perl > > examples of server push and can not get them to work. > > Does anyone have an idiot proof example of a working server push or sending > > output in chunks in Python? > > Check out: http://wp.netscape.com/assist/net_sites/pushpull.html > > There are basically two ways to do this. Either use the > above mentioned "multipart response", which only seems to work on > certain browsers (confirmed on netscape and mozilla, IE doesn't seem > to work). The other method is just flushing your output and > continue to write more data... but this won't allow you to > 'clear the page' in the client's browser (multipart repsonses will). > > --Irmen > From mis6 at pitt.edu Mon Jul 14 14:40:12 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Jul 2003 11:40:12 -0700 Subject: Multiple Class Inheritance Question References: Message-ID: <2259b0e2.0307140658.26192b82@posting.google.com> Andy Jewell wrote in message news:... > Read guildo's essay on new style classes - that explains it all. > > In the 'old days' i.e. before Python 2.2.x the rules were different. Now > a > new algorithm is used which copes better with this. As I said, read the > essay (it's on www.python.org - just search for 'new style classes essay' > ). > > hth > -andyj ... and in Python 2.3 the rule has changed again ... http://www.python.org/2.3/mro.html Michele From gh at ghaering.de Wed Jul 30 12:49:17 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 30 Jul 2003 18:49:17 +0200 Subject: Is there a standard module library function to access /etc/passwd or /etc/group In-Reply-To: <16469f07.0307300416.351ba776@posting.google.com> References: <16469f07.0307300416.351ba776@posting.google.com> Message-ID: <3F27F70D.7030209@ghaering.de> Robin Cull wrote: > Hi all, > > I'm writing a script that needs to do lookups on the UNIX passwd and > groups file [...] import pwd, grp Next question? :) -- Gerhard From research at aceretail.com Fri Jul 18 17:45:37 2003 From: research at aceretail.com (Terry Smith) Date: Fri, 18 Jul 2003 21:45:37 GMT Subject: Jerry Pournelle, Byte, Python, and Python in a Nutshell References: <3ebfb0c2$0$2616$a1866201@newsreader.visi.com> Message-ID: I had an article in Byte called 'Solving the Eight Queens Problem'. There was a lot I didn't know then... :-) My all time fav article from Byte was a two parter on the alpha beta technique for searching game trees - written in Basic. VERY educational. Can anyone point me at that, I'd love to read it again! On 12 May 2003 16:13:11 GMT, bokr at oz.net (Bengt Richter) wrote: >On 12 May 2003 14:33:38 GMT, grante at visi.com (Grant Edwards) wrote: >[...] >[OT] Are old mags and journals worth anything? I have tons (almost literally ;-) >of old Bytes, DrDobbs, ACM Communications, SigPlan, SigOps, IEEE Computer, etc. etc. >which I'd like to dispose of without feeling like I've thrown away money or >something of value to someone. > >Regards, >Bengt Richter From alanmk at hotmail.com Fri Jul 4 11:26:52 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 04 Jul 2003 16:26:52 +0100 Subject: Python Code Snippets References: <87y8ze8hgm.fsf@pobox.com> Message-ID: <3F059CBC.77900722@hotmail.com> > Aur?lien G?ron writes: >> Does anyone know where I can find a lot of Python code snippets? John J. Lee wrote: > http://www.uselesspython.com/ > > They're working on useless 2, with categories. Maybe it's time to consider a name change as well? I know that the name was originally chosen partly for humility and partly for humour (i.e. it's Monty Pythonic). But "useless" is fairly offputting. The site looks pretty useful to me. OTOH, I suppose it's a pretty catchy name, eh? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ben at dadsetan.com Wed Jul 9 03:12:02 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 09 Jul 2003 09:12:02 +0200 Subject: Deleting specific characters from a string Message-ID: Hi all, I would like deleting specific characters from a string. As an example, I would like to delete all of the '@' '&' in the string 'You are ben at orange?enter&your&code' so that it becomes 'benorange?enteryourcode'. So far I have been doing it like: str = 'You are ben at orange?enter&your&code' str = ''.join([ c for c in str if c not in ('@', '&')]) but that looks so ugly.. I am hoping to see nicer examples to acheive the above.. Thanks. Ben. From news at yebu.de Thu Jul 3 04:35:32 2003 From: news at yebu.de (Karl Scalet) Date: Thu, 03 Jul 2003 10:35:32 +0200 Subject: function overloading In-Reply-To: References: Message-ID: Alex Martelli schrieb: > > We don't (bind several different objects to the same name in a given > scope). If you're keen on being able to call setPos(x,y) as well as > setPos(pos) there are several ways you can achieve this effect -- e.g. > > def setPos(x,y): > "whatever" > > setPos_2args = setPos > what is the benefit of this "renaming" over just name the dispatch-function setPos_2args directly: def setPos_2args(x,y): "whatever" > .... > > def setPos(*args): > if len(args)==2: return setPos_2args(*args) > if len(args)>1: raise TypeError > if type(args[0]) == postype: return setPos_postype(*args) > return setPos_anyother(*args) > ... Karl From tismer at tismer.com Fri Jul 4 21:09:39 2003 From: tismer at tismer.com (Christian Tismer) Date: Sat, 05 Jul 2003 03:09:39 +0200 Subject: My Big Dict. In-Reply-To: <94974e1a.0307030332.138a7054@posting.google.com> References: <20030702073735.40293ba2.christophe.delord@free.fr> <94974e1a.0307020532.1cb19956@posting.google.com> <94974e1a.0307030332.138a7054@posting.google.com> Message-ID: <3F062553.9020901@tismer.com> Paul Simmonds wrote: [some alternative implementations] > I've done some timings on the functions above, here are the results: > > Python2.2.1, 200000 line file(all data lines) > try/except with split: 3.08s > if with slicing: 2.32s > try/except with slicing: 2.34s > > So slicing seems quicker than split, and using if instead of > try/except appears to speed it up a little more. I don't know how much > faster the current version of the interpreter would be, but I doubt > the ranking would change much. Interesting. I doubt that split() itself is slow, instead I believe that the pure fact that you are calling a function instead of using a syntactic construct makes things slower, since method lookup is not so cheap. Unfortunately, split() cannot be cached into a local variable, since it is obtained as a new method of the line, all the time. On the other hand, the same holds for the find method... Well, I wrote a test program and figured out, that the test results were very dependant from the order of calling the functions! This means, the results are not independent, probably due to the memory usage. Here some results on Win32, testing repeatedly... D:\slpdev\src\2.2\src\PCbuild>python -i \python22\py\testlines.py >>> test() function test_index for 200000 lines took 1.064 seconds. function test_find for 200000 lines took 1.402 seconds. function test_split for 200000 lines took 1.560 seconds. >>> test() function test_index for 200000 lines took 1.395 seconds. function test_find for 200000 lines took 1.502 seconds. function test_split for 200000 lines took 1.888 seconds. >>> test() function test_index for 200000 lines took 1.416 seconds. function test_find for 200000 lines took 1.655 seconds. function test_split for 200000 lines took 1.755 seconds. >>> For that reason, I added a command line mode for testing single functions, with these results: D:\slpdev\src\2.2\src\PCbuild>python \python22\py\testlines.py index function test_index for 200000 lines took 1.056 seconds. D:\slpdev\src\2.2\src\PCbuild>python \python22\py\testlines.py find function test_find for 200000 lines took 1.092 seconds. D:\slpdev\src\2.2\src\PCbuild>python \python22\py\testlines.py split function test_split for 200000 lines took 1.255 seconds. The results look much more reasonable; the index thing still seems to be optimum. Then I added another test, using an unbound str.index function, which was again a bit faster. Finally, I moved the try..except clause out of the game, by using an explicit, restartable iterator, see the attached program. D:\slpdev\src\2.2\src\PCbuild>python \python22\py\testlines.py index3 function test_index3 for 200000 lines took 0.997 seconds. As a side result, split seems to be unnecessarily slow. cheers - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: testlines.py URL: From no_replies at fake_email_address.invalid Fri Jul 11 15:37:48 2003 From: no_replies at fake_email_address.invalid (Robert Oschler) Date: Fri, 11 Jul 2003 19:37:48 GMT Subject: A very short story about Python in a Nutshell References: <3F0DC98E.BDC96606@engcorp.com> Message-ID: Only 50? Amazon just called and they're taking my house! :) Ditto on "Python in a nutshell" great book. thx -- Robert Oschler "Let the web hear you, add your voice to your web site in minutes!" -- http://audiodirect.spiderchase.com/ (For a limited time, free voiceover with every sign-up, use this link instead) -- http://audio.spiderchase.com/ "Peter Hansen" wrote in message news:3F0DC98E.BDC96606 at engcorp.com... > So there I was just sitting there, minding my own business, and in walks > one of the programmers, holding "Python in a Nutshell". [1] > > "Peter," he says, "this has gotta be the best book you've bought so far. [2] > Every thing I need to look up, it's got it." > > THE END > > (I told you it was a very short story.) > > -Peter > > [1] http://www.amazon.com/exec/obidos/ASIN/0596001886/qid%3D1057868151/sr%3D11-1 /ref%3Dsr%5F11%5F1/102-0808187-6963307 > > [2] I've bought at least 50 computer books in the last couple of years. From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 15 07:29:23 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 11:29:23 GMT Subject: How to crash Python in 1 easy step (python 2.2.2) References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: Paul Miller enlightened us with: > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. sybren at sybren:sybren$ python Python 2.2.3+ (#1, Jul 5 2003, 11:04:18) [GCC 3.3.1 20030626 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdin.readline() '\n' >>> As you can see, my python handles it just fine. I'm running Debian Unstable on my box. Guess it isn't so unstable after all ;-) I started python from an xterm managed by Fluxbox. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From max at alcyone.com Tue Jul 15 02:06:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 23:06:20 -0700 Subject: anything like C++ references? References: <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> <3F138ADC.4BF9DB3A@alcyone.com> Message-ID: <3F1399DC.BC428285@alcyone.com> Stephen Horne wrote: > Sorry. I hope no offense was caused. None here. I just thought you were being serious about the suggestion. When you made your comment to someone else, I realized that you were just waxing philosophical, not suggesting an actual change be put in Python. (Well, on this subject, anyway. :-) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Honesty has nothing to hide \__/ Joi From yvan_charpentier at hotmail.com Thu Jul 10 17:39:35 2003 From: yvan_charpentier at hotmail.com (yvan) Date: 10 Jul 2003 14:39:35 -0700 Subject: Create another Excel instance Message-ID: <9ee55987.0307101339.701965a7@posting.google.com> I am using Excel to save data. Everything works as i intend it to if no other instance of Excel is running. If another instance is running, it will do the job, but also close that instance. How can i prevent that from happening? Here is the code that creates and deletes the instance: class CExcel: def __init__(self, bVisible = 0): import sys import pythoncom sys.coinit_flags = 0 pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) import win32com.client.dynamic self.xlApp = win32com.client.dynamic.Dispatch("Excel.Application") self.xlApp.Visible = bVisible self.xlBook = self.xlApp.Workbooks.Add() self.xlSheet = self.xlApp.ActiveSheet def __del__(self): import pythoncom if self.xlSheet != None: del(self.xlSheet) if self.xlBook != None: self.xlBook.Close(0) del(self.xlBook) if self.xlApp != None: self.xlApp.Quit() del(self.xlApp) pythoncom.CoUninitialize() Thank for your help, -Yvan From gerrit.muller at embeddedsystems.nl Fri Jul 11 03:13:46 2003 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 11 Jul 2003 09:13:46 +0200 Subject: Nice presentation of Dana Moore on Oscon Message-ID: <3F0E63AA.4000107@embeddedsystems.nl> A colleage attended me on the presentation of Dana Moore on Oscon: "The Seven Habits of Highly Effective Technology Disruption Python Survival in a Java & .Net World" http://www.infoether.com/~rich/pycon2003.pdf A very nice presentation. I do have one small comment: Python is characterized as "weakly typed", which should be "dynamic types", or what people often mean to say "not static typed". The difference has been discussed many times in this newsgroup. Dynamic typing requires a different approach than static typing. Programmers from the static world have to make a mental adjustment to become effective in this different paradigm. kind regards, Gerrit Muller -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From ghowland at lupineNO.SPAMgames.com Sat Jul 5 03:51:05 2003 From: ghowland at lupineNO.SPAMgames.com (Geoff Howland) Date: Sat, 05 Jul 2003 07:51:05 GMT Subject: Python executables References: <20030703090622.1420.48614.Mailman@mail.python.org> Message-ID: On Thu, 03 Jul 2003 07:04:49 -0400, David Scott Williams wrote: >>I think everyone that uses Python wants it to gain acceptance for the >>great language that it is. I believe that stating an attitude in this >>way is pretty counter productive in gaining any kind of wide-spread >>acceptance. >> >Unfortunately, though, I don't think you get any more tread coming to >the Open Source developers and asking them how to hide your bits... This >is your issue, reversed. Why should Open Source developers be unanimously opposed to this? I can see that some will be, but just because you Open some of your programs doesnt mean you will Open all of them. There are business models to Open Source software, but they're much less developed and practiced than just selling the software. IMO, some things are better domains for open source than others, and other people will have different views. I think the important thing here is not to alienate people who have different views than you just because you have different opinions. Why should Python only be used by people who want to create open source software? Should everyone else be discouraged or prodded? >I think if your goals are un-reasonable, asking a hammer salesman how >best to use his tool to screw something into drywall is again, similary, >counter-productive. Scripting languages are hard to obfuscate, if not >damned near impossible. Even Java byte-code can be decompiled back to >fairly decent looking source... I didn't think Python was trying to be a hammer. It's obviously not trying to be Everything (which is good), but that doesnt mean it should be saying "we dont do this, bugger off". Especially for something that is really more religious. There is a practical side to this, which is "hiding things is not easy because Python isnt built to hide things", and I think that is fine. I think it's more important for Python to be about making coding easy and readable, but I still dont think it should be discouraged as a community policy. I know I was at first very put off by the open source community because of how totalitarian the sentiment seemed to be that "everything must be open/free". I've finally started to get over that and enjoy releasing bits here and there, but giving things away doesn't pay bills. I have a feeling that others are equally put off by it, and it only slows down acceptance for everyone that "maybe some things I write are good to release open source". >>Some people will care enough, and will avoid Python because the >>ability to protect their end results aren't there. >> >This loss is unfortunate, perhaps someday they will see that software >really isn't a commodity, but a service. In that "even a radio is a service", it will definitely be true, but radios are sold as well. Some software is more a service than others. Some software is more like a radio. Some software is even less service than a radio (like games), where they are sometimes a one-shot experience. You can't sell service on this, and there is sometimes little replay value. The worth is in the experience the first time. Service varies, and so sales needs to be varying as well. >Perhaps you could write an open source python code obfuscator? Or >write it in C and make it closed source? I wasnt suggesting "someone else" do it really. I was more addressing the attitude that I thought could put people off. At one point I personally considered this important, and after reviewing it long enough I decided I didn't care. It wasn't worth the effort to hide things, and the majority of people would pay for the software anyway (that were going to), so no loss. I just think those that want to do it shouldn't be discouraged from touching Python or asking for help. :) -Geoff Howland http://ludumdare.com/ From FBatista at uniFON.com.ar Fri Jul 11 08:11:41 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 11 Jul 2003 09:11:41 -0300 Subject: text file edit object Message-ID: #- file = TextFile( "foo.txt" ) #- del file[:-10] # remove last 10 lines #- file.save() myfile = open("foo.txt", "r") mylines = myfile.readlines()[:-10] myfile.writelines(mylines) myfile.close() I only see two problems with this: - Poor performance on very big files - Bad support on "hanging in the middle" . Facundo From lists at andreas-jung.com Mon Jul 7 01:16:13 2003 From: lists at andreas-jung.com (Andreas Jung) Date: Mon, 07 Jul 2003 07:16:13 +0200 Subject: anything new on the ternary operator? In-Reply-To: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> Message-ID: <2147483647.1057562173@[192.168.0.100]> --On Montag, 7. Juli 2003 2:13 Uhr +0000 Russell Reagan wrote: > "Bob Gailer" wrote > >> I was looking forward to having it. > > "Sean Ross" wrote > >> - (if C: x else: y) won the vote > > I'm still learning python, so don't flame too much :-) > > What is superior about using the proposed ternary operator instead of > using the 'and' and 'or' operators to simulate inline logic? Please stop the discussion. The ternary operator is dead (which is a very good thing) because GvR made the decision. -aj From ta-meyer at ihug.co.nz Wed Jul 16 01:04:46 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 16 Jul 2003 17:04:46 +1200 Subject: FCNTL module deprecation warning In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130256635B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2809@its-xchg4.massey.ac.nz> > There isn't (or at least shouldn't be) any file named > fcntl.py anywhere in your Python installation. FCNTL.py, > yes, but not fcntl.py (or .dll, or .pyd, etc). I found the problem (and it was even something suggested in one of the answers to my original post) - I had (in both the 2.3b2 and 2.2.3 directories) a fnctl.pyc, which, I presume from the behaviour, must have been a compiled version of FNCTL.py (a FNCTL.pyc could never then be created, of course). How it got there without being capitalised, I don't know. (Well, I know one way it could have - if I do set PYTHONCASEOK and then import fcntl, a fcntl.pyc file appears, which is actually a compiled FCNTL. But until today, I'd never heard of (so presumably never set) PYTHONCASEOK. They could have appeared in the testing that I did after reading the responses to my question, but then what caused the original behaviour that prompted the post?). In any case, Python does what I expect now, and what I'm told it's meant to do, so that's all I really care about. If it ever happens again, at least I'll know how to fix it. Thanks to those that helped :) =Tony Meyer From paul_rudin at scientia.com Tue Jul 1 04:49:03 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 01 Jul 2003 09:49:03 +0100 Subject: dcom client from non-windows python Message-ID: This is mostly idle speculation from a position of considerable ignorance :-) In theory it should be possible to do client side dcom from non-windows boxes. The existing python win32com stuff is only distributed for windows. The python wrappers could be generated from a type library on a windows box; copied across to (e.g.) a linux box and used to do write client side dcom python programs to talk to a servers running on a windows box. I wonder how much of the current dcom client code depends on the presence of windows? Does this sound like a big job getting this kind of thing to work? Or should it be fairly easy to modify the existing com client stuff for this purpose? Maybe somebody has already done this (although I could find anything with a quick google)? (I thought I'd already posted something similar this, but various newsservers disagree so I post again. Apologies if it turns out to be a repeat.) From mcherm at mcherm.com Mon Jul 14 09:47:44 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Mon, 14 Jul 2003 06:47:44 -0700 Subject: anything like C++ references? Message-ID: <1058190464.3f12b480b7d3a@mcherm.com> In the (lengthy) thread "anything like C++ references?" there developed (yet another) huge discussion of how assignment and parameter passing works in Python. In response, Ian Bicking wrote: > Python is not novel in the way it deals with variables. Scheme and > Smalltalk, for instance, act exactly the same, as do many other > dynamically typed languages [...]. > This isn't a funny little feature, this is the way all strong, > dynamically typed languages work. [...] > The problem you have is you are still thinking of variables as slots, > which is not correct. Variables in Python are bindings. Assignment > never copies anything, or creates anything except for changing the > variable to point to a different address location. *Every* Python > assignment (a=b) is like the C assignment (a=&b). I have nothing whatsoever to add to this... it is just so clearly and simply stated that I felt it was worth repeating. Of course, lots of other people said the same thing in other ways, but I felt that Ian's phrasing is particularly useful in explaining things to programmers coming from a C-style background, even if it doesn't seem to reach Stephen Horne. -- Michael Chermside From paul at boddie.net Mon Jul 14 12:35:33 2003 From: paul at boddie.net (Paul Boddie) Date: 14 Jul 2003 09:35:33 -0700 Subject: Using xml.xpath question. References: <23891c90.0307110057.bbe91e3@posting.google.com> Message-ID: <23891c90.0307140155.6e012fd5@posting.google.com> bvelkur at yahoo.com (0wl) wrote in message news:... > Works like a charm!!!!! > > My Ignorance shines bright.... :-). Or perhaps the documentation doesn't? ;-) > Anywhere I can read about this stuff.. I think I picked up on this stuff by reading the W3C specification and browsing the xml.xpath sources. You could do some investigation in Python 2.2 by using the built-in help command; for example: help(xml.xpath) And the specification for XPath 1.0 is found here: http://www.w3.org/TR/xpath Perhaps a tutorial is in order. Paul From grante at visi.com Wed Jul 16 08:20:52 2003 From: grante at visi.com (Grant Edwards) Date: 16 Jul 2003 12:20:52 GMT Subject: Q: simple sockets, bind, and socket error 10048 References: <3f1532e3.3717465@news.online.de> Message-ID: <3f154324$0$159$a1866201@newsreader.visi.com> In article <3f1532e3.3717465 at news.online.de>, Johannes Eble wrote: > Note that I start a client one by one (in the same client's dos > box). It seems that the older port numbers can't be used > anymore even if the client is closing the connection and > terminating. The port can't be used because it's still in use. When you close a TCP connection, it doesn't go away immediately. It goes into a "wait" state for several minutes just in case there are packets belonging to that connection wandering around the internet. If you want to skip that waiting state (a decision which a small risk associated), set the SO_REUSEADDR option on the socket. > I do not understand why the port is still in use. Stevens chapter 18: http://www.amazon.com/exec/obidos/ASIN/0201633469/qid=1058357912/sr=2-1/ref=sr_2_1/103-3800181-0657431 -- Grant Edwards grante Yow! I like the way ONLY at their mouths move... They visi.com look like DYING OYSTERS From owski at hotmail.com Wed Jul 16 10:12:04 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 14:12:04 +0000 (UTC) Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> Message-ID: <20030716081156943-0600@news.xmission.com> In <1058328099.572993 at yasure> Donn Cave wrote: > Quoth Adam Ruth : > .... >| In Python, there is no situation where "you really can't avoid >| pointers". > > That's trivially true, no such situation can exist because that > Python can't be coded. I'll repeat an example that I proposed > a couple days ago, though: user implemented sequences could be > implemented with a single simple indexing function, returning > a pointer/target/whatever; Python could assign directly to that, > making "seq[i] = x" the same kind of operation as and automatically > symmetrical with "x = seq[i]". > > It can't be done without pointers, as far as I can see. You may not > care if it can be done, but I think you'd agree that "there is no > situation that I care about where you really can't avoid pointers" > would be kind of a lame version of your assertion. > > Donn Cave, donn at drizzle.com > I did a quick google search and couldn't find the thread you're referring to. Could you summarize it for me? It sounds interesting. I do so love the taste of my foot in my mouth. Adam Ruth From harry.g.george at boeing.com Mon Jul 21 15:42:57 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 21 Jul 2003 19:42:57 GMT Subject: Voting Project Needs Python People References: Message-ID: "Alan Dechert" writes: > We've decided to go with Python for the demo of the voting machine I > described on this forum yesterday. Thanks to all of you for your feedback. > > We have an excellent team together. We're looking for a few good Python > coders willing to volunteer for this free open source project. It will be > on sourceforge.net later today. > > I can't offer you any money right now but I think it will be a good > opportunity for Python users and the Python community in general. It's > likely to be fairly high-profile and will gain significant exposure for > Python. > > Here are some of the people involved: > > University of California Santa Cruz computer science graduate, Adrianne Yu > Wang will be the project administrator and lead the project. > > http://home.earthlink.net/~adechert/adrianne_resume.doc > > She will get help from Jack Walther, a UCSC graduate student and big Python > fan. > > http://www.cse.ucsc.edu/~jdw/ > > They will be advised by computer science professors Doug Jones (U of Iowa) > and Arthur Keller (UCSC) > > http://www.cs.uiowa.edu/~jones/ > > http://www.soe.ucsc.edu/~ark/ > > Ed Cherlin will also act in a mainly advisory role but will assist with the > design of the project and documentation. > > http://home.earthlink.net/~adechert/cherlin_resume.doc > > We anticipate that a successful demo will help expedite funding for the > overall project which is aimed at implementing a uniform transparent voting > system. We have very prominent academics interested in the project from > many of the top universities around the country: Political scientists, > lawyers, economists, computer scientists, and psychologists. > > Stanford computer scientist David Dill has been helpful (he referred Ed > Cherlin and Prof Keller to me, among others). Professor Dill has gotten > involved in voting modernization issues in a big way. > > http://www.verifiedvoting.org/index.asp > > Henry Brady was my co-author for the original UC Berkeley proposal for > California. > > http://home.earthlink.net/~adechert/src_proposal.html > > Professor Brady is widely known for his papers and books on voting systems. > The main author of the Caltech-MIT reports from their voting project, Steve > Ansolabehere was one of Henry's students when Henry taught at Harvard. > Henry has two Ph.D.s from MIT. > > http://www.apsanet.org/new/2003chairs.cfm > > We are pulling together a great voting modernization projects. It's an > opportunity to get in on it at an early stage. It should be rewarding for > you, your community, and democracy. > > Please contact me if you want to join us. > > -- Alan Dechert 916-791-0456 > adechert at earthlink.net > > > Please post the sourceforge link when it is set up. I was curious why http://www.notablesoftware.com/evote.html wasn't mentioned. I had the impression that was an early (and continuing) portal for these issues. Is the intent to do opensource all the way to commodity chips? Else a proprietary BIOS could be the weak link. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From peter at engcorp.com Thu Jul 10 18:15:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 18:15:01 -0400 Subject: Convert between Windows style paths and POSIX style paths References: Message-ID: <3F0DE565.1CEA39C6@engcorp.com> Noah wrote: > > Does anyone have a function to convert back and forth between > NT style paths and POSIX style? It seems trivial, but > I want to make sure I don't overlook some obscure detail. > Is it a simple matter of translating / and \ characters? > > FYI, I need a Python function that does what cygpath does so that > I can run a script on either NT or UNIX or Cygwin. > I want my config files use one style of path. You can use forward slashes in paths under Win32, except at the command prompt. Even if you switch to use all forward slashes, however, what do you plan to do about drive letters? There is no obvious mapping to anything under POSIX, I think. Are you planning on disallowing paths that go anywhere but the current drive under NT? -Peter From fredrik at pythonware.com Sun Jul 13 05:33:30 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Jul 2003 11:33:30 +0200 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: John Roth wrote: > > Read the source, Luke. > > I haven't gotten into the Python source, and my name > is not Luke. And life's to short to waste on movies... > On reading this over, it does sound a bit more strident than my > responses usually do, but I will admit to being irritated at the > assumption that you need to read the source to find out the > answer to various questions. Well, you obviously didn't bother to read the documentation for os.environ, so pointing you to the source sounds like a reasonable idea. From peter at engcorp.com Tue Jul 15 17:17:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 17:17:11 -0400 Subject: Sio serial module install problem with ActiveState References: <3F132FB3.CF0E6B44@engcorp.com> <3F13703C.C12392D6@engcorp.com> <6e07b825.0307151214.3d2cce2@posting.google.com> Message-ID: <3F146F57.94A49564@engcorp.com> "yaipa h." wrote: > > All, > > Worked like a charm for me too! I used it to develop an > automated attendant for a Serial Oven Controller. The > attendant ran from Sparc Solaris using Python 2.1 and pySerial. > > The only weird thing, which I didn't get a chance to > debug, was a perfectly working script under RS-232 > got terribly out of sync when R/W I/O to a RS-485 > serial network. Any reason why that would be? Well, one reason might be that RS232 is point-to-point, while RS-485 is many-to-many, at least in principle. Was this a bus network, or at least a "multidrop" situation with one master and many slaves? There are no guarantees in those situations, unless you've been very careful to ensure proper handshaking, timing, and such. If you want to discuss this, please define "out of sync" in more detail... it could mean anything. -Peter From not.valid at address.org Thu Jul 3 02:58:46 2003 From: not.valid at address.org (not your business) Date: Thu, 03 Jul 2003 06:58:46 GMT Subject: How Do You Get Redirected Input? References: Message-ID: Cliff Wells wrote: > On Wed, 2003-07-02 at 12:10, not your business wrote: >> I have a shell tool that accepts arguments on the command line. I would >> like >> to check if the input is being piped in. That is, > > import sys > > if sys.stdin.isatty(): > print "not piped in" > else: > print "piped in" > > Excellent, sir. Thank you very much. From jar at mminternet.com Tue Jul 29 22:19:22 2003 From: jar at mminternet.com (james roush) Date: Tue, 29 Jul 2003 19:19:22 -0700 Subject: Trustudio plugin for Eclipse IDE References: Message-ID: In article , brian_l at yahoo.com says... > james roush wrote in message news:... > > I've been trying, without success, to download the Trustudio plugin for > > the Eclipse IDE. I've been trying to get it from > > http://www.xored.com/download.php. > > > > Has anyone gotten it from somewhere else? > > http://sourceforge.net/projects/trustudio/ > I managed to het it from the Trustudio web sight after all. They must have been having server problems earlier. -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From guettler at thomas-guettler.de Thu Jul 31 08:24:01 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 31 Jul 2003 14:24:01 +0200 Subject: regular expression References: Message-ID: Wiebke P?tzold wrote: > Hi all, > > I wrote a little program. Here it is: > > import sys > import Mk4py > > db = Mk4py.storage("c:\\datafile.mk",1) > vw = db.view("people") > > def func(row): > try: > if row.Nachname[0:1]=='G': > return 1 > else: > return 0 > except AttributeError: > return 0 > > > vf = vw.filter(func) > > for r in vf: > print vw[r.index].Nachname,vw[r.index].Kongressbereich > > > I create a database that contains a table. 'Nachname' and > 'Kongressbereich' are special fieldnames. This program can search for > a special letter. In my example it is 'G'. and the search takes place > in 'Nachname'. > Mow I want to use regular expression. So that I can limit my search. > For example: I can search for Ge and it is not relevant wich letters > follow > Could somebody help me with this task? You can do it without regular expressions, too: if nachname.startswith("Ge"): ... # "Ge" somewhere in the string? if nachname.find("Ge")!=-1: ... The corresponding regular expressions would be: if re.match(r'^Ge.*$'): ... if re.match(r'^.*Ge.*$'): ... .* matches everything ^ matches start of string $ matches end of string See the documentation of the module "re" thomas From llothar at web.de Wed Jul 9 15:12:23 2003 From: llothar at web.de (Lothar Scholz) Date: 9 Jul 2003 12:12:23 -0700 Subject: Shared vs static link performance hit --and Windows? References: Message-ID: <6ee58e07.0307091112.4931c31b@posting.google.com> Christos "TZOTZIOY" Georgiou wrote in message news:... > Last night I was compiling the latest python snapshot at my home Linux > system (a K6-III @420 --the extra 20 Hz is overclocking :); then I tried > building a shared version of the interpreter. I did some speed > comparisons, and pystone reported ~6090 pystones for the shared and > ~7680 pystones for the (default) static build. > Yes, today i recommend to not use the -fPIC option for certain libraries when compiling a .so library. If you use it you get one more indirection and this can be very bad on systems with long CPU pipelines (PIV systems). If you don't use -fPIC then the shared library will be patched and is only shared on disk but not in memory. I hope that the UNIX community gives up this 20 year old ELF format and start to use a new one with better performance - look at KDE to see the pain. From naren at trillium.com Wed Jul 16 20:29:08 2003 From: naren at trillium.com (Narendra C. Tulpule) Date: 16 Jul 2003 17:29:08 -0700 Subject: Recursion in compile() Message-ID: <781faf41.0307161629.6295618b@posting.google.com> Hi, is there any way to allow recusrion in compile()? Something like: src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \ '\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n' cobj = compile(src_code, 'myfile', 'exec') eval(cobj) I did a search on 'recursion' in comp.lang.python but didn't turn up anything relevant. Maybe I've highhhhhh expectations :-) -- Naren. From rosendo at dbora.com Tue Jul 29 13:16:08 2003 From: rosendo at dbora.com (rosendo) Date: 29 Jul 2003 10:16:08 -0700 Subject: urllib2 http status Message-ID: I'm writing a http client to test some applications. The code below it's the core of the client: try: start_ts = time.time() request = urllib2.Request('http://%s%s' %(req.host,req.path), req.data, req.headers) request.add_header("Referer", 'http://%s%s' %(req.host,req.path)) c.add_cookie_header(request) c.clear() #request = urllib2.Request('http://www.google.com') try: response = urllib2.urlopen(request) data = response.read() headers = response.info().headers #status = response.info().status d = c.extract_cookies(response, request) except urllib2.URLError, msg: print "URLError: ", msg; except urllib2.HTTPError, msg: print "HTTPError: ", msg; except: print sys.exc_type,sys.exc_value duration = time.time() - start_ts print 'The result had status: %s duration: %5.2f http://%s%s' %(response.info().status, duration, req.host,req.path) except: print sys.exc_type,sys.exc_value print 'cagadita....' + str(req) Before this code we declare c = ClientCookie.Cookies(), etc...... Then i don't know how to know the status of the response, because the property: response.info().status seems not to function like i wait, that it's with an 200, 301, 400, etc..... How can obtein this status? I prefer not use httplib, but with urllib2 i'm not sure if i could obtain the HTTP status. Thanks in advance. Rosendo. From bdesth.nospam at removeme.free.fr Thu Jul 31 13:10:43 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 31 Jul 2003 19:10:43 +0200 Subject: Python's biggest compromises In-Reply-To: <899f842.0307310555.56134f71@posting.google.com> References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <3f294ba4$0$8919$626a54ce@news.free.fr> Anthony_Barker wrote: (snip) > > What to you think python largest compromises are? > > The three that come to my mind are significant whitespace, dynamic > typing, and that it is interpreted - not compiled. IMHO these are not compromises, but features. Bruno From InsaneStewy at hotmail.com Sat Jul 19 22:00:22 2003 From: InsaneStewy at hotmail.com (Id0x) Date: 19 Jul 2003 19:00:22 -0700 Subject: Newbie! I'm a newbie! What's wrong with this program? Message-ID: <5da8e4b3.0307191800.48dc0a6d@posting.google.com> I'm very new at programing, and while I was practicing I came across something that confuses me. The code for the program is at the bottom. The program it self is designed to convert hours to minutes. Now the problem is, after I run the program I get strange results. [\| Running the Program |/] INPUT: Ms-Dos Prompt: C:\python23\> python practice.py OUTPUT: There are 300 None minutes in 5 hours <--- Problem occurs here [\|End Running of Program|/] Now the problem is... where does the "None" come from? And why is it there? Here is the code. Please email me if you can. Your help is appreciated. InsaneStewy at hotmail.com import math ##loads the math modual ########Start created Functions######### ##Function for converting minutes to hours## def minHour(x): min = 60 hour = min * x print hour ##Function creates a new line## def newLine(): print #######End created Functions######## ###Start Variables#### x_hours = 5 ###End Variables#### newLine(); print "There are", minHour(x_hours), "minutes in", x_hours, "hours"; newLine(); print "Program Terminated."; newLine(); From gminick at hacker.pl Tue Jul 29 03:49:12 2003 From: gminick at hacker.pl (Wojtek Walczak) Date: Tue, 29 Jul 2003 07:49:12 +0000 (UTC) Subject: newbie needs a little help... trying to write an ftp script. References: Message-ID: Dnia 28 Jul 2003 11:40:48 -0700, google account napisa?(a): [...] > The docs suggest that I could do something like.... > > import ftplib > > ftp = ftplib.FTP('172.30.30.30') # This is wrong, somehow...? > ftp.login(user,pass) ^^^^ Do not use pass in this way - it's a python's keyword. Use some other name instead. > ftp.retrlines('LIST') # I believe it might need to be > ftp.retrlines('ls -al') > ftp.sendcmd('prompt') > ftp.cwd('folder') > ftp.retrbinary(retr *tgz) > ftp.quit() Here's a simple example: import ftplib,sys ftp = ftplib.FTP('ftp.python.org') ftp.login('anonymous','qwe at asd.pl') print ftp.retrlines('LIST') ftp.cwd('pub/python') print ftp.retrlines('LIST') print ftp.retrbinary('retr README', sys.stdout.write) ftp.quit() -- [ Wojtek Walczak - gminick (at) underground.org.pl ] [ ] [ "...rozmaite zwroty, matowe od patyny dawnosci." ] From jocsch at phreaker.net Sun Jul 6 13:44:13 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Sun, 06 Jul 2003 19:44:13 +0200 Subject: absolute beginners question about API documentation Message-ID: Hi all, I' new to python programming but a longtime java programmer. Is there an API documentation like the javadoc API from java? I'm want to know all methods I can use on dictionaries. Where can I get an overview about these? I looked on python.org but haven't found such an overview. Thanks, Markus From bokr at oz.net Thu Jul 17 23:11:56 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 03:11:56 GMT Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: On Thu, 17 Jul 2003 11:53:05 +0100, Alan Kennedy wrote: >JanC wrote: > >> The verb "gignooskoo" (trying to write it with Latin letters ;) > >Why limit yourself to that nasty little us-ascii alphabet? >;-) > >Here it is in a format where almost everybody will be able to see the >original greek verb on their screen. > >#--------- > >γίγνωσκω >#--------- > >For anybody who has MS Internet Explorer 5+, Netscape 6+, Mozilla 1+, >i.e. any browser that supports XML, simply save this to a disk file >and open it in your chosen browser. > Sorry, that doesn't work for my old browser (NS4.5 ;-) Try this: ====< giginooskoo.html >====================================================== gignooskoo

γίγνωσκω

============================================================================== >Of course, I could also have used charset "iso-8859-7", in which case >the character codes would be one-byte-only. But I don't think that >would have travelled well over UseNet to most of you. > The above seems to work for me. Does it you? Windows-1253 as char set should also work, I think. (I made the char numeric entities decimal, as some old browsers don't do &#x...;) (There's also some unnecessary formatting ;-) Regards, Bengt Richter From shalehperry at comcast.net Tue Jul 22 20:37:43 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Tue, 22 Jul 2003 17:37:43 -0700 Subject: lists and files question In-Reply-To: <3F1DCF52.7040607@hotmail.com> References: <3F1DCF52.7040607@hotmail.com> Message-ID: <200307221737.43290.shalehperry@comcast.net> On Tuesday 22 July 2003 16:57, hokiegal99 wrote: > This code: > > import os, re, string > setpath = raw_input("Enter the path: ") > for root, dirs, files in os.walk(setpath): > id = re.compile('Microsoft Excel Worksheet') > fname = files > # print fname > content = open(fname[1],'rb') > > Produces this error: > > IOError: Error[2] No such file or directory 'Name of File' > if you replace your logic with some prints you will quickly see the problem. What happens is os.walk() passes filenames without their path. You need to use os.path.join() to get the full name back. From anthony_barker at hotmail.com Fri Jul 4 13:57:10 2003 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 4 Jul 2003 10:57:10 -0700 Subject: Inputbox with win32api? References: Message-ID: <899f842.0307040957.7756ffe5@posting.google.com> After a bit of hunting I found import pywin.mfc.dialog InternetAddress = pywin.mfc.dialog.GetSimpleInput("Email Address?") Thanks, Anthony http://xminc.com/linux Bob Gailer wrote in message news:... > At 12:44 PM 6/27/2003 -0700, Anthony_Barker wrote: > > >Is there a simple way of throwing up a simple Inputbox with win32 api > >in python? > > > >I could use tk > >data=tkSimpleDialog.askstring( title="Input",prompt="Email Address?") > > > >but that adds 700K to the package when I distribute it to non python > >users as it forces me to include tk. (Using MacMillian installer). From jflanigan at netzero.net Wed Jul 2 20:29:48 2003 From: jflanigan at netzero.net (jose flanigan) Date: 2 Jul 2003 17:29:48 -0700 Subject: read in Matlab *.mat files on a win32 machine and on Solaris? Message-ID: Does anybody have any code for python to read in Matlab *.mat version 5 files on a win32 machine and on Solaris? I found matfile (. ), which covers Linux, but I can't get it to compile on Solaris on win32. Thanks in advance. From gh at ghaering.de Wed Jul 2 08:08:17 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 02 Jul 2003 14:08:17 +0200 Subject: how to pass a file descriptor in a swig module In-Reply-To: References: Message-ID: kj.kjn wrote: > My function func(File * des) is embedded in a module swig. > > I would to know how to call this function from python script and if it's > necessay > > to declare a typemaps ? Not sure if that helps here, but Python file objects have a function called fileno() to return the file number. -- Gerhard From fredrik at pythonware.com Wed Jul 2 05:55:11 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Jul 2003 11:55:11 +0200 Subject: How do I get the fractions of the visible part of a canvas? References: Message-ID: Mickel Gr?nroos wrote: > I would like to be able to ask the canvas something like: > > t = canvas.visiblebox() > > and it would return a two-tuple of two-tuples with coordinates (of the > a and b points in the picture above), say: > > t = ((10,10), (90,30)) > > Using these values I could calculate the fractions myself. > > Any ideas? this might work: t = ( (w.canvasx(0), w.canvasy(0)), (w.canvasx(w.winfo_width()), w.canvasy(w.winfo_height())) ) From bokr at oz.net Fri Jul 18 17:50:24 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 21:50:24 GMT Subject: "\n" in ASCII-file References: Message-ID: On Fri, 18 Jul 2003 13:26:59 +0200, =?ISO-8859-1?Q?Gerhard_H=E4ring?= wrote: >Martin P wrote: >> Hello, >> >> for a short exercise-program I have to read the lines in an ASCII-file. >> >> But every line has a new-line-feed ("\n") at the end of the line. (The >> ASCII-file was made with Windows Notepad). >> Is this only because I used Windows (and Notepad)? > >Yes. > >> And... is there any special method to read lines from a file without "\n"? > >Most of the time, I want to strip any trailing whitespace and do Nit: ^^^^^^^^ >something like: > >f = file("/path/to/my/file") >for line in f: > line = line.strip() .rstrip() ^^^^^^^^^ > # ... > >Unlike Karl's method, this scales to larger files without needing to >read the whole file into memory. > >Files are iterable since Python 2.2. > Regards, Bengt Richter From gerrit.muller at embeddedsystems.nl Tue Jul 15 09:48:36 2003 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Tue, 15 Jul 2003 15:48:36 +0200 Subject: link collection Message-ID: <3F140634.2010201@embeddedsystems.nl> As a service to the visitors of the Gaudi systems architecting website: http://www.extra.research.philips.com/natlab/sysarch/ I have added a page with links to Python resources at http://www.extra.research.philips.com/natlab/sysarch/PythonLinks.html It is my intention to have this page as a quick starting point for system architects. They can benefit a lot from Python, for instance to make tools, simulations or prototypes. I welcome suggestions for improvements, although I am not in favor of a big maintenance effort. This link collection is bootstrapped by proudly stealing the links mentioned in Dr Dobbs Python URL by Steven Taschuk. Many thanks to Steven. kind regards Gerrit From Olivier.POYEN at clf-dexia.com Wed Jul 9 05:46:11 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Wed, 9 Jul 2003 11:46:11 +0200 Subject: Executables under Win32 Message-ID: <8963D6370B323E4AA3241200F0EAF7318C0F87@FCEXVEXM002.dcl.int.dexwired.net> May I suggest you use google groups search engine. You'll get a lot a answer, such as py2exe and MacMillan installer. AFAIK, there should even be some hints in the python F.A.Q HTH, ---OPQ > -----Message d'origine----- > De : Fuzzyman [mailto:michael at foord.net] > Envoy? : mercredi 9 juillet 2003 10:37 > ? : python-list at python.org > Objet : Executables under Win32 > > > IS there a tool to make Python Executables (binaries) under Win32... > or must people have a distribution of Python to use any scripts I > write ? > > I don't need to hide my source code - but would liek to make it easy > for a newbie to use my scripts. > > Fuzzyman > --- > Everyone has talent. What is rare is the courage to follow > talent to the dark place where it leads. -Erica Jong > Ambition is a poor excuse for not having sense enough to be > lazy. -Milan Kundera > > http://www.voidspace.org.uk > Where Headspace Meets Cyberspace > Cyberpunk and Science Resource Site > Exploring the worlds of Psychology, Spirituality, Science and > Computing > -- > http://www.fuchsiashockz.co.uk > http://groups.yahoo.com/group/void-shockz > http://www.learnlandrover.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From davidb at mcs.st-and.ac.uk Tue Jul 15 16:34:31 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 15 Jul 2003 13:34:31 -0700 Subject: Embedding Python in a plugin References: Message-ID: <4de76ee2.0307151234.4a2abbe5@posting.google.com> Daniel Holth wrote in message news:... > Hello! I am trying to embed Python into an xmms plugin using > Debian/unstable/i386, gcc 3.3.1 and Python 2.2.3+. The plugin is a shared > library loaded by xmms. The plugin is dynamically linked with the python > library. Sounds good so far! > Running scripts works but when I try to import python extensions I get these > kinds of errors: > > Traceback (most recent call last): > File "", line 1, in ? > File "/home/dholth/lib/python2.2/site-packages/xmmspy.py", line 12, in ? > import time > ImportError: /usr/lib/python2.2/lib-dynload/time.so: undefined symbol: > PyExc_IOError Yes, I hate it when these crop up. I've also seen ones involving _Py_NoneStruct or something similar. > I'm using all the compiler options I can find! > > /bin/sh ./libtool --mode=link gcc -Wall -I/usr/include/xmms > -I/usr/include/gtk-1.2 -I/usr/include/glib-1.2 -I/usr/lib/glib/include -g > -O2 -I/usr/include/python2.2 -I/usr/include/glib-1.2 > -I/usr/include/python2.2 -g -O2 -I/usr/include/python2.2 -o libxmmspy.la > -rpath /usr/lib/xmms/General -module -avoid-version -Xlinker > -export-dynamic xmmspy.lo -lstdc++ -lpython2.2 -L/usr/lib -L/usr/X11R6/lib > -lgtk -lgdk -rdynamic -lgmodule -lglib -ldl -lXi -lXext -lX11 -lm -lxmms > > ... including "-Xlinker -export-dynamic" as suggested by distutils. I think that you can probably remove some of those options and stick with the "-Xlinker -export-dynamic" but you may need to use "-Xlinker -R " for runtime linking. Maybe -rpath handles that. I'm a newcomer to this myself, so I'm sure I'll be corrected if I'm out of line. > How do I embed Python in an application where the main application has no > knowledge of Python, only the dynamically loaded plugin does? Which > programs do this already? These problems receive some attention in the Python FAQ and in the Extending and Embedding section of the Python manual. Unfortunately, some of the recommendations I've seen aren't workable if you don't have any control over how the target application was built: using various options with dlopen, for example. Anyway, the problem you have at the top of this message can probably be solved by linking against the time module, which is probably residing in /usr/lib/python2.2/lib-dynload/time.so or somewhere similar. Good luck! David -- http://www.boddie.org.uk/david/Projects/ From jjl at pobox.com Tue Jul 15 17:49:12 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Jul 2003 22:49:12 +0100 Subject: [OT] sentances with two meanings References: Message-ID: <87oezvbgvb.fsf@pobox.com> Syver Enstad writes: [...] > Does "to know" in english also mean to feel someone? In my own language > the direct translation of the english know also means to feel. I could > say (translated) "I know the cold", meaning I feel the cold > weather. There's a similar meaning in English. Isn't used often, probably because it implies some kind of seriousness, usually as "to know ". "I know the cold" works, but it'd sound like you were about to tell us that you did 30 years hard labour in Siberia (OK, not necessarily *quite* that extreme ;-). Or maybe it sounds serious because it isn't used often <0.5 wink>. Not usually used about people, though, because "to know " in a context which implies anything other than the everyday meaning is associated with "the biblical sense" (which is almost an idiomatic phrase in itself!). How the hell did nature sneak all this subtlety of English usage into my brain without me noticing it? making-a-link-with-Python-would-be-easy-but-pointless-ly y'rs, John From sjmachin at lexicon.net Wed Jul 2 09:05:23 2003 From: sjmachin at lexicon.net (John Machin) Date: 2 Jul 2003 06:05:23 -0700 Subject: remove special characters from line References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> <3f01e0b0$0$43854$39cecf19@news.twtelecom.net> Message-ID: "Chris Rennert" wrote in message news:<3f01e0b0$0$43854$39cecf19 at news.twtelecom.net>... > I apologize for being vague on what a "special" character is in my context. > For me, it would be anything that isn't A..Z , a..z, or 0..9 . > My list seems to work, or like it was suggested I could have used a string > as well. I thank everyone for the help, and I am really enjoying learning > Python. > That's good news ... and here's a couple of more lessons: (1) You can use the translate method: # once import string id_trans = "".join([chr(x) for x in range(256)]) good_chars = string.letters + string.digits bad_chars = "".join([x for x in id_trans if x not in good_chars]) # then once for each maybe_bad_string good_string = maybe_bad_string.translate(id_trans, bad_chars) That is a bit over the top, but reading the doc to understand what is going down will pay dividends. (2) Here's a more straightforward way using the re module # once import re subber = re.compile(r"[^A-Za-z0-9]").sub # then once for each maybe_bad_string good_string = subber("", maybe_bad_string) # simpler but slower: good_string = re.sub(r"[^A-Za-z0-9]", "", maybe_bad_string) # and as a bonus extra show_where_junk_was_string = subber("?", maybe_bad_string) HTH, John From postmaster at 127.0.0.1 Sat Jul 12 23:27:45 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Sun, 13 Jul 2003 15:27:45 +1200 Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: One more thing Elaine - I may offend others on this list in saying this, but if you're doing GUI applications, I strongly suggest that you dive in and familiarise yourself with Tkinter. It could well be the only GUI you ever need in Python. Don't be intimidated if the Tkinter docs you come across urge you to approach it from a Tk viewpoint- there's an excellent guide at: http://www.astro.washington.edu/owen/TkinterSummary.html I argue for Tkinter over another popular Python-accessible GUI, wxWindows, because Tkinter is smaller, faster and far less buggy, and has a really nice 'feel' within the Python environment. David From aahz at pythoncraft.com Wed Jul 2 20:12:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Jul 2003 20:12:48 -0400 Subject: What's the use of module spaces? (was Re: Circular Inheritance) References: Message-ID: In article , Ian Bicking wrote: >On Wed, 2003-07-02 at 10:03, Aahz wrote: >> In article , >> Ian Bicking wrote: >>> >>>You might encounter less problems if those classes go together in a >>>single module, but module boundaries are just there to help the >>>programmer organize code, they have little formal meaning. >> >> That's not true. Modules define a namespace, and Python's execution >> model makes heavy use of the "global" (read, current module's) namespace >> for name resolution. > >Certainly modules have considerable *semantics* and effect execution. >But they have little *meaning*. There's all sorts of semantics >associated with classes, but that's incidental to the meaning of a class >-- a class is a set up behaviors common to a kind of object. A module >is just a pile of stuff the programmer likes to keep together. It's >essentially a clerical feature. You say that as if the organizing power of clerical work has little intrinsic meaning. I disagree. It's precisely that organizing power that lends value. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From bdesth.nospam at removeme.free.fr Sun Jul 27 18:10:45 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2003 00:10:45 +0200 Subject: Static typing In-Reply-To: <5627c6fa.0307270537.1afc94d3@posting.google.com> References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> <5627c6fa.0307270537.1afc94d3@posting.google.com> Message-ID: <3f244c06$0$21113$626a54ce@news.free.fr> Tayss wrote: > Bruno Desthuilliers wrote in message news:<3f23ae06$0$21093$626a54ce at news.free.fr>... > >>>FWIW, I do favor the addition of optional static typing for the two >>>reasons Scott described - interface documentation and optimization. >> >>Interface documentation may be obtained in others ways (docstring for >>exemple). > > > Indeed! As I remember, Jython uses doc strings for typing, when it > presents an API to Java. So it's in the comments, and I think that's > an oddly appropriate place for hints to the compiler. In CPython, it is not supposed to be a hint to the compiler, it's supposed to be API documentation for the programmer. >>And I'm not sure static typing would optimize anything, but >>not being a Python (nor anything else) guru, I would not bet my hand on >>this... > > > If you mess around with lisp, you can easily see the compiled assembly > language of your functions when you experiment with optional typing. > (By calling the function "disassemble".) Normally, the compiler spews > a lot of general code because it doesn't know what you've passed in. > But when you promise that you're passing in numbers or something, the > assembly language is much tighter. Lisp is not Python. I was talking about static typing 'optimizing' anything in Python. > Sort of like when someone asks you to move something to a different > house, and you have no idea how big it is. If you were told, "It's > just a pillow," you know that you don't need to order a huge truck or > take any special precautions. Err... Given the actual speed and cost of a decent PC processor, I'm not willing to trade my time for a few milliseconds. And if I really need to have a really fast code, I know where my C compiler is !-) Bruno From bignose-hates-spam at and-zip-does-too.com.au Fri Jul 11 23:30:32 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 12 Jul 2003 13:20:32 +0950 Subject: The "intellectual property" misnomer References: Message-ID: On Fri, 11 Jul 2003 22:47:21 -0400, Tim Peters wrote: > Ben Finney wrote: >> Guido van Rossum wrote: >> > The PSF holds the intellectual property rights for Python >> Ugh. Please don't propagate this ridiculous, meaningless term. > > Guido isn't writing a treatise on the law, he's briefly explaining > (part of) what the PSF does. The term he used doesn't explain anything, and only confuses. It would have been *less* confusing to say "The PSF holds something unspecified for Python". At least there is no pretence of explanation there. > I doubt many are confused by what he said People may have an assumption about what is meant by the term, but they are almost certainly wrong, since the fields of law that are sometimes lumped together by that term have almost nothing in common. There is nothing useful indicated by the term "intellectual property rights", because it presumes there is some commonality between fields of law that deal with different intellectual concepts, impose different restrictions, and presume different rights. Those who are not confused by the term, are misguided as to what it means. > and you proved you're not [confused by the term] > [by listing some disparate fields of law that might be referred to by > the term] This doesn't follow at all. I requested that the "rights" being referred to should be stated, not handwaved with a term that presumes that copyright, patent, trademark, trade secret, or many other disparate legal areas can be lumped together. If PSF holds rights that are covered by *all* those fields of law, I'd be very surprised; but if the "rights" are *not* covered by all those different legal areas, then the term is useless. >> If the PSF holds the copyright to Python, please say that. >> If the PSF holds patents which cover Python, please say that. >> If the PSF owns the trademark for Python, please say that. >> If the PSF has trade secrets in Python, please say that. > > So you somehow managed to divine Guido's intent from that "ridiculous, > meaningless term" No, I requested that the term be clarified, because *I don't* know what is meant by "The PSF holds the intellectual property rights for Python". It's a meaningless statement as it stands. If the PSF holds software patents in Python, I imagine many would be outraged. I don't believe it does. If it's not the case, why imply it with an overbroad term? If the PSF holds trade secrets in Python, they are surely nullified by the publishing of the code. If it's not the case, why imply it with an overbroad term? > <0.5 wink> -- part of the PSF's business is indeed dealing with all > legalities affecting the use of Python. Then a more meaningful statement would be "The PSF handles all legalities affecting the use of Python". At least that doesn't attempt to specify something that can't be pointed to specifically with a single term. The harm done by implying ideas should be treated as property is insidious and extremely counterproductive. There's nothing gained by using this term that is worth that. > I don't think pedantic verbosity makes it any clearer, but may mislead > due to omission. And using a term that attempts to blanket wildly different legal rights is *not* misleading due to omission? [snip attempted proof-by-google] -- \ "I used to work in a fire hydrant factory. You couldn't park | `\ anywhere near the place." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From paulpaterson at users.sourceforge.net Sat Jul 26 11:20:24 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sat, 26 Jul 2003 15:20:24 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Stefan Schwarzer wrote: > Hi Paul > > Paul Paterson wrote: > >> This is a very interesting (and Pythonic) approach, thanks for >> suggesting it! This is certainly what I would try to do if I were >> writing the code from scratch. It may be possible to construct a >> "namespace" type object which gets passed to the function. > > > I think the most common way to make a namespace in Python is Thanks, the bare namespace class is essentially what I am going to try. > > Of course, if you have a better name for your container, that's even > better. Think of Ian's Point example. :-) I think you may have missed my original post; I am writing a generic VB to Python converter so generating good names based on code intent would be pretty tough! Perhaps in v2.0 ;) My current thinking is (for the orignal example of changing one variable, 'y' but not another, 'x'), class Namespace: pas # ByVal arguments passed directly, ByRef via a namespace def change(x, byrefs): x = x + 1 byrefs.y = byrefs.y + 1 ns = Namespace() # The local namespace ns.x = 0 ns.y = 0 change(ns.x, ns) # Now ns.x = 0, ns.y = 1 Paul From FBatista at uniFON.com.ar Tue Jul 8 10:42:42 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 8 Jul 2003 11:42:42 -0300 Subject: Container behaviour (was: print attitude) Message-ID: #- Personally, I think the internal difference between str and repr hits #- right upon a proper difference: str is for a "reasonable" #- human-readable representation, and repr is for as faithful and #- informative a representation as possible. These both have their uses #- and I approve of the distinction. Beyond the specific utilization of str or repr, the detail that get me confused is: repr (container) => repr (elements) str (container) => repr (elements) Why cannot I, when I want the repr of a container, get the repr of its elements, and when I want the str of a container, get the str of its elements? Thank you all. . Facundo From staschuk at telusplanet.net Thu Jul 17 20:05:22 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 17 Jul 2003 18:05:22 -0600 Subject: hex to signed integer In-Reply-To: ; from bokr@oz.net on Thu, Jul 17, 2003 at 03:07:42PM +0000 References: Message-ID: <20030717180522.C931@tibia.amotlpaa.bogus> Quoth Bengt Richter: [...] > >>> -2**31 > -2147483648L > Oops, is that a wart/buglet BTW? That it's a long and not an int? Certainly not a bug, arguably a wart, and in any case it's 2's-complement's fault, not Python's: -2**31 is equivalent to -(2**31), and the inner expression doesn't fit into an int (on suitable machines). I suppose long arithmetic could produce ints when possible, but it seems unlikely to be worth the trouble. -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From akaihola at ambi-spam-me-not-tone.com Mon Jul 21 16:48:42 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Mon, 21 Jul 2003 23:48:42 +0300 Subject: os.spawn[*] help In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I want to open some text in xemacs (on Windows) using os.spawn[*], but I > want the text to appear in the current xemacs window, as opposed to > opening a new xemacs window. If you can do it from the command line, you can do it from Python. Use gnuserv and gnuclient (maybe gnuclientw in windows). See the xemacs docs for more accurate information--I haven't used xemacs on windows. From davecook at nowhere.net Fri Jul 11 15:02:26 2003 From: davecook at nowhere.net (David M. Cook) Date: Fri, 11 Jul 2003 19:02:26 GMT Subject: treeview / pygtk problem References: Message-ID: <6RDPa.8635$R92.1496@news2.central.cox.net> In article , Andre Lerche wrote: >> col1 = g.TreeViewColumn ("col 1", renderer, text=0) >> col2 = g.TreeViewColumn ("col 2", renderer, text=1) >> >> That should solve your problem! >> >> -Tim >> tim at gerla.net > > Yes, this has solved my problem, I was really to dumb. Hardly; this API is quite obscure. Dave Cook From megalith at btinternet.com Fri Jul 25 05:57:51 2003 From: megalith at btinternet.com (Gordon Chapman) Date: 25 Jul 2003 02:57:51 -0700 Subject: Regex: Limiting Scope without capturing results References: <173ef463.0307240355.cf896bb@posting.google.com> Message-ID: <173ef463.0307250157.751a21f9@posting.google.com> Skip Montanaro wrote in message news:... > Sure, use (?:). Full details at 11: Thanks guys, exactly what I was after. G. From CousinStanley at hotmail.com Tue Jul 15 17:45:22 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 15 Jul 2003 14:45:22 -0700 Subject: "Introduction to Tkinter" available in html format? References: Message-ID: | ... | if it isn't too much trouble | could you send it to me at my email Psymaster ... I tried 3 different permutations of your eMail address and all 3 failed ... The one I use here is real ... Send me a good eMail address ... -- Cousin Stanley Human Being Phoenix, Arizona From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 21 05:45:08 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 21 Jul 2003 19:35:08 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> Message-ID: On Sun, 20 Jul 2003 15:16:48 +0100, Alan Kennedy wrote: > Ben Finney wrote: >> Which quickly leads to "You must use $BROWSER to view this site". >> No thanks. > > No, that's the precise opposite of the point I was making. My position > is "You must use markup-capable software to perceive what I've > written. Your choice of software is entirely up to you: the only > requirement is the ability to process (x|ht)ml". I try to avoid > platform/language/os/browser dependent anything: that was the whole > point of the post. You also stipulated "... from a Usenet post". Most Usenet readers do not handle markup, nor should they. There are many benefits from the fact that posts are plain text, readable by any software that can handle character streams; parsing a markup tree for an article is a whole order of complexity that I'd rather not have in my newsreader. Expecting people to use a news reader that attempts to parse markup and render the result, is like expecting people to use an email reader that attempts to parse markup and render ther result. Don't. -- \ "I was in the grocery store. I saw a sign that said 'pet | `\ supplies'. So I did. Then I went outside and saw a sign that | _o__) said 'compact cars'." -- Steven Wright | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From donn at drizzle.com Wed Jul 23 01:36:45 2003 From: donn at drizzle.com (Donn Cave) Date: Wed, 23 Jul 2003 05:36:45 -0000 Subject: How to disable spawnv's child process output messages References: None Message-ID: <1058938603.850678@yasure> Quoth nushin2 at yahoo.com (nushin): | I have a program called hello_earth.py that is spawned by | hello_moon.py, using spawnv( ) API as: | | os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello_earth.py'),('>/dev/null | &')) | | I do not wish to see any output messages from the hello_earth.py when | it is launched by its parent process and i do wish to see *only* the | output messages from the parent process in the shell. Is Python | capable to so such a thing? What is the parent process in the shell? You mean the one that calls spawnv()? If so - yes, Python can do that. But not so easily. You can look at how spawnv is implemented (it's in Python), and read up on the dup2 function (man 2 dup2) to see what's needed. spawnv can't do any kind of redirection. I think I posted an example here a couple weeks ago. Or you can use the shell, more or less the way you were going but you never invoked it - os.spawnv(os.P_NOWAIT, '/bin/sh', ['sh', '-c', 'python hello_earth.py > /dev/null']) which is really about the same as os.system('python hello_earth.py > /dev/null &') Donn Cave, donn at drizzle.com From m at moshez.org Thu Jul 17 03:55:45 2003 From: m at moshez.org (Moshe Zadka) Date: 17 Jul 2003 07:55:45 -0000 Subject: Python Quiz In-Reply-To: References: , <3f156704$1@mail.hmgcc.gov.uk> Message-ID: <20030717075545.14098.qmail@green.zadka.com> On Thu, 17 Jul 2003, "Raymond Hettinger" wrote: > Didn't FORTRAN popularise the idea of having > the language separate from tons of special purpose > libraries? Python has "batteries included", which are part of the core language in the sense that most programs depend on them. It does use nice modular design for that, but I'd doubt if "separation" is the correct term :) -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From usenet_spam at janc.invalid Tue Jul 15 22:02:18 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 02:02:18 GMT Subject: Library for pop over ssl? References: Message-ID: Marco Herrn schreef: > Hi, I know of poplib, which does what I need except that it doesn't > support SSL encryption. imaplib has SSL-support. But I want it with > pop3. Is there a library available that does this or do I have to > implement it myself? You can always use stunnel to SSL-ize a "normal" protocol... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From chasm at rift.sytes.net Wed Jul 2 19:02:08 2003 From: chasm at rift.sytes.net (Julian Tibble) Date: Wed, 2 Jul 2003 23:02:08 +0000 (UTC) Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> <020720031459050258%pecora@anvil.nrl.navy.mil> Message-ID: In article <020720031459050258%pecora at anvil.nrl.navy.mil>, Louis M. Pecora wrote: > In article , Bob > Gailer wrote: > >> "When an integer a is divided by another m, one has >> a = km + r >> where the remainder is some positive integer less than m. > > Maybe I'm misunderstanding this, but what about -7 divided by 5? We > get k=-1 and r=-2. -7 = (-2) * 5 + 3 So actually, k = -2 and r = 3 > m can be negative. Maybe your quote was for the positive integers only. True, that definition does not make sense when m is negative. When I came across the subject in introductory group theory they said "positive divisor". Julian From simon_place at whsmithnet.co.uk Sun Jul 6 17:42:11 2003 From: simon_place at whsmithnet.co.uk (simon place) Date: Sun, 06 Jul 2003 22:42:11 +0100 Subject: PEP idea. ( removing __slots__ ) In-Reply-To: References: <3f073594$1_2@news1.vip.uk.com> <3f083043$1_3@news1.vip.uk.com> <3f085fa7_3@news1.vip.uk.com> Message-ID: <3f08984c$1_3@news1.vip.uk.com> > No. Some classes have slots for efficiency, and their subclasses have > dictionaries for generality. > > Likewise, some classes have slots to save the dictionary for most > instances, but some instances may need additional attributes, in which > case Python creates the dictionary on-the-fly. I know subclasses can add a __dict__, but i really thought a class with __slots__ could not have a __dict__, doesn't the script below show this behavior? PythonWin 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> class A(object): ... __slots__=['a'] ... >>> b=A() >>> b <__main__.A object at 0x00EFABF0> >>> b.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'A' object has no attribute '__dict__' >>> b.a Traceback (most recent call last): File "", line 1, in ? AttributeError: a >>> b.a=1 >>> b.a 1 >>> b.b=1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'A' object has no attribute 'b' >>> From mcfletch at rogers.com Sat Jul 19 18:36:23 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 19 Jul 2003 18:36:23 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: <3F19C7E7.8000602@rogers.com> Okay, rather than respond to the fragments first, which just seems to be confusing people, as they aren't getting the previous discussion. Here's a quick sketch of what I'm creating: class Meta( type ): tableName = common.StringProperty( "tableName", """The table in which this class stores it's primary data""", defaultValue = "", ) implementationBase = common.ClassByNameProperty( "implementation", """Base class for implementation""", defaultValue = "wxpytable.dbresultset.DBResultSet", setDefaultOnGet = 0, ) ... Now, those objects from "common" are part of a fairly involved hierarchy of descriptor classes which provide type coercion, default-value retrieval, automated lookup of factory functions, managed list-of-type support, and a dozen other features. Here's the framework of what a "basicproperty" does: * hooks the __set__ event (and __get__ and __delete__) o is thereby a descriptor o can be introspected from the object with the properties + has documentation + has meta-data for coercion, type-checking, default values, operations for choosing common values, etceteras, etceteras + can be readily sub-classed to produce new effects, such as using weak references or storing values in a database based on schema objects, or calling methods on a client... * checks the data type of the value o if necessary, coerces the value (normally defering to the "baseType" for the property) * finally, stores the value o tries to do what would have been done if there were no descriptor (with the new, coerced value) o does *not* create new names in the object's namespace (all names are documented w/ descriptors, there's not a lot of '_' prefixed names cluttering the namespace) o does *not* require a new dictionary/storage-object attribute for the object (the descriptor works like any other descriptor, a *stand-alone* object that replaces a regular attribute) It's that last part that I'd like to have a function/method to accomplish. That is, store (and obviously retrieve as well) attribute values for objects, instances, types, classes, __slot__'d instances, etceteras under a given name without triggering any of the __setattr__ machinery which defers to the __set__ method of the associated descriptor. I can work around the problem by violating either of those two bullet points under "finally, stores the value", but I'm looking for something that *doesn't* violate them. See below for responses to particular points... Bengt Richter wrote: ... > client.__dict__['v'] = value >the above line should work for this example, so it must be different from >what you were doing before? Perhaps the client object before was a class? >I guess I'm not getting the big picture yet of your design intent. > That's what the base properties do, but they just can't work when doing a meta-class, as it's __dict__ is a dict-proxy, which doesn't allow assignment. I'm looking for a method to tell the Python system "Okay, what would you have done if there were no descriptors? Here's the key and value to set, go set them." That sample was just to demonstrate why calling object.__setattr__ wouldn't work (it recursively calls the descriptor). >Are you trying to make a base class that has properties that can >set same-named properties in the subclass via attributes >of objects instantiated from the subclass? Or as attributes of the >subclass? Do you need the property ability to munge its arguments dynamically? >Otherwise a plain old attribute assignment to the subclass per se should install >the property for its instances, no? > > Nope, I'm trying to make meta-classes which have rich properties. The particular project is a plug-in system, where the classes (the metaclass-instances) want to have all sorts of rich metadata associated with them in a way which meshes with the rest of the system (i.e. using a descriptor-based introspection mechanism). ... Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From cjw at sympatico.ca Wed Jul 16 15:31:53 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 16 Jul 2003 15:31:53 -0400 Subject: Numarray for Python 2.3 In-Reply-To: References: Message-ID: <3F15A829.9090200@sympatico.ca> Tim Rowe wrote: > Does numarray-0.5.win32-py2.2.exe work with Python 2.3? If not, is > there a version that will? > > Tia, > > Tim No, not the last time I tried. It seems that Python 2.3 looks for a different .dll structure than python 2.2. Below is an extract from a recent posting by Perry Greefield to the PySci list which sets out current development intentions for numarray. I have copied your question, with this response, to Perry Greenfield. Colin W. From: "Perry Greenfield" Date: Tue, 15 Jul 2003 19:45:52 -0400 [Eric Jones] >> >> Numarray will be the successor to Numeric. I talked with Perry >> Greenfield from STSci at OSCON last week. STSci is developing >> numarray. >> >> He said that pretty much the only things left before numarray is a >> "feature complete" replacement for Numeric are PyObject array support >> and Paul Dubois Masked Array (MA) classes. He wants a full >> replacement before releasing 1.0. >> >> I'll let him pronounce the official release dates, but it is >> not so far off. >> No dates fixed in stone, but here is the basic plan 0.6 to be released this week, this reorganizes numarray as a package 0.7 (few weeks?) Will include PyObject support 0.8 (2 months?) Will include MA support. At this point we hope to replicate all Numeric functionality (other than the planned changes). v1.0 will come out when 0.8 has been tested by users for a little while (with perhaps a 0.9 if many changes and fixes are needed) [Eric Jones] >> Numarray and Numeric will co-exist for a long while. Numarray is new >> and therefore less well tested. It also has slower performance for >> small arrays by about a factor of 3, but is faster for large arrays. >> There are also many packages that rely on Numeric out in the wild, >> >> and the transition will be slow. >> There may be some rough corners where performance of numarray needs optimization that haven't yet been handled (e.g. printing? slicing?) Perry Greenfield From walter at livinglogic.de Wed Jul 9 17:11:56 2003 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 09 Jul 2003 23:11:56 +0200 Subject: Deleting specific characters from a string In-Reply-To: References: Message-ID: <3F0C851C.4000500@livinglogic.de> Behrang Dadsetan wrote: > Hi all, > > I would like deleting specific characters from a string. > As an example, I would like to delete all of the '@' '&' in the string > 'You are ben at orange?enter&your&code' so that it becomes > 'benorange?enteryourcode'. > > So far I have been doing it like: > str = 'You are ben at orange?enter&your&code' > str = ''.join([ c for c in str if c not in ('@', '&')]) > > but that looks so ugly.. I am hoping to see nicer examples to acheive > the above.. What about the following: str = 'You are ben at orange?enter&your&code' str = filter(lambda c: c not in "@&", str) Bye, Walter D?rwald From mis6 at pitt.edu Wed Jul 30 07:41:29 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 30 Jul 2003 04:41:29 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <2259b0e2.0307290940.49ff417d@posting.google.com> <45228044.0307291352.696b16aa@posting.google.com> Message-ID: <2259b0e2.0307300341.67aee0fa@posting.google.com> chrisperkins37 at hotmail.com (Chris Perkins) wrote in message news:<45228044.0307291352.696b16aa at posting.google.com>... > mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307290940.49ff417d at posting.google.com>... > > I have posted a recipe with the itertools solution suggested in this > > thread: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212959 > > > > That's great, but your recipe contains a very serious error - you > spelled my name wrong ;) > > Chris Perkins (not Perking) Oops! It was a typo, I am going to correct it immediately! Michele From lorenb2 at bezeqint.net Sun Jul 20 17:28:38 2003 From: lorenb2 at bezeqint.net (Bobbie) Date: Sun, 20 Jul 2003 23:28:38 +0200 Subject: httplib\urllib attributes problem References: Message-ID: <005201c34f05$e273da60$6700a8c0@inet43> thanks. question: why can't I just totally erase that "self.addheaders = " line ? B. ----- Original Message ----- From: "Jordan Krushen" Newsgroups: comp.lang.python To: Sent: Monday, July 21, 2003 9:48 AM Subject: Re: httplib\urllib attributes problem > On Mon, 21 Jul 2003 07:45:19 GMT, Jordan Krushen > wrote: > > > At least for this one, here's the relevant code from urllib2.py: > > > > class OpenerDirector: > > def __init__(self): > > server_version = "Python-urllib/%s" % __version__ > > self.addheaders = [('User-agent', server_version)] > > > > You should be able to override your opener's addheaders attribute > > (untested): > > > > opener.addheaders = None > > Actually, it's late. Use this instead: > > opener.addheaders = [] > > This won't break if something else tries to append to the list. > > J. > -- > http://mail.python.org/mailman/listinfo/python-list > From drs at ecp.cc Wed Jul 9 03:51:35 2003 From: drs at ecp.cc (drs) Date: Wed, 09 Jul 2003 07:51:35 GMT Subject: dcom & Bad File Descriptor error Message-ID: I am periodically getting a Bad File Descriptor error from Python DCOM servers. I have seen a number of posts regarding this error and threads, but these are not multithreaded servers. Further, if i register the servers with the --debug flag, the errors go away, so I am not able to find out much in the way of information. Has anyone else seen this? Any suggestions? Python 2.0/2.1/2.2 on win2k pro/server Thanks, -doug From bokr at oz.net Thu Jul 17 13:47:33 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 17:47:33 GMT Subject: Accessing and updating global variables among several modules References: Message-ID: On 17 Jul 2003 05:28:49 -0700, fumingw at tom.com (Fuming Wang) wrote: [...] > >Hi, > >Thanks for the replies. I have actually found a solution to the >problem. The problem is caused by Python creating two copies of the >module that is passed to the interpreter. Here is a short report of >what the problem is and how to avoid it. Hope this can be of help for >others. > >Fuming > >P.S. I am running Python 2.3 b2 on Windows2000 > [... Very nice and clear exposition and demonstration of an importing gotcha and how to avoid it. ...] Thank you for writing that up so well. I am sure it will be of help. Regards, Bengt Richter From skywalkerpackage at hotmail.com Wed Jul 16 07:31:22 2003 From: skywalkerpackage at hotmail.com (Johannes Eble) Date: Wed, 16 Jul 2003 11:31:22 GMT Subject: Q: simple sockets, bind, and socket error 10048 Message-ID: <3f1532e3.3717465@news.online.de> Hello Python community, I am trying the echo-client and echo-server examples in Chapter 10, "Programming Python" by Mark Lutz. It is probably the most simple sockets sample: A socket server just echoing the socket clients' requests. The program works so far. I first start the server in one dos box, then the client in another dos box on my machine. However, I wonder why the client always gets a new port. This is printed in the server's dos box: g:\WingIDE\profiles\Johannes Eble\sock>python echo-server.py Server connected by ('127.0.0.1', 1048) Server connected by ('127.0.0.1', 1049) Server connected by ('127.0.0.1', 1050) Server connected by ('127.0.0.1', 1056) Server connected by ('127.0.0.1', 1057) Server connected by ('127.0.0.1', 1058) Note that I start a client one by one (in the same client's dos box). It seems that the older port numbers can't be used anymore even if the client is closing the connection and terminating. I have tried to bind the client to port 4000. I can start the client one time without an error. But the second time I get a socket error: g:\WingIDE\profiles\Johannes Eble\sock>python echo-client.py Client has socket address '127.0.0.1' 4000 Client received: 'Echo=>Hello network world' g:\WingIDE\profiles\Johannes Eble\sock>python echo-client.py Traceback (most recent call last): File "echo-client.py", line 18, in ? sockobj.connect((serverHost, serverPort)) File "", line 1, in connect socket.error: (10048, 'Address already in use') I do not understand why the port is still in use. Why can't I define a constant socket address for my client? Doesn't Python release the client's port address as soon as the client calls close() on its socket object or, at latest, when the client process terminates? I have tried a sockobj.shutdown(2) on the client (before close() ) without an effect. Any help would be great. Regards Johannes From sismex01 at hebmex.com Tue Jul 29 11:44:55 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 29 Jul 2003 10:44:55 -0500 Subject: variable assignment in "while" loop Message-ID: > From: Andy Todd [mailto:andy47 at halfcooked.com] > Sent: Martes, 29 de Julio de 2003 10:23 a.m. > > Spot on, with one (minor) correction. With a for loop you have to > iterate over the results of a call to a method on the cursor, e.g.; > > for info in mydbcursor.fetchall(): > print "Information:", info > > You could replace fetchall() with fetchmany() or, if you are feeling > contrary, fetchone() ;-) > > Regards, > Andy > Are you sure about this? Because, if you have to iterate through .fetchall() (for example), then the cursor isn't actually an iterable object, the result of fetchall() is (it's a list, which is iterable), same goes for fetchmany(); BUT, if you iterate over the results of fetchone() then you're gonna do a columnwise iteration over a single row. :-) So... anyone... do cursors have an __iter__() method? I don't have a DB module at hand to check it out... -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From daniel.dittmar at sap.com Tue Jul 29 12:49:35 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 29 Jul 2003 18:49:35 +0200 Subject: variable assignment in "while" loop References: Message-ID: sismex01 at hebmex.com wrote: > Are you sure about this? Because, if you have to iterate > through .fetchall() (for example), then the cursor isn't > actually an iterable object, the result of fetchall() is That cursors are iterable belongs to the optional extensions of the DB API spec so you can't expect that to work for all drivers. Due to the dynamic nature of Python, it's quite easy to add the methods .next () and .__iter__ () at runtime to the cursor class (if the driver is written in Python and not an extension). Daniel From mis6 at pitt.edu Wed Jul 16 20:20:52 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Jul 2003 17:20:52 -0700 Subject: [OT] sentances with two meanings References: <3F142A58.80426AA4@hotmail.com> Message-ID: <2259b0e2.0307161620.4a9353f1@posting.google.com> Alan Kennedy wrote in message news:<3F142A58.80426AA4 at hotmail.com>... > Syver Enstad wrote: > > > > Given the biblical meaning of "known", this could have even more than > > > two meanings :-) > > > > Does "to know" in english also mean to feel someone? In my own language > > the direct translation of the english know also means to feel. I could > > say (translated) "I know the cold", meaning I feel the cold > > weather. > > To "know" someone, in the biblical sense, is to have "carnal > knowledge" of them, i.e. "knowledge of the flesh", i.e. to have had > sexual relations with them. > > Some of the English translations of the bible use terms such as "And > Adam knew Eve, and Eve begat 2 children", etc, etc. These translations > are probably from the middle ages, or earlier. It comes at least from the Latin version and I would not be surprised if the double sense of "known" was in the Greek version too (any Greek here?). Now, Latin had to verbs for "to know": "scire" and "cognoscere". Only the second one had the sexual double meaning. The double meaning has been preserved in modern latin languages: Italian -> conoscere French -> connaitre Spanish -> conocer The other verb "scire" has generated (if I am not mistaken) "sapere", savoir", "saber" and of course "science", which are sexually clean, at least as far as I know ;) P.S. according to http://www.freedict.com/cgi-bin/onldict.cgi scio -> to know, understand. cognosco -> to examine, inquire, learn From klapotec at chello.at Tue Jul 29 11:00:44 2003 From: klapotec at chello.at (Christopher Koppler) Date: Tue, 29 Jul 2003 15:00:44 GMT Subject: Defining/declaring constants in Python References: <7h3fzkpk0lv.fsf@pc150.maths.bris.ac.uk> Message-ID: On Tue, 29 Jul 2003 11:56:54 GMT, Michael Hudson wrote: >Christopher Koppler writes: > >> If you really, really, REALLY want a varia^Wconstant that cannot be >> changed, no matter how hard you try, in Python, have a look at this: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 > >Of course, it's still possbile to change the values of these >'constants', you just have to muck about quite a bit to manage it. Oops. Yeah, should have written: constant that cannot be changed, unless you're prepared to do some very heavy lifting ;-) --Christopher From Robert at AbilitySys.com Mon Jul 14 22:28:56 2003 From: Robert at AbilitySys.com (Robert at AbilitySys.com) Date: Mon, 14 Jul 2003 19:28:56 -0700 Subject: Stop Python from exiting upon error in Windows References: Message-ID: Can you nest exceptions? I already have a few legitimate try/except blocks where I know there's a chance the act could go bad, do I just stick a try: at the beginning of the whole body of code and an except: at the end? - Robert "Tom Plunket" wrote in message news:n2o6hvcahk7dlmn9t26tvis8umnfg1tdeo at 4ax.com... > Robert wrote: > > > How can I stop the Python interpreter from exiting when an error occurs? > > create a batchfile, tell Windows that the association of Python > files is to that batch file, and put this in the file: > > python.exe %1 > pause > > > Or- catch the error in your mainline, and do a sys.raw_input() > call on exception. > > -tom! From owski at hotmail.com Wed Jul 16 20:03:38 2003 From: owski at hotmail.com (Adam Ruth) Date: Thu, 17 Jul 2003 00:03:38 +0000 (UTC) Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> <20030716160013839-0600@news.xmission.com> Message-ID: <20030716180329385-0600@news.xmission.com> In Stephen Horne wrote: > On Wed, 16 Jul 2003 22:00:22 +0000 (UTC), Adam Ruth > wrote: > >>In <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed at 4ax.com> Stephen Horne wrote: >>> On Wed, 16 Jul 2003 19:06:40 +0000 (UTC), Adam Ruth >>> wrote: >>> >>>>You are correct in that there are times when pointer semantics would >>>>be somewhat useful, but they're never necessary. His statement was >>>>that there are time that "you really can't avoid pointers". >>> >>> Hmmm - those words were in a context. I never claimed that "you >>> really can't avoid pointers" in *current* Python - that's obviously >>> not true. But if the copy-on-write stuff were implemented, the need >>> would arise. For example... >> >>It sure seemed that way to me: >> >> >>>>They're an unhappy necessity, akin to stop-lights. You need them >>>>because roads intersect, but if roads don't intersect, don't use >>>>them! >>> >>>Absolutely true. And the worst thing you can do when you really can't >>>avoid pointers is to obscure the issue even more by disguising them >>>as something else. >> > > Right - "the worst thing you can do when you really can't avoid > pointers" is not the same as "really can't avoid pointers". > > You have taken the condition out of a conditional scentence and quoted > it as if it were a statement. That's a pretty clear case of quoting > out of context to misrepresent what someone said, isn't it. > > Now lets restore the rest of what Adam said... > >: I came to Python from Ada, and all I have to say is: Pointer-like >: semantics are evil. They're worse than goto's, they're deadly, >: damaging, and should be avoided at all costs. >: >: They're an unhappy necessity, akin to stop-lights. You need them >: because roads intersect, but if roads don't intersect, don't use them! > > Guess what - when Adam said pointers are an 'unhappy necessity' he was > talking about ADA - NOT PYTHON. In Ada, pointers (or rather access > types) are definitely not overused (where I worked you needed > management permission and a damned good reason to use them due to the > military contract terms), but sometimes they are unavoidable. > > > Please be more careful what you snip. Actually, no, I wasn't talking about Ada. I was talking in general and about Pythyon. In languages with pointers, they are there to overcome a weakness (the roads intersecting). But where the roads don't intersect ( Python) there's no need to use them (or their semantics, as the case may be). So your response about diguising pointers as something else seemed to me to be referring to Python, since the prior message was about disguising a pointer as a mutable list in Pythyon. Anyway, glad we cleared that up. Sorry about misrepresenting you, I really thought you were talking about Python. In retrospect, my metaphor wasn't very clear. > >>The reference is passed by value >>to the function, just as you describe it should. > > Yes - there has to be pass-by-value at some level since Python is > implemented in C. But to me this just says that we are seeing the > side-effect of an implementation detail. I don't see it as a side effect, I see it as the core design. References are a very concrete type, they happen to be implemented as pointers in C. In Java they're not implemented as pointers, I'm not sure what they're implemented with, but it isn't pointers. In that case it must pass by reference (ala Java), but the semantics in Python of passing references by value is maintained. > > No need to argue this - you don't need to explain it to me because I > understand. It just see things from a different perspective. > > Python, however, has a >>futher layer of abstraction on top of its one data type, and that's >>objects. I would venture that it's the extra layer of abstraction >>that makes Python work in a more intuitive, proper way. This is, >>however, just my opinion. But it does seem that new programmers who >>learn this abstraction find it natural and simple. It's people >>coming from C, et al., that seem thrown off by it. > > No, my background isn't just in C - that is a long way from being the > first language I used, and I've used Python regularly longer than C++. I wasn't referring to you, but to the people that come to the newsgroup and ask questions about it. I still don't really understand what it is that bugs you about it, but that's more on my end. > >>As a side note, based on your description of your eduction and studies >>in an earlier post, I realize now how different our backgrounds seem >>to be. I'm coming from a world where the focus is engineering (Ada >>is the only language purpose-built for engineering, AFAIK). You seem >>to come from a background more focused on science and theory. > > Nope - I just happen to be interested in learning the theory too, and > particularly in experiencing a broad range of languages to understand > the ideas behind them. > > How come you didn't notice ada in my list? It's such a small word :). I'm sure I did, but wasn't thinking in this context then, so I didn't INCREF the information and it got garbage collected. > > About the first half of my programming career was working in the > defence industry as a software engineer. A lot of that was working at > very low level stuff (the 80c196kc microcontrollers I mentioned) and > with a lot of messing around with target hardware and in-circuit > emulators. The rest of my time in defence was spent using Ada. > > I first messed around with writing my own language quite young, with > an Atari ST. I liked the idea of text adventures and decided to write > one, but basically got caught up in the engine and the scripting > stuff. Pretty cool, though, through the rose-tinted glasses of memory. > > Anyway, I stayed interested in compilers and stuff, but the reason I > got interested in LR and parsing theory has little to do with parsing > as most see it. A grammar, seen as describing a sequence of tokens, > can deal with many things - the tokens don't have to be words. They > might be events, for instance. And the state of the 'parser' may be > used to select a response strategy in an AI. I wanted it for a game I > was going to write a few years back which would construct strategies > from various elements by building them into a kind of grammar, and use > the resulting state model as a real time AI. > >>Perhaps this is >>the cause of our different world views (on this issue). Just a >>thought, though it is interesting we both chose Python. > > Strictly speaking, the reason I chose Python at the time was because > at work we used macs with terminal emulators. If you wanted a utility, > you either wrote it under VMS or you were stuffed as mac interpreters > and compilers were hard to come by. > > I see it as one of the happiest flukes - I just wish I'd found Python > earlier. Interesting. I chose it mainly because I was experimenting with Smalltalk to learn dynamic programming, and it seemed a more practical language (I never got used to the whole image thing in Smalltalk). One of the things that I really liked about both languages is how they handled references. Perhaps that's why I'm so vehement about this whole topic. Well, that and too much caffeine. Adam Ruth From imbosol at aerojockey.com Tue Jul 29 20:17:54 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Wed, 30 Jul 2003 00:17:54 GMT Subject: metaclasses References: Message-ID: Raymond Hettinger wrote: >> It seems this is a more general way to build classes than inheritance. >> Is this a reasonable viewpoint? >> >> >>> >> >>> def meth1(self): >> ... print "i am meth1" >> ... >> >>> def meth2(self): >> ... print "i am meth2" >> ... >> >>> Foo = type("Foo",(),{'meth':meth1}) # make a class >> >>> foo = Foo() # make an instance >> >>> foo.meth() # call a method >> i am meth1 > > It is a less general way for building classes. Actually, the question doesn't make sense. Metaclasses and inheritance are two different dimensions of generality. Neither is more or less general than the other, because they generalize in different ways. However, his use of the built-in metatype 'type' is more general than the class statement, which seemed to be what he was asking. One can supply a list of bases which, unlike the class statement, need not be a fixed length. In fact, the bases can be calculated dynamically. Likewise with the class dict. -- CARL BANKS From jjl at pobox.com Mon Jul 21 10:06:59 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Jul 2003 15:06:59 +0100 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: <87k7acq8ho.fsf@pobox.com> Marc Wilson writes: [...] > While I'm sure Python is a lovely language, the choice is due to PSP using > the scripting engine: if I have to write something from scratch (or even > from bits'n'bobs), I'll use a language I already know. [...] Very wise. It would take you a whole afternoon to learn Python well enough to do what you want with PIL <0.2 wink>. http://effbot.org/zone/pil-imageenhance.htm http://effbot.org/zone/pil-imagefilter.htm And I'm sure that afternoon will pay off again. OK, and another day to get out of the mess your OS (whichever one you use) will try to get you into with naming conventions, filesystem paths and other plumbing <0.8 wink>. John From bokr at oz.net Mon Jul 7 20:48:21 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Jul 2003 00:48:21 GMT Subject: getting a submatrix of all true References: <52fe159d.0307041016.4dcb4a5c@posting.google.com> Message-ID: On Mon, 07 Jul 2003 11:00:11 -0500, John Hunter wrote: >>>>>> "Jon" == Jon writes: > > Jon> Sadly I can only give you a method which is certainly not > Jon> optimal, but at least finds something which is probably not > Jon> too bad, and fairly quickly. Uses the Numeric module to speed > Jon> up, so that a few thousand by a few hundred is quickly > Jon> computable. I'm curious to know if it does much better or > Jon> worse than other algorithms. > >Hi Jon, thanks for the suggestion. For my data set, your solution >performed a little better size-wise than my poor man's approach, which >I gave in the original post. And it is certainly fast enough. I >liked your idea of zero-ing out the elements when you made a decision >to delete a row or column. When I was thinking about solutions using >Numeric, I kept running up against the problem of deleting a row or >column (which entails a whole array copy so is expensive). > >If anyone wants to try their algorithm on "real world data" which, >unlike the ones discussed here, have lots of correlation between >missing rows and columns that might be exploited, I have uploaded the >missing data matrix to a web server. It can be loaded with: > > from urllib import urlopen > url = 'http://nitace.bsd.uchicago.edu:8080/summer/jdh/missing.dat' > L = [ [ int(val) for val in line.split()] > for line in urlopen(url).readlines()] > # L is 1072x83 > The statistics on this data is interesting, referring to counts of 1's: (not very tested) [15:31] C:\pywk\clp\submx>python showmx.py -f missing.dat -counts nr=1072, nc=83 totcc=6239, totrc=6239 => *100./(83*1072) => 7.01 count:freq -- cols with count ones occurred freq times 0:16 1:4 8:3 14:2 16:4 20:4 21:3 23:1 25:6 27:1 28:7 32:4 41:1 59:1 60:3 62:3 65:1 95:2 96:1 108:3 125:1 134:1 158:1 177:1 199:1 206:2 237:1 241:1 252:1 254:1 1061:2 count:freq -- rows with count ones occurred freq times 0:3 1:2 2:460 3:67 4:140 5:66 6:42 7:49 8:61 9:17 10:46 11:23 12:8 13:8 14:12 15:10 16:3 17:5 18:1 19:7 20:4 21:2 22:5 23:1 27:2 28:2 30:2 31:1 33:1 34:1 36:2 38:1 40:1 41:1 44:4 45:7 48:1 55:2 56:2 And sorted per descending frequency of number of cols and rows with particular counts: [15:31] C:\pywk\clp\submx>python showmx.py -f missing.dat -counts -freq nr=1072, nc=83 totcc=6239, totrc=6239 => *100./(83*1072) => 7.01 freq:count -- cols with count ones occurred freq times 16:0 7:28 6:25 4:32 4:20 4:16 4:1 3:108 3:62 3:60 3:21 3:8 2:1061 2:206 2:95 2:14 1:254 1:252 1:241 1:237 1:199 1:177 1:158 1:134 1:125 1:96 1:65 1:59 1:41 1:27 1:23 freq:count -- rows with count ones occurred freq times 460:2 140:4 67:3 66:5 61:8 49:7 46:10 42:6 23:11 17:9 12:14 10:15 8:13 8:12 7:45 7:19 5:22 5:17 4:44 4:20 3:16 3:0 2:56 2:55 2:36 2:30 2:28 2:27 2:21 2:1 1:48 1:41 1:40 1:38 1:34 1:33 1:31 1:23 1:18 There are two columns with 1061 ones out of a possible 1072, so they account for 2 in most of the row counts. Hence the most popular row count (2) mostly goes to 0. Interestingly, 4(2) is 'way more popular than 3(1). This doesn't look like what I'd expect from uniform overall probability of some percentage. Discounting the stuck columns, no ones shouldn't be more likely than one one, since there's only one way to get all zeroes, but there's then 81 equally probable ways to get one one. Look at a uniform 5% on 1072 x 83 (twice to show variation). There's a distribution with tails, centered on 5% of 1072 and 83 it seems: [17:48] C:\pywk\clp\submx>showmx.py 1072 83 5 -counts nr=1072, nc=83 totcc=4338, totrc=4338 => *100./(83*1072) => 4.88 count:freq -- cols with count ones occurred freq times 35:1 39:1 40:2 41:1 42:5 43:1 45:5 46:3 47:2 48:6 49:3 50:5 51:5 52:5 53:5 54:5 55:5 56:5 58:3 59:4 61:1 62:2 63:1 64:1 65:3 70:1 78:2 count:freq -- rows with count ones occurred freq times 0:21 1:74 2:134 3:219 4:218 5:176 6:113 7:64 8:29 9:15 10:6 11:2 12:1 [17:48] C:\pywk\clp\submx>showmx.py 1072 83 5 -counts nr=1072, nc=83 totcc=4394, totrc=4394 => *100./(83*1072) => 4.94 count:freq -- cols with count ones occurred freq times 37:1 40:1 41:3 43:1 44:2 45:2 46:5 47:5 48:1 49:3 50:6 51:8 52:7 53:7 54:3 55:3 56:4 57:3 58:3 59:1 60:1 61:1 62:1 63:1 64:3 65:2 68:2 69:1 70:1 72:1 count:freq -- rows with count ones occurred freq times 0:19 1:58 2:150 3:218 4:218 5:173 6:111 7:63 8:38 9:13 10:5 11:5 12:1 >I think I may adapt your algorithm to terminate when the percent >missing falls below some threshold, removing the requirement that >*all* missing values be removed. This will drop the worst offenders >observation or variable wise. Then I can use a regression approach to >fill in the remaining ones. > > Jon> Interesting problem! Yes. So many, so little time ... ;-/ > >I agree. There are lots of extensions to the original formulation >that are relevant to the missing value problem. As we have seen in >the posts here, there are good exact solutions for smallish matrices, >but for larger ones a statistical approach is required. The right >statistical solution surely depends on the correlation structure of >the matrix. I'm pretty sure there are better exact algorithms than the brute force one I first posted, but I haven't done a new one since, just some little things to show things about the data, as above. > >Also, it would be nice to generalize to higher dimensions (eg 3D >matrices). For my problem, I have N observations of M variables over >D days. So this is the 3D version of the 2D problem above. Your >solution is readily adaptable to this case. More generally, you might >want to impose extra requirements, like, no days can be dropped, or at >most 10% of the days can be dropped, or if you want to compute changes >in variables over days, that no days can be dropped. > I'm wondering if you might not have other considerations about which data points to drop too. E.g., if an observation makes the difference between being able to invert a matrix or not, you might opt to drop several other things instead, even though in terms of count the set would be less optimum. (Curiousness: what do your observations represent?) >The more general formulation is something like > > Given an N-D (N0, M0, P0, ...) boolean matrix X with a covariance > matrix C, what is the largest submatrix of X of dimensions (N1, M1, > P1, ...) such that the fraction of remaining dimensions satisfies > > (N1/N0, M1/M0, P1/P0, ...) >= (alpha, beta, gamma, ..) > > and the total percent true <= p. > >The original problem is a special case of this where alpha=0, beta=0, >p=0 and C unspecified. > >Anyone looking for a dissertation project :-) ? > >John Hunter > Regards, Bengt Richter From hwlgw at hotmail.com Mon Jul 21 05:31:13 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 21 Jul 2003 02:31:13 -0700 Subject: How to save web pages for offline reading? Message-ID: I am trying to download pages from Python, for offline reading. This to save telephone costs :-) If a page contains something like and I use fp=urllib.urlopen(...) and then fp.read(), I get the HTML but not the CSS. As a result the page looks bad when reading offline. How to solve this? Also the .GIF's in a page would be nice, but this is less important and also would take more time to download. From intentionally at blank.co.uk Wed Jul 16 17:16:24 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 22:16:24 +0100 Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> Message-ID: <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> On Wed, 16 Jul 2003 19:06:40 +0000 (UTC), Adam Ruth wrote: >In Michael Chermside >wrote: >> Look, first of all, let me say that I disagree with Stephen Horne in >> this discussion. Or, to be more precise, I think that the approach he >> is using is not one which is useful in describing Python. HOWEVER, >> that doesn't mean that there's NOTHING to what he is saying, and your >> claim that there is no situation requiring "pointers" in Python seems >> wrong to me. Thankyou - nice to know I'm not *completely* insane ;-) >You are correct in that there are times when pointer semantics would be >somewhat useful, but they're never necessary. His statement was that >there are time that "you really can't avoid pointers". Hmmm - those words were in a context. I never claimed that "you really can't avoid pointers" in *current* Python - that's obviously not true. But if the copy-on-write stuff were implemented, the need would arise. For example... >>> class c : ... x = 0 ... >>> k = c() >>> def fn(a) : ... a.x=1 ... >>> fn(k) >>> k.x At the moment, the result is 1. With copy-on-write, object parameters would behave exactly the same as integer or other immutable parameters. The result would be 0. You'd need pointers or references or call-by-reference to do a number of things. >I definitely went a little overboard, and it sounds like I'm saying, >"not only are pointers not necessary, they're never desirable". My tone >was a bit more knee jerk than was prudent. Then I withdraw certain comments I've made. I really can't complain about people going "a little overboard", can I ;-) >This is just as clear as the C++ version, and more clear than the Python >version that wraps with the list. > >This example, though, doesn't really show the difference, it's too >trivial. All of the versions are clear enough, with the difference >being academic. I agree with both of these comments. >I would be interested in seeing a more complex example where something >would be substantially cleaner with pointers. I have to acknowledge the >possibility that they exist, I don't know everything... yet :) I was told today that both Perl and ML have something equivalent to pointers. I don't know either language, though. Given the current audience, mentioning Perl may be a mistake - but we could look up the rationale for including them in ML. That is something to do with caution, though. I imagine that ML is a very different language to Python. I have used Haskell and Miranda, which are at least broadly the same paradigm but may or may not be quite a similar languages, but even those I never exactly knew well. The rationales might not be very portable. From mertz at gnosis.cx Fri Jul 4 16:00:28 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 04 Jul 2003 16:00:28 -0400 Subject: Least used builtins? References: Message-ID: |> I haven't used: apply, buffer, coerce, globals, intern, iter, locals, |> oct, slice, super, unichr, unicode. Sean 'Shaleh' Perry wrote previously: |apply isn't as useful as it used to be. |locals and globals is useful in some interesting ways. |iter is really new so no surprise you haven't used it yet. |most people don't play with octal so I doubt oct() gets a lot of mileage. |The unicode stuff is new and most English only coders don't use it. I wouldn't mind moving quite a bit of __builtins__ into standard modules. Doing that only creates a one-line incompatibility, i.e. you might need to add: from itertools import enumerate To the top of a module/script. Some quick thoughts: Current builtin Possible Home --------------- --------------- abs math apply functional basestring internal bool buffer callable sys chr classmethod new cmp coerce compile code complex math delattr dict dir divmod math enumerate itertools eval code execfile code file filter functional float getattr globals hasattr hash internal hex math id internal input int intern internal isinstance sys issubclass sys iter len list locals long map functional max math min math object internal oct math open ord pow math property new range raw_input reduce functinal reload repr round math setattr slice staticmethod new str super internal tuple type unichr unicode vars xrange itertools zip itertools This sort of thing would cleanup the minimal Python interpreter, while not deeply hiding/removing anything. Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From Brian.Inglis at SystematicSw.ab.ca Tue Jul 22 04:29:14 2003 From: Brian.Inglis at SystematicSw.ab.ca (Brian Inglis) Date: Tue, 22 Jul 2003 08:29:14 GMT Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: On Tue, 08 Jul 03 12:43:14 GMT in alt.folklore.computers, jmfbahciv at aol.com wrote: >In article , > shoppa at trailing-edge.com (Tim Shoppa) wrote: > > >>Remember the Dilbert where PHB complains that his programmers are using >>way too many semicolons? :-) > >All RIGHT! That's a good PHB. It was so difficult to distinguish >between a semicolon and a colon on the listings. That's a lousy printer operator: the ribbon should have been flipped end around long before it got to that stage. (That's the old equivalent of shaking a laser toner cartridge.) You also wouldn't be able to differentiate between commas and dots, some apostrophes and quotes, maybe bars and bangs, possibly parens brackets and braces, if you had and used them. Thanks. Take care, Brian Inglis Calgary, Alberta, Canada -- Brian.Inglis at CSi.com (Brian dot Inglis at SystematicSw dot ab dot ca) fake address use address above to reply From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 21 13:04:47 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 21 Jul 2003 17:04:47 GMT Subject: How to save web pages for offline reading? References: Message-ID: Will Stuyvesant enlightened us with: > But it downloads only the HTML, not the .GIFs in it. There is an -A > option (from wget --help): do "man wget" and you'll soon find out that there is an option to download all required files. Hint: --page-requisites This option causes Wget to download all the files that are necessary to properly display a given HTML page. This includes such things as inlined images, sounds, and referenced stylesheets. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From bokr at oz.net Fri Jul 11 13:56:48 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jul 2003 17:56:48 GMT Subject: Enter parameters into Fortran executable from python cgi script References: <2c6431ab.0307110634.1bf59a6b@posting.google.com> Message-ID: On 11 Jul 2003 07:34:51 -0700, lamar_air at hotmail.com (lamar_air) wrote: >I have a fortran executable which when run from cmd it asks for a >series of parameters which you enter then hit enter. >From my python cgi script i want to be able to run the executable. >Enter the 4 or 5 parameters needed then end the executable and >redirect to another web page which will display some results given >from an output file from the fortran executable. > >When the user clicks submit on the form it seems to hang up on the >interaction between python cgi and fortran exe. In this example the >fortran exe only accepts on variable then terminates. > >How do i do this correctly? >testrun3 can be accesed from any dir because it's directory is set in >the environment variables. > >import os >os.system("testrun3") >os.system("Y") >os.system("exit") Using p2test.py in the role of testrun3, which I assume expects a "Y" input and later an "exit" input (we'll talk about whether you need \n later below), here is an example using os.popen2 to feed input to child via chin.write and get output via chout.read: ====< p2test.py >=========================== import sys first_inp = sys.stdin.readline() print 'first input was:',`first_inp` print >>sys.stderr, 'Dummy error message' second_inp = sys.stdin.readline() print 'second input was:',`second_inp` 1/0 # sure to make exception ============================================ Interactively: >>> import os >>> chin,chout,cherr = os.popen3(r'python c:\pywk\clp\p2test.py') >>> chin.write('Y\nexit\n') >>> chin.close() >>> print chout.read() first input was: 'Y\n' second input was: 'exit\n' >>> print cherr.read() Dummy error message Traceback (most recent call last): File "c:\pywk\clp\p2test.py", line 7, in ? 1/0 # sure to make exception ZeroDivisionError: integer division or modulo by zero There can be deadlock situations, which you can read about at http://www.python.org/doc/current/lib/popen2-flow-control.html but you don't have a lot of data going to the child process, and you are not having a continuing interchange with it, so there shouldn't be a problem. As a first attempt, I'd just substitute 'testrun3' for r'python c:\pywk\clp\p2test.py' in the above and see what you get. If it doesn't work, you can experiment by removing the \n after the Y and/or the exit, in case testrun3 is calling some single-character low level input for Y (like getch() in C). HTH Regards, Bengt Richter From skip at pobox.com Thu Jul 31 01:04:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 00:04:19 -0500 Subject: urlretrieve a file whose name has spaces in it In-Reply-To: <5a4226f0.0307301631.3dd0c00f@posting.google.com> References: <10caf2e2.0307291439.33d9fcc3@posting.google.com> <5a4226f0.0307301631.3dd0c00f@posting.google.com> Message-ID: <16168.41811.821108.301302@montanaro.dyndns.org> Kevin> You can easily escape spaces with "%20" as in: Kevin> urllib.urlretrieve("http://website.com/path/string string1 Kevin> foo.doc".replace(" ", "%20"), "local_file") Better yet, use url.quote() to make sure all special characters get quoted in the right way depending on where they are in the URL: import urllib help(urllib.quote) Skip From shane at zope.com Thu Jul 10 14:01:33 2003 From: shane at zope.com (Shane Hathaway) Date: Thu, 10 Jul 2003 14:01:33 -0400 Subject: Business model for Open Source - advice wanted In-Reply-To: <246a4e07.0307100613.fc2fc50@posting.google.com> References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <3F0DA9FD.40802@zope.com> Frank Millman wrote: > I am busy developing an accounting package, using Python and wxPython, > together with PostgreSQL on a Unix platform or SQL Server on a Windows > platform. I am a qualified accountant and have been developing > accounting software, mostly customised, for over 20 years. [...] > I have been toying with the idea of releasing it > under an Open Source license. I agree with Evan: open source has turned out to be a very effective model for Zope Corp. Once your product is popular (partly because it's Free), you can sell your expertise in a lot of ways: - You can sell to different verticals using your open source product as a platform. Every business has different accounting needs, but businesses of a certain category tend to be quite similar. You could make packages for real estate, law, medical practices, retail shops, etc. The vertical customizations should be simple enough that it doesn't cost you much to create them, but should have enough "meat" that it's more cost effective for a business to buy the customized product than to re-create it on their own. - Sell training courses. You might have two levels of training: one for end users and one for larger companies that want to customize your product. Training courses can be a lot of fun, and people are often willing to pay quite a bit for a week's worth of expert knowledge. - When working with small shops with no IT staff, you could consider becoming an application service provider, keeping the software running smoothly and the data backed up without any intervention by your customer. The recurring income could be enough to sustain the business for a long time. The important thing is to build strong relationships of trust with both customers and potential customers, invite people to use your products and services, and follow up on commitments. That's a key to success in any business. Free, open source software gives you an advantage in the process of building relationships. If you cultivate those relationships through mailing lists and personal contacts, business opportunities will surface in the most unexpected places. Well, that's how it works for Zope, anyway! ;-) I think many open source businesses struggle primarily because they spend too much time on the technology and not enough time connecting with people. I am fortunate to work for a company that has its priorities straight. Shane From bkc at Murkworks.com Thu Jul 3 16:36:58 2003 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 3 Jul 2003 16:36:58 -0400 Subject: Python on Pocket PC (with graphics) References: Message-ID: There's nothing pretty yet. win32gui has been ported, so you can create simple win32 windows apps and dialogs. win32ui was not ported. venster and ctypes looks promising, and should be easy to port. if wxWindows got ported, you could use it, but I've waited over a year for "them" to finish wxEmbedded. -- Novell DeveloperNet Sysop #5 _ "Fabien" wrote in message news:c007a5d3.0307011629.421145b0 at posting.google.com... > Hello, > > I'm completly new on python and on Pocket PC ! I want to write an > application and plane to us python, but I need graphical display. If I > well enderstood, I will not find any port of TkInter on Pocket PC. Is > there a way to use the standard pocket PC API from python ? any web > site or book to start from without boriing anyone on this group ? > > Thanks for the answer ! > > Fabien ARNAUD > -- > http://mail.python.org/mailman/listinfo/python-list > From member33375 at dbforums.com Tue Jul 15 20:41:05 2003 From: member33375 at dbforums.com (sprmn) Date: Wed, 16 Jul 2003 00:41:05 +0000 Subject: tkinter Message-ID: <3114992.1058316065@dbforums.com> does anyone know of any sites with good tutorials on tkinter on them? -- Posted via http://dbforums.com From richardc at hmgcc.gov.uk Mon Jul 14 07:56:57 2003 From: richardc at hmgcc.gov.uk (richardc) Date: Mon, 14 Jul 2003 12:56:57 +0100 Subject: A few beginning questions Message-ID: <3f129a8a$1@mail.hmgcc.gov.uk> Ive just started playing with Python and have a couple of questions. Im looking for an agument parsing library (from the command line), Ive come across optik and argtools. What other ones are there are any of them any good, is there a 'standard' lib for doing this. Also how should I '#define' magic numbers in Python. I spent ages looking around for a 'define' statement or anything that will allow me to create a constant value 'object'. Am I missing something very obvious ? Also, what 'IDE/editor' do people recomend for MAC OSX, so far Ive found 'Hydra' to be the best as it works on plain files and has Python syntax highlighting... what else is there and are any of them any good. Has nobody written an editor/IDE in Python with wxWindows so that it runs on all platforms ? Many thanks Rich From bobx at linuxmail.org Thu Jul 10 12:33:23 2003 From: bobx at linuxmail.org (Bob) Date: 10 Jul 2003 09:33:23 -0700 Subject: ftp a file by date and name match References: <1001ff04.0307080629.7ef1e277@posting.google.com> Message-ID: <1001ff04.0307100833.2f86f802@posting.google.com> John Hunter wrote in message news:... > >>>>> "Bob" == Bob writes: > > Perhaps you'll join the ranks of the converted? Mayhaps. : ) The only problem I am having is that I do NOT know the name of the file to match, only the pattern of the file name. From sross at connectmail.carleton.ca Sun Jul 6 17:25:13 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 6 Jul 2003 17:25:13 -0400 Subject: anything new on the ternary operator? References: Message-ID: >From Guido's EuroPython 2003 "State of the Python Union" slides http://www.europython.org/Talks/Slides/Slides_Guido_python_euro2003.ppt Conditional Expressions - Vote in March - (if C: x else: y) won the vote - But not by a landslide - Now in Filibuster mode :) - When in doubt, don't change it - Competing forces: - feature bloat - handy feature From newsgroups at jhrothjr.com Wed Jul 23 19:05:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 23 Jul 2003 19:05:47 -0400 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: "Steven Taschuk" wrote in message news:mailman.1058985883.11441.python-list at python.org... > Quoth John Roth: > [...] > > I can kind of understand the justification for the Borg pattern > > in Python releases before 2.2, because there was no way of > > creating a true singleton in those releases. However, in 2.2 and > > later, it's really easy to create one using new style classes. > [...implementing singletons with __new__...] > > That being the case, I'd like to see the Borg pattern go the way > > of a fondly remembered hack that is no longer necessary. > > Just out of curiosity: why do you prefer singletons to Borgs in > the first place? The root of the problem is that someone wants to call the class constructor and get back something that acts like there's only one instance. AFIC, the best solution is to not do that; there are other patterns that are just as easy to understand and a lot more tractable. However, assuming that you actually want to do it, 2.2 gives you a simple and straightforward way to implement the classical singleton pattern. It's a class where there will be one and only one instance. However unwise it may be, it's a basic OO pattern. > (I don't see Borg as a hack to get the behaviour of a singleton; I > see it as a more direct way to solve the problem which singletons > are supposed to solve. Thus to me Borg is actually preferable, in > those exceedingly rare cases when that problem actually arises.) It's a hack because it's fiddling with the internal representation of the object. At one time I had to maintain a large set of changes to IBM's MVS, and I'm very sensitive to what happens to the developer's flexibility when someone nails an internal issue that ***SHOULD*** be subject to change between releases without consequences, and suddenly forecloses the developers options in the area. Bad. Bad. Bad. John Roth > > -- > Steven Taschuk staschuk at telusplanet.net > "I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein > From anthony at interlink.com.au Sun Jul 6 09:36:15 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Sun, 06 Jul 2003 23:36:15 +1000 Subject: Frustration with spurious posts. In-Reply-To: <3F081C10.8CF6B57@hotmail.com> References: <3F081C10.8CF6B57@hotmail.com> <3F06FD11.967D8D8A@hotmail.com> Message-ID: <200307061336.h66DaFqT027267@localhost.localdomain> >>> Alan Kennedy wrote > Is there some sort of mail header that these virus checking gateways > could examine, to see if the email is from a list, rather than an > individual, before it sends these emails? Maybe we need to invent one, > e.g. > > X-Dont-Send-Me-Virus-Reports: YES Won't help - the virus that fakes 'python-list at python.org' (or python-list at cwi.nl - while it's old, I'm sure it's out there still) won't generate this header. Greg Ward's aware of the issue, and he's working on it - offers of useful round tuits to help him wouldn't be a bad thing. > > "Be strict when sending and tolerant when receiving." > > RFC 1958 - Architectural Principles of the Internet - section 3.9 > > Do this mean we should quietly tolerate the "you sent me a virus!" > emails? > > ;-) No, it means you should send very firmly worded "fix your fucking mail gateway" messages to the people sending back useless bounce messages. -- Anthony Baxter It's never too late to have a happy childhood. From martin at v.loewis.de Sat Jul 5 04:04:21 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Jul 2003 10:04:21 +0200 Subject: AIX + GCC 2.95.3 - Python (2.1 or 2.2) - building the shared library (.so) for python - HOW TO?!? References: <3F056D69.1090705@polbox.com> Message-ID: hab writes: > (If I use standard -shared linking, during the _import python is crashing.) > As seen in in AIX-NOTES there should be used ld_so_aix. But I suspect > that it was prepared for standard xlC (CC) compiler. How to make it > running for GCC compiler? Nobody knows anything about AIX in the Python world. You have to make it work yourself. > 1. Why is such nonuderstandable-ultimate-tricky solution prepared for AIX? There are two possible reasons: 1. AIX is such a strange system that you need to play dirty tricks to make it load modules dynamically. 2. Whoever ported shared loading to AIX didn't know anything about the system, and tried random things until he got a working solution. I don't know which one it is, but I'm leaning towards 1) > 2. Does it work only for xlC (CC) or also for GCC? If, how to do it? Nobody knows. > 3. What is the entry point function? How I can find it in the sources? You mean, of python itself? It's main(), and it is defined in Modules/python.c. Regards, Martin From m at moshez.org Mon Jul 14 15:24:01 2003 From: m at moshez.org (Moshe Zadka) Date: 14 Jul 2003 19:24:01 -0000 Subject: anything like C++ references? In-Reply-To: References: , , <000301c348c7$3c501980$21795418@dell1700> Message-ID: <20030714192401.25922.qmail@green.zadka.com> [Moshe Zadka] > In computer science, the theoretical model one first learns is a turing > machine. Turing machines have no variables or values, merely tapes. [Andrew Dalke] > Actually, we started off with state machine, then worked our way though > DFA/NFA, PDA, etc., ending up with a TM. Obviously, I meant "first turing-equivalent". Of course, whether this is true also depends: in CS "Computability" this is true, but in Math, we covered this in "Logic 2", and there we did, IIRC, recursive functions and counting machines first. Counting machines are mostly useful as something on the way to prove recursive functions are turing complete. > I remember being intrigued > that the way we learned these was in opposite order to they way they > were first researched. > > Can anyone suggest why? My thought was that mathematicians > like generalizing, so the most general models were pondered first. > Only as people started to experiment with variations, and with actual > computer hardware to back them up, did people start thinking about > more limited cases. Well, I think that it's natural to study DFAs first, as a turing machine is a DFA with a tape, so it's useful to know *why* the tape is needed. Also, DFAs are a good explanation of "what are computers", as a computer is necessarily finite. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From http Thu Jul 31 15:27:14 2003 From: http (Paul Rubin) Date: 31 Jul 2003 12:27:14 -0700 Subject: HTML DOM parser? Message-ID: <7x7k5y5wfh.fsf_-_@ruckus.brouhaha.com> Is there an HTML DOM parser available for Python? Preferably one that does a reasonable job with the crappy HTML out there on real web pages, that doesn't get upset about unterminated tables and stuff like that. Many extra points if it understands Javascript. Application is a screen scraping web robot. Thanks. From spinard at ra.rockwell.com Fri Jul 11 11:15:45 2003 From: spinard at ra.rockwell.com (Steve Pinard) Date: 11 Jul 2003 08:15:45 -0700 Subject: How to get all IP addresses in python? References: Message-ID: <6cd58b6.0307110715.1bb9bc23@posting.google.com> Try socket.getaddrinfo rather than socket.gethostbyname. It returns a list of tuples. tuple[4][0] of each list element is the IP address. addrs = socket.getaddrinfo(socket.gethostname(), None) for addr in addrs: print addr[4][0] The above worked on my machine but I only have one NIC card. - Steve From shane at zope.com Thu Jul 10 11:36:33 2003 From: shane at zope.com (Shane Hathaway) Date: Thu, 10 Jul 2003 11:36:33 -0400 Subject: Securing PyDoc and CGIHTTPserver In-Reply-To: <2621b014.0307100535.449ad06f@posting.google.com> References: <2621b014.0307100535.449ad06f@posting.google.com> Message-ID: <3F0D8801.3000105@zope.com> Jon Schull wrote: > The port number used by pydoc is currently set by the user at the > command line. Many people probably use the example given in the > python module documentation : "python -p 1234" However, if the port > were chosen at random and printed out, then only pydoc and the user > would know how to access the pydoc server. What about binding only to the local (loopback) interface? That way, the system won't even listen for external connections. It's like a built-in firewall. The change is a one-liner. The DocServer computes the hostname for the loopback interface but then binds to all interfaces. So change this line: self.address = ('', port) to: self.address = (host, port) Shane From drlinux at columbus.rr.com Thu Jul 3 12:00:25 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Thu, 3 Jul 2003 12:00:25 -0400 Subject: python 2.3b[12] In-Reply-To: <3F037015.3D6D7034@alcyone.com> References: <3F037015.3D6D7034@alcyone.com> Message-ID: <200307031200.25633.drlinux@columbus.rr.com> On Wednesday 02 July 2003 19:51, Erik Max Francis wrote: > Dave Reed wrote: > > > ./python > > Python 2.3b1 (#1, Jun 14 2003, 15:08:24) > > [GCC 3.2.3] on sunos5 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> > > > > I thought maybe this was just someone forgetting to update the startup > > message for the new beta, but I've seen other messages that show > > Python 2.3b2. > > > > Any ideas on what happened? > > Hmm, mine doesn't (built from scratch on Linux): > > max at oxygen:~% python2.3 > Python 2.3b2 (#1, Jun 29 2003, 20:30:58) > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > Are you sure you're running the version you think you are? I even ran it directly from the build directory and it still reports b1. I do have b1 installed in another directory (that was in the path when I compiled b2). Maybe I need to remove that version of python before compiling the new one. I used different --prefix= values when compiling each one, but since the other one was still in the path, it may have messed up. Dave From belred1 at yahoo.com Sat Jul 12 15:13:46 2003 From: belred1 at yahoo.com (Bryan) Date: Sat, 12 Jul 2003 19:13:46 GMT Subject: Accessing and updating global variables among several modules References: Message-ID: "Fuming Wang" wrote in message news:a12f6af8.0307111938.4d7a9851 at posting.google.com... > Hi, > > I have several modules that need to access global variables among > them. I can do that by import modules: > > module A: > gA = 'old' > > module B: > import A > print A.gA > >>> 'old' > > change gA in module A after some initialization: > def init_fuct(): > gA = 'new' > the bug is here.... change your init_fuct() like this and everything should work. def init_fuct(): global gA gA = 'new' what happened is that you created a new local gA variable and never set your global one. bryan > no change in module B: > print A.gA > >>> 'old' > > However, when I modify these global variables in one module, the other > modules would not see the changes. Any one has any suggestions? ( I > don't want to use from A import *) > > > Thanks, > Fuming From P at draigBrady.com Tue Jul 29 05:19:19 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 29 Jul 2003 10:19:19 +0100 Subject: Python on a USB storage device? In-Reply-To: References: Message-ID: <3F263C17.2080200@draigBrady.com> Heiko Wundram wrote: > On Mon, 2003-07-28 at 19:27, Kevin Altis wrote: > >>Does anyone have experience running Python from a USB storage device? > > > I don't have experience running Python from an USB storage device, but > I've been using a 1GB USB-Stick to carry around a Knoppix distribution > with me, for those PCs which can boot from USB and don't have a CD-ROM > drive (there are quite a few where I work as sys-admin). USB works well > here, so I guess if you use USB to carry around a Python installation, > this should work well too. > > USB 2.0 doesn't matter, as the USB-sticks I know of don't even support > it (the normal transmission speed of those sticks is an average 5 MB/s, > and that's way below USB 1.1 max speed of 11 MB/s). Careful, see http://www.pixelbeat.org/speeds USB 2.0 = 60 MB/s USB 1.1 = 1.5 MB/s You can get flash chips now that do 6MB/s P?draig. From jkraska at san.rr.com Wed Jul 16 02:01:01 2003 From: jkraska at san.rr.com (Courageous) Date: Wed, 16 Jul 2003 06:01:01 GMT Subject: [OT] sentances with two meanings References: Message-ID: >It's archaic now, so if you asked someone "Do you know Guido van Rossum", no-one would think you >were asking "Have you had sex with GvR" I bet that, when first authoring Python, Mr. Van Russom never imagined that as a consequence he might here those particular words in that particular order. :) C// From bokr at oz.net Wed Jul 9 04:57:36 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Jul 2003 08:57:36 GMT Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <1057686623.3738.62.camel@lothlorien> Message-ID: On Tue, 8 Jul 2003 20:28:52 +0200, holger krekel wrote: [...] > >but i use the same idea (filter-functions) for more advanced walkers: > > p = path('/music') > for i in p.filterwalk(AND(nolink, isfile, isplayable, match(repattern))): > play_mp3(i) > >where filterwalk is a generator because i don't want the playscript to >first try to gather *all* files for obvious reasons (as would happen with >list comprehension). This has proven to be incredibly useful and easy to >read (if you don't engange in list-comprehension <-> functional-style >wars). Just because Guido somewhat dislikes "functional support" like >lambda, map, filter and friends to be in the __builtin__ module >doesn't mean it's bad :-) > What if we had a file systems package from which to import support for various file system access, e.g., from filesystems import fs_win32share # might e.g., use or clone samba infrastructure? puterfs = fs_win32share.mount(r'\\puter\sharename') #(cf. virtual block device steps below) p = puterfs.path(r'\music') for i in p.filterwalk(AND(nolink, isfile, isplayable, match(repattern))): play_mp3(i) ... i.e., play mp3's stored as windows shared files via LAN. Taking a cue from os.path, which is posixpath for slackware linux, and ntpath for NT4, perhaps they could be callable as os.path('/some/path/to/a/dir') to create a path object suitable for the default file system, referring to the specified directory. A path object could then have a file method, and the builtin file function might really be the bound method os.path('').file. It isn't right now, so I write it out below to be clear. An useful binding might be os.file also. from filesystems import f_as_blockdev a_drive_vbd = f_as_blockdev.mount(os.path('').file(r'\\.\A:')) # physical NT floppy A from filesystems import fs_apple applefdfs = fs.apple.mount(a_drive_vbd) srcp = applefdfs.path(r'\music') dstp = os.path('.') for i in p.filterwalk(AND(nolink, isfile, isplayable, match(repattern))): dstp.copy(i) or maybe looking at a CDROM file as an apple floppy image, and copying some files to the local file system, e.g., from filesystems import f_as_blockdev a_drive_img_vbd = f_as_blockdev.mount(os.path('').file(r'X:\apple\floppies\fdimg.1')) # CDROM X: from filesystems import fs_apple applefdfs = fs.apple.mount(a_drive_img_vbd) srcp = applefdfs.path(r'\music') dstp = os.path('.') # assumes callable instantiates path object for default local file system for i in p.filterwalk(AND(nolink, isfile, isplayable, match(repattern))): dstp.copy(i) # assumes copy method copying to './filename' for filter-surviving filenames. Etc., etc., (ok, very short songs on floppy ;-) I.e., path magic would be file-system-appropriate, yet provide a uniform generic interface with reasonable (but presumably configurable in some file-system-specific ways) defaults. File systems would be mounted using virtual block devices, unless the mount method for the file system can reasonably bypass that to synthesize a file system object using non-block/char device access, e.g., as a local proxy object for a remote file system (or virtual file-system view, e.g., of an html href/imgref tree or news thread, or database, etc. etc.). Note that a virtual file system could well have GUI side effects when written to. The frame buffer device would be interesting to capture access to via a virtual file system module along the lines of the above. Note also that GUI windows have a hierarchy that could map to a virtual file object hierarchy. Imagine a virtual svg file system mounted to an x-window instance, so that when you wrote svg source to it you would get the visual effects in that window. Alternatively, mount on a full-screen virtual device, etc. Creating virtual sub-"directories" could create child windows... I see various plotting packages factored into this form as well. And binary mode writes for fast stuff. For grahic vfs's IWT their mount methods should accept a virtual frame buffer device, so that something transparent and fast can ultimately talk almost directly to hardware. Maybe it could be prototyped using tkinter infrastructure, though. Or pygame/sdl. I've been thinking of prototyping a simple plotting graphic vfs along the above lines. Maybe its calcomp driver writing nostalgia (I wrote a rasterizing driver to plot calcomp command streams on a versatec 'way back. Of course a random access canvas will make it easier (there wasn't space to brute force a full image and then feed the raster plotter ;-) Just a couple of thoughts to throw in the idea hopper (this variation HOTTOMH, so very alpha ;-) Too many irons in the coals (not to say fire ;-/) Regards, Bengt Richter From gumuz at looze.net Fri Jul 4 05:52:12 2003 From: gumuz at looze.net (Guyon Morée) Date: Fri, 4 Jul 2003 11:52:12 +0200 Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> Message-ID: <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> I like the initiative for a messageboard for Python, but I think it would be similar to this newsgroup.... and I am quite happy with it so I don't really see a use for it imho "Kyle Babich" wrote in message news:191e20c8.0307031711.42d4e46b at posting.google.com... > I have just opened pyBoards.com, a community for Python programmers. > Please stop by and check it out. > > http://www.pyBoards.com > > Tell me what you think, > Kyle From duanek at chorus.net Tue Jul 29 09:49:54 2003 From: duanek at chorus.net (Duane Kaufman) Date: 29 Jul 2003 06:49:54 -0700 Subject: newbie needs a little help... trying to write an ftp script. References: Message-ID: <59023571.0307290549.285169b@posting.google.com> Hi, I have had a similar need recently, and have found a module called ftputil: http://www.ndh.net/home/sschwarzer/python/python_software.html This enables one to deal with FTP hosts on a file basis, and makes things _much_ easier. Good luck, Duane Wojtek Walczak wrote in message news:... > Dnia 28 Jul 2003 11:40:48 -0700, google account napisa?(a): > [...] > > The docs suggest that I could do something like.... > > > > import ftplib > > > > ftp = ftplib.FTP('172.30.30.30') # This is wrong, somehow...? > > ftp.login(user,pass) > ^^^^ > Do not use pass in this way - it's a python's keyword. Use some other > name instead. > > > ftp.retrlines('LIST') # I believe it might need to be > > ftp.retrlines('ls -al') > > ftp.sendcmd('prompt') > > ftp.cwd('folder') > > ftp.retrbinary(retr *tgz) > > ftp.quit() > Here's a simple example: > > import ftplib,sys > > ftp = ftplib.FTP('ftp.python.org') > ftp.login('anonymous','qwe at asd.pl') > print ftp.retrlines('LIST') > ftp.cwd('pub/python') > print ftp.retrlines('LIST') > print ftp.retrbinary('retr README', sys.stdout.write) > ftp.quit() From iambrenNOSPAM at sympatico.ca Tue Jul 22 18:11:39 2003 From: iambrenNOSPAM at sympatico.ca (Bren) Date: Tue, 22 Jul 2003 18:11:39 -0400 Subject: Problem building extension sample with Python 2.2.3 References: <7h34r1eznbq.fsf@pc150.maths.bris.ac.uk> Message-ID: <0kdrhv4m4040p8dq8pf45o6fhr7fk86h7k@4ax.com> On Tue, 22 Jul 2003 17:51:02 -0400, Bren wrote: >On Tue, 22 Jul 2003 13:53:53 GMT, Michael Hudson >wrote: > >>iambren at sympatico.ca (Bren) writes: >> >>> Hi, >>> >>> I'm trying to build the sample extension file from >>> http://www.python.org/doc/current/ext/simpleExample.html. >>> >>> I get a linker error: >>> >>> Linking... >>> spam.obj : error LNK2001: unresolved external symbol >>> __imp__Py_InitModule4TraceRefs >>> >>> Also, I find it necessary to ignore python22_d.lib and link >>> python22.lib explicitly when I make a Debug build. >> >>There's your problem, I think. You seem to be trying to build a debug >>version of your module against a release version of Python. This >>won't work. > >Thanks, that worked! > >Now, I am working on embedding python in a C/C++ app, so I would like >very much to be able to debug the code in C/C++ functions when they >are called by Python. Is it possible I could get a debug version of >this lib/dll somewhere to let me do this? Is there a python22_d.lib? Nevermind, I see the answer in another thread. Ugh, this could be much easier... -----= 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 elainejackson7355 at home.com Sat Jul 12 17:07:48 2003 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 12 Jul 2003 21:07:48 GMT Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: Thank you. Wayne Pierce wrote in message news:2a897f11.0307121139.21470fbb at posting.google.com... | "Elaine Jackson" wrote in message news:... | > Can Python be compiled? If so, how? (I have the 2.2 version of the interpreter.) | > TIA for any and all helps | | If you want to be able to distribute your Python apps without the end | user needing a Python interpreter take a look at the following: | | http://www.mcmillan-inc.com/install1.html | | Wayne From bgailer at alum.rpi.edu Mon Jul 21 08:18:20 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 21 Jul 2003 06:18:20 -0600 Subject: ODBC to Oracle (data source name not found) In-Reply-To: <4VJSa.97003$GL4.26848@rwcrnsc53> Message-ID: <5.2.1.1.0.20030721061538.01d49578@66.28.54.253> At 04:23 AM 7/21/2003 +0000, Michael J. Moore wrote: >I have set up an ODBC connection to an oracle database named MIKE on my >local machine. I have tested this ODBC connection using EXCEL and it works >fine. The same data source results in ... >----------------- >Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > >>> import dbi > >>> import odbc > >>> d=odbc.odbc('mike/mike/guess') >Traceback (most recent call last): > File "", line 1, in ? >dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not >found and no default driver specified in LOGIN I had the same problem. I asked the same question. No answer. A search of Microsoft extensive online "help" got several links to pages with this error listed amongst others, but NO explanation! Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From mis6 at pitt.edu Sat Jul 19 09:30:37 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jul 2003 06:30:37 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <2259b0e2.0307190530.17a48052@posting.google.com> Skip Montanaro wrote in message news:... > Michele> I often feel the need to extend the string method ".endswith" > Michele> to tuple arguments, in such a way to automatically check for > Michele> multiple endings. For instance, here is a typical use case: > > Michele> if filename.endswith(('.jpg','.jpeg','.gif','.png')): > Michele> print "This is a valid image file" > > This is analogous to how isinstance works, where its second arg can be a > class or type or a tuple containing classes and types. > > I suggest you submit a feature request to SF. A patch to stringobject.c and > unicodeobject.c would help improve chances of acceptance, and for symmetry > you should probably also modify the startswith methods of both types. > > Skip Too bad my skills with C are essentially unexistent :-( Michele From aahz at pythoncraft.com Tue Jul 15 10:41:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2003 10:41:52 -0400 Subject: anything like C++ references? References: <3f67hvgi36s7rmtn59rajj2gpir8hhfiph@4ax.com> <3F13ADDD.57BF2969@alcyone.com> Message-ID: In article <3F13ADDD.57BF2969 at alcyone.com>, Erik Max Francis wrote: > >The value is the object. The object is the value. Actually, that's not quite true, and it's something I've been wrestling with how to describe. What's the value of a file object? I think in a very real sense, a file object doesn't have a "value". You could try arguing that the file contents are the value, but that value is not contained within the object -- the object is a proxy. Saying that the filename is the value doesn't work, either, especially when you want to talk generically about file-like objects (such as StringIO and sockets). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From rune.hansen at sinsenveien83.com Fri Jul 25 07:15:51 2003 From: rune.hansen at sinsenveien83.com (Rune Hansen) Date: Fri, 25 Jul 2003 13:15:51 +0200 Subject: Tkinter and Mac OS X In-Reply-To: References: Message-ID: Hi David, I believe the python (2.2.3) that comes with MacOS 10.2.x is unable to use Tk out of the box. In other words it's not compiled with the Tk libs present. Compiling Python 2.3c2 is a "no brainer", and I guess downloads will be availible at http://homepages.cwi.nl/~jack/macpython.html pending the release. If you'd like to compile it your self follow the instructions in Python[src]/Mac/OSX/README regards /rune David Stark wrote: > I have Mac OS 10.2 which ships with python. I downloaded TclTkAqua from > ActiveState and installed it. Then I get: > > >>>>import Tkinter > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter > > > After digging around on www.python.org I get the impression that I have to > download the source and do my own build. Do I really have to go through > this? Is the OS X distribution of python different (for a reason)? > > From ilya at cray.glas.net Mon Jul 14 03:52:27 2003 From: ilya at cray.glas.net (Ilya Etingof) Date: Mon, 14 Jul 2003 07:52:27 +0000 (UTC) Subject: pySNMP: SNMPget example References: <538fc8e.0307100356.4bf46554@posting.google.com> Message-ID: > 2) when using: 'from pysnmp import role' (found on > http://pysnmp.sourceforge > .net/examples/2.x/snmpget.html), I get the message 'ImportError: You seems to use pysnmp 2.x API which differs from the latest 3.x branch (though, a compatibility layer exists in 3.x distribution). That's why I suggest you looking at the 3.x docs and examples at: http://pysnmp.sourceforge.net/docs/3.x/index.html > 3) A general question: how can I get a list of what I can type after > the 'from > pysnmp import ...' dir() may help but in this case I'd better see an example. > 4) How can I use: 'from snmpget import snmpget'. It does not accept > this. There is no such module as snmpget in pysnmp. > 5) Anyone has a simple example for the following application: I have a > cable > modem (which has an SNMP agent inside). I want to make a script where > I can > do SNMPgets (and later SNMPSet and SNMPwalk). Python 1.5.2 (#3, Aug 25 1999, 19:14:24) [GCC 2.8.1] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> from pysnmp.proto import v1 >>> from pysnmp.proto.api import generic >>> from pysnmp.mapping.udp import role >>> req = v1.GetRequest() >>> req.apiGetPdu().apiSetVarBind([('1.3.6.1.2.1.1.1.0', None)]) >>> tr = role.manager(('router-1.glas.net', 161)) >>> (answer, src) = tr.send_and_receive(req.encode()) >>> rsp = v1.GetResponse() >>> rsp.decode(answer) >>> vars = rsp.apiGetPdu().apiGetVarBind() >>> print vars [('.1.3.6.1.2.1.1.1.0', OctetString('Cisco Internetwork Operating System Software\015\012IOS (tm) 5400 Software(C5400-JS-M), Version 12.2(11.8b), MAINTENANCE INTERIM SOFTWARE\015\012 Copyright (c) 1986-2002 by cisco Systems, Inc.\015\012 Compiled Tue 30-Jul-02 19:02 by pwade'))] >>> > 7) What is the difference between snmpget and getrequest in pysnmp? The only difference is the SNMP request object (GetRequest vs GetNextRequest) you create when building SNMP message. -ilya From wim_wauters at skynet.be Thu Jul 10 06:52:05 2003 From: wim_wauters at skynet.be (WIWA) Date: 10 Jul 2003 03:52:05 -0700 Subject: SNMP support for Python under Windows References: <538fc8e.0307091027.1825b454@posting.google.com> <3F0C65FB.1B86A0C2@engcorp.com> <538fc8e.0307091335.70526148@posting.google.com> <3F0CB4ED.C195374F@engcorp.com> Message-ID: <538fc8e.0307100252.20261deb@posting.google.com> Hi Peter, Thanks for this useful information. I tried this on my Windows2000 system and it seems to work. I used distutils and modified the PATH entry. I'll check on my Windows XP machine and will let you know if I found any discrepancy. Thanks again for all your effort. I have another question, but will put that in a separate message on this discussion forum. Any help is welcome. - Wim Peter Hansen wrote in message news:<3F0CB4ED.C195374F at engcorp.com>... > WIWA wrote: > > > > I did two things, both unsuccessfull: > > > > 1) If I install the pySNMP modules under lib/site-packages and then > > type sth like: > > from pysnmp import session it gives the error message "ImportError: No > > module named pysnmp". The same happens if I unstall pySNMP directly > > under the lib directory. Installs in this context means 'copy paste' > > the *.py files of the pySNMP distribution. > > I misled you the first time, but have since taken another look > at the installation to see how it works. In order to import > anything from a package (roughly, a set of .py files that includes an > __init__.py file), you need to put those files in a directory > which is named for the package (e.g. pysnmp in this case) _and_ > which is available in sys.path. (Do "import sys" and "sys.path" > to see the list. You probably have lib/site-packages in that > list, so just put all the PySNMP files under it in a folder called > pysnmp.) > > > - Do I need to explicitly mention in my script where pySNMP is > > installed? > > Not if it's in a folder called pysnmp that is itself in one of the > sys.path folders, or under the current folder. > > > 2) I installed distutils 1.0.2 for Windows and it installed into the > > Python directory. So ar so good, I think... > > Distutils is included in Python so you probably didn't need to do > that, and maybe shouldn't have. I'm not sure whether that will have > broken the standard distutils. It's repairable if it did. On my > Python 2.2.1 setup here, the standard distutils is v1.0.3. > > > I go to DOS prompt and go to the directory where disutils is installed > > and type in python setup.py install, but DOS replies: > > 'Python is not recognized as an internal or external command, program > > or batchfile". > > Now that's a different problem. You need python.exe to be findable > from the DOS PATH. The simplest approach might be to check the FAQ > entry at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp > > As a test of the pysnmp installation, without having to change PATH > at all, change to the Python directory ("cd \python" or whatever) > and run the interactive interpreter ("python") and just type > "import pysnmp" to see if it works. > > > System coordinates are Windows XP. Python version is 2.2.2 and pySNMP > > is version 3.0.0. > > Should all be no problem, although I suspect instructions in that > FAQ entry may be a little light on XP advice. Let us know if you > see any area that could be improved so others can benefit from this > exchange... > > -Peter From CousinStanley at hotmail.com Sun Jul 6 17:17:52 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 6 Jul 2003 14:17:52 -0700 Subject: Calculating Year, Month and Day of Life References: Message-ID: | I'm learning as much about Python as I can. Keep on as Python is definitely a good programming language choice and there are a lot of good learning resources available, this NewsGroup being among the best ... | I like it because it has both a theorhetical/academic side | and a practical/get-stuff-done side. I believe most programming languages exhibit this sort of two-faced duality, which can be a function of one's mindset when seeking a solution for a particular problem, but Python makes the transitiion from the sublime to the pragmatic much quicker and less painless ... | It also helps me to better understand C, C++ and Java. | It's great. This is true ... However, after tasting the savory flavors of the Python stew, you may find the flavors of other languages a bit more bitter and harder to swallow ... | I was class of 1998 at Virginia Tech. I left Va Tech in Jan. 1978, which now seems like a baZillion years ago ... I do miss the friendly Virgina people and the beautiful country-side around Blacksburg, but I DON'T miss the snow and the cold ... | | When it comes to tech schools... | there's no place like Virginia Tech. | Go Hokies !!! Go Hokies !!!! -- Cousin Stanley Human Being Phoenix, Arizona From mis6 at pitt.edu Tue Jul 15 09:32:48 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Jul 2003 06:32:48 -0700 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> <20030714172215452-0600@news.xmission.com> Message-ID: <2259b0e2.0307150532.1b6b20b7@posting.google.com> Tim Roberts wrote in message news: > Whether or not I agree with you, you have made me think. That's worth the > price of my Internet connection this month. +1 QOTW Michele From tanzer at swing.co.at Mon Jul 7 02:53:56 2003 From: tanzer at swing.co.at (tanzer at swing.co.at) Date: Mon, 07 Jul 2003 08:53:56 +0200 Subject: Frustration with spurious posts. In-Reply-To: Your message of "Sun, 06 Jul 2003 13:54:40 BST." <3F081C10.8CF6B57@hotmail.com> Message-ID: Alan Kennedy wrote: > Is there some sort of mail header that these virus checking gateways > could examine, to see if the email is from a list, rather than an > individual, before it sends these emails? Maybe we need to invent one, > e.g. > > X-Dont-Send-Me-Virus-Reports: YES If you look at the headers of any mail coming from you'll: Precedence: bulk Looks good enough to me. -- Christian Tanzer tanzer at swing.co.at From mporter at despammed.com Sun Jul 27 08:50:14 2003 From: mporter at despammed.com (Michael Porter) Date: Sun, 27 Jul 2003 13:50:14 +0100 Subject: Pythoncom shutdown problems References: Message-ID: <3f23c957$0$965$cc9e4d1f@news.dial.pipex.com> "Hannes Grund" wrote in message news:mailman.1059266799.22153.python-list at python.org... > Dear all, > probably offtopic for the general python list, but I don't know were to go > else. > > I'm currently developing somekind of middleware > wich makes heavy use of pythonwin/com extensions. > (The complete setup is: win2000/winXP, python2.2, > win32all-152, wxPython resp. wxWindows). > > The software is aimed to manage data held by a software > suite (called chemoffice) to manage chemical substances. > It exposes it main components via COM, the intagration > to python via win32com.client.Dispatch works well. > The problem: > > When calling a special method on some of these COM objects > one component launches a process which appears to be a subprocess > of svchost.exe. > The result is that I'm unable to terminate the python process > after this process has been started, furthermore if > I shutdown the python process manually, it keeps alive, causing > problems during windows shutdown (i.e. you have to remove > it manually as well). > > Any help or hint would be highly appreciated, > > thanks in advance, > Hannes Grund > This may be unrelated, but I had a similar problem when using Python via COM as a scripting language with the XMetal XML editor. In this case XMetal would refuse to shut down after running one of my Python macros (the GUI would disappear but the xmetal process would not close and would have to be sutdown manually). The solution in this case was to explicitly run the Python garbage collector before shutdown by installing an Macro which did: import gc gc.collect() Perhaps a similar thing might work for you? Mike. From richard at stockcontrol.net Tue Jul 22 07:53:36 2003 From: richard at stockcontrol.net (Richard Walkington) Date: 22 Jul 2003 04:53:36 -0700 Subject: Memory errors when using imaplib with large email attachments Message-ID: <2144d9df.0307220353.a958f84@posting.google.com> Hello, I'm using python to connect to an IMAP server and download mail. When downloading messages with large attachements (> 10MB) Python socket module crashes with a memory error. Is there anything I can do about this? Below is the trace back from using the imaplib example program from the documentation to download the mailbox in question. Thanks in adavance, Richard Walkington Traceback (most recent call last): File "imap_test.py", line 8, in ? typ, data = M.fetch(num, '(RFC822)') File "c:\python23\lib\imaplib.py", line 417, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File "c:\python23\lib\imaplib.py", line 1000, in _simple_command return self._command_complete(name, self._command(name, *args)) File "c:\python23\lib\imaplib.py", line 830, in _command_complete typ, data = self._get_tagged_response(tag) File "c:\python23\lib\imaplib.py", line 931, in _get_tagged_response self._get_response() File "c:\python23\lib\imaplib.py", line 893, in _get_response data = self.read(size) File "c:\python23\lib\imaplib.py", line 231, in read return self.file.read(size) File "c:\python23\lib\socket.py", line 301, in read data = self._sock.recv(recv_size) MemoryError From newsgroups at jhrothjr.com Thu Jul 31 18:06:44 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 18:06:44 -0400 Subject: handle
tags References: Message-ID: "Behrang Dadsetan" wrote in message news:bgc3ad$o57$1 at online.de... > Luca Calderano wrote: > > Hi guys... > > > > I've done a subclass of SGMLParser > > to handle the contents of a web page, > > but i'm not able to handle the
tag > > > > can someone help me??? > > > > S.G.A S.p.A. > > Nucleo Sistemi Informativi > > Luca Calderano > > > > > I do not know SGMLParser.. but HTML is not SGML nor any subset. It is > some ill language which one even rarely finds "pure" (written in the way > the spec says it MUST be) > > I believe SGML does not like none closing tags. BR is one of the many > none closing tags in HTML (also look at IMG or HR) > > Depending on what you are doing you should maybe use XHTML as an input > if you can (XML well-formed HTML, XML being a subset of SGML) or you > should probably look for a completely different parser "technology". > Maybe HTMLParser will help you a little more. > > Do not forget, random downloaded HTML from Internet is often broken. > You might rather want to use tidylib (corrects broken HTML code into > XHTML) and a XHTML/SGML parser or a DOM. > > Hope it helps even though the effort I took to check my statements was > small :) You're basically correct, though. You can't parse HTML with either an SGML or an XML parser. You also can't parse it reliably if it has Javascript embedded that generates HTML. John Roth > > Regards, > Ben. > From jjl at pobox.com Mon Jul 7 18:11:07 2003 From: jjl at pobox.com (John J Lee) Date: Mon, 7 Jul 2003 23:11:07 +0100 (BST) Subject: A story about Python... sort of In-Reply-To: <5.2.1.1.0.20030707120140.025cb7d8@66.28.54.253> Message-ID: On Mon, 7 Jul 2003, Bob Gailer wrote: > At 01:48 PM 7/7/2003 +0100, John J. Lee wrote: > > >"Tony Meyer" writes: [...] > >No matter how distant, it's nowhere near as far off as 'solving' chess > >(which is no doubt physically impossible, at least with classical > >(Turing machine) computation). > > Physically impossible? or impractical. If it can be solved by Turing > machine computation then it is physically possible, even though it might > take more time/resources than anyone cares to expend. I really did mean impossible, not impractical (barring a drastic pruning of the space of possible games, of course). What is computable depends on the laws of physics. A complete (brute-force) Turing-machine (ie. classical) enumeration of all possible chess games (as opposed to a quantum computation) would probably take more computational resources than our universe has to offer. My excuse for not attempting to work out the number of chess games is that my undergrad maths books are currently propping up the monitor I'm using to write this <0.5 wink>. A Google result (appropriately enough, given the origin of the name Google) suggested 10**120, and I seem to have a number in my head of 10**80 non-virtual particles in the universe (though I've no recollection where *that* number came from either!-). That's 10**40 chess games for every particle in the universe, which is quite a lot . If you took over the universe and did nothing else with it but play chess games, you'd still never finish the problem. In other words, it's physically impossible to do it. Possibly there is a quantum algorithm that makes use of many universes to solve the problem, though (no I'm not joking: the many-worlds 'interpretation' is widely accepted amongst physicists working on quantum computation). Wait a minute... [...] Scott Aaronson at UC Berkeley has since drawn my attention to some comments by Richard Cleve (quant-ph/9906111) pointing out that chess and chess-like games (with a fixed number of choices per move, especially if this number is small) are not very suitable for speedup by Grover searching. At best one would expect a speedup by a moderate, fixed factor. This does not rule out quantum chess-playing algorithms altogether, just algorithms based on Grover-accelerated brute-force searching. But there is no special reason to expect better quantum chess algorithms to exist. So, it seems quite plausible that complete solution of the chess problem is flat-out physically impossible. Very readable talk by David Deutsch (founder of the theory of universal quantum computers) about the relationship between physics and computation: http://www.qubit.org/people/david/Articles/PPQT.pdf And his home page: http://www.qubit.org/people/david/David.html > But remember "When Harley Was One" and he invented the G.O.D.? I don't get the reference there. John From ss3canon at earthlink.net Wed Jul 2 22:19:14 2003 From: ss3canon at earthlink.net (Mike) Date: Thu, 03 Jul 2003 02:19:14 GMT Subject: PySpy Message-ID: I've read about this code animator but its main site doesn't exsist anymore. Does anyone still use it and can ya point me to where I can download it? From adechert at earthlink.net Sun Jul 20 20:34:46 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 00:34:46 GMT Subject: Possible use of Python for a voting machine demo project --your feedback requested References: Message-ID: "Ian Bicking" wrote in message news:mailman.1058740232.22829.python-list at python.org... > > If you really want pixel-for-pixel control, then SDL will provide this > for you. Pygame (pygame.org) provides an interface to SDL, though it's > somewhat low-level, pyui (pyui.sf.net) is slightly higher-level, but > poorly documented and maybe not that helpful. In particular, I'd be > concerned about text rendering, and then the consistent translation of > that to print. > > PDF would be easier to generate, though I'm not sure how you would make > that interactive. Reportlab generates PDFs nicely. Perhaps it would be > possible to lay out the boxes accurately so you know where they are, > then let the PDF renderer fill in the text. How exactly you would > render the PDF I'm not sure... though heck, it doesn't have to be that > interactive. You could simply render it to images, and compose those > images to come up with the screen. That's probably easier and a better > experience than allowing any change in flow or layout based on something > the user does (i.e., you wouldn't want a selection to take up more space > once selected, even if the text itself becomes larger). Maybe there's > other rendering techniques you could use that I'm not aware of. > Thanks for your thoughts on that. > The interface looks really dense to me, though, while not being large > enough for common ballots anyway. Once you add in judges, you're > getting a lot of options. And the county commissioner input is way too > dense. > It is fairly dense, but it will be used on large screens where it looks pretty good. Also, if you print it out on tabloid paper, the print is "regulation size" for printed ballots. There is a tremendous advantage to getting everything on one page if possible. Having multiple pages slows down the process greatly. The time it takes is a big cost factor for election administration and for voters. This ballot has 45 candidates in 10 contests and another 3 public measures. Some ballots in some jurisdictions will have more than this, but this is a normal amount of stuff on average. > Also, I suspect that the entire ballot is way to dense to be > used with a touchscreen, where the accuracy of input isn't very good. > We'll see. The touch screen we intend to use works well with a stylus. So if we get too many mistakes using fingers, we may just have people using a stylus exclusively. > You're going to have to plan on all votes being multi-page, and you > might as well just program for that. ... > I'll take this as a prediction, not necessarily correct, however. Our team includes some people with extensive experience with voting machine evaluation -- they think it will work. But again, we won't know for sure until we try. But beyond that, most voting machine PCs we are proposing to use will be mouse driven. So even if it proves to be too dense for a stylus (very unlikely, imo) it is certainly not too dense for a mouse. Virtually all of the testers using the web based version will be using a mouse. >The printout could still be single > page, but then it won't look like the ballot they filled out, though > that's probably fine. > Right. "Most experts agree" that such a printout should only show the selections made -- not all the choices. With 13 contests, it is no problem to get all of this on one page. There is probably no ballot so large that the choices would not fit on one page. Furthermore, when larger type is provided to vision impaired, it's normally give at twice the size (not larger) under existing guidelines. So, even in these cases one page should be adequate. > I really don't know why everyone wants to use touchscreens in voting > machines. I hate touch screens, they are a horrible input method. > A lot of people agree with you. Certainly, the Australians that designed their system would agree. They went for a keypad. http://www.softimp.com.au/evacs.html On the other hand, a lot of people really really like the touch screens. We can't make them all mouse driven since a percentage of the voters will have a big problem with that. But there is no reason to give up on mouse driven systems just because some people can't use them. Mice are very cheap and most people are used to them. So we just need to have enough non-Mice systems to accommodate those that need/want them. One nice thing about the touch screen with our system is that it will look and work exactly the same whether you use a mouse or touch screen. For some, neither will work so we have to be able to accommodate them. This is a small percentage and I don't think we're going to worry about that for the demo. We're proposing a very large multi-campus study that would investigate all these sorts of issues. > ATM-style input is much better -- real buttons lined up along the side > of the screen. Very reliable, not just the hardware, but the accuracy > of input. The only problem is when the buttons are misaligned, so it's > not clear how the screen selection maps to the buttons. The only > advantage of touchscreens is they are somewhat more flexible, but that's > also their greatest flaw. > > You could even fit those buttons only normal monitors. The buttons will > be further away from the screen, but you can paint in strips on the > enclosure right up to the screen so that it is very clear how the > buttons correspond to the screen. Even if the buttons were an inch from > the screen and raised up off the screen, the stripes would make it very > clear. > > Anyway, I wish you luck -- we certainly need open voting systems. The > current closed systems scare me. > I appreciate your taking the time to write. Alan Dechert From httpd at ncsa.uiuc.edu Tue Jul 1 18:52:14 2003 From: httpd at ncsa.uiuc.edu (httpd at ncsa.uiuc.edu) Date: Tue, 1 Jul 2003 17:52:14 -0500 Subject: Movie In-Reply-To: <200307012251.h61MpsU30834@mail.ncsa.uiuc.edu> References: <200307012251.h61MpsU30834@mail.ncsa.uiuc.edu> Message-ID: <200307012252.h61MqEx30882@mail.ncsa.uiuc.edu> [This message last updated January 21, 1998] Dear user: This is an automated message. The NCSA HTTPd is no longer a supported product. The web pages are still available. FAQ page: HyperNews page: Another source of answers to your questions may be the newsgroup comp.infosystems.www.servers.unix or comp.infosystems.www.providers Alternatively, the Apache Server (originally based on the NCSA HTTPd, and still a free server) is still actively developed. We recommend you take a look at it as a possible replacement for the NCSA HTTPd. For information about licensing NCSA HTTPD, contact Jae Allen at jallen at ncsa.uiuc.edu. NCSA HTTPd Technical Support From rastm2 at aol.commorespam Sun Jul 20 14:01:34 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 18:01:34 GMT Subject: Stopping a loop with user input. in curses References: Message-ID: <20030720140134.18124.00000261@mb-m15.aol.com> Hey Alex, I wrote a detailed explanation earlier today and it seams to have disappeared. That's okay, because I had really beat up your code. You know, it didn't occure to me till hours later that all you really had to do is move the second while loop into the "theClock()" definition like this. I move the second while loop into the "theClock()" function so that it handles the key press. Then consolodated the while loops into one loop. If the finished variable is 0(zero) then the loop continues else it breaks the loop and the function has no where else to go but out. The problem with your original code is that the call to "theClock()" function never sees the 'q' key press because the second while loop never gets executed while the first while loop is forever executing. I don't have curses installed so I can't test this for you, but it should work. --------8<----------------------- # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() # If 'q' is pressed, exit finished = 0 while not finished: # finished = 0 until the 'q' key is pressed c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) Ray-- From bokr at oz.net Fri Jul 25 23:00:12 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 03:00:12 GMT Subject: How to detect typos in Python programs References: Message-ID: On 26 Jul 2003 01:54:19 GMT, bokr at oz.net (Bengt Richter) wrote: [code that got += line switched. needs change to increment after conditional print:] --- prtok.py~ Fri Jul 25 18:52:53 2003 +++ prtok.py Fri Jul 25 19:58:24 2003 @@ -43,6 +43,6 @@ print header header = None print '%15s:%-3s'% (key, freq), - npr +=1 if npr%4==3: print + npr +=1 print Regards, Bengt Richter From usenet_spam at janc.invalid Tue Jul 15 23:13:04 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 16 Jul 2003 03:13:04 GMT Subject: Library for pop over ssl? References: Message-ID: Skip Montanaro schreef: > >> Hi, I know of poplib, which does what I need except that it > >> doesn't support SSL encryption. imaplib has SSL-support. But I > >> want it with pop3. Is there a library available that does this > >> or do I have to implement it myself? > > JanC> You can always use stunnel to SSL-ize a "normal" protocol... > JanC> > > Doesn't stunnel only work for servers? It works for both servers & clients. I use it with Xnews (my newsreader) to access secure NNTP servers. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From max at alcyone.com Tue Jul 15 20:14:49 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Jul 2003 17:14:49 -0700 Subject: Python Mystery Theatre -- Episode2: =?iso-8859-1?Q?As=ED?= Fue References: <3F140F34.1030401@mitretek.org> Message-ID: <3F1498F9.840667@alcyone.com> Aahz wrote: > My experience is that most people do it the way Ray did, * > . I do it Ray's way, too. I'm not really sure why. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Nine worlds I remember. \__/ Icelandic Edda of Snorri Sturluson From rastm2 at aol.commorespam Sun Jul 20 13:22:18 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 17:22:18 GMT Subject: Stopping a loop with user input. in curses References: Message-ID: <20030720132218.18124.00000258@mb-m15.aol.com> Hey Alex, You know, it didn't occure to me till hours later that all you really had to do is move the second while loop into the "theClock()" definition like this. Same reason applies. # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() # If 'q' is pressed, exit finished = 0 while not finished: c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) From scasjos at mixmail.com Tue Jul 8 08:39:46 2003 From: scasjos at mixmail.com (jose maria) Date: 8 Jul 2003 05:39:46 -0700 Subject: Socket Win32 IO References: <99071af2.0307070647.6ab3e329@posting.google.com> <3F099791.6AA68B8F@engcorp.com> Message-ID: <99071af2.0307080439.2bacd2d4@posting.google.com> Peter Hansen wrote in message news:<3F099791.6AA68B8F at engcorp.com>... > jose maria wrote: > > > > Hi all I?m a newbie in python Im try to modify in win32 IOTCL of file > > handle socket to set parameter 0x98000001 but i have error > > (api_error:(1, 'DeviceIoControl', 'Incorrect function.')) > > and I dont know how continue. > > the porpuse of this code its to make a simple sniffer > > > > fh=Sock.fileno() # Get file handle > > test=win32file.DeviceIoControl(fh,SIO_RCVALL,'',0) # Failed > > .... > > .... > > Is that ("incorrect function") really the error you are getting? > Can you post the actual traceback, if it's not? > > I get either of these when playing with DeviceIoControl, but not > what you showed: > > >>> win32file.DeviceIoControl(3, 0x98000001, '', 0) > Traceback (most recent call last): > File "", line 1, in ? > pywintypes.api_error: (6, 'DeviceIoControl', 'The handle is invalid.') > >>> from socket import * > >>> s = socket(AF_INET, SOCK_STREAM) > >>> s.fileno() > 32 > >>> win32file.DeviceIoControl(32, 0x98000001, '', 0) > Traceback (most recent call last): > File "", line 1, in ? > pywintypes.api_error: (87, 'DeviceIoControl', 'The parameter is incorrect.') > > -Peter Hello Peter tanks for you attenion and time Yes really I forget put in the message one parameter in the function I put the traceback and all code I hope that this help you. Thousands of pardons for my bad English Traceback: ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on wi Type "help", "copyright", "credits" or "license" for more informatio >>> from socket import * >>> import win32api >>> import win32file >>> Ip=getprotobyname("ip") >>> SIO_RCVALL=0x98000001 >>> ip=('xxx.xxx.xxx.xxx',0) >>> Sock=socket(AF_INET,SOCK_RAW,Ip) #Raw Socket >>> Sock.bind(ip) # Bind Socket to ip >>> fh=Sock.fileno() # Get file handle >>> test=win32file.DeviceIoControl(fh,SIO_RCVALL,"", 0,None) # The function Traceback (most recent call last): File "", line 1, in ? pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.') EndTraceBack: From ianb at colorstudy.com Thu Jul 3 20:56:32 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 03 Jul 2003 19:56:32 -0500 Subject: CGI script is in plain text In-Reply-To: <3F04B0A4.32692.3596CD0@localhost> References: <3F04B0A4.32692.3596CD0@localhost> Message-ID: <1057280192.13137.24.camel@lothlorien> On Thu, 2003-07-03 at 15:39, A wrote: > I have a webhosting account with one company. > They have Apache running. > When I start CGI script from a web browser, the result is plain text( the copy of that script) > I can not access > httpd.conf > file so I changed > .htaccess > file. I put into it > > Options +ExecCGI > Sethandler /usr/bin/python.exe .py Try renaming the file to .cgi -- as long as the #! line is right, it doesn't matter the extension. Also, you may have to put the script in the cgi-bin directory. Ian From just at xs4all.nl Fri Jul 25 11:22:17 2003 From: just at xs4all.nl (Just) Date: Fri, 25 Jul 2003 17:22:17 +0200 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: In article , holger krekel wrote: > Jason Orendorff wrote: > > I wrote the 'path' module at: > > http://www.jorendorff.com/articles/python/path > > > > There was some discussion on it here: > > http://groups.google.com/groups?th=42ab4db337b60ce3 > > > > Just a few comments: > > > > Ian and Holger wondered why 'path' should subclass 'str'. It's because > > a path is a string. Benefit: you can pass 'path' objects to functions > > that expect strings (like functions in 'win32file'). I find this > > really useful in practice. > > IMO you'll almost never use the following string-methods on a 'Path' object: > > capitalize center count decode encode > expandtabs find index isalnum isalpha isdigit > islower isspace istitle isupper > ljust lstrip rjust splitlines startswith > swapcase title translate zfill > > and so these methods pollute a Path object's name-space quite a bit. > Also 'join', '__contains__', startswith etc. produce some ambigouity. > > I think it's convenient enough to use "str(path)" if passing a 'path' > instance as a string somewhere. If the path object has a __str__ method, apparently it should work without explicit conversion. However, this seems to fail for me on OSX, where an attempt is made to convert to unicode. Providing a __unicode__ method doesn't help. But then again, I think we'd be fine if we add the most used path-taking functions to the path object as methods. I can even see adding some win-specific methods to it. Just From westernsam at hotmail.com Fri Jul 4 10:27:28 2003 From: westernsam at hotmail.com (sam) Date: 4 Jul 2003 07:27:28 -0700 Subject: Exceptions and modules Message-ID: <292c8da4.0307040627.59acda19@posting.google.com> Hello, consider the following code: import sys import threading class MyException(Exception): pass #from module1 import MyException class runner(threading.Thread): def __init__(self, callableObj): self.callableObject=callableObj threading.Thread.__init__(self) def run(self): try: self.callableObject.makeCall() except MyException, err: print "MyException" print sys.exc_type, err except Exception, err: print "Exception" print sys.exc_type, err if __name__ == '__main__': if len(sys.argv) != 3: print "Usage " else: callableObj = getattr(__import__(sys.argv[1]), sys.argv[2])() thread=runner(callableObj) thread.start() from module1 import MyException class Callable: def makeCall(self): raise MyException("MyException") Now I start the process: python module1.py module2 Callable And the result is: Exception module1.MyException MyException So the Exception isn't recognised even though it has the same namespace and name as the exception defined in the module. I have to uncomment the 7th line to get my example to behave as I would like it to. Is this a bug/feature? Is there any reason why it shouldn't work the way I expect it to? Regards, Sam Owen From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 11 18:56:57 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 12 Jul 2003 00:56:57 +0200 Subject: call one python script from within another In-Reply-To: References: Message-ID: <3f0f40b9$0$49103$e4fe514c@news.xs4all.nl> Tubby Tudor wrote: > What is the best way to call one python script from within another > python script? For example: > > one.py finishes succesfully and calls two.py which finishes OK and then > calls three.py > > Thanks guys! > one.py: --------------- import two import three def main(): .... body of your code here .... main() # run code in one two.main() # run code in two three.main() # run code in three ------------------ Will this do? If not, you have to explain better what exactly you want to achieve... --Irmen From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 2 19:30:00 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 02 Jul 2003 23:30:00 GMT Subject: Conservative language design References: <3F0285F0.EDF697E3@alcyone.com> <6qllvh9oi3.fsf@salmakis.intevation.de> Message-ID: On Wed, 2 Jul 2003 15:43:33 +0200, holger krekel wrote: > Actually Guido made it pretty clear that he will be very careful about > adding language features especially at the syntax level. Thank goodness the Boolean type made it in, then. (Not a syntax-level change, but still a pretty fundamental one.) -- \ "First they came for the verbs, and I said nothing, for verbing | `\ weirds language. Then, they arrival for the nouns and I speech | _o__) nothing, for I no verbs." -- Peter Ellis | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From castong at mathstat.concordia.ca Wed Jul 30 13:46:29 2003 From: castong at mathstat.concordia.ca (Danny Castonguay) Date: Wed, 30 Jul 2003 13:46:29 -0400 Subject: Syntax: pointers versus value References: <3F27F673.3000801@mathstat.concordia.ca> Message-ID: <3F280475.3000500@mathstat.concordia.ca> Tino Lange wrote: > Use: > listB = listA[:] -------------------------------------------------------------------- In the example I have given, it does solve the problem. However, for some reason I don't understand, it doesn't work in the next example: def ps_of_missing_edges(initial_graph, missing_edges): num_m_e = len(missing_edges) #number of missing_edges num_e_pset = 2**num_m_e graphs = [] for i in range(0,num_e_pset): #iteration will stop at 2^num-1 temp_i = i #use temp_i to find i's bit values new_graph = initial_graph[:] print 'initial_graph is ' + str(initial_graph) for j in range (0,num_m_e): if temp_i%2 == 1: new_graph[missing_edges[j][0]-1].append(missing_edges[j][1]) temp_i = temp_i >> 1 graphs.append(new_graph) return graphs -------------------------------------------------------------- the output when I call: ps_of_missing_edges([[2,3],[1],[1]], [[2,3],[3, 2]]) is: initial_graph is [[2, 3], [1], [1]] initial_graph is [[2, 3], [1], [1]] initial_graph is [[2, 3], [1, 3], [1]] initial_graph is [[2, 3], [1, 3], [1, 2]] -------------------------------------------------------------- Therefore, somehow initial_graph's value changes even though the assignment is new_graph = initial_graph[:] Assuming that the assignment does it's job, then I don't see how initial_graph's value changes. Thank you, From mike at kordik.net Fri Jul 4 14:30:11 2003 From: mike at kordik.net (Mike) Date: Fri, 04 Jul 2003 18:30:11 GMT Subject: RTS/CTS and DTR/DTS control Message-ID: Is there a library in Python that will give me control over the handshaking lines directly? Thanks From MACALISTER at coltonhouse43.freeserve.co.uk Thu Jul 24 14:53:02 2003 From: MACALISTER at coltonhouse43.freeserve.co.uk (Iain Macalister) Date: Thu, 24 Jul 2003 19:53:02 +0100 Subject: running python Message-ID: How do you run files written with python if you don't have the compiler and stuff on your computer? From h.goebel at goebel-consult.de Mon Jul 28 07:19:03 2003 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Mon, 28 Jul 2003 13:19:03 +0200 Subject: autoconf-style checking for installed libs with DistUtils In-Reply-To: <87znj12fym.fsf@pobox.com> References: <60uav-or3.ln1@nb2.stroeder.com> <87znj12fym.fsf@pobox.com> Message-ID: <3f2506a8$0$13005$9b4e6d93@newsread4.arcor-online.net> John J. Lee schrieb: > Michael Str?der writes: >>Is it possible to probe for installed libs with DistUtils? > I wonder if SCons (pure-Python) could help in some way with this kind > of stuff? It *does* have some (newish, I think) autoconfiguration > code, but I don't know if it has any distutils support. SCons has some support for Library checks. But you may want to have a look at Autoscons which offers more stuff (still under development). In addition I am currently working on implementing a whole bunch of autoconf stuff for Autoscons. If you are interested, I can send you some fragments. Regards Hartmut Goebel -- | Hartmut Goebel | IT-Security -- effizient | | h.goebel at goebel-consult.de | www.goebel-consult.de | From doug.hendricks at tnzi.com Thu Jul 17 19:04:22 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 17 Jul 2003 16:04:22 -0700 Subject: Connecting Oracle8i to Python References: Message-ID: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) wrote in message news:... > doug.hendricks at tnzi.com (the_rev_dharma_roadkill) wrote in message news:... > > Hello, > > I'm a newbie to Python. In order to get much use out of it at my > > site, I must be able to connect it to Oracle8i databases. I'm running > > Python 2.2.2 on Tru64 (osf1 V5.1a). > > > > First question: > > What do you recommend? > > DCOracle2? Note that I am not running Zope or any other web software. > > cx_Oracle? > > Other? > > > > Second question (important only if you recommend DCOracle2) > > I can "make" DCOracle2, but I don't see any hints anywhere on how to > > install it on a non-zope system. If I try any obvious thing, like cp > > -r to lib/python2.2/site-packages, at BEST I get: > > > > > python > > Python 2.2.2 (#1, May 9 2003, 14:15:51) [C] on osf1V5 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import DCOracle2 > > Traceback (most recent call last): > > File "", line 1, in ? > > File "DCOracle2/__init__.py", line 37, in ? > > from DCOracle2 import * > > File "DCOracle2/DCOracle2.py", line 104, in ? > > import dco2 > > ImportError: dlopen: DCOracle2/dco2.so: symbol "OCILobIsTemporary" > > unresolved > > > > I actually can get past this now using libocijdbc8 but now I get: > >>> import DCOracle2 > Traceback (most recent call last): > File "", line 1, in ? > File "DCOracle2/__init__.py", line 91, in ? > import DA > File "DCOracle2/DA.py", line 90, in ? > from db import DB > File "DCOracle2/db.py", line 89, in ? > import DCOracle2, DateTime > ImportError: No module named DateTime > > > How many other non-standard modules do I need to install to get > DCOracle2 working in a non-zope vanilla environment? It's working now. I was trying to run python and import DCOracle2 while I was sitting in the directory directly above the "build directory". As it turns out, this is a very bad idea. This directory is named "DCOracle2", so maybe python grabs this as the module directory (search current directory before other directories) when what I wanted was the code in the lib/python2.2/site-packages/DCOracle2 directory. Starting python from any other directory, it works fine. So as I no longer need the build directory anymore, this should not be a problem From stephen at theboulets.net Wed Jul 30 08:37:37 2003 From: stephen at theboulets.net (Stephen Boulet) Date: Wed, 30 Jul 2003 07:37:37 -0500 Subject: Upgrading python In-Reply-To: References: Message-ID: I guess that I had in mind a move from 2.2.2 to 2.2.3. What's the rule for a minor upgrade like this? -- Stephen Martin v. L?wis wrote: > Stephen Boulet writes: > > >>When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3? > > > If you want to, you can have both 2.2 and 2.3 installed, side-by-side. > If you want to replace 2.2, you should uninstall it first. > > Regards, > Martin From peter at engcorp.com Tue Jul 8 16:18:44 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 16:18:44 -0400 Subject: Newbie - Directory/File Creation References: <68a42404.0307081209.4baafd5@posting.google.com> Message-ID: <3F0B2724.D87E5D9F@engcorp.com> Michael J Whitmore wrote: > > If I do the following, a file is created in the current working > directory: > TestFile = open("TestTest.out", 'w') > > My question is how to create a file that includes a pathname without > having to mkdir beforehand. > Example: > TestFile = open("TestDir\TestTest.out", 'w') > > Shouldn't open be smart enough to create the TestDir directory before > creating TestTest.out ? > > Is there another command that will do this? Use os.path.makedirs() first, although if you really want to do this, I would separate the "ensure this directory exists" part from the "create this file" part. Or combine the two, but call your own method which internally checks whether the path exists (os.path.split() and os.path.isdir() are good for part of this), then creates it if necessary using makedirs(), then finally creates the file and returns the file object. -Peter From http Sun Jul 20 19:06:11 2003 From: http (Paul Rubin) Date: 20 Jul 2003 16:06:11 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: <7xllus94t8.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > I approve of the Mercuri system (I think that's what it's called when a > paper ballot is generated from an electronic ballot - the all-electronic one > I use now is scary). I was just thinking though. Suppose I wanted to rig > the elections by paying for votes. If I know the format of the ballot, I > could generate them myself on specially marked paper then give that > to the people who I've payed for the vote, who go through the process > of voting but use the paper I gave them instead of the printout.. Later, I > or my cronies get access to the ballots (eg, "I'm a reporter and I want to > verify the votes") and can see if my special ballots are included, and > reward/punish as appropriate. There is supposed to be no way to tell the paper ballots apart from one another. Otherwise the ballot would be a voting receipt, something that a good voting system should not provide. Search for "receipt-free voting" in Google to see what a big problem this is for computerized systems. From sabu at pure-elite.org Wed Jul 2 00:13:26 2003 From: sabu at pure-elite.org (Xavier) Date: Wed, 2 Jul 2003 00:13:26 -0400 Subject: My Big Dict. Message-ID: <00ec01c34050$49ab4bb0$6401a8c0@boxen> Greetings, (do excuse the possibly comical subject text) I need advice on how I can convert a text db into a dict. Here is an example of what I need done. some example data lines in the text db goes as follows: CODE1!DATA1 DATA2, DATA3 CODE2!DATA1, DATA2 DATA3 As you can see, the lines are dynamic and the data are not alike, they change in permission values (but that's obvious in any similar situation) Any idea on how I can convert 20,000+ lines of the above into the following protocol for use in my code?: TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} I was thinking of using AWK or something to the similar liking but I just wanted to check up with the list for any faster/sufficient hacks in python to do such a task. Thanks. -- Xavier. oderint dum mutuant From drobinow at yahoo.com Thu Jul 10 22:55:25 2003 From: drobinow at yahoo.com (David Robinow) Date: 10 Jul 2003 19:55:25 -0700 Subject: python mode problem in emacs References: <3097083.1057868749@dbforums.com> Message-ID: <59a4b541.0307101855.4bd36ed6@posting.google.com> pygeek wrote in message news:<3097083.1057868749 at dbforums.com>... > I went on to look for the file '.emacs' or 'emacs.el' to include a > few lines of > command so that emacs would load python-mode. > I looked through and searched my hard drive, and there wasn't > such a file > by the name '.emacs' or 'emacs.el'. What's going on here? Where are > the files? This is really a question for comp.emacs, but here goes: 1) .emacs is not distributed with emacs. You have to create it. 2) You may find the Windows Emacs FAQ useful. See http://www.gnu.org/software/emacs/windows/ntemacs.html 3) emacs looks for ~/.emacs. The "~" refers to your home directory which should be pointed to by the HOME environment variable. You need to create this yourself. If it does not exist emacs will look in the root of the C: drive. From tcronj at ananzi.co.za Thu Jul 24 03:09:27 2003 From: tcronj at ananzi.co.za (Tertius) Date: Thu, 24 Jul 2003 09:09:27 +0200 Subject: Design tool In-Reply-To: <3f1e985d$0$236@hades.is.co.za> References: <3f1e985d$0$236@hades.is.co.za> Message-ID: <3f1f8660$0$229@hades.is.co.za> Tertius wrote: > Can anyone suggest a favorite, design/Case/UML Tool used by the open > source community? (in particular the Python community) > > Thanks, > Tertius > Thanks for the suggestions. Tertius From alanmk at hotmail.com Wed Jul 9 07:17:08 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 09 Jul 2003 12:17:08 +0100 Subject: regexp and filenames References: Message-ID: <3F0BF9B4.7186537C@hotmail.com> hokiegal99 wrote: > Macs allow characters > in filenames that Windows does not, specifically the following: > > : * ? " < > | / \ > > I would like to write a script that searches through a directory for > filenames that contain any of the aboved listed characters and replaces > them with a - (the minus sign). > > I'm familiar with regexp, but I've only used it in Python to act on the > contents of a file, not filenames in a directory. Any pointers on how to > approach this are welcome! I think regular expressions are perhaps a little overkill for this job, and perhaps inefficient also. Here is a solution that uses the string.translate() function to do the same thing. #============================== import string undesired = r""":*?"<>|\/""" transtab = string.maketrans(undesired, '-' * len(undesired)) filenames = [ 'file1:', 'file2*', 'file3?', 'file4"', 'file5<', 'file6>', 'file7|', 'file8\\', 'file9/', ] for f in filenames: print string.translate(f, transtab) #============================== I expect, although I haven't timed it, that this will run faster than a regular expression based solution. Note the use of a raw string (r"") to contain the undesired characters, which allows us to use the string escape character (\) without escaping it. (But even still, it may not appear as the last character in the string). Another poster has shown how to navigate directory hierarchies, so I'll leave it to you to combine the two code snippets. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ianb at colorstudy.com Tue Jul 8 14:01:31 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 13:01:31 -0500 Subject: path module In-Reply-To: References: Message-ID: <1057687291.8459.71.camel@lothlorien> On Tue, 2003-07-08 at 09:52, Hallvard B Furuseth wrote: > If there is going to be a New Wonderful Path module, I suggest you give > some thought to paths on systems that don't fit the simple Unix/Windows > path model. A path to a filename may e.g. looks different from a path > to a directory. It's a long time since I used anything like that, but I > think Tops-20 filename paths looked like this: > > device:file.ext;version > > where most components were optional. The device: part could also be a > 'logical name' (basically an alias) for a directory or device, I don't > remember if it could alias a file name too. > > The Common Lisp pathname type might be worth looking into, > > They have done a lot of work to try to get it right, and from what > I hear they did a good job. Interesting, but I think a bad idea. I don't believe Python has been ported to Tops-20, and I'm not sure if there's a viable VMS port either. Most filesystems don't have the complexity that the Lisp pathname encapsulates. If someone was using VMS paths, I would assume they would subclass path for that OS, adding the portions that applied. I think it's unreasonable to expect people programming on normal platforms to pay attention to components like version, so even including it in a structured manner is asking for trouble. On some level such filesystems would probably be supportable, though. You just wouldn't adapt the filesystem's native structure, though presumably your os module would know how to parse such a path and emit such a path. But like you can use / instead of \ for filenames on Windows, I would expect / to work on most other filesystems as well. Ian From __peter__ at web.de Wed Jul 30 11:36:12 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jul 2003 17:36:12 +0200 Subject: changing the List's behaviour? References: Message-ID: Heather Coppersmith wrote: >> class DefaultList(list): >> def __init__(self, sequence=[], default=None): list.init(self, sequence) > > That's asking for trouble. That mutable default argument for > sequence is evaluated at class definition-time, and all instances > of DefaultList created without a sequence argument will end up > sharing one list. > > Do this instead: > > class DefaultList( list ): > def __init__( self, sequence = None, default = None ): > if sequence is None: > sequence = [ ] > >> list.__init__(self, sequence) I can see the trouble only if the sequence argument is used to initialize a member, e.g. def __init__(self, seq=[]): self.seq = seq # bad, multiple instances may share one list However, in the DefaultList case, sequence is never changed. So I don't see what can go wrong. Am I overlooking something? - Peter From donn at drizzle.com Fri Jul 18 23:53:17 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 19 Jul 2003 03:53:17 -0000 Subject: IMAP examples References: Message-ID: <1058586796.44329@yasure> Quoth "Tony Meyer" : |> It would be nice if it also explained some of the magic numbers |> and strings in comments or in some text around the example: |> |> Why data[0] |> Why M.search(None, 'ALL') |> and why '(RFC822)' as the 2nd arg in the M.fetch() | | You're not asking for documentation about imaplib here, you're asking for | documentation about the imap protocol; of course it's not there, you're | looking in the wrong place. If you don't understand imap, why should you | understand how to use imaplib? | | Using imaplib is very similar to simply passing the commands to an imap | server - much more so, for example, than twisted's imap support (which hides | details of IMAP, and so should provide more documentation than imaplib). Well, to be fair, the first question, "Why data[0]" has more to do with imaplib than IMAP4rev1. I doubt it has an interesting answer, though - might as well just say "Because". Donn Cave, donn at drizzle.com From max at alcyone.com Wed Jul 23 04:39:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 Jul 2003 01:39:48 -0700 Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <3F1E49D4.A539CABF@alcyone.com> Robin Becker wrote: > ....can't one do > class TheSomething: > .... > > TheSomething = TheSomething() > > then it's harder to get at the class which presumably is now only > available as TheSomething.__class__ Well, you can name the class Hugahglaugahglaugalgha, or delete the original class name explicitly, or any such thing. The point is that in Python, if you're accessing a name starting with underscores in something you don't own, you probably shouldn't be. "We're all adults here." -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Why place value or judgement on color? \__/ Andrew Coler From ianb at colorstudy.com Thu Jul 3 04:21:11 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 03 Jul 2003 03:21:11 -0500 Subject: Py + CGI or other ? In-Reply-To: References: Message-ID: <1057220471.13134.7.camel@lothlorien> On Thu, 2003-07-03 at 02:35, Krisztian Kepes wrote: > A question: > - how to I make the change ? > So, I take an interest in Python+Web. Where I starting this learning ? Well, there's many options you have when using Python for web programming. Look at: http://www.python.org/cgi-bin/moinmoin/WebProgramming > 1. > I use php used in module, not in cgi ? > The python can load to apache in module ? Yes, there is a mod_python (modpython.org). There are also several frameworks built ontop of that, and several frameworks that don't embed themselves in Apache, but offer similar advantages over CGI. > 2. > Or I must create an CGI library ? But... on many commercial hosts CGI is the only support option you'll have for using Python. If you don't want to use CGI, you'll have to specifically look for a host that supports Python: http://www.python.org/cgi-bin/moinmoin/PythonHosting > 3. > The BaseHTTPServer is good for starting an cgi development ? No, it's a novelty, and maybe useful for applications where you want an embedded HTTP server. > 4. > Can the python handle the session of web browsers ? Most of the web frameworks handle sessions. > 5. > Can the python access other db servers (not mysql) ? Yes, there are drivers for using Python with most common databases. Ian From adalke at mindspring.com Thu Jul 24 03:29:22 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 24 Jul 2003 01:29:22 -0600 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: Alan Dechert: > BTW, do you know about cumulative binomial distribution? I think we need to > include a tool like this to give us some "C.L" (confidence level) short of > verifying that every single paper ballot matches its electronic counterpart. > > http://www.reliasoft.com/newsletter/2q2001/cumulative_binomial.htm > > What I really want is a calculator. Do you know of a free calculator for > this? If not, could you make one? (for free, of course). I don't know anything about it, although looking at it I think I understand what it's trying to do. Here's the equation for those following along r 1 - C.L. = Sum C(N, k) * (1-R)**k * R**(N-k) k=0 where R(N, k) = N! / (k! * (N-k)!) and C.L. is the confidence level, N is the number of votes tested r is the maximum allowable number of errors, and R is the reliability (scanning errors, attempts at voting fraud, etc.) The problem is, I don't see how to use it. Here's the case I had in mind. Suppose you have 100,000 votes and want to be 90% certain that there is no more than 1% error. This means you'll need to retest N ballots (the ballots "under test"). Then the variables are: C.L. = 0.90 N = to be determined r = N * 0.01 R = ??? and I just don't know what to use for R. Let's say it's <0.1%. Then N*0.01 1 - 0.9 = Sum C(100000, k) * (1-0.001)**k * (0.001) ** (N-k) k=0 and solve for N. I wouldn't want to write a calculator for it without the verification of someone who knows it better than I do. The only way I know to solve this iteratively, and given the large and small numbers involved, I would worry about numerical problems like overflow and underflow. (OTOH, for those cases, approximations like the Stirling expansion for factorials come into play. But my math for this is entirely too rusty.) So no, I can't help you further than this. BTW, I don't think you need to distribute a calculator for this. I think you just need some tables which give values for a few select points, as in: # | 75% certain | 90% | 98% || 90% | 98% ballots | of no more than | .. | || | | 1% error rate | 1% | 1% || 5% | 5% ------------------------------------------------------------ 100 | values .... 200 | values .... ... Andrew dalke at dalkescientific.com From nushin2 at yahoo.com Wed Jul 23 14:50:34 2003 From: nushin2 at yahoo.com (nushin) Date: 23 Jul 2003 11:50:34 -0700 Subject: How to disable output messages of the child process, in spawnv( )? Message-ID: I'd like to disable the output of the process spawned by spawnv( ) API, but the catch is that i *have to* see the output of the parent process making the spawnv( ) call. Has anyone done that? I have some pointers that by using dup2( ) API i might be able to do that, any ideas how? Also, i have to spawn as an asynch call, using P_NOWAIT, e.g.,: os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) Regards, BB (Nushin) From vze4rx4y at verizon.net Thu Jul 17 03:37:50 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 17 Jul 2003 07:37:50 GMT Subject: Python Quiz References: <3f156704$1@mail.hmgcc.gov.uk> Message-ID: > I admit that Python probley gained no insiration from FORTRAN and any > 'similarities' are coincidental. Didn't FORTRAN popularise the idea of having the language separate from tons of special purpose libraries? Raymond Hettinger From harry.g.george at boeing.com Thu Jul 10 14:00:53 2003 From: harry.g.george at boeing.com (Harry George) Date: Thu, 10 Jul 2003 18:00:53 GMT Subject: Python vs PHP References: <3F0D2827.4070501@mxm.dk> <7xisqagvjt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Max M writes: > > Ahem ... How os Python web development fragmented? Most of it probably > > takes place in the Zope world. > > Nonsense, look at all the Python web platforms there are that don't use Zope. > > > But mod_python is an official Apache module. Wich sets it about on par > > with PHP. > > Nonsense, it's not on a par with PHP. It doesn't include any template > system, any sessions, etc. > > > > It has a standard library that beats the socks of PHP's builtin functions. > > Nonsense, it doesn't include any SQL database interfaces and you're > left on your own to find one, install it, and get it working. > > > On top on this there are severeal modules for templating etc. PHP does > > not have these modules, so everybody has to do it in PHP's own faulty > > way. > > Nonsense, you're trying to spin a deficiency as an advantage. PHP is > its own template system, for better or worse. Python doesn't include > any template system and you're left on your own to find or write one, > install it, and get it working. > > > Python is not fragmented, but there are more high level modules for > > doing things. > > Nonsense, of course Python (for web development) is fragemented, look > at all these different Python web modules we've been discussing. > Python does have a lot of modules (like Numeric) that PHP doesn't, but > they're not that useful for web programming. PHP is narrowly focused > on web programming and is far superior to Python for that purpose > unless you spend a lot of time enhancing Python with add-ons before > you even start writing your applications. > > > There are more PHP developers, that's right, but they are all starting > > from scratch, with a poor language. So it's their loss. > > Nonsense, Python is a better language than PHP, but that's the only > advantage Python has for web development. The language is a small > part of the overall system. And it's Python developers who must start > from scratch, not PHP developers. Python could catch up by adding > more stuff to the standard library, but it hasn't done that yet and > most of the suitable Python modules for PHP-like usage aren't really > ready for prime time. This may be a case of "web application" meaning different things to different people. Ours are architected as Model-View-Controller, with the Model being a fairly sophisticated knowledge-based engineering app (this lots of those add-ons you mentioned). We wrap that with web-aware View and Controller code (which imports the Model) for headers/footers, transaction state memory mgmt, exception handling, etc. We sometimes do dynamic selection of which "imports" to do, based on user-supplied data, or data from uploaded files. In this context, the webification aspects are pretty simple -- we give developers a framework and they fill in their particular View and Controller functions. The intellectual energy is in the Model, where PHP isn't going to help. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 294-8757 From danb_83 at yahoo.com Fri Jul 4 13:27:32 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Jul 2003 10:27:32 -0700 Subject: Least used builtins? References: Message-ID: sandskyfly at hotmail.com (Sandy Norton) wrote in message news:... [snip] > I know there some plans to reduce the number of builtins in some > future version of python (Python 3.0?): So which builtins do you least > use? > > Pesonally, I don't think I've ever used the following: intern, buffer, > coerce I haven't used: apply, buffer, coerce, globals, intern, iter, locals, oct, slice, super, unichr, unicode. From jjl at pobox.com Tue Jul 29 17:39:36 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 22:39:36 +0100 Subject: gzip HTTP results problem References: <003401c355c1$cb6949f0$6400a8c0@EVOD31> Message-ID: <87n0ex57xj.fsf@pobox.com> "Fredrik Lundh" writes: > Bill Loren wrote: > > > I've encountered a problem trying to decode gzip data > > returned from an HTTP server I communicate with (I use urllib2). > > I've tried to use both the gzip and zlib come-along python libraries but > > alas. > > > > Have anyone of you ppl succeeded in talking gzip with an HTTP > > server ? > > this might help: > > http://effbot.org/zone/consumer-gzip.htm > > (that piece of code is used in production code, so it should > work...) That would go nicely with my unreleased latest version of ClientCookie, which is plug-compatible with urllib2. but makes it easier to add new functionality like this (I submitted a patch to Python library based on this a while back, and am hoping for comments). The idea is that you pass processor objects to build_opener just as if they were handler objects. Processors pre-process requests and post-process responses. This stops you having to subclass things like AbstractHTTPHandler. Ask if you want a copy. (code below is completely untested, unworking, purely illustrative!) import ClientCookie from GzipConsumer import GzipConsumer from cStringIO import StringIO class stupid_gzip_consumer: def __init__(self): self.data = [] def feed(self, data): self.data.append(data) class stupid_gzip_wrapper: def __init__(self, response): self._response = response c = stupid_gzip_consumer() gzc = GzipConsumer(c) gzc.feed(response.read()) self.__data = StringIO("".join(c.data)) def __getattr__(self, key): # delegate unknown methods/attributes if key in ("read", "readline", "readlines"): return getattr(self.__data, key) else: return getattr(self._response, key) class HTTPGzipProcessor(ClientCookie.BaseProcessor): def http_response(self, request, response): # post-process response enc = response.hdrs.get["content-encoding"] if ("gzip" in enc) or ("compress" in enc): return stupid_gzip_wrapper(response) else: return response https_response = http_response opener = ClientCookie.build_opener(HTTPGzipProcessor) ClientCookie.install_opener(opener) response = urlopen("http://www.example.com/") print response.read() response.close() John From ianb at colorstudy.com Sat Jul 5 03:43:18 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 05 Jul 2003 02:43:18 -0500 Subject: Least used builtins? In-Reply-To: References: Message-ID: <1057390998.514.87.camel@lothlorien> On Sat, 2003-07-05 at 02:18, Dr. David Mertz wrote: > |just means that "core Python" (i.e., the subset of Python's > |standard library used by 95% of significant code) > > Nah... I think the ratio is exactly the opposite. Putting all > the things I mentioned before into outside modules would require > no modification at all to 95% of my modules (well, excluding some > unusual introspective code I've written). And the 5% that would > be affected would need one extra import line at top (unless some > mechanism like startup.py eliminated even that one line). When I say 95%, I mean the things that show up somewhere in 95% of all Python applications -- not in 95% of all modules, but somewhere in the application. Which is to say, most applications would require human intervention to be ported to any environment where those functions weren't available. If a function or type hits that 95% (or whatever number), I don't see a big benefit to keeping it out of builtins, unless there's a really good conceptual reason that it belongs somewhere else. Some of these, like classmethod, aren't used that often, but will be -- Python programmers on the whole still haven't taken new style classes to heart. I think enumerate could be there too -- I've certainly seen the pattern in most code, and eventually one would hope that pattern where enumerate is useful will be increasingly be implemented with enumerate. > |I disagree. There's nothing saying you have to describe > |everything in __builtins__ -- using that module as a teaching > |outline is surely a bad idea. > > As soon as a new programmer gets an interactive shell they run > 'dir()'. And then they wonder what all those names are about. > And a natural presentation puts everthing builtin together, for > example in a reference text. That's a reference text, where a larger size really doesn't matter. A good presentation will tell the programmer to ignore most of those, or that some will only be explained later. > |That describes most of my modules! I seldom import sys -- I probably > |import os much more often, but certainly not half of the time. > > Really?! How do you get sys.argv then? Or sys.stdin? Admittedly, > a simple 'print' usually gets you the sys.stdout you want, but > what about sys.stderr? I usually don't need those. Those are only needed for the front end of a command-line application, for the most part. One module among many. The rest might deal with a file-like object, but I wouldn't hardcode sys.stdin or sys.stdout. And sys.argv is certainly only useful for a certain context (a command line program) but even then I'd never use it outside of __main__. Ian From hawkfish at trustedmedianetworks.com Mon Jul 28 16:21:36 2003 From: hawkfish at trustedmedianetworks.com (Richard Wesley) Date: 28 Jul 2003 20:21:36 GMT Subject: unittest problems Message-ID: Hi all - I am trying to retrofit some units test into our code using the unittest module. I can get individual rewrites to work, but I am having trouble writing the "one test to run them all and in the darkness bind them" script. There are two main sources of trouble: - Test data that is stored next to the script that uses it; - Several levels of scripts (top/utils/tests) with tests/data scattered at all levels; Are there any good examples out there of a more complex set of tests in a multilevel tree/package with attached test data? What about standard conventions for hooking stuff together (suite(), etc.)? TIA, -- - rmgw ---------------------------------------------------------------------------- Richard Wesley Trusted Media Networks, Inc. "Oh boy! Have you forgotten the plot again?" - Rocket J. Squirrel From tdelaney at avaya.com Mon Jul 21 20:42:07 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 22 Jul 2003 10:42:07 +1000 Subject: Flat file to associative array. Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D426D@au3010avexu1.global.avaya.com> > From: Alex [mailto:bogus at antispam.com] > > What would be the best way to convert a flat file of products into > a multi-dimensional array? The flat file looks like this: > > Beer|Molson|Dry|4.50 > Beer|Molson|Export|4.50 > Shot|Scotch|Macallan18|18.50 > Shot|Regular|Jameson|3.00 Have you tried any of the CSV/DSV (delimiter-separated libraries). They may be overkill, but you may also be able to get a 1 or 2 line solution out of them. Tim Delaney From florian.proff.schulze at gmx.net Tue Jul 22 13:54:30 2003 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Tue, 22 Jul 2003 19:54:30 +0200 Subject: Check from C that Interpreter is running Message-ID: Hi! I want to check from C that the Python Interpreter is still running and it's save to call things like PySys_GetObject, PyFile_WriteString etc. I need this in a C function which might be called during shutdown in a program embedding Python. Currently I get this error: Fatal Python error: PyThreadState_Get: no current thread Abort! Regards, Florian From ulope at gmx.de Sun Jul 6 22:09:17 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 7 Jul 2003 04:09:17 +0200 Subject: PEP idea. ( removing __slots__ ) References: <3f073594$1_2@news1.vip.uk.com> <3f083043$1_3@news1.vip.uk.com> <3f085fa7_3@news1.vip.uk.com> <3f08984c$1_3@news1.vip.uk.com> Message-ID: "simon place" schrieb im Newsbeitrag news:3f08984c$1_3 at news1.vip.uk.com... > > No. Some classes have slots for efficiency, and their subclasses have > > dictionaries for generality. > > > > Likewise, some classes have slots to save the dictionary for most > > instances, but some instances may need additional attributes, in which > > case Python creates the dictionary on-the-fly. > > I know subclasses can add a __dict__, but i really thought a class with > __slots__ could not have a __dict__, doesn't the script below show this > behavior? > Consider this: C:\Dokumente und Einstellungen\Administrator>python Python 2.3a2 (#39, Feb 19 2003, 17:58:58) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class blah(object): ... __slots__ = ['a','__dict__'] ... >>> a = blah() >>> a.__dict__ {} >>> a.b = 5 >>> which of course is kina wierd.... Ciao Ulrich From http Fri Jul 11 16:30:07 2003 From: http (Paul Rubin) Date: 11 Jul 2003 13:30:07 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <87k7apyuor.fsf@pobox.com> Message-ID: <7x3chcbycw.fsf@ruckus.brouhaha.com> Ian Bicking writes: > I should have said "securing cookies isn't hard", so that's not the > reason not to use them (though you shouldn't just use plain-vanilla > cookies). The signature scheme we've discussed does cause some configuration hassle. There has to be a host-specific secret key and it has to be kept secret. If it leaks to an attacker, the attacker can then create malicious cookies. So the scheme has to be used with care. From mis6 at pitt.edu Tue Jul 1 07:28:58 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 1 Jul 2003 04:28:58 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <2259b0e2.0307010328.1e1b4a04@posting.google.com> rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0306301931.3f15fbb7 at posting.google.com>... > Hi, > > I have been thinking about how to overload the assign operation '='. Notice that you can always override __setattr__ ... Michele From max at alcyone.com Mon Jul 28 17:46:05 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 28 Jul 2003 14:46:05 -0700 Subject: octet string conversion References: Message-ID: <3F25999D.FD71D120@alcyone.com> Matthew wrote: > I am working on some software that uses SNMP to get information from > routers and switches. I am using the pysnmp module (v2.0.8) to do the > snmp part. The problem that I am having is that when I query a router > for mac addresses pysnmp returns octetstrings like this: > > \000\002\263\254\264\351 > \010\000 \301F\021 > \010\000 \300\303[ > \000\002\263\254\264\241 I presume these are the repr of the strings you get back. If so, this is simply in binary format. To convert, take the ord of each character and print the hexadecimal code: >>> S = '\010\000 \301F\021' >>> ':'.join(['%x' % ord(x) for x in S]) '8:0:20:c1:46:11' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Take the slow train / To my destination \__/ Sandra St. Victor From akroy at lloydcoil.com Wed Jul 2 00:17:44 2003 From: akroy at lloydcoil.com (akroy at lloydcoil.com) Date: Wed, 2 Jul 2003 00:17:44 -0400 Subject: Application Message-ID: <410-2200373241744647@M2W095.mail2web.com> not able to open the file. please send as attachment not as a zip file. regards. vandana Original Message: ----------------- From: python-list at python.org Date: Mon, 30 Jun 2003 7:08:30 +0530 To: ingh at lloydcoil.com Subject: Re: Application Please see the attached zip file for details. -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From eniac at sdf-eu.org Tue Jul 22 16:53:28 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Tue, 22 Jul 2003 22:53:28 +0200 Subject: wxPython Probleme Message-ID: Hey, here's my piece of code : class HtmlWindow(wxHtmlWindow): def __init__(self,parent,id): wxHtmlWindow.__init__(self,parent,id) class channelTree(wxTreeCtrl): def __init__(self,parent,id): wxTreeCtrl.__init__(self,parent,id) self.root = self.AddRoot("Sites") for i in range(len(names)): self.AppendItem(self.root,names[i]) EVT_TREE_SEL_CHANGED(self,105,self.OnCelChanged) def OnCelChanged(self,event): item = event.GetItem() print self.GetItemText(item) class MainSplitter(wxSplitterWindow): def __init__(self,parent,id): wxSplitterWindow.__init__(self,parent,id) self.html = HtmlWindow(self,-1) self.html.LoadPage("welcome.html") self.SplitHorizontally(self.html,wxWindow(self,-1),500) self.Show(1) If you look at the channelTree class I've created a wxTreeCtrl when you change a sel a execute onCelChanged Now I would like that when you change a sel he loads an other page into the HtmlWindow. But I don't really have an idea on how to do this any help ? From nagylzs at freemail.hu Tue Jul 29 18:19:40 2003 From: nagylzs at freemail.hu (=?ISO-8859-2?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Wed, 30 Jul 2003 00:19:40 +0200 Subject: blanks embedded in python 2.3 optparse References: <3f2625b7$0$24594$626a54ce@news.free.fr> Message-ID: <3F26F2FC.2040702@freemail.hu> > > >is there a way to pass a param with blank embedded with optparse ? >(C:\Python23\Doc\lib\module-optparse.html) > > >for instance >prog --name=mr jones > > >and have "mister jones" as a single entry for name ? > >reading the docs I see nothing about that. > >the only thing is the nargs to pass nargs at a time, but here you can't tell >in advance how many words in the name there is > > For Unix and windows: prog --name="mr jones" For unices, this should work too: prog --name=mr\ jones Know nothing about macs and others. Laci From bgailer at alum.rpi.edu Thu Jul 17 11:47:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 17 Jul 2003 09:47:39 -0600 Subject: list() coercion In-Reply-To: <3F16B1BA.97793556@hotmail.com> References: Message-ID: <5.2.1.1.0.20030717094450.0284ae60@66.28.54.253> At 03:24 PM 7/17/2003 +0100, Alan Kennedy wrote: >Bob Gailer wrote: > > > I have just read the docs 2.2.5 Iterator Types. Unfortunately this page > > seems to be written for someone who already understands the page. Is > > there any other explanation or examples? > >Try A. M. Kuchling's "What's new in Python". > >http://www.python.org/doc/2.2.1/whatsnew/node4.html That still sounds like it was written for someone who already understands the material. What I'd like is something that I could read once, that would define each new term, and would leave me a clear understanding of the topic. Perhaps I will attempt to digest the topic then write the kind of explanation that I wanted to start with and submit that to the document folks. I find the same frustration with other Python documentation. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From skip at pobox.com Fri Jul 11 08:57:51 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Jul 2003 07:57:51 -0500 Subject: text file edit object In-Reply-To: References: Message-ID: <16142.46159.401871.530479@montanaro.dyndns.org> Facundo> What about something like this: Facundo> try: Facundo> infile = file("foo.txt", "r") Facundo> lines = infile.readlines()[:-10] Facundo> infile.close() Facundo> outfile = file("foo.txt.new", "w") Facundo> outfile.writelines(lines) Facundo> outfile.close() Facundo> except: Facundo> print >> sys.stderr, "edit failed" Facundo> raise Facundo> else: Facundo> os.rename("foo.txt2", "foo.txt") Yes, that's what I thought of first, however the errors (and how you recover from them) are different between the reading and writing phases. Facundo> One question: is this method (file, readlines) efficient on big Facundo> files? Should be, though you have the obvious overhead of gulping the entire file. For very large files it would probably be more efficient to read the file in smaller chunks and only avoid writing the last ten lines. However, the code gets that much more baroque. ;-) Skip From gavriep at yahoo.com Tue Jul 15 06:17:09 2003 From: gavriep at yahoo.com (Gavrie Philipson) Date: 15 Jul 2003 03:17:09 -0700 Subject: How to crash Python in 1 easy step (python 2.2.2) References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: pwmiller1 at adelphia.net (Paul Miller) wrote in message news:<2e363c08.0307130944.4c470bc3 at posting.google.com>... > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > everything about the system is standard except for what's been updated > by RedHat itself. If anyone who has the time and ability to track > down this bug needs more information, please email me. I'm seeing the same effect on RH9, using KDE's "konsole" terminal emulator. When pressing Ctrl-Shift-Enter, it actually sends the ^[OM characters (Escape, O, M). Manually sending the key sequence Esc-O-something also crashes Python. Why this happens is still a good question... From cfaust at scpscience.com Tue Jul 8 11:15:34 2003 From: cfaust at scpscience.com (Faust, Chris) Date: Tue, 8 Jul 2003 11:15:34 -0400 Subject: Please unsubscribe me Message-ID: <039569BFBC06984CACAE270CEF7146740368D8@EX> -----Original Message----- From: python-list-request at python.org [mailto:python-list-request at python.org] Sent: Tuesday, July 08, 2003 9:46 AM To: python-list at python.org Subject: Python-list digest, Vol 1 #16415 - 14 msgs Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-admin at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From hwlgw at hotmail.com Thu Jul 17 02:03:28 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 16 Jul 2003 23:03:28 -0700 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: > [Guyon Mor?e] > I can't seem to find any decent examples on how to use the IMPALIB module. > the docs aren't that sophisticated unfortunately.... the cookbook entry > comes close, but i'd like to know if someone knows some nice examples > somewhere. I did not use it myself but there is an example in the book "Python Standard Library" by Fredrik Lundh. The example file is called imaplib-example-1.py, maybe you can find it somewhere on the internet. If my english was better I would love to help improve the python documentation, most modules in the standard libraries lack good examples how to *use* them with just a simple description. And a short motivation for the design of a module if possible like "just copied the C API" or "Because of efficiency ..." or "We use a class framework here because ...". A gigantic task. The PSL book by effbot is great but it's a book. And it needs a new version. From jlh at cox.net Sat Jul 5 23:02:14 2003 From: jlh at cox.net (Jeff Hinrichs) Date: Sun, 06 Jul 2003 03:02:14 GMT Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: "Charles Shannon Hendrix" wrote in message news:hff5eb.e9h.ln at escape.shannon.net... > In article , Cameron Laird wrote: > [..snip...] > One really funny problem was when I guy reformatted his Python code, > around 15K lines of it, and basically unindented *ALL* of the code to > column 1. It was the only recoverable copy of the code too. > > He had to read the entire program line by line to recreate the logic. What happens if you replace brackets { with '' in C/C++. What you are talking about is being bitten by a lack of version control not a problem with the language, imho. What if this same programmer removed all asterisks from some c source? As mentioned in an earlier post, tabnanny. I knew a guy, who in his first couple of weeks as a programmer, was cleaning up some testing folders and managed to rm * the development source. After soiling myself and taking a deep breath, I restored the files from backup. Two lessons to be learned: 1) It wasn't rm's fault nor the fault of my source code, it was my own brain-dead action. 2) That which does not kill us, makes us stronger. -jeff From guettler at thomas-guettler.de Mon Jul 7 09:06:13 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 07 Jul 2003 15:06:13 +0200 Subject: Several __getstate__ methods Message-ID: Hi! I use ZODB3. I want to pickle parts of my database and import it on a different system. Since, as far as I know, ZODB uses the __getstate__ method for pickling the objects. For my export, I want to ignore some parts of my objects. If I will change __getstate__ I am in trouble because Zope uses it. Using a global variable in __getstate__ to see if I am in "zope-getstate" or "my-export getstate" mode is dangerous, since the application is multithreaded. I thought about using a dict which holds the variable for each thread. What other solutions are possible? Example: class MyClass: def __init__(self, root) self.root=root I want to ignore the reference to root, since I want to import the object into a new root. thomas From adalke at mindspring.com Thu Jul 24 15:51:43 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 24 Jul 2003 13:51:43 -0600 Subject: Tokenize References: <8%VTa.133$313.72262@news.uswest.net> <3F203257.AD0A4B30@hotmail.com> Message-ID: Ken Fetting wants a 'StringTokenizer'. Alan Kennedy points out > >>> s = "This is a string to be tokenised" > >>> s.split() > ['This', 'is', 'a', 'string', 'to', 'be', 'tokenised'] ... > Or maybe you have something more specific in mind? Another option is the little-known 'shlex' module, part of the standard library. >>> import shlex, StringIO >>> infile = StringIO.StringIO("""ls -lart "have space.*" will travel""") >>> x = shlex.shlex(infile) >>> x.get_token() 'ls' >>> x.get_token() '-' >>> x.get_token() 'lart' >>> x.get_token() '"have space.*"' >>> x.get_token() 'will' >>> x.get_token() 'travel' >>> x.get_token() '' >>> As you can see, it treats '-' unexpectedly (compared to the shell). Also, with __iter__ in newer Pythons, if these module were useful then it would be nice if "for token in shlex..." worked. Andrew dalke at dalkescientific.com From woodsplitter at rocketmail.com Sun Jul 13 10:44:18 2003 From: woodsplitter at rocketmail.com (David Rushby) Date: 13 Jul 2003 07:44:18 -0700 Subject: HTML Help (CHM) file for Python 2.2.3 References: Message-ID: <7876a8ea.0307130027.6fbb13fe@posting.google.com> L?tez? wrote in message news:... > Hi Python Fans! > > Could you send me a download URL of a compiled > HTML Help (CHM) file for Python 2.2.3 ? Right here: http://kinterbasdb.sourceforge.net/other/pystd_docs/python-223-std-docs.chm By the way, the Python program used to create that file is available here: http://www.orgmf.com.ar/condor/pythlp.py Hern?n Mart?nez Foffani's site also provides usage instructions in the "For home builders" section: http://www.orgmf.com.ar/condor/pytstuff.html The program is quite easy to use--I was impressed. From vm_usenet at yahoo.com Sat Jul 5 12:18:22 2003 From: vm_usenet at yahoo.com (vm_usenet) Date: 5 Jul 2003 09:18:22 -0700 Subject: A possible bug in python threading/time module? References: Message-ID: "Tim Peters" wrote in message news:... > [Tim] > > Turns out that the Windows implementation of the Python C API function > > PyThread_start_new_thread() contained several "laziness" errors > > > > ... > > > > I'm testing putative fixes on a Win98 box and don't see any hangs any > > more. However, with more than about 3000 threads, > > > > thread.error: can't start new thread > > > > gets raised because MS's _beginthread() fails (with errno == EAGAIN == > > "there are too many threads"). > > FYI, these fixes have been checked in and will be part of 2.3 final (and > 2.2.4, if that's ever released). > > The maximum number of threads you can have alive simultaneously on 32-bit > Windows in an all-default Python build is actually about 2000. This is > because each thread gets a megabyte of stack space by default, and 2048 > threads would entirely exhaust the 31-bit user virtual address space just > for thread stacks. If you want to know more about that, Google on > > CreateThread default stack size > > The top hit is to the current relevant MSDN docs. I understand what you are saying. Obviously there is a limit for the amount of threads running at the same time. Thank you for taking the time to find the problems, and for fixing them. Here's to a better Python! vm From suresh_vsamy at rediffmail.com Fri Jul 4 06:14:05 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 4 Jul 2003 10:14:05 -0000 Subject: Converting canvas coordinates to window coordinates in tkinter......... Message-ID: <20030704101405.27614.qmail@webmail26.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From simonb at webone.com.au Mon Jul 21 18:53:00 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 22 Jul 2003 08:53:00 +1000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) References: Message-ID: On Mon, 21 Jul 2003 09:58:19 +0000, Irmen de Jong wrote: > QOTW: "To 'Tron' fans: yes, you could assign the name TimBit to it [the > TimBot] but it's a broken Bit; what's the use of a Bit that's always true?" > -- Christos Georgiou > > "Whether or not I agree with you, you have made me think. That's worth > the price of my Internet connection this month." > -- Tim Roberts > > > Discussion > ---------- > Aahz writes a rebuttal to Artima.com, because a recent interview with > Bruce Eckel on that site might give the wrong impression regarding > Python's type system. > > The interview with Bruce Eckel is at: > > I found Aahz' rebuttel here: http://www.artima.com/forums/flat.jsp?forum=106&thread=7590&message=21284&redirect=true&hilite=true&q=aahz Simon Burton. From rstephens at vectron.com Mon Jul 7 17:05:28 2003 From: rstephens at vectron.com (Ron Stephens) Date: 7 Jul 2003 14:05:28 -0700 Subject: Merlin, a fun little program References: <3F08CFDF.6050603@earthlink.net> Message-ID: Oren wrote """You can still use Google for this """ Yes indeed. I have played with the Google API's, registered and also use pygoogle. They make this kind of thing easier, no doubt about it. The reason I used my hand-rolled web scraper on Yahoo is that using the Google API's means that other potential users, like those who download form my web site, can't run my code it uses Google api's unless they download and register also; which might be pain for them. At any rate, doing my own was fun and informative for me. A big disadvantage to web scraping is that they code tends to break over time, though. This happened to me with Max M's original; two year old algorithm. Google broke it, and I didnt realize it unit I can back and retried the code. The two links you gave are good ones and I studied both in my efforts; I recommend them. Thanks for the inputs. I guess the bigger question is; is there anything wrong with web scraping? I surely never meant any harm in it, and certainly no money is involved. But maybe I should give it up and do other things? Ron Stephens From other at cazabon.com Sun Jul 6 03:26:34 2003 From: other at cazabon.com (Kevin) Date: Sun, 06 Jul 2003 07:26:34 GMT Subject: Threading issue: [Error 9]: bad file descriptor Message-ID: Has anyone else run into random IOErrors ([Error 9] bad file descriptor) in multi-threaded Python apps? I've searched the newsgroups, and the only references I can find to that seem to be sporadically related to threading, but nobody seems to have a "fix" or even a clear understanding of what the issue is. The app I'm running into this with (once in a while... not really repeatable predictably) is using 3 threads, and I'm using locks around all shared objects. The error seems to be happening mostly when I'm trying to delete a temporary file that was originally created by a different thread. ANy suggestions? Thanks, Kevin. From jeffr at euc.cx Wed Jul 30 12:00:35 2003 From: jeffr at euc.cx (Jeffrey P Shell) Date: Wed, 30 Jul 2003 10:00:35 -0600 Subject: Web tool kit : pro - cons ? In-Reply-To: <1059578213.12751.94.camel@lothlorien> Message-ID: On Wednesday, July 30, 2003, at 09:16 AM, Ian Bicking wrote: > On Wed, 2003-07-30 at 01:28, Jeffrey P Shell wrote: >> Database Abstraction is another key issue. Zope gets points here not >> only for the built in ZODB database, but for SQL Methods / Database >> Adapters. There is nothing in Zope that is tied to Postgres, MySQL, >> Oracle, Sybase, SQLite, etc. Yet it's always been able to use any of >> them since before it was Zope. There's just a nice simple abstraction >> layer that one seldom has to think about. > > Praising SQL Methods? Maybe I've been missing something, but SQL > Methods seem really primitive to me, certainly worse than the DB API > (though I suppose they preceded the DB API). The transaction stuff is > convenient -- if sometimes mysterious (like so many Zope things). But > it's not solving a terribly difficult problem. Object Relational mapping is a terribly difficult problem, and SQL Methods do not attempt to solve that. But SQL Methods are *great* for reading data, and for composing complex queries. A fair amount of applications (at least, older school applications) for the web, particularly intranets, have been about publishing the RDBMS data on the web. That's what SQL Methods do best. When it comes to DML statements, they're not stellar. If you're using an RDBMS as a primary persistence system, then yeah - a lot more work can be involved. I've started writing around this in a lot of my Zope applications with a simple core framework to deal with basic CRUD (Create/Read/Update/Delete) statements where complex queries (usually only needed on reads) aren't required. >> Other tools try the O-R >> mapping route for abstraction with varying degrees of success. >> SkunkWeb has PyDO, Webware has one (I can't remember its name right >> now). Zope's model is nice because it's not intrinsic to Zope that >> you use SQL - it's just a nice model to plug into if you need it, when >> you need it. I don't know how other toolkits stack up here. Some may >> just say "go find a Python adapter that works for you and do what you >> want with it", which seems to be as good of a way to go as any. > > PyDO and MiddleKit (Webware's) are both independent of their frameworks > (it's kind of unfortunate that they appear to be tied, though), as are > the other ORMs (like my SQLObject). All three provide something > approximating business objects built around database rows. They all put the model too close to the Python code for my personal comfort. Sometimes that's good. Other times, not so much. A couple of more interesting systems are Modeling ( http://modeling.sf.net/ ) and Ape ( http://hathaway.freezope.org/Software/Ape ). Ape is a really cool system - but (in current release) you do lose any benefits of the RDBMS (primarily, advanced queries) in favor of a tight abstract persistence system. It's tied to Zope and the ZODB at present (it allows installation of other ZODB storage types), but I think there are plans to make it more independent (at least from Zope). Ape keeps all of the collaborating components related to persistence separated from your business/content objects. What this allows for is the ability to completely change out the storage type. Not just switching from MySQL to Postgres, but switching from RDMBS backed storage to file based storages. The mappers and other components are responsible for marshaling the objects data into something readable by the target storage type. So unlike previous SQL storage backends for the ZODB which basically stored Pickled objects, Ape can turn them into real readable tables and rows. Or it can turn file like persistent objects like Page Templates, Python Scripts, images, etc, into readable and editable files on the file system. You can add a new HTML page or image into a mounted directory under this scheme, and Ape picks it up immediately. Extra data, such as Properties, are written out to separate files, and any other data that Ape doesn't understand is stored as Pickles. It's pretty seamless, and pretty amazing to watch it in action. Shane based the designs for ape on patterns from Martin Fowler's `Patterns of Enterprise Application Architecture `_ > My impression of Zope's SQL Methods is that they encourage distinctly > un-OO style of programming, and instead everything is done through a > heap of ad hoc queries and eclectic query results. At least, that's > the > code I've encountered, and it's taken discipline to avoid doing the > same > thing -- maybe there are better ways to use SQL Methods than what I've > been exposed to. (If so, it would be better if Good Zope Style was > documented, not just learned through wisdom born of failure -- but I > haven't found that sort of documentation for Zope yet). Ad Hoc queries have their place. And SQL Methods return a fairly optimized stream of read-only objects that behave like Python objects. Since they're read only, they can be brought into memory more efficiently than a list of dictionaries, and they don't have to worry about name collision. SQL Methods also let you attach 'Brains' to results. A Brain is a class that gets mixed in with the result object and allows for adding extra business logic (again - read only), which is a nice way to add extra computational or logical pieces to a record. Is it a perfect system? No. But neither is O-R mapping. Both have their place. But either system is better than a lot of what I see in ASP, PHP, and ColdFusion scripts where a bunch of SQL is splattered down in the middle of a script or template. SQL and Code mix about as well in my stomach as HTML and Code. Which is to say - not at all (unless you're writing a dynamic DML query builder ;). SQL Methods may not encourage a distinctly OO style of programming, but they do encourage reuse. And they encourage being written by people who know SQL well. Some people can write good HTML, some people can write good Python, some people can write insanely great SQL. SQL Methods, (old) DTML/ZPT, and Python Scripts/Products were all Zope's way of allowing people with different strengths be able to collaborate on web site, rather than just allowing the code geek to be the only one in control. It's an admirable design decision that you don't see in many other places. I think that the Enterprise Objects Framework had some of the same goals - that a Model (defines the mapping between objects and the persistence system, typically RDBMS) could be maintained by someone who was more familiar with data modeling, or with the target database model, while someone else could worry about the user interface. J.Shell | Eucci & Co. | http://euc.cx/ http://notype.com/drones/artists/eucci.html RIVE | http://notype.com/rive/ GDBODYCOUNT | http://notype.com/rive/static/024/ From schull at digitalgoods.com Thu Jul 10 09:35:41 2003 From: schull at digitalgoods.com (Jon Schull) Date: 10 Jul 2003 06:35:41 -0700 Subject: Securing PyDoc and CGIHTTPserver Message-ID: <2621b014.0307100535.449ad06f@posting.google.com> PyDoc's author Ka-Ping Yee has suggested that PyDoc be patched to prevent access from unauthorized IP addresses (https://sourceforge.net/tracker/?func=detail&atid=305470&aid=672656&group_id=5470), and that without such a patch, its not " suitable for running on boxes that aren't behind firewalls" It's hard to know how much to worry about such things (Comments?). However, even with the patch, IP addresses can be spoofed. Here is an additional security tactic that might be adopted. The port number used by pydoc is currently set by the user at the command line. Many people probably use the example given in the python module documentation : "python -p 1234" However, if the port were chosen at random and printed out, then only pydoc and the user would know how to access the pydoc server. I'm considering a similar strategy for a server based on the CGIHTTPServer module, so comments would be welcome. From staschuk at telusplanet.net Thu Jul 31 07:18:03 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 05:18:03 -0600 Subject: Python speed vs csharp In-Reply-To: ; from mike@nospam.com on Wed, Jul 30, 2003 at 11:09:22PM -0700 References: Message-ID: <20030731051803.A11030@tibia.amotlpaa.bogus> Quoth Mike: [a number-crunching hotspot benchmarks at 210s in Python] > translated it to C and ran it. The C code runs in approximately 7.5 > seconds. That's compelling, but C isn't: part of my simulation includes a > parser to read an input file. I put that together in a few minutes in > Python, but there are no corresponding string or regex libraries with my C > compiler, so converting my Python code would take far more time than I'd > save during the resulting simulations. It seems you're speaking here as if the options are a pure-Python program and a pure-C program. Is there a reason you can't move just this one hotspot function out to C, leaving the parser etc. in Python? -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From vze4rx4y at verizon.net Tue Jul 22 13:59:48 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 22 Jul 2003 17:59:48 GMT Subject: How do I get info on an exception ? References: Message-ID: [Cameron Laird] > >> But unsatisfying--at least to me. > > > >Submit a patch. > . > . > . > I deserved that. It wasn't a jab. Truly, if you see a way to clarify the docs, submit a patch. If everyone finds it helpful, it will be accepted. That's how the docs improve over time. I've personally written or accepted over a hundred of these in the past year. > There was more to my post, of course. Part of what I was trying to > express is that exception interfaces are almost always relegated to > a footnote, with only a generalized description, even in the frequent > case that a method's exceptions are more complicated than its invoca- > tions. No doubt, exceptions often get less explanation than everything else. However, in this case, the docs seemed reasonably clear to me. The part that could be improved is where it talks about returning a message or a tuple, as if either one but not both could occur at any time. It would be more accurate to say, that in all cases an exception instance is returned; the instance has a __str__ method so it can be printed as if it were a string; the instance has an attribute "args" which is the tuple (errno, errmsg); and the instance has a __getitem__ method so the args tuple can be directly unpacked as if the instance had been the tuple itself. OTOH, that is long-winded and distracts from the flow of knowledge about sockets. It is also how all exception instances work. > So, Raymond, do you have general guidelines for how you think excep- > tions should be documented? Unless there are interesting values being returned, it is probably sufficient to name the exception, state what it represents, and describe where it fits in the class structure (i.e. socket.herror is a subclass of socket.error). When you think about it, why have three paragraphs on an exception whose code is as simple as: class xyzException(Exception): pass # raised when xyz occurs When interesting values are returned, describe the meaning of each element in the instance's arg tuple (i.e. (errno, errmsg)). Afterall, the code behind it may be as simple as: raise socket.herror(errno, errmsg) # reveal the packet's error information Elsewhere in the docs, functions descriptions should list the names of the exceptions they can raise unless it is obvious or pertains to a whole collection of functions (i.e. all high-volume socket operations can potentially raise a timeout). In general, I like the documents to be as specific as possible without replicating the code or locking in a particular implementation. However, there is a competing force to keep module documents centered on how to use the module. For example, I found the unittest documentation to be highly specific and thorough, yet unsatisfactory because you practically had to read a book on the subject to be able to make basic use of the module. To fix it, I added a new introductory section that covers (in one page) the 5% of the module that will meet 95% of your needs (enough to get you up and running). Raymond Hettinger From bdesth.nospam at removeme.free.fr Wed Jul 9 17:35:03 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 09 Jul 2003 21:35:03 +0000 Subject: Python vs PHP References: <3F094FA4.9030800@ploiesti.astral.ro> Message-ID: <3F0C8A87.8070505@removeme.free.fr> Ian Bicking wrote: > (snip) > What you should remember when moving away from PHP, is that you no > longer have to use the server-page metaphor -- most of your application > logic should be in plain Python modules. Then you'll use your PSP (or > similar) page to present that code and respond to user input. Funny... when using PHP, I personnally write the logic in separate modules, and keep the presentation in 'server pages' that call the modules and format/print the result... I don't see why coding in PHP should be that different from coding in Python (except that one of them is a far better language whatsoever... Too bad I can't afford Python-powered hosting) Bruno From o_otaotao at hotmail.com Mon Jul 28 06:41:34 2003 From: o_otaotao at hotmail.com (PythonMan) Date: Mon, 28 Jul 2003 18:41:34 +0800 Subject: Any Software can Python <-> Delphi ? Message-ID: Any Software can change Python source code to Delphi ? thx -- From Bill.Scherer at verizonwireless.com Mon Jul 28 13:27:43 2003 From: Bill.Scherer at verizonwireless.com (Scherer, Bill) Date: Mon, 28 Jul 2003 13:27:43 -0400 (EDT) Subject: pretty printing graphs In-Reply-To: Message-ID: On Mon, 28 Jul 2003, John Hunter wrote: > > I have a tree structure (directed acyclic graph), where each node can > represent itself as a multi-line string that is not very wide (eg, 10 > chars per line). I would like to print the graph like > > C > C1 C2 > C1a C1b C2a C2b [P&M] John - Do you strictly require plain text output? If not, look into graphiz. It's fairly easy to generate dot files from python and then generate output in postscript or in a bitmap format (jpg, png, etc) using the graphiz tools. graphiz can be had from http://www.graphviz.org There is a python interface to graphviz available from http://www.cs.brown.edu/~er/software , but I have not used it. graphviz's output is customizable to some extant, and looks rather nice. HTH, Bill > > Where C, C1, etc.. are the multiline string blocks referred to above. > Does anybody know of a tool that can do this. Here is an example, > somewhat long because I have to create the multiline strings. > > from __future__ import division, generators > > def enumerate(seq): > "Waiting for python 2.3" > for i in range(len(seq)): > yield i, seq[i] > > class O: > > def __init__(self, text): > self.text = text > def __str__(self): > return self.text > > class Node: > def __init__(self, o): > self.node = o > self.children = [] > > def __str__(self): > s = '' > #s += str(self.node) + '\n\n' > if len(self.children)==0: return s > childStrs = [str(child.node) for child in self.children] > > lines = [[] for tmp in childStrs] > for lineNum, t in enumerate(childStrs): > lines[lineNum].extend(t.split('\n')) > > maxLines = max([len(l) for l in lines]) > sep = ' ' > for lineNum in range(maxLines): > row = '' > for childNum in range(len(childStrs)): > row += lines[childNum][lineNum] + sep > s += row + '\n' > s += '\n\n' > for l in self.children: > s += str(l) > return s > > > > n0 = Node(O("""1 2 3 0 > 1 2 3 4 > 1 2 1 5 > 1 2 1 1 > 4 3 2 2 > 4 3 2 7 > 2 3 2 3 > 2 3 2 9""")) > > > n1 = Node(O("""1 2 3 0 > 1 2 3 4 > 1 2 1 5 > 1 2 1 1 > ---------- > 1 1 0 0""")) > > n2 = Node(O("""4 3 2 2 > 4 3 2 7 > 2 3 2 3 > 2 3 2 9 > ---------- > 0 1 1 0""")) > > > > n1a = Node(O("""1 2 1 5 > 1 2 1 1 > ---------- > 1 1 1 0""")) > > n1b = Node(O("""1 2 3 0 > 1 2 3 4 > ---------- > 1 1 1 0""")) > > n2a = Node(O("""2 3 2 3 > 2 3 2 9 > ---------- > 1 1 1 0""")) > > n2b = Node(O("""4 3 2 2 > 4 3 2 7 > ---------- > 1 1 1 0""")) > > > n0.children.extend([n1, n2]) > n1.children.extend([n1a, n1b]) > n2.children.extend([n2a, n2b]) > print n0 > > Which prints: > > 1 2 3 0 4 3 2 2 > 1 2 3 4 4 3 2 7 > 1 2 1 5 2 3 2 3 > 1 2 1 1 2 3 2 9 > ---------- ---------- > 1 1 0 0 0 1 1 0 > > > 1 2 1 5 1 2 3 0 > 1 2 1 1 1 2 3 4 > ---------- ---------- > 1 1 1 0 1 1 1 0 > > > 2 3 2 3 4 3 2 2 > 2 3 2 9 4 3 2 7 > ---------- ---------- > 1 1 1 0 1 1 1 0 > > > This does part of the work, printing the child nodes on the same rows, > but doesn't the hierarchical part very well. What I would like is > something like this: > > 1 2 3 0 > 1 2 3 4 > 1 2 1 5 > 1 2 1 1 > 4 3 2 2 > 4 3 2 7 > 2 3 2 3 > 2 3 2 9 > > 1 2 3 0 4 3 2 2 > 1 2 3 4 4 3 2 7 > 1 2 1 5 2 3 2 3 > 1 2 1 1 2 3 2 9 > ---------- ---------- > 1 1 0 0 0 1 1 0 > > > 1 2 1 5 1 2 3 0 2 3 2 3 4 3 2 2 > 1 2 1 1 1 2 3 4 2 3 2 9 4 3 2 7 > ---------- ---------- ---------- ---------- > 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 > > > Thanks, > John Hunter > > -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From sybrenUSE at YOURthirdtower.imagination.com Thu Jul 24 12:08:06 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 24 Jul 2003 16:08:06 GMT Subject: i've been close to python's cradle :) References: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e enlightened us with: > recently i've visited SARAH, the academic supercomputer in > Amsterdam, Holland. this is next to the CWI, where Guido founded > Python.... Nice one. Where are you from? I live close to the CWI, and will probably even do a few courses there. Perhaps I'll look up Guido sometime :) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From peter at engcorp.com Sat Jul 12 05:43:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Jul 2003 05:43:36 -0400 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> Message-ID: <3F0FD848.849E5D88@engcorp.com> Erik Max Francis wrote: > > > ACT II -------------------------------------------- > > >>> class MyMistake(Exception): > > ... pass > > > > >>> try: > > ... raise MyMistake, 'try, try again' > > ... except MyMistake, msg: > > ... print type(msg) > > ... > > > > > > I'm not sure what mystery you're trying to get at here. This is what > Python prints for all instances: [snip] He's showing a case where a programmer thought he/she was using a sort of "parallel form" with the "MyMistake, 'try, try again'" part and the "MyMistake, msg" part. The programmer expected print type(msg) to show "". This is probably an example of an error promoted by leaving the redundant "raise Class,args" form of exception-raising in Python, instead of having a single obvious way: "raise Class(args)" as would be more Pythonic. ;-) -Peter From afriere at yahoo.co.uk Wed Jul 23 23:32:54 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 23 Jul 2003 20:32:54 -0700 Subject: Standard behaviour of a getSomething method References: Message-ID: <38ec68a6.0307231932.7a7f53eb@posting.google.com> "Batista, Facundo" wrote in message news:... > When I want to know about a attribute (e.g.: myAttrib) of an object, I > should use the specific method (e.g.: getMyAttrib). > > Considering that this attribute is always another object (everything is > an object in Python), what should getMyAttrib do? Given that your method is called 'get*' and not 'copy*', my feeling is that an accessor method should in general return the object itself. A client programmer might be surprised if they 'got' a mutable object, changed it, but it did not change at all. As has been pointed out, either way, documenting what it does is essential. However, while the importance of accessing attributes only via such 'accessor methods' is sometimes stressed, it appears to be more pythonic to access attributes directly. (ie just use myobj.myAttrib) The ususal critique, -- namely that direct access increases the 'coupling' between object, making it difficult to alter the implementation of an object without altering its public interface -- is met in Python by the use of python properties (which allow the wrapping of what, to client code, looks like direct attribute access.) At least that is how I have (recently) quelled my unease about direct attribute access. (My older code is still filled with get* and set* methods for all sorts of attributes which usually do nothing more than 'return self.attribute') The advantage of doing it that way is faster (you save method calls), more readible code. From shannon at news.widomaker.com Sun Jul 6 20:31:56 2003 From: shannon at news.widomaker.com (Charles Shannon Hendrix) Date: Sun, 6 Jul 2003 20:31:56 -0400 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: I keep hitting the wrong key when following up... :( In article <3F082031.3010503 at netscape.netNOTthisBIT>, Donald 'Paddy' McCarthy wrote: >> Is part of the if statement, or did someone with different >> tab settings from the author make a mistake and align it accidentally? > It would be nice if tabs as indentation for Python was deprecated but > failing that, If you don't use tabs, its wonderful. That would make it even worse. > If you do try python, try not to indent with tabs, and please try it, I > did and look at me now :-) Its precisely because I used it at work that I don't use it now... There is a lot to like about it, but there's never been a compelling reason to use it. We used it because it was buzzword compliant at the time. -- Ah... you gotta love it when your ISP switches to a SPAMMING newsfeed. Sigh... -----= 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 tim.one at comcast.net Thu Jul 10 10:00:59 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 10 Jul 2003 10:00:59 -0400 Subject: Windows Python 2.3b2 bug? Edit with IDLE In-Reply-To: Message-ID: [Bartolom? Sintes Marco] > I am using Python 2.3b2 in a Windows 98 SE machine. If I right-click > a .py file, the menu shows an "Edit with IDLE" option, but when I > select it no IDLE window opens, as Python 2.2.2 did. Is it a known > bug, or am I doing something wrong? Thanks It's a known bug, and will be fixed before the next release. There's a new version of IDLE in a new location in 2.3, but the installer wasn't updated accordingly (to point the "Edit with IDLE" action to IDLE's new home). From hokiegal99 at hotmail.com Sun Jul 13 11:44:05 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 13 Jul 2003 08:44:05 -0700 Subject: removing spaces from front and end of filenames References: <3F10BABB.D548961B@alcyone.com> Message-ID: <93f5c5e9.0307130744.7e9d8377@posting.google.com> Erik Max Francis wrote in message news:<3F10BABB.D548961B at alcyone.com>... > hokiegal99 wrote: > > > This script works as I expect, except for the last section. I want the > > last section to actually remove all spaces from the front and/or end > > of > > filenames. For example, a file that was named " test " would be > > renamed "test" (the 2 spaces before and after the filename removed). > > Any > > suggestions on how to do this? > > That's what the .strip method, which is what you're using, does. If > it's not working for you you're doing something else wrong. for root, dirs, files in os.walk('/home/rbt/scripts'): for file in files: fname = (file) fname = fname.strip( ) print fname When I print fname, it prints the filenames w/o spaces (a file named " test " looks like "test"), but when I ls the actual files in the directory they still contain spaces at both ends. That's what I don't understand. It seems that .strip is ready to remove the spaces, but that it needs one more step to actually do so. Any ideas? From skip at pobox.com Sat Jul 19 11:15:07 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 19 Jul 2003 10:15:07 -0500 Subject: feature request: a better str.endswith In-Reply-To: <2259b0e2.0307190530.17a48052@posting.google.com> References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <2259b0e2.0307190530.17a48052@posting.google.com> Message-ID: <16153.24699.376795.233736@montanaro.dyndns.org> >> I suggest you submit a feature request to SF. A patch to >> stringobject.c and unicodeobject.c would help improve chances of >> acceptance, and for symmetry you should probably also modify the >> startswith methods of both types. Michele> Too bad my skills with C are essentially unexistent :-( Look at it as an opportunity to enhance those skills. You have plenty of time until 2.4. ;-) In any case, even if you can't whip up the actual C code, a complete feature request on SF would keep it from being entirely forgotten. Skip From bhards at bigpond.net.au Wed Jul 23 08:38:54 2003 From: bhards at bigpond.net.au (Brad Hards) Date: Wed, 23 Jul 2003 12:38:54 GMT Subject: pythonic malloc References: <7g1xwjqujm.fsf@pikespeak.metacarta.com> <7g7k6a5o3r.fsf@pikespeak.metacarta.com> Message-ID: eichin at metacarta.com wrote: > >> Now I just have a question about portability. Will this break on a >> big-endian box? That is, does: > > read struct.__doc__, it explains about endianness in detail (in > particular, that's what the "<" at the beginning is all about.) Thankyou for your patience. Now that you mention it, I do remember reading about that in the past, but I guess I'm more rusty than I thought. Brad From bh at intevation.de Wed Jul 2 07:06:28 2003 From: bh at intevation.de (Bernhard Herzog) Date: 02 Jul 2003 13:06:28 +0200 Subject: Good code patterns in Python References: <3F0285F0.EDF697E3@alcyone.com> Message-ID: <6qllvh9oi3.fsf@salmakis.intevation.de> Erik Max Francis writes: > The > complete solution to this would probably be a conditional expression, > e.g.: > > variable = (if condition: someValue else: otherValue) > > eliminating the duplication which can lead to errors. (Python, of > course, doesn't have such a construct, and the silence after the > conditional expression PEP vote and the long silence thereafter suggests > that it never will.) Guido broke his silence at EuroPython: The ternary operator will not be added to Python. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From tjreedy at udel.edu Fri Jul 25 14:02:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2003 14:02:23 -0400 Subject: python assignment References: Message-ID: "dan" wrote in message news:fbf8d8f2.0307241825.bd3b315 at posting.google.com... > >>> for x in range(3): > ... for y in range(3): > ... temp[y] = x+y > ... v[x] = temp + [] > ... > >>> v > [[0, 1, 2], [1, 2, 3], [2, 3, 4]] #expected behavior > > but again the +[] looks funky in the morning light. Can I always > assume that an operation of this sort will return a new object, even > if it has no effect on one of the operands? > > I suppose a clearer fix would be v[x] = copy.copy(temp), eh? or add temp = [None]*3[] between 'for x' and 'for y' so you start with an explicitly new temp for each x loop. Terry J. Reedy From usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org Thu Jul 10 04:07:26 2003 From: usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org (Sami Juvonen) Date: Thu, 10 Jul 2003 08:07:26 GMT Subject: syslogd? References: Message-ID: On Wed, 09 Jul 2003 14:42:50 -0700, Dan Stromberg blurted: > Does anyone know of a syslogd (server side, not a client) implementation > in python? > I need something that'll help me ditch a particular kind of message It's not in python, but syslog-ng will let you do that. http://www.balabit.com/products/syslog_ng/ http://www.oreilly.com/catalog/bssrvrlnx/chapter/ch10.pdf -sami. -- "...you want a .sig with that?" From sketerpot at chase3000.com Thu Jul 10 16:13:27 2003 From: sketerpot at chase3000.com (Peter Scott) Date: 10 Jul 2003 13:13:27 -0700 Subject: How does python work References: Message-ID: <659f82ff.0307101213.4000e098@posting.google.com> "Geiregat Jonas" wrote in message news:... > I'm asking myself how Python code get's executed ... > What happens first etc ... > First read the file and then .. > How python handle's variable internally ... > also could someone point me to the build in functions in the python source > code ? The Python Library Reference has a section on "Built-in Functions, Types, and Exceptions" at . There is also a section documenting some rather low level internal modules at , such as parser, which lets you access the parse tree, and dis, a disassembler for python bytecode. -Peter From bgailer at alum.rpi.edu Fri Jul 18 19:05:06 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 18 Jul 2003 17:05:06 -0600 Subject: feature request: a better str.endswith In-Reply-To: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <5.2.1.1.0.20030718164409.01c3fb78@66.28.54.253> At 05:01 AM 7/18/2003 -0700, Michele Simionato wrote: >I often feel the need to extend the string method ".endswith" to tuple >arguments, in such a way to automatically check for multiple endings. >For instance, here is a typical use case: > >if filename.endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > >Currently this is not valid Python and I must use the ugly > >if filename.endswith('.jpg') or filename.endswith('.jpeg') \ > or filename.endswith('.gif') or filename.endswith('.png'): > print "This is a valid image file" > >Of course a direct implementation is quite easy: > >import sys > >class Str(str): > def endswith(self,suffix,start=0,end=sys.maxint):#not sure about > sys.maxint > endswith=super(Str,self).endswith > if isinstance(suffix,tuple): > return sum([endswith(s,start,end) for s in suffix]) # multi-or > return endswith(suffix,start,end) > >if Str(filename).endswith(('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > >nevertheless I think this kind of checking is quite common and it would be >worth to have it in standard Python. > >Any reaction, comment ? One of my favorite languages is APL. All APL variables are arrays of 0 or more dimensions, and most of the operations in APL take arrays as arguments and return arrays as results. So I am often frustrated in Python when I have to write a construct such as your example, when, IMHO, it would be easy to extend Python to accept sequences as arguments where only single values are currently allowed. One example is providing a sequence of integers to index another sequence, vis. given seq = [3, 5, 7, 1 ,4], seq[(1,3, 0)] would produce [5, 1, 3]. Currently the tersest way to do this is [seq[x] for x in (1,3,0)]. The new extension would probably execute faster, and is more readable. There are probably more situations that could also benefit from such an extension. I know that I can create some of these using magic methods, but how much nicer if they were native. In APL one can specify indexes for the various dimensions of an array. If B is a rank 2 array, B[1 2;3 4] retrieves columns 3 and 4 of rows 1 and 2. WIBNI one could in a similar way drill into a nested list. I know the various importable array modules do some of these tings, but they are limited to homogeneous data. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From shoppa at trailing-edge.com Wed Jul 9 08:19:46 2003 From: shoppa at trailing-edge.com (Tim Shoppa) Date: 9 Jul 2003 05:19:46 -0700 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: Charles Shannon Hendrix wrote in message news:... > In article , Tim Shoppa wrote: > > > And it's not the same as Makefiles, either. Everybody has at one time > > been bitten by how 8 spaces is not at all the same in a Makefile as > > one tab; and it doesn't help that with many editing/viewing tools that it > > is impossible to see the difference. > > Listing one bad thing to defend another? I don't think the choice made in Python is bad. Different, yes. I usually think that "Different is good", in fact :-). > I hate that part of make too. > > However, its very easy to tab a makefile properly, because the logic > is implicit in the rule sets. You just find each rule and indent its > members properly. It's not ambiguous. > > You also get an error... Not always. GNU Make is pretty good about flagging errors, but many other make utilities fail silently in the same circumstances. > > Compare that to all the punctuation marks that *some* other languages require. > > Remember the Dilbert where PHB complains that his programmers are using > > way too many semicolons? :-) > > Don't get me started on code reviews by non-programmers. > > Somewhere I have one saved, that I still can't figure out. I'd love to see it! I keep a couple on my office walls where "EXTREME CHANCE OF FATALITY" is the conclusion. Tim. From duncan at NOSPAMrcp.co.uk Tue Jul 15 05:37:58 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 15 Jul 2003 09:37:58 +0000 (UTC) Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <3F130ED4.2030804@skynet.be> <3F13C137.6090705@igpm.rwth-aachen.de> Message-ID: "Helmut Jarausch" wrote in news:3F13C137.6090705 at igpm.rwth-aachen.de: > Obviously Python allows references to references, since > e.g. 'once' (the 'name' of a function) is a reference to > the code and 'f' is a reference to that reference. (you call it > name binding) There is no 'obviously' about it. 'once' is a name bound to the function. 'f' is another name bound to the same function. There are no references to references here. It is true that the function knows that its name is 'once', and indeed the code object used by the function also has a name 'once', but: def once(x): return x f = once Both 'f' and 'once' are names bound directly to the same function object. +------+ +----------------+ | once |------------->| function object| +------+ +----------------+ ^ +------+ | | f |----------------+ +------+ Assignment in Python simply makes a new binding to the existing object. It doesn't matter what type the existing object was, it never makes a copy of the object nor adds an extra level of indirection. > A similar situation arises in Maple and there one has the choice > to either derefence all references down to the real object > or to just derefence a single time. > > Example > > def once(x): return x > def twice(x): return 2*x > ref= once > def caller(): > callee=ref # (*) > print callee(1) > > caller() # prints 1 > ref= twice > caller() # prints 2 so that demonstrates name binding > > how can I get the current value (like 'xdef' in TeX) > of 'ref' in the assignment (*) above, so that > 'callee' becomes an (immutable) reference to 'once' ? > You did get the current value of 'ref' so that the first time callee was bound to the same function that 'once' and 'ref' were bound to, and the second time the local variable 'callee' was bound to the same function that 'twice' and 'ref' were bound to at that time. Each time you call 'caller' you get a new local variable, none of the values are preserved from the previous call. If you want to preserve state, save an attribute in a global, or better a class instance. -- 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 amk at amk.ca Thu Jul 10 11:01:38 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 10 Jul 2003 10:01:38 -0500 Subject: Sample Web application References: Message-ID: On 09 Jul 2003 20:53:17 -0500, Ian Bicking wrote: > But more generally, I can't stand writing about how to work around > problems, when (as a programmer) it is within my power to fix those > problems. It seems far better to spend time fixing problems than merely > documenting them. I don't believe it's possible to fix the installation problems. Quixote works with Apache, IIS, AOLserver, Medusa, and Twisted; there seems nothing that can be done to simplify things across that entire range. It can be made easier in one particular case, of course. For example, setting up an SCGI application with Apache requires three steps: 1) Compile mod_scgi and install it. (On Debian unstable, you can install it with apt-get. 2) Add a directive to httpd.conf and restart: SCGIServer 127.0.0.1 6500 SCGIHandler On 3) Run the SCGI application so that it listens to port 6500. The Dulcinea package (http://www.mems-exchange.org/software/dulcinea/) includes scripts for running multiple web sites on a machine and easily configuring them, but that's a feature that isn't being pushed very strongly, and we made little effort to make this feature usable by outsiders. --amk When is a cat not a cat? When it builds a cat-flap... -- The Doctor, in "Survival" From mertz at gnosis.cx Tue Jul 1 03:30:28 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 01 Jul 2003 03:30:28 -0400 Subject: Howto: extract a 'column' from a list of lists into a new list? References: Message-ID: "Greg Brunet" wrote previously: |>>> tbl.Fields() |[('STOCKNO', 'C', 8, 0), ('DACC', 'C', 5, 0), ('DEALERACCE', 'C', 30, |0), ('D-ACCRTL', 'C', 9, 0), ('D-ACCCST', 'C', 9, 0)] NAME,TYPE,LEN,DEC = range(4) names = [row[NAME] for row in tbl.Fields()] -- 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 Marco.LaRosa at csiro.au Thu Jul 24 19:48:59 2003 From: Marco.LaRosa at csiro.au (Marco.LaRosa at csiro.au) Date: Fri, 25 Jul 2003 09:48:59 +1000 Subject: Newbie question regarding py2exe. Message-ID: Hi all, Firstly thanks for the responses. I should say that I am new to mailing lists also. I now realise I need to provide more info than what I did : ) > Thomas said: Don't work in the py2exe directory. I have been working well away from there. > Ray says: >That ment that the setup.py became as simple as ... > ># setup.py >from distutils.core import setup >import py2exe > >setup(name="myscript", > scripts=["myscript.py"], >) My setup.py references only the very first module of the app. That is, the module which sets the GUI event loop in motion. In an earlier attempt, I explicitly listed all of the modules in the setup.py file and some of them did compile. However, the process always died when it got the first module. The module which gets the GUI going is simple, standard python code. No special imports or anything other strange tricks. I have tried converting a simple gui app using py2exe and it worked without problems. However, when I try to compile my code, I get errors from Modulefinder.py (They are definitely errors Thomas : ) The final error in the traceback is as follows: File "C:\......\modulefinder.py", line 267, in load_module co = compile(fp.read()+'\n',pathname,\exec') File "", line 357 SyntaxError: invalid syntax I would include it all but I can't get it out of the dos command prompt window (sorry, I usually develop on SGI - developing on windows is still new to me) The code I have developed is for modelling structure-activity relationships. Ergo, it is quite complex. It uses Python (obviously), wxPython, Numeric, and Chaco (for plotting). I don't think any of these packages is a problem because the output tells me py2exe doesn't even make it to a module which uses them. Finally, I get the same error using the updated py2exe package. The only other thing I can think of is the path. Does py2exe use the PYTHONPATH environment variable? Any ideas would be greatly appreciated. Cheers, Marco From bokr at oz.net Tue Jul 15 19:10:38 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2003 23:10:38 GMT Subject: anything like C++ references? References: Message-ID: On Tue, 15 Jul 2003 03:16:08 +0100, Stephen Horne wrote: >On 14 Jul 2003 23:31:56 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark >'Kamikaze' Hughes) wrote: > >> It looks like you've almost reached understanding, though you've been >>given a bad start with a very idiosyncratic and monolingual >>understanding of what "computer science" teaches--that was certainly not >>in the classes I took, but apparently yours were different. > >Really. My computer science lessons were taught in a way that >respected the source of most of the theory in mathematics - >algorithms, Church's lambda calculus and that kind of stuff. > >What did your lessons teach? > >> Since every operation in Python operates on pointers, there's no use >>in having a special syntax for it. You don't need all the * and & and >>-> line noise. > >The point of the thread is not pointers - they are a side issue. > >When you use variables, you are using a concept from mathematics. In >mathematics, variables bind to values. All values are immutable. > >Python binds variables to objects, not values. For immutable objects >this is an unimportant implementation detail. For mutable objects, it >breaks the mathematical principle of variables being bound to values. Only if you persist in thinking of Python name bindings as variable bindings in your sense. They are not. They are aliases. That concept exists in C/C++ and is e.g. a major concern in optimization. > >> Stop trying to make Python into C/C++, and you'll be happier with it. >>Or stop using Python, if you really don't like the design philosophy. >>There are plenty of Algol-derived languages out there. PHP and >>especially Perl are more C-like in their internal logic, and you might >>find them more pleasant. > >This is bogus. > >I don't want Python to become C or C++. I want Python to respect >principles that come from mathematics and computer science. Not for >reasons of theory pedanticism, but because the current system can and >does regularly cause confusion and errors. > That always happens when you use the wrong theory to interpret your data ;-) Quit projecting your "variable binding" idea onto Python's name bindings. It doesn't fit. Not because it's bad, but because it's the wrong theory. >The fact that Python claims to be a very high level language, and yet >you have to worry about the binding of variables to objects - Python's bindings are not about what you call variables. I think we should call them by a different word, e.g., aliases. I.e., different names for the same thing. >something that should be a low level implementation detail - has very >real everyday implications. > >Respect the idea of variables binding to values and suddenly the need >for pointers becomes more obvious. You cannot abuse mutable objects to >fake pointer functionality (another everyday fact of Python >programming) if the binding of variables to values (rather than just >objects) is respected. > Quit it with this "respect" thing ;-) Python's name bindings just aren't your variable bindings, and Python's names aren't variable names. They're aliases. Persisting in calling Python's names variables-in-your-sense is disrespect ;-) (See another post for a namespace (attibute name space of class NSHorne instances ;-) that forces name binding to copied objects having equal values). Regards, Bengt Richter From peter at engcorp.com Mon Jul 21 08:46:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 08:46:33 -0400 Subject: listening com ports References: Message-ID: <3F1BE0A9.79D6D92@engcorp.com> > Enrique Palomo wrote: > > can anyone tell me what must i use to listen the com1 and com2 ports and write it to file?? Google for "PySerial". From paul at boddie.net Wed Jul 16 12:21:22 2003 From: paul at boddie.net (Paul Boddie) Date: 16 Jul 2003 09:21:22 -0700 Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> Message-ID: <23891c90.0307160821.59b55bef@posting.google.com> Duncan Booth wrote in message news:... > > To "take someone in" means to trick or deceive them. [Dictionary reference] > take someone in 1 to include them. 2 to give them accommodation or shelter. > 3 to deceive or cheat them. English is a great language to confuse people with when one considers different verb/preposition combinations, especially when some of them are used for slang purposes. Anyway, to elaborate on the above: A. "I couldn't take it (all) in," refers to the observation of events or quite commonly some kind of sensory experience. This is only ever used with passive objects or events, though. B. "The vicar was completely taken in by the deception." (Note that this has subtle differences from... "The vicar was completely taken by the idea." ...which may indicate enthusiasm or obsession.) C. "After trying all his other acquaintances, it was the bishop who finally took him in." (This means that the bishop offered accommodation or shelter, and not that the bishop was behind an elaborate or ambitious deception.) I'm sure other alternatives exist, some with dubious meanings. :-) I suppose this goes to show that "modifiers" which change the behaviour of known "operations" (frequently in subtle ways) can be impediments to the understanding of a language. It could be interesting to consider whether Python, as an artificial language, manages to successfully avoid such possibilities for confusion. Paul From wl at flexis.de Tue Jul 8 04:58:21 2003 From: wl at flexis.de (Wolfgang) Date: Tue, 08 Jul 2003 10:58:21 +0200 Subject: SWIG and Python in use? In-Reply-To: References: Message-ID: Hi, Alan Sheehan wrote: > I am considering scripting a large C++ application. > > In particular I am interested in test driving and end-user scripting > the "application layer" in Python and giving it access to a large > collection of C++ objects and their methods. > > I note that SWIG is a mature tool and refers to supporting Python > v1.x. > > Has/Does anyone use SWIG to bind with Python 2.x ?. > > Does it still work? > Any pitfalls, caveats ? I've used swig a little bit. It's very good to generate interfaces for C librarys. It can build interfaces for a lot of languages not only python. To interface C++ there are some problems. Simple C++ clases are easy to interface but if us use virtual methods, templates an so on that possible with swig but you have to write a lot of wrapper code. Not an easy task. To interface the app to python 2.2 and above, consider to use Boost.python: http://www.boost.org/libs/python/doc/index.html Today I use Boost.python for my new projects. It's easy to interface C++ librarys and all C++ stuff. Less code to write and for me it's easier. (I don't know the Python C Api in detail, with boost.python I wrote a C++ interface for a database within 3 days) bye by Wolfgang From intentionally at blank.co.uk Thu Jul 17 13:05:58 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 17 Jul 2003 18:05:58 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> Message-ID: <9akdhvsiu4laeh6gna5f5ljdu9nrnckkkt@4ax.com> On Thu, 17 Jul 2003 12:35:48 -0400, "Terry Reedy" wrote: > >"Stephen Horne" wrote in message >news:hub7hvgjjm0prt5p3jn92npmb3gf777mr9 at 4ax.com... >> A goal of Python is to be a 'very high level language'. Another is >to >> 'do the right thing'. > >At this point, we need to differentiate between Guido's goal for >Python, your goal for Python, and anybody else's. The above may by >your goals but not necessarily others' (primary) goals. Really - funny that these two goals didn't originate from me, then. I just repeated two phrases that get used quite a bit around here. For example... http://www.python.org/doc/1.5.2/tut/node3.html """ Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than the shell has. On the other hand, it also offers much more error checking than C, and, being a very-high-level language, it has high-level data types built in... """ Care to claim that the phrase "the right thing" is my invention? What if I add "(tm)" >> Python isn't really a member of that list. ... >> It isn't an experimental language. It doesn't obsess on one >particular >> concept. It is a language for getting things done with very little >> fuss. > >This is, I believe, expresses Guido's goal for Python much better than >your two goals above. So, by your own statement, he has met *his* >goal pretty well. In my view, a very high level language which does the 'right thing' *is* a language for getting things done. When I argue in terms of the practical issue of accidental side-effects - one which Guido himself identified, as shown by the link I gave earlier in the thread - then people give theory-style reasons why I'm wrong. The fact that I hadn't really thought through the theory at the start of the thread is proof positive that the practical issue is where I'm coming from. When I debate the theory arguments used against me, people suggest that I'm just fussing too much about high-and-mighty theoretical BS. As you just did. Funny, that. Oh, and the other main suggestion is that I'm just from a C background and can't get used to Python. Again that is quite simply false. I had been programming for nearly ten years before I ever used C, I only used it for a couple of years, and I have been programming Python longer than C++. From bgailer at alum.rpi.edu Wed Jul 30 13:09:26 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 30 Jul 2003 11:09:26 -0600 Subject: Bottleneck: easy obscurity "encryption" via xor In-Reply-To: <3f26f477$0$49098$e4fe514c@news.xs4all.nl> References: Message-ID: <5.2.1.1.0.20030730110650.02b83830@66.28.54.253> At 12:25 AM 7/30/2003 +0200, Irmen de Jong wrote: >Tino Lange wrote: > >>It turns out not to be quick at all. I really didn't expect this to be >>a bottleneck, but it takes quite some time. > >>> return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, >>> _salt = salt: operator.xor(ord(char), _salt), str), "") > >Running this on a large string builds up a huge list of ints, >that you are converting to chars and then concatenating them >together using +... this creates a HUGE number of temporary >string objects. >The usual pattern of fast string joining is: > >''.join(list-of-fragments) > >So first try: > > return ''.join(map(lambda char, _salt = salt: > chr(operator.xor(ord(char), _salt)), string)) > >This runs MUCH faster already. > >But the version I'd recommend is: > >def xorcrypt(string, salt = 255): > if salt <0 or salt> 255: > raise "Invalid salt! Must be 0<=salt<=255!" > return ''.join( [ chr(ord(c) ^ salt) for c in string ] ) Great minds think alike? I came up with (independently!): return ''.join([chr(ord(char) ^ salt) for char in txt]) I also favor comprehension because it is more readable. >because >1) salt must be 0..255 not only <=255 >2) forget about map & lambda, use a list comprehension. > >That implementation runs about 20 times faster than your original one; >0.11 seconds for 100 Kb source data. (python 2.3) > >HTH, >--Irmen de Jong > > >-- >http://mail.python.org/mailman/listinfo/python-list > > > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From adalke at mindspring.com Mon Jul 14 12:28:38 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 14 Jul 2003 10:28:38 -0600 Subject: anything like C++ references? References: , <000301c348c7$3c501980$21795418@dell1700> Message-ID: Moshe Zadka: > In computer science, the theoretical model one first learns is a turing > machine. Turing machines have no variables or values, merely tapes. Actually, we started off with state machine, then worked our way though DFA/NFA, PDA, etc., ending up with a TM. I remember being intrigued that the way we learned these was in opposite order to they way they were first researched. Can anyone suggest why? My thought was that mathematicians like generalizing, so the most general models were pondered first. Only as people started to experiment with variations, and with actual computer hardware to back them up, did people start thinking about more limited cases. Andrew dalke at dalkescientific.com From jonathan.hayward at pobox.com Thu Jul 31 19:24:33 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: 31 Jul 2003 16:24:33 -0700 Subject: Bug help: CGI forking Message-ID: I am trying to have a CGI script which forks a daemon the first time, and on subsequent times asks the daemon to do all the work. The daemon and the CGI script are run by the same code. I'm trying to have a class that will handle daemon multithreading, the "hollow shell" CGI script starting up the daemon, and the CGI script talking with the daemon. I tried to use recipes from O'Reilly's _Python Cookbook_, but I must have messed up. The script usually hangs, and when it doesn't hang, the daemon sometimes isn't started. I think I have a fork bug, at least. Any bugfixes and/or clarifications welcome: class multitasking_manager(ancestor): """Class to handle multithreading and multiprocessing material.""" def __init__(self): ancestor.__init__(self) thread_specific_storage = {} thread_specific_storage_lock = thread.allocate_lock() def check_and_start_daemon(self): if not self.is_daemon_running(): self.start_daemon() def get_page_from_daemon(self): self.check_and_start_daemon() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockIn = sock.makefile("r") sockOut = sock.makefile("wb") try: sock.connect((configuration.get_search_server_ip(), \ configuration.get_search_server_port())) for current_environment_key in os.environ.keys(): sockOut.write("environmental_variable " + \ current_environment_key + "\r\n") cPickle.dump(os.environ[current_environment_key], sockOut) for cgi_key in cgi.FieldStorage().keys(): sockOut.write("cgi_value " + cgi_key + "\r\n") cPickle.dump(cgi.FieldStorage[cgi_key]) sockOut.write("\r\n") result = cPickle.load(sockIn) sockOut.close() sockIn.close() sock.close() except socket.error, e: return "Content-type: text/html\n\n

There was an error loading this page.

" + str(e) def get_thread_specific_storage(): thread_id = thread.get_ident() result = thread_specific_storage.get(thread_id) if thread_specific_storage is None: try: thread_specific_storage_lock.acquire() thread_specific_storaget[thread_id] = result = {} finally: thread_specific_storage_lock.release() return result def is_daemon_running(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((configuration.get_search_server_ip(), \ configuration.get_search_server_port())) sock.close() return 1 except socket.error: return 0 def run_daemon(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", configuration.get_search_server_port())) sock.listen(5) while 1: try: newsocket, address = sock.accept() start_new_thread(self.run_daemon_thread, (newsocket, address)) except socket.error: sock.close() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", configuration.get_search_server_port())) sock.listen(5) def run_daemon_thread(sock, address): """Reads a CGI or other header variable alone on a line, format like cgi_value environmental_variable REMOTE_ADDR and then a pickled value. There is exactly one space between the two elements, and neither element may contain a space""" sockIn = sock.makefile("wb") sockOut = sock.makefile("r") line = sockIn.readline() while line: if get_thread_specific_storage()["cgi"] == None: get_thread_specific_storage()["cgi"] = {} if get_thread_specific_storage()["environmental_variables"] == \ None: get_thread_specific_storage()["environmental_variables"] = {} cgi = get_thread_specific_storage["cgi"] environmental_variables = \ get_thread_specific_storage["environmental_variables"] line = re.sub("[\r\n]+", "", line) if line != "": query_line = re.split("\s+", line) input_type = query_line[0] input_name = query_line[1] if input_type == "cgi_value": cgi[input_name] = cPickle.load(sockIn) elif input_type == "environmental_variables": environmental_variables[input_name] = cPickle.load(sockIn) else: generate_output() print_output(sockOut) line = sockIn.readline() sockIn.close() sockOut.close() sock.close() def start_daemon(self): try: first_pid = os.fork() except OSError, e: log_error("Failed to make first fork for daemon. Error: " + \ e.strerror) return if first_pid == 0: os.chdir("/") os.setsid() os.umask(066) try: second_pid = os.fork() except OSError, e: log_error("Failed to make second fork for daemon. Error: " + \ e.strerror) return if second_pid == 0: self.run_daemon() ++ Jonathan Hayward, jonathan.hayward at pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From max at alcyone.com Wed Jul 2 06:02:59 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 03:02:59 -0700 Subject: Assign to True / False in 2.3 References: Message-ID: <3F02ADD3.6047F561@alcyone.com> Culley Angus wrote: > I was a little suprised to find that I could assign a value to 'True', > and 'False' without warning though, and was wondering if this is > deliberate. This is true of pretty much all Python features. The only special dispensation goes to None, which is a warning now (in the 2.3 beta): Python 2.3b2 (#1, Jun 29 2003, 20:30:58) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> None = 0 :1: SyntaxWarning: assignment to None Python takes the approach of "We're all adults here." If you're using Python, it presumes that you don't need handholding, and that you won't do things you know you shouldn't do. For instance, imagine the havoc that things like this would cause: >>> int = float >>> file = str >>> sys = 'This is really not a module' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Shooters, looters / Now I got a laptop computer \__/ Ice Cube From eppstein at ics.uci.edu Tue Jul 1 21:42:27 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 01 Jul 2003 18:42:27 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: In article <3jc4gvgn5rb4c4008eedg958ee594lu8p2 at 4ax.com>, Tom Plunket wrote: > How can I create a functor object in Python? > > What I want (being a C++ coder ), is to be able to create an > object that I is callable. The following is my attempt, but it > doesn't work: ... > class SomeClass: > def __init__(self): > self.countdown = Countdown() > self.countdown.SetCallback(30, lambda s=self: s.Callback) The error is in this line. Should be s.Callback(). As it is, your lambda is a function that returns a function object, rather than calling it as you apparently intend. > # I have also tried 'lambda: self.Callback' > self.done = False -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From stuff at slinkp.com Thu Jul 17 14:24:59 2003 From: stuff at slinkp.com (Paul Winkler) Date: 17 Jul 2003 11:24:59 -0700 Subject: Choosing the right framework References: Message-ID: "Carsten Gehling" wrote in message news:... > I may be ignorant of major Plone issues, but here are my main "grudges" > against it (please bear in mind that I haven't researched Plone for more > than 3 days, and some of my arguments may look plain stupid ;-) : > > > 1) I don't the idea, that the user authentication (login form) to managin > g > the content of the website is visible on the website's pages. This is trivial to change - you don't even have to write or modify any code to do so, it's a matter of unchecking a box on a configuration form. Granted, *finding* the form in question might take a while for a novice :-\ In this case, it's at /your_plone_site/portal_membership/manage_editActionsForm > 2) I want the content management interface to be similar to the one I > currently use in my own CMS. (One frame with a tree structure of the page > hierarki, one frame with the page displayed, and content editing forms as > popup windows). > This is also very doable. All forms, templates, and images used by CMF, and therefore by Plone, are in /your_plone_site/portal_skins. *Everything* can be changed. So what I'd do, rather than focusing on how CMF and/or Plone and/or CPS looks / feels, is look at its feature set and see how closely it matches what you want & need to do. For Plone at least, there is also a very active IRC channel - #plone on irc.openprojects.net In order to do this you need to 1) learn how to read/write ZPT 2) The real difficulty would be in learning what/where are all the existing templates & forms and customizing them to do what you want, while understanding plone/cmf well enough to not throw the baby out with the bathwater. In my experience, you don't want to start from scratch - there's an awful lot of useful functionality already implemented and tested, and you should leverage it. So even if it seems slower than starting over, I suggest customizing things based on an existing skin. It might be worth playing around some with CMFDefault (the basic stuff that plone is based on); it's simpler and less featureful, so you might be able to grasp more of the core concepts and functionality before deciding whether you want / need to tackle Plone. Also, you might want to look at the Plone Book: http://plone.org/documentation/book A lot of the ideas apply to plain old CMFDefault too. check the FAQ section for some quickie how-to tidbits. Chapter 6 tells you all about customizing look & feel. Want to see some CMF/plone sites that look different from each other? Check out these: http://www.plone.org/about/sites Of course, these don't show you the content management interface, but that's just as skinnable as the end-user presentation... With all that said, I sometimes use plain old CMF as a base instead of Plone because there's just less of it to deal with :-) ANother zope/cmf-based content management system is CPS, worth a look: http://www.nuxeo.org/cps From stephane.bidoul at softwareag.com Sun Jul 27 10:35:29 2003 From: stephane.bidoul at softwareag.com (=?ISO-8859-1?Q?St=E9phane_Bidoul?=) Date: 27 Jul 2003 07:35:29 -0700 Subject: datetime1 - datetime0, same tzinfo, different dst Message-ID: <82a334e5.0307270635.3ce7e078@posting.google.com> Hi, I'm playing around with the new datetime module. Looks nice, and a welcome addition to the core... I've a question about a behaviour of substractions of "aware" datetimes around DST switch. The problem is that the difference gives wrong results when the 2 datetimes have the same tzinfo instance, but have different utc offsets due to DST. The behaviour is consistent with what the documentation says, but I find it quite unintuitive. Is that the designed behaviour? Assuming doctzinfo is the sample tzinfo module form the documentation, below is a commented session that illustrates question. My win2k sp4 system is in Belgium: GMT+1 with DST. Thanks. -sbi Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> from doctzinfo import utc, Local, LocalTimezone Let's create 2 dates, d0: winter time and d1: summer time. >>> d0 = datetime(2003,3,30,tzinfo=Local) >>> print d0.dst() 0:00:00 # ok: this is winter time >>> d1 = datetime(2003,3,31,tzinfo=Local) >>> print d1.dst() 1:00:00 # ok, this is summer time, DST is 1 hour >>> print d1.astimezone(utc) - d0.astimezone(utc) 23:00:00 # difference of UTC is 23h, ok, it's a short day... >>> print d1 - d0 1 day, 0:00:00 # now that's surprising!!! Well, it's actually consistent with the documentation that says that no utc conversion is done when the 2 dates have the same tzinfo, but I find it somewhat unintuitive in this case. Now, let's do the same with 2 different tzinfo instances, that have the same behaviour has the Local instance. >>> d0 = datetime(2003,3,30,tzinfo=LocalTimezone()) >>> print d0.dst() 0:00:00 >>> d1 = datetime(2003,3,31,tzinfo=LocalTimezone()) >>> print d1.dst() 1:00:00 >>> print d1.astimezone(utc) - d0.astimezone(utc) 23:00:00 # as expected >>> print d1 - d0 23:00:00 # as expected too So in this case it works, but should we create new tzinfo instances for each datetime we create. The sample tzinfo module seems to imply they are best used as singletons. From jeffr at euc.cx Wed Jul 30 14:50:56 2003 From: jeffr at euc.cx (Jeffrey P Shell) Date: Wed, 30 Jul 2003 12:50:56 -0600 Subject: Web tool kit : pro - cons ? In-Reply-To: <1059584280.12753.159.camel@lothlorien> Message-ID: On Wednesday, July 30, 2003, at 10:58 AM, Ian Bicking wrote: > On Wed, 2003-07-30 at 11:00, Jeffrey P Shell wrote: >>> PyDO and MiddleKit (Webware's) are both independent of their >>> frameworks >>> (it's kind of unfortunate that they appear to be tied, though), as >>> are >>> the other ORMs (like my SQLObject). All three provide something >>> approximating business objects built around database rows. >> >> They all put the model too close to the Python code for my personal >> comfort. Sometimes that's good. Other times, not so much. >> >> A couple of more interesting systems are Modeling ( >> http://modeling.sf.net/ ) and Ape ( >> http://hathaway.freezope.org/Software/Ape ). > > I don't really see the advantage of Modeling -- it seems terribly > verbose to me, though I suppose that's because of its origins in > Objective C. I don't see any advantage to separating the mapping from > the class -- it's all code, it's all written by the same people, and if > you need separate people to handle the pieces and you can't let them > both work with the same class, either you don't have enough > communication between people or you are making the whole thing a lot > more difficult than it should be. Modeling feels too formal to me -- > more like Java than Python. A Python ORM doesn't have to be hard. > > APE seems like the other side of formal, where it tries too hard to > seamlessly support every Python object and in the process is just > another object database (ala ZODB) that happens to be able to use a > relational database as a backend. But that's what makes it impressive - it's a fully abstract persistence system. The ZODB is very well designed, and has been in use for a good number of years and in many situations. Ape is a framework that lets you customize how that persistence happens. > A relational database cannot hold arbitrary Python objects unless you > want to ruin everything that's good about a relational database. What > notions of inheritance that can be implemented have significantly > different semantics than Python inheritance (and composition is usually > better than inheritance anyway, and that is well supported by > relational > databases). Attributes aren't columns, Python types aren't database > types. Relations are a different environment all around. I personally > can't see the use case where you'll want to radically change storage > mechanisms while leaving a business class alone. Yes, you may want to > radically change the storage -- but it only matters that the > *interface* > to that class can stay the same, not that the entire class > implementation is storage-neutral. A class shouldn't necessarily care about how its stored. A contact record is a contact record is a contact record. Storage shouldn't factor into the business object at all. Maybe ties to the persistence framework should factor in, but storage is a responsibility of the persistence framework. > That it requires some effort and > thought to move from an RDBMS to a flat file (for instance) is not a > big > problem in my mind. Moving from, say, Postgres to MySQL without effort > *is* nice, and achievable without having separate mapping objects. I > think if APE is going to be relational, it has to be more like an ORM. But Ape is not relational. It does files extremely well. I've thought about using it do deal with LDAP. It should take effort to move from an RDBMS to a flat file, but that effort shouldn't affect the main application classes - that's the responsibility of the persistence layer. In any case, I decided a few months ago to stop chasing the pure O-R mapping grail and went with a chain of data-operating business components instead of data-backed business objects. I realized that the read/write logic was part of my application more than it was part of the core model (the table definitions or LDAP schema), and went with an explicit system [1]. It's a similar set of patterns to those used by Ape, but implemented further up the application chain. I recently applied the same patterns to LDAP with pretty good results [2]. A module called 'forms.py' sits in the package and contains a host of Formulator form definitions, LDAP mappers (which set some flags on attributes, such as if its a single value and if it should be deleted when an empty/nonexistent value is passed to the Gateway which does the actual communication to the LDAP server), and - when needed - extra PreWrite / PostRead handlers which can apply extra logic to getting data for a particular objectClass combination out of the database (such as converting a number expressed in bytes to and from Megabytes for easier editing). Most application changes just require tweaking the 'forms.py' module to add another attribute and a widget/validator for it. So - the mapper file has extra benefits to my applications in that I get HTML form building and validation as part of the process. By dropping my earlier requirements of having a 'Contact' class that could map 1-1 with a RDBMS (or other system) and instead having a ContactMapper (semi-storage specific) and/or ContactSchema (storage agnostic - only there to provide rules), I've gotten some fairly robust applications that have surprised me (considering how the plan came into being and generally executed while watching the Sopranos). This is a similar system to Zope 3, which separates Schema (used as part of the Interface system) from implementation. Schema definitions allow you to write up nice contracts, such as "an 'age' value is an integer in the range of 0 - 150". They're completely implementation agnostic (as long as the implementation implements the interface). I'm looking forward to seeing that system settle out - I know it would make my LDAP application's schema definitions for Python a lot nicer to look at. [1] http://toulouse.amber.org/archives/2003/05/14/ component_relational_mapping.html [2] http://toulouse.amber.org/archives/2003/06/26/ applying_mapping_patterns_to_ldap.html J.Shell Eucci & Co. http://euc.cx/ Rive, finest recordings since 1994,2003 http://notype.com/rive/ From rsteiner at visi.com Tue Jul 8 04:48:01 2003 From: rsteiner at visi.com (Richard Steiner) Date: Tue, 08 Jul 2003 03:48:01 -0500 Subject: Collective memory References: <3F09F136.6060000@srv.net> Message-ID: Here in alt.folklore.computers, Dennis Lee Bieber spake unto us, saying: >Kevin Handy fed this fish to the penguins on Monday 07 July 2003 03:16 >pm: > >> In FORTRAN, certial columns were allocated to specific purposes. >> 1-5 for the line number, 6 for comment/continuation, 7-75 for the >> program line, 76-80 for sequence numbers. [iirc] > > > C in 1 for Comment Or an "*" in some compilers. > Anything in 6 for Continuation ...except a space. :-) -- -Rich Steiner >>>---> http://www.visi.com/~rsteiner >>>---> Eden Prairie, MN OS/2 + BeOS + Linux + Win95 + DOS + PC/GEOS = PC Hobbyist Heaven! :-) Now running in text mode on a PPro/200. Eat my dust, GUI freaks! The Theorem Theorem: If If, Then Then. From gumuz at looze.net Wed Jul 30 06:31:21 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 30 Jul 2003 12:31:21 +0200 Subject: funny slashdot quote regarding python 2.3 release Message-ID: <3f279da0$0$13799$4d4ebb8e@news.nl.uu.net> suspect that most time-critical code is not written in python. Depends on which time is critical: CPU time, or programmer time? -jcr From borcis at users.ch Tue Jul 29 10:26:06 2003 From: borcis at users.ch (Borcis) Date: Tue, 29 Jul 2003 16:26:06 +0200 Subject: Any Software can Python <-> Delphi ? References: <_icVa.1123902$ZC.164425@news.easynews.com> Message-ID: <3F2683FE.9050506@users.ch> Joe Francia wrote: > PythonMan wrote: > >> Any Software can change Python source code to Delphi ? >> thx >> > > You might find an easier time of it to embed your Python in Delphi, or, Beats me that people keep trying to achieve (necessarily idiomatic) machine translation of human languages, while the (clearly easier) problem of idiomatically translating between computer languages looks too hard for serious attention. From jdhunter at ace.bsd.uchicago.edu Mon Jul 21 17:10:57 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 21 Jul 2003 16:10:57 -0500 Subject: os.spawn[*] help In-Reply-To: (Stephen Boulet's message of "Mon, 21 Jul 2003 14:59:43 -0500") References: Message-ID: >>>>> "Stephen" == Stephen Boulet writes: Stephen> Can someone who understands the os module better than I Stephen> offer some insight? I want to open some text in xemacs Stephen> (on Windows) using os.spawn[*], but I want the text to Stephen> appear in the current xemacs window, as opposed to Stephen> opening a new xemacs window. Stephen> Is this doable? Thanks. Yep, check out emacs-server and emacs client. http://www-2.cs.cmu.edu/cgi-bin/info2www?(emacs)Emacs%2520Server http://www-2.cs.cmu.edu/cgi-bin/info2www?(emacs)Invoking%20emacsclient I have only used this for GNU emacs, but I assume XEmacs has the same or related functionality. In a nutshell, from within emacs run the function server-start. Then, create the text you want to feed to an existing emacs session, by writing to a temporary file: >>> file('somebuffer', 'w').write('Some message\n') and send it to the emacs server with >>> os.system('emacsclient "somebuffer") This will open the buffer 'somebuffer' in the already running emacs session with the text 'Some message' Do you know about pymacs BTW http://www.iro.umontreal.ca/~pinard/pymacs? John Hunter From andy at wild-flower.co.uk Sat Jul 19 09:16:42 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sat, 19 Jul 2003 14:16:42 +0100 Subject: __getitem__ and arguments In-Reply-To: <10eb079f.0307190110.30deb5b9@posting.google.com> References: <10eb079f.0307190110.30deb5b9@posting.google.com> Message-ID: <200307191416.42602.andy@wild-flower.co.uk> On Saturday 19 Jul 2003 10:10 am, KanZen wrote: > I'm trying to understand the difference between __setitem__ and an > > ordinary method. For example: > >>> class A(object): > > def __getitem__(self, *args): > print len(args) > def normalMethod(self, *args): > print len(args) > > >>> a=A() > >>> a.normalMethod(1, 2, 3) > > 3 > > >>> a[1, 2, 3] > > 1 > > For __getitem__() the arguments become a tuple. I can't seem to find > this in the language spec. Can anybody explain this to me? > > Thanks, > KanZen. Maybe the following will help: -------------8<---------- >>> class A(object): def __getitem__(self,*args): print args def test(self,*args): print args >>> a=A() >>> a[1] (1,) >>> a[1:2] (slice(1, 2, None),) >>> a.__getitem__(1) (1,) >>> a.test(1) (1,) -------------8<---------- This tells us what we could already guess from the formal parameter list: *args returns a tuple of the arguments. Try: -------------8<---------- >>> class A(object): def __getitem__(self,index): print index def test(self,index): print index >>> a=A() >>> a[1] 1 >>> a[1:2] slice(1, 2, None) >>> a.__getitem__(1) 1 >>> a.test(1) 1 -------------8<---------- As you can see, both methods do the same. I think you're just seening the effect of the variable arguments syntax. I'm sure a Guru will correct me if I'm wrong, but I don't see evidence of a 'special case' here... ;-) hth -andyj From martin at v.loewis.de Wed Jul 30 00:43:22 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2003 06:43:22 +0200 Subject: Upgrading python References: Message-ID: Stephen Boulet writes: > When I upgrade from 2.2.3 to 2.3 on windows, do I first uninstall 2.2.3? If you want to, you can have both 2.2 and 2.3 installed, side-by-side. If you want to replace 2.2, you should uninstall it first. Regards, Martin From imbosol at aerojockey.com Wed Jul 30 22:41:50 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 31 Jul 2003 02:41:50 GMT Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> Message-ID: Asun Friere wrote: > aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article , >> John Machin wrote: >> > >> >So ... could we please change that to "much kudos"? >> >> Nope. Kudos is a mass noun, but it's a discrete mass noun. So you need >> to say "many kudos". > > I believe it is customary to use the construction 'great kudos,' > which, in any case, you all deserve. Am I the only person to say "kudoi to everyone"? -- CARL BANKS From mhammond at skippinet.com.au Tue Jul 29 04:59:46 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 29 Jul 2003 18:59:46 +1000 Subject: Cannot register dll created using "py2exe --com-dll" In-Reply-To: <57de9986.0307290052.688e54c5@posting.google.com> References: <57de9986.0307290052.688e54c5@posting.google.com> Message-ID: Giles Brown wrote: > I'm feeling quite dumb this morning. > > I'm trying to build a COM server DLL using py2exe and it ain't working. Not too surprising seeing as it was checked in just days ago :) > > Command line for registering dll: > regsvr32 c:\pvcs\madeupname\model\dist\application.dll > > Result when I try to register dll: > """DllRegisterServer in c:\pvcs\madeupname\model\dist\application.dll failed. > Return code was: 0x80040201 > """ This generally just means that there was a Python exception. As regsvr is a GUI app, the exception is lost. You may like to add "import win32traceutil" at the top of your script (see win32traceutil.py for details) - or if that fails, at the top of boot_com_servers.py. > I have tried an exe server, but this does not register either. Try an EXE server build with the console flag set. This should allow you to see the exception without redirecting error output. > Also does anyone know what argument to use to get py2exe to build something > other than "application.[dll/exe]". I thought 'output_base' as an argument > to setup() would do it, but no joy. Can't recall - sorry. Mark. From reply.in.the.newsgroup at my.address.is.invalid Tue Jul 8 10:57:14 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 08 Jul 2003 16:57:14 +0200 Subject: COM Programming References: <6308fa3f.0307080220.5889317b@posting.google.com> Message-ID: TB: >Also has anybody got any references to more info about Python using >COM? http://safari.oreilly.com/JVXSL.asp?x=1&mode=section&sortKey=rank&sortOrder=desc&view=book&xmlid=1-56592-621-8&open=false&g=&srchText=python+win32&code=&h=&m=&l=1&catid=&s=1&b=1&f=1&t=1&c=1&u=1&r=&o=1&page=0 http://www.python.org/windows/win32com/ http://www.python.org/windows/win32/ -- Ren? Pijlman From terry at wayforward.net Thu Jul 10 11:16:27 2003 From: terry at wayforward.net (Terence Way) Date: Thu, 10 Jul 2003 11:16:27 -0400 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: Two companies that make money spring to mind: 1. sleepycat software (they support Berkeley DB); and 2. the MySQL folks (they support, um, MySQL) They have different licenses, MySQL being dual licensed: GPL and proprietary, while sleepycat is custom and OSI-compatible. My understanding is that they both make good money. -- I think you're right on target that accounting systems need customization... and you'll make money customizing it. Your only problem would then be marketing your product/service. Business people seldom read freshmeat, I fear. -- Don't worry about people reneging on support contracts. Companies get large enough, investors/directors will blow a fuse if they find out that the accounting system is unsupported: if you target the right companies the support checks will flow uninterrupted. If you're still worried about 'em, offer a pay-per-incident, like MS. -- If your product is good enough, *I* may be one of those consultants that uses your software, gets the support license, and uses it to support all my clients. This is a *good* thing. For one thing, any enhancements I add get folded into your product, so you and all your customers benefit. For another, I won't be claiming I wrote the thing: support by the original author of a product is still important. -- Consider the target company size. Given the $50-$100 support range, I'm thinking small companies < 10 people. Your support fee is way too low for larger companies. That is all. Hope this helps. From news at yebu.de Wed Jul 2 09:38:16 2003 From: news at yebu.de (Karl Scalet) Date: Wed, 02 Jul 2003 15:38:16 +0200 Subject: Problems with io. In-Reply-To: <8e35bad8.0307020516.55bb1ddc@posting.google.com> References: <8e35bad8.0307020516.55bb1ddc@posting.google.com> Message-ID: freone schrieb: > Hello, > some time ago I started to learn python, today i wanted make a very > samll and simple program. > file = open("test.txt", "r+") > file.readlines() > file.close() > And it doesn't work... > Why? Assuming file 'test.txt' exists, your program should work. In your case, you can ommit the + in 'r+', or the 'r+' alltogether. Also, choosing file as a variable is not a good idea, as it hides the builtin function (which could have been used as well instead of open()). What your problem might be, is not seeing anything as you do not fetch the result of fil.readlines(). So just do lines = fil.readlines() print lines #or for line in lines: print line > > (sorry for such ask but it is anonyoning me why it doesn't work, if u > don't reply i'll understand it) From m at moshez.org Wed Jul 16 10:33:22 2003 From: m at moshez.org (Moshe Zadka) Date: 16 Jul 2003 14:33:22 -0000 Subject: Choosing the right framework In-Reply-To: References: Message-ID: <20030716143322.11957.qmail@green.zadka.com> On Wed, 16 Jul 2003, "Carsten Gehling" wrote: > It'll probably be run behind an Apache httpd server, so I guess Twisted is > out of the question. Why, did Apache's reverse proxy module stop working suddenly? In general, I prefer configuring things via reverse proxies. The alternatives (like fast cgi or persistent CGI) looked like they were just as complicated as writing a web server in the first place, without the advantage of easy testability. [For that matter, this is also how I always configured Zope, too.] Note, however, that Twisted is *not* a web framework. It has a web server, but writing in that raw is much like writing raw mod_python code -- it's often useful, but most of the time, it is the wrong level of abstraction. Twisted's "official" templating system is Woven. However, Twisted also works with Quixote and it is quite possible to adapt other frameworks to it. And lest I forget, webtk[0] also runs on top of Twisted. It, is, however, still strange to me why you rejected Plone so carelessly as it *is*, actually, a CMS. Maybe you had good reasons too -- but until you explain those reasons, it will be hard to guess whether they apply to other web frameworks. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From Kepes.Krisztian at peto.hu Tue Jul 1 04:00:46 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Tue, 01 Jul 2003 10:00:46 +0200 Subject: Python - get key pressing Message-ID: Hi ! I want to create an py program what process datas for long time. But: I want to abort it if I need. Not with Ctrl+Break ! If I push a key (B, or other), the script must stop his work, and save the result created before. What I need to catch the keyboard events - without stopping a script ? Example: while False: DoWorkPeriodic() if KeyEvent=='B': SaveWork Stopit KK From nicola-mingotti_NO_spam at libero.it Wed Jul 30 03:56:10 2003 From: nicola-mingotti_NO_spam at libero.it (Nicola Mingotti) Date: Wed, 30 Jul 2003 09:56:10 +0200 Subject: Thank you developers for 2.3 -- correction References: Message-ID: On Wed, 30 Jul 2003 09:50:42 +0200, Nicola Mingotti wrote: > On Wed, 30 Jul 2003 08:21:09 +0200, Tino Lange wrote: > >> On Wed, 30 Jul 2003 05:35:02 GMT, David Lees >> wrote: >> >>> .... >>>2.3 5.04 sec >>>version 2.2.3 9.77 sec > >> ... >> By the way: What was/is the speed with 2.1.x on the same system? >> >> Emacs Sequence in Pan ... Mail left before completion :) On my pc it works if i put k = 0L instead of k= 0 > ... > t1 = time.time() > k = 0L > ... bye . From pyth at devel.trillke.net Tue Jul 8 15:16:31 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 8 Jul 2003 21:16:31 +0200 Subject: path module In-Reply-To: <1057690391.5396.68.camel@software1.logiplex.internal>; from LogiplexSoftware@earthlink.net on Tue, Jul 08, 2003 at 11:53:11AM -0700 References: <1057687291.8459.71.camel@lothlorien> <1057690391.5396.68.camel@software1.logiplex.internal> Message-ID: <20030708211631.K6906@prim.han.de> Cliff Wells wrote: > On Tue, 2003-07-08 at 11:01, Ian Bicking wrote: > > > Interesting, but I think a bad idea. I don't believe Python has been > > ported to Tops-20, and I'm not sure if there's a viable VMS port > > either. Most filesystems don't have the complexity that the Lisp > > pathname encapsulates. If someone was using VMS paths, I would assume > > they would subclass path for that OS, adding the portions that applied. > > I think it's unreasonable to expect people programming on normal > > platforms to pay attention to components like version, so even including > > it in a structured manner is asking for trouble. > > There is talk that Windows will have versioning in its next filesystem > (WinFS). It would surprise me if there weren't similar plans on the > Linux side. Right. Reiserfs plans this and Subversion has it (speaking about URLs here, not only local pathes). But i think the way you specify versions will be vastly different so the best bet probably is to pass an additional argument to a path-like object, e.g. for subversion fn = svnpath('py.py', rev=1050) or remotely fn = svnpath('http://.../py.py', rev=7362) where 'rev' specifies a revision number (which identifies exactly one state of a subversion-repository). Other than that, a 'svnpath' could probably behave like a regular local 'path' object, i guess. Hmmm, the above wouldn't be hard to do because svn has python bindings on all levels ... but enough advertisement :-) Either way, i believe that path/file versioning deserves some thoughts as it might be a "next big thing" (besides java and .NET, of course :-) cheers, holger From staschuk at telusplanet.net Tue Jul 22 06:30:37 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 22 Jul 2003 04:30:37 -0600 Subject: detecting containers during object introspection In-Reply-To: ; from davidcfox@post.harvard.edu on Tue, Jul 22, 2003 at 04:00:35AM +0000 References: Message-ID: <20030722043037.B576@tibia.amotlpaa.bogus> Quoth David C. Fox: [...] > However, the real problem occurs if the developer makes a change like > this (or even just adds a new attribute which is a non-standard > container), and does increment the version number. Because the version > number was incremented, the regression test would *expect* some of the > dictionary elements to change type or structure, and would simply update > the standard example dictionary. Then, any *subsequent* changes to the > structure of the values in that container would go undetected (unless > the developer had also updated the recursive comparison operation to > take into account that the unknown object was a container). Yes, I see. Thorny. What if your recursive comparison operation choked on values of unknown types rather than falling back on the weak "have same type" criterion? That way, the developer who changes the structure by introducing values of (e.g.) a new dict work-alike type would see tests fail, which would remind her to add to that comparison operation the necessary knowledge of the new type. Fail safe, in other words, where "safe" means "no false positives from the regression test". -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From randall at tnr.cc Wed Jul 9 19:02:21 2003 From: randall at tnr.cc (Randall Smith) Date: Wed, 09 Jul 2003 23:02:21 GMT Subject: Why Python In-Reply-To: <3f0be9ac@news.comindico.com.au> References: <3f0be9ac@news.comindico.com.au> Message-ID: <1a1Pa.56247$xg5.26938@twister.austin.rr.com> Tony Steward wrote: > Hello All, > I am looking for a programming language to use to write a database type > application to run on windows machines. Is python for me or pls suggest what > is. > > Is there a page that explains in simple terms what Python can do on windows? > Is there an IDE? > Is the windows api pre wrapped? > > Thanks > Tony > > Download the version for ActiveState. It has lots of Windows goodies. Randall From danbmil99 at yahoo.com Tue Jul 22 20:59:08 2003 From: danbmil99 at yahoo.com (dan) Date: 22 Jul 2003 17:59:08 -0700 Subject: python assignment Message-ID: without stirring the pot too much -- could someone please point me to whatever documentation exists on the philosophy, semantics, and practical implications of how Python implements the assignment operator? So far I can't find much useful in the regular documentation. I understand the basic concept that names are bound to objects which exist on the heap, but that still doesn't explain why a = b doesn't _always_ cause a to point to the same object as b. What determines when the object in question is copied? What determines when a future maniplulation of the variable will cause it to point to an object that is already referenced by another variable? (see code below for an example). What I need is an exact and unambiguous algorithm for determining when an assignment will change the id of the variable (or should I say, when the evaluation of an expression will cause a new object to be created). Some of the issues involved can be discerned from the following session: >>> a = 1 >>> b = a >>> a is b True >>> a += 1 >>> a -= 1 >>> a is b True >>> a = 1.0 >>> b = a >>> a is b True >>> a += 1 >>> a -= 1 >>> a is b False >>> a == b True From skip at pobox.com Tue Jul 15 11:14:25 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jul 2003 10:14:25 -0500 Subject: md5 consistent across platforms/Python versions? In-Reply-To: References: Message-ID: <16148.6737.800694.82908@montanaro.dyndns.org> Gary> Can someone tell me whether an MD5 hash using Python's MD5 library Gary> IS guaranteed to return the same results for the same input Gary> string, across platforms and Python versions? Gary, Yes, it is. MD5 is inherently platform- and language-independent. The test_md5.py script in the Python distribution uses the same test inputs as found in RFC 1321 and produces the same output as the C reference implementation contained in the RFC. Skip From buki at bukis.org Mon Jul 14 15:14:30 2003 From: buki at bukis.org (Andreas Bauer) Date: Mon, 14 Jul 2003 21:14:30 +0200 Subject: some questions References: <3f12f613$0$8731$9b622d9e@news.freenet.de> Message-ID: <3f130110$0$31819$9b622d9e@news.freenet.de> Andreas Bauer wrote: > Hi, > > I need some information on how to deal with strings which I have > divided by using split(). I'm new to python and don't know how to > handle these split up strings. > And I some one could recommend a good tutorial I would be very > glad. Can't hardly find any. > > Thanks in advance. > > Andreas Could anybody tell me how to hide a varibale e.g. in a url Example for i in (0,5): u = urllib.urlopen("http://www.versionxzy.com/page - here the variable e.g page1,page2,page3... -.html thanks Andi From mis6 at pitt.edu Fri Jul 18 08:01:47 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Jul 2003 05:01:47 -0700 Subject: feature request: a better str.endswith Message-ID: <2259b0e2.0307180401.5dae02f2@posting.google.com> I often feel the need to extend the string method ".endswith" to tuple arguments, in such a way to automatically check for multiple endings. For instance, here is a typical use case: if filename.endswith(('.jpg','.jpeg','.gif','.png')): print "This is a valid image file" Currently this is not valid Python and I must use the ugly if filename.endswith('.jpg') or filename.endswith('.jpeg') \ or filename.endswith('.gif') or filename.endswith('.png'): print "This is a valid image file" Of course a direct implementation is quite easy: import sys class Str(str): def endswith(self,suffix,start=0,end=sys.maxint):#not sure about sys.maxint endswith=super(Str,self).endswith if isinstance(suffix,tuple): return sum([endswith(s,start,end) for s in suffix]) # multi-or return endswith(suffix,start,end) if Str(filename).endswith(('.jpg','.jpeg','.gif','.png')): print "This is a valid image file" nevertheless I think this kind of checking is quite common and it would be worth to have it in standard Python. Any reaction, comment ? Michele From andre.lerche at update.com Fri Jul 11 11:39:17 2003 From: andre.lerche at update.com (Andre Lerche) Date: 11 Jul 2003 08:39:17 -0700 Subject: treeview / pygtk problem References: Message-ID: Hi Tim, Tim Gerla wrote in message news:... > On Thu, 2003-07-10 at 11:53, Andre Lerche wrote: > > Hi list, [...] > > renderer = g.CellRendererText () > > col1 = g.TreeViewColumn ("col 1", renderer, text=1) > > col2 = g.TreeViewColumn ("col 2", renderer, text=1) > ----^ > That's your problem right there: text= expects a sequence from 0 to n. > So try: > > col1 = g.TreeViewColumn ("col 1", renderer, text=0) > col2 = g.TreeViewColumn ("col 2", renderer, text=1) > > That should solve your problem! > > -Tim > tim at gerla.net Yes, this has solved my problem, I was really to dumb. Thanks, Andre From eddie at holyrood.ed.ac.uk Tue Jul 29 10:19:34 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 29 Jul 2003 14:19:34 +0000 (UTC) Subject: Python on a USB storage device? References: Message-ID: "Kevin Altis" writes: >Does anyone have experience running Python from a USB storage device? >Whether it is the need for doing a demo of your application, doing a bit of >consulting, or just showing off Python, it would be handy to be able to run >Python on machines that don't already have Python installed. I'm thinking >about giving this a try, but wondered if anyone is already doing it and the >downsides, if any? >CD-ROM is not very effective because the media is read-only and too big to >carry in your pocket. I think USB 2.0 is supposed to be roughly 20x faster >than USB for storage devices, but I'm guessing that if you can live with the >load times for machines that don't have USB 2.0, plain USB should still be >effective. >HP Windows desktops, Linux, and Mac OS X already have Python installed and >Mac OS X (Panther) will have Python 2.3. But even so, you generally have to >install additional packages to get the functionality you want. Having all >you need on a USB storage device and not needing to install anything on the >host machine seems like it would be very convenient. Yes, I have an oldish windows Python distribution on a 128Mb stick. It works quite nicely but you do have to be aware that without the usual registry entries it won't search for libraries etc. so well. I tend to keep all programs to be run in one directory. I also pruned lots of stuff out to minimise space used. It would be nice to have an installer that allowed you to selectively install core plus whatever you might actually want. Or maybe there is one, I'm not a windows person which is the whole reason for having this, it allows me to quickly do things on user's machines. It would work on Linux too except you need to have permission to create mount tables etc. to get the filesystem. {Network tip #4265: never ask whether something can be done, just state that it can't - that'll get you a lot more responses :)} Eddie From gordons_lists at gmx.net Fri Jul 11 19:21:57 2003 From: gordons_lists at gmx.net (Gordon Wetzstein) Date: Sat, 12 Jul 2003 01:21:57 +0200 (MEST) Subject: socket problem References: <20030711230938.GA22310@intarweb.us> Message-ID: <955.1057965717@www25.gmx.net> > On Sat, Jul 12, 2003 at 01:05:27AM +0200, Gordon Wetzstein wrote: > > Hello everyone, > > > > I have a problem with python sockets. I broadcast a lot of pickled > objects > > with socket. sendto(...), that works. Ireceive them on the other site > with > > socket.recvfrom(16384) The pickled objects are smaller (like 10000 > bytes) > > than the max bytes. > > > > The problem appears if I send too many pickled objects very quickly one > > after another, then I only receive a part of the sent objects. I print > > them before I send them, they are there but they never reach the > > destination. When I do a time.sleep(0.1) (but not lesser than 0.1) after > > socket.send() all is good but it's too slow! > > > > Does anyone know what the problem is? And maybe a solution! > > > > UDP is an inherently unreliable protocol. If you require reliable data > transmission, consider using TCP. > > Jp > > -- But then I can't use braodcast, can I? Gordon > -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ Jetzt ein- oder umsteigen und USB-Speicheruhr als Pr?mie sichern! From google at daishi.fastmail.fm Fri Jul 25 16:30:40 2003 From: google at daishi.fastmail.fm (daishi) Date: 25 Jul 2003 13:30:40 -0700 Subject: Using getattr to access inherited methods Message-ID: Hi, The following code appears to be doing what I'd expect, but I'm wondering if someone could confirm that there aren't any "gotchas" hidden in using methods accessed in this way. In particular, should I be concerned that in the example below, f is different from g and h when applying f to instances of test.Sub? For my simple example things appear reasonable, but ... Thanks, Daishi ---test.py class Super: def __init__(self): self.fn = None def applyFn(self, arg): if self.fn: return self.fn(arg) else: return "No function defined" class Sub(Super): def __init__(self): self.fn = self.aFn def aFn(self, x): return x+2 ---Python shell % python Python 2.2.3+ (#1, Jul 5 2003, 11:04:18) [GCC 3.3.1 20030626 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> test.Super >>> test.Sub >>> s = test.Sub() >>> s.__class__ >>> f = getattr(test.Super, 'applyFn') >>> g = getattr(test.Sub, 'applyFn') >>> h = getattr(s.__class__, 'applyFn') >>> f >>> g >>> h >>> f(s, 3) 5 >>> g(s, 3) 5 >>> h(s, 3) 5 >>> From noemail at nospam.com Thu Jul 3 20:10:32 2003 From: noemail at nospam.com (python newbie) Date: Fri, 04 Jul 2003 00:10:32 GMT Subject: trying to connect to Amazon web services References: Message-ID: This is what I get, by the way, when I running the script as shown in orig post. (yes I'm using my actual numbers for wishlist id and for amazon license). I inserted the 'number not shown' below. ----------------- http://xml.amazon.com/onca/xml?v=1.0&f=xml&t=webservices-20&dev-t= &type=heavy&page=1&WishlistSearch= Traceback (most recent call last): File "E:\MyProjects1\python\Amazon\getWishList.py", line 3, in ? mywishlist = amazon.searchByWishlist(' number not shown'); File "E:\MyProjects1\python\Amazon\amazon.py", line 297, in searchByWishlist return search("WishlistSearch", wishlistID, None, type, page, license_key, h ttp_proxy) File "E:\MyProjects1\python\Amazon\amazon.py", line 251, in search raise AmazonError, data.ErrorMsg amazon.AmazonError: We encountered an error processing your request. Please retr y. ---------------- "python newbie" wrote in message news:u0MMa.1116$ez7.28745829 at newssvr15.news.prodigy.com... > Hey Py fans, > I have two basic motivations that I'm going for. > > One, to learn Python. > > Another, to download the list of 92 books I have added to my Amazon wishlist > up to now, so that I could write a clean csv file of these books to my hard > drive. > > I downloaded the pyAmazon web services package, and read the code examples, > however ( and you probably don't even have to know about pyAmazon to be able > to offer a suggestion ) I'm not sure how to connect to the Internet. > > My script is so far, this: > ------------------- > import amazon > amazon.setLicense('< i put my number here >') > mywishlist = amazon.searchByWishlist(' < i put my number here >'); > ------------ > > .. I'm going to figure out how to get the book info from the 'mywishlist' > object later, but if I run this script like this, this doesn't connect to > the Internet or to Amazon. > > How would I do that, I'm wondering? > > Thanks > > From usenet at marnanel.org Tue Jul 29 16:54:55 2003 From: usenet at marnanel.org (Marnanel) Date: Tue, 29 Jul 2003 16:54:55 -0400 Subject: Showing IP address of a user... In-Reply-To: <7b454334.0307291005.53ee8c07@posting.google.com> References: <7b454334.0307291005.53ee8c07@posting.google.com> Message-ID: Fazer wrote: > I was wondering how I can show an IP address of a person who visits a > Python web-page? Would I have to use Environment variables to access > Apache's server variables which hold such values like in PHP or what? This is defined by the Common Gateway Interface, so it should be the same across all HTTP servers. It's certainly going to work the same way across all languages on the same HTTP server. os.environ is your friend: import os print 'Content-Type: text/plain' print print os.environ['REMOTE_ADDR'] ( has the specification of all the environment variables, in case you need more.) M From max at alcyone.com Sat Jul 12 19:12:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 16:12:29 -0700 Subject: new in town References: Message-ID: <3F1095DD.D890936@alcyone.com> Joe Francia wrote: > Gerhard is undeserving of your flippancy. I didn't detect flippancy, just a request for more concrete information. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Now I must follow them! \__/ Beowulf, King of the Geats From doug.hendricks at tnzi.com Wed Jul 30 00:11:25 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 29 Jul 2003 21:11:25 -0700 Subject: Python 2.3c2 References: Message-ID: Skip Montanaro wrote in message news:... > >>>>> "Doug" == the rev dharma roadkill writes: > > Doug> Just grabbed and tried it on Tru64 5.1A (hp/compaq alpha ES40): > Doug> Looks good: > Doug> make test gives: > Doug> ............ > Doug> 221 tests OK. > Doug> 34 tests skipped: > Doug> test_aepack test_al test_audioop test_bsddb test_bsddb3 test_bz2 > Doug> test_cd test_cl test_curses test_dl test_email_codecs test_gdbm > Doug> test_gl test_imageop test_imgfile test_linuxaudiodev test_locale > Doug> test_macfs test_macostools test_mpz test_nis test_normalization > Doug> test_ossaudiodev test_pep277 test_plistlib test_rgbimg > Doug> test_scriptpackages test_socket_ssl test_socketserver > Doug> test_sunaudiodev test_timeout test_urllibnet test_winreg > Doug> test_winsound > Doug> Ask someone to teach regrtest.py about which tests are > Doug> expected to get skipped on osf1V5. > > Doug, > > Can you confirm that you anticipate those skips on osf1V5? If so, I'll > the appropriate entry in regrtest.py. > > Also, assuming you're connected to a network, can you try: > > ./python Lib/test/regrtest.py -unetwork > > where you executed make test before? > > Thanks, > > Skip Sorry! I didn't look back here at this note until 2.3final was released (some help I am). I'm a python newbie so I'm not sure what to expect of test skipping. We don't have berkeley db or gdbm. We don't use our machine as a web server and most webby services are shut off. Our network and firewall are fairly restrictive. On running ./python Lib/test/regrtest.py -unetwork ON PYTHON 2.3FINAL we get: test test_socket_ssl crashed -- exceptions.IOError: [Errno socket error] (61, 'Connection refused') test test_timeout failed -- Traceback (most recent call last): File "/u13/home/doug/python/Python-2.3/Lib/test/test_timeout.py", line 127, in testRecvTimeout self.sock.connect(self.addr_remote) File "", line 1, in connect error: (61, 'Connection refused') test test_urllibnet failed -- errors occurred; run in verbose mode for details ... 222 tests OK. 3 tests failed: test_socket_ssl test_timeout test_urllibnet 30 tests skipped: test_aepack test_al test_audioop test_bsddb test_bsddb3 test_bz2 test_cd test_cl test_curses test_dl test_email_codecs test_gdbm test_gl test_imageop test_imgfile test_linuxaudiodev test_locale test_macfs test_macostools test_mpz test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_rgbimg test_scriptpackages test_sunaudiodev test_winreg test_winsound Ask someone to teach regrtest.py about which tests are expected to get skipped on osf1V5. Again, sorry I didn't get back to you sooner. I've only started to look at Python in the last few weeks. Doug From tjreedy at udel.edu Sat Jul 12 14:39:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2003 14:39:07 -0400 Subject: The "intellectual property" misnomer References: Message-ID: "Tim Peters" wrote in message news:mailman.1057978117.8939.python-list at python.org... > [Ben Finney] > > If the PSF holds the copyright to Python, please say that. > > > > If the PSF holds patents which cover Python, please say that. > > > > If the PSF owns the trademark for Python, please say that. > > > > If the PSF has trade secrets in Python, please say that. > > So you somehow managed to divine Guido's intent from that "ridiculous, > meaningless term" <0.5 wink> -- part of the PSF's business is indeed dealing > with all legalities affecting the use of Python. I don't think pedantic > verbosity makes it any clearer, but may mislead due to omission. In response to a query of mine, someone -- I believe you, Tim -- said that CNRI, not PSF, was still attempting to trademark 'Python' as applied to computer languages (but having some difficulty). Last I know, CNRI still has copyrights to Python 1.?-1.6. So I was a bit puzzled as to what Guido meant by his blanket statement. Has CNRI (and the Dutch institute before it) renounced its (their) 'IP' claims with respect to Python in favor of PSF? If not, then "The PSF holds the intellectual property rights for Python" would not be true as commonly interpreted, at least as by this commoner. (But then I know that Guido most definitely ain't a lawyer). Terry J. Reedy Terry J. Reedy From ny_r_marquez at yahoo.com Wed Jul 23 10:29:51 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 23 Jul 2003 07:29:51 -0700 Subject: Future Warning with win32com code Message-ID: <8a27e309.0307230629.66d15fd8@posting.google.com> I finally got around to start testing some of my old apps with Python 2.3. I've had no problems so far, but I did get one intriging warning. The following is from the Python Command Line: Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client >>> ie=win32com.client.DispatchEx('InternetExplorer.Application.1') >>> ie.Navigate('http://webserver/SomePage.asp') >>> print ie.ReadyState D:\Py23\lib\site-packages\win32com\client\dynamic.py:446: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.dispid) 4 >>> The code works well, as can be seen by the returned result. But what I want to know is what needs to be done to avoid any problems in the future, with 2.4. Should I submit this to the Win32 extensions project? Or is it so obvious that it will undoubtedly by resolved and I shouldn't worry about it? From ianb at colorstudy.com Fri Jul 4 02:27:44 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 04 Jul 2003 01:27:44 -0500 Subject: CGI script is in plain text In-Reply-To: <3F052F2F.1426.547BB32@localhost> References: <3F04B0A4.32692.3596CD0@localhost> <3F052F2F.1426.547BB32@localhost> Message-ID: <1057300063.13132.30.camel@lothlorien> On Fri, 2003-07-04 at 00:39, BMA TRADING wrote: > > Try renaming the file to .cgi -- as long as the #! line is right, it > > doesn't matter the extension. Also, you may have to put the script in > > the cgi-bin directory. > > > > Ian > > > Dear Ian, > Thank you for your reply. > I tried to rename it but it does NOT work. > In the same directory I can successfully run Perl script( .pl extension) but no Python > scripts. > Any idea? Well, be sure the file is set as executable ("chmod +x filename"). If all else fails, try a .pl extension :) Who knows... might just work. Ian From madsurfer2000 at hotmail.com Sun Jul 20 12:28:36 2003 From: madsurfer2000 at hotmail.com (-) Date: 20 Jul 2003 09:28:36 -0700 Subject: Strings and Unicode References: Message-ID: I wrote: > I have a function that takes a string as an input parameter. This > function then urlencodes the string and sends it to a server with > telnetlib.Telnet > > The problem is that the string gets converted into what seems to be > Unicode. How can I check to see if the input-string is Unicode and > convert it to a different character set (in this case ISO-Latin1). I see that my question may have been asked in the wrong way, so here's more details: I'm using Python 2.2.2. under Windows XP. The function I was talking about actually takes two strings, and I send both parameters to the urlencode function. The urlencode-function I use is imported from urllib. My function: def addPOSTParam(self,name,value): param = urlencode({name: value}) self.POSTParameters.append(param) Example: client.addPOSTParam("param","abc ?") POSTParameters then looks like: ['param=abc+%C3%A6'] Here, the '?' character is converted into what seems to be Unicode I would have expected the following: ['param=abc+%E6'] type(value) gives: I probably should have tested type() before, because it seems to be a standard string. Hope this explains my problem better. As you probably have guessed I'm trying to send information to a web-server, but since this is mostly a project for learning, I don't want to use the included HTTP classes. From djc at object-craft.com.au Mon Jul 14 00:25:12 2003 From: djc at object-craft.com.au (Dave Cole) Date: 14 Jul 2003 14:25:12 +1000 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: >>>>> "Bernard" == Bernard Delm?e writes: >> I'm hoping someone can help me. I've downloaded the csv.pyd file >> from http://www.object-craft.com.au/projects/csv/download.html and >> put it into my C:\Python22\DLLs directory. Bernard> Mmh...works for me - ActivePython 2.2.2 Are you sure you Bernard> downloaded the pyd file corresponding to your python version? Bernard> Running the MS "depends" utility on csv.pyd reveals that it Bernard> only needs python22.dll, msvcrt.dll and kernel32.dll. Are Bernard> these all on your PATH? >> Traceback (most recent call last): File "", line 1, in ? >> import csv Bernard> What's pyshell? did you try from good ole trusty python.exe Bernard> in a DOS box? Try putting the .pyd in C:\Python22\Lib\site-packages - Dave -- http://www.object-craft.com.au From max at alcyone.com Wed Jul 2 03:12:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 00:12:48 -0700 Subject: Good code patterns in Python References: Message-ID: <3F0285F0.EDF697E3@alcyone.com> Kirk Job-Sluder wrote: > Will Stuyvesant wrote: > > > If you know that your source code is going to be used > > later by others, then I feel that code with the pattern: > > > > if some_condition: > > some_name = some_value > > else: > > some_name = other_value > > > > is often a mistake. Much better, safer, would be: > > > > some_name = some_value > > if not some_condition: > > some_name = other_value > > > > Why? > > My personal opinion is that it depends on context. The first idiom > is more clear when you are dealing with some kind of a switch. The > second idiom works better if you have a default value that needs to be > overridden in some cases. I presume the "mistake" he's referring to with the first snippet is the potential problem that could happen if the variable is named incorrectly: if condition: variable = someValue else: varaible = otherValue # [sic] note the typo! When you really want an atomic assignment of one singular variable. The complete solution to this would probably be a conditional expression, e.g.: variable = (if condition: someValue else: otherValue) eliminating the duplication which can lead to errors. (Python, of course, doesn't have such a construct, and the silence after the conditional expression PEP vote and the long silence thereafter suggests that it never will.) I still don't think this significant of a risk to warrant widespread conversion of statements to the form Will suggests, especially when you have things like PyChecker that can check for (probable) typos. It's a slightly unfortunate wart in dynamic languages without conditional operators, but I don't think it rises to the level of something that should be corrected via such (what seems to me) a heavy-handed style. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ When the solution is simple, God is answering. \__/ Albert Einstein From sismex01 at hebmex.com Wed Jul 2 12:05:29 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 2 Jul 2003 11:05:29 -0500 Subject: My Big Dict. Message-ID: > From: psimmo60 at hotmail.com [mailto:psimmo60 at hotmail.com] > Sent: Mi?rcoles, 02 de Julio de 2003 08:32 a.m. > > [...snippage...] > > d={} > for l in file("test.txt"): > try: i=l.index('!') > except ValueError: continue > d[l[:i]]=l[i+1:] > > This example is *almost* ideal; how about, instead of using .index and slices, let the computer do s'more of your work: D = {} for line in file("test.txt"): try: k,v = line.split("!",1) D[k] = v.strip() except ValueError: continue and presto. split() takes an optional second argument which specifies the maximum number of splits it's allowed to perform. Also, although I've kept your basic code form, it's bad style to not explicitly close any opened files, unless you absolutely know they're going to close once the operation finishes. -gustavo -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From jack at performancedrivers.com Tue Jul 15 10:40:39 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 15 Jul 2003 10:40:39 -0400 Subject: Confusing automated translators. In-Reply-To: ; from pinard@iro.umontreal.ca on Tue, Jul 15, 2003 at 10:24:17AM -0400 References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: <20030715104039.F1005@localhost.localdomain> On Tue, Jul 15, 2003 at 10:24:17AM -0400, Francois Pinard wrote: > [John J. Lee] > > > Alan Kennedy writes: > > > > I'd love to hear of other similar phrases. And somehow I intuit > > > there's people in this ng who know lots of them :-) > > > There are so many... > > Automated translators which ignore punctuation are pretty fragile, too. > Here is a case where the exact same words are used, besides punctuation. My favorite example is comifying a list. "1, 2, and 3" vs "1, 2 and 3" (journalist seem to prefer the later) "I dedicate this book to my parents, Jane, and God." "I dedicate this book to my parents, Jane and God." -jack From heafnerj at spam.vnet.net Tue Jul 15 09:39:07 2003 From: heafnerj at spam.vnet.net (Joe Heafner) Date: Tue, 15 Jul 2003 08:39:07 -0500 Subject: Mac OS X, Fink, Python, and web browser Message-ID: Hi. I'm running Mac OS X (10.2.6), Fink 0.5.3, Python2.2 and all requisite libraries, VPython (http://www.vpython.org). VPython comes with and installs IDLE_fork. Pressing F1 inside IDLE_fork is supposed to bring up help documents in the system's default web browser. Could someone please tell me where and how to get IDLE_fork to use Safari (1.0)? JH From mmuller at enduden.spam.filter.com Fri Jul 25 16:47:14 2003 From: mmuller at enduden.spam.filter.com (Michael Muller) Date: Fri, 25 Jul 2003 16:47:14 -0400 Subject: Static typing References: Message-ID: Thanks for bringing Pyrex to my attention: I haven't seen it before and it looks like a really nice tool for writing extensions. In article , "Terry Reedy" wrote: > AFAIK, There is no consensus and no concrete plans for Python itself. > However, there are various third party efforts. Pyrex is, in part, > Python + type declarations for C compilation. Weave implicitly types > vars as ints or floats. Psyco make declaration unnecessary. Terry J. > Reedy > -- Remove the spam and filter components to get my e-mail address. From afriere at yahoo.co.uk Thu Jul 31 22:34:30 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 31 Jul 2003 19:34:30 -0700 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <38ec68a6.0307301841.dfb951a@posting.google.com> Message-ID: <38ec68a6.0307311834.7f96017b@posting.google.com> ansible at typhoon.xnet.com (James Graves) wrote in message news:... > That's handy. I had known about 'set expandtab' for a while, but I > wanted to figure out how to use it for just Python. Note how Keith Jones, in the following post, achieves the same: au FileType python set et I wasn't aware of the 'FileType' setting, but it has the advantage of working with files which vim recognises as python source, but which don't necessarily end in 'py'. Nice! From bokr at oz.net Mon Jul 28 22:07:14 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 02:07:14 GMT Subject: pretty printing graphs References: Message-ID: On Mon, 28 Jul 2003 12:13:10 -0500, John Hunter wrote: > >I have a tree structure (directed acyclic graph), where each node can >represent itself as a multi-line string that is not very wide (eg, 10 >chars per line). I would like to print the graph like > > C > C1 C2 >C1a C1b C2a C2b > The outline format is not good? I.e., C C1 C1a C1b C2 C2a C2b An outline would be simple to print recursively. [... snip code etc ...] > >This does part of the work, printing the child nodes on the same rows, >but doesn't the hierarchical part very well. What I would like is >something like this: > > 1 2 3 0 > 1 2 3 4 > 1 2 1 5 > 1 2 1 1 > 4 3 2 2 > 4 3 2 7 > 2 3 2 3 > 2 3 2 9 > > 1 2 3 0 4 3 2 2 > 1 2 3 4 4 3 2 7 > 1 2 1 5 2 3 2 3 > 1 2 1 1 2 3 2 9 > ---------- ---------- > 1 1 0 0 0 1 1 0 > > >1 2 1 5 1 2 3 0 2 3 2 3 4 3 2 2 >1 2 1 1 1 2 3 4 2 3 2 9 4 3 2 7 >---------- ---------- ---------- ---------- >1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 > > > How about (I added a name in the first node line for debugging, and boxing): (code follows output). Not tested much ;-) [19:04] C:\pywk\clp>python pphunter.py +----------+ | n0| |1 2 3 0| |1 2 3 4| |1 2 1 5| |1 2 1 1| |4 3 2 2| |4 3 2 7| |2 3 2 3| |2 3 2 9| +----------+ +----------+ +----------+ | n1| | n2| |1 2 3 0| |4 3 2 2| |1 2 3 4| |4 3 2 7| |1 2 1 5| |2 3 2 3| |1 2 1 1| |2 3 2 9| |----------| |----------| |1 1 0 0| |0 1 1 0| +----------+ +----------+ +----------+ +----------+ +----------+ +----------+ | n1a| | n1b| | n2a| | n2b| |1 2 1 5| |1 2 3 0| |2 3 2 3| |4 3 2 2| |1 2 1 1| |1 2 3 4| |2 3 2 9| |4 3 2 7| |----------| |----------| |----------| |----------| |1 1 1 0| |1 1 1 0| |1 1 1 0| |1 1 1 0| +----------+ +----------+ +----------+ +----------+ ====< pphunter.py >============================================== from __future__ import division, generators def enumerate(seq): "Waiting for python 2.3" for i in range(len(seq)): yield i, seq[i] class TextBox: def __init__(self, text): self.text = text lines = text.splitlines() self.bb = len(lines)+2, max(map(len, lines))+2 # rows,cols bounding box def __str__(self): return self.text class Node: PageHeight = 6*11; PageWidth = 78 def __repr__(self): return ''%self.textBox.text.splitlines()[0] def treebb(self): # tree bb incl this node childMaxHeight, childTotWidth = 0, 0 for child in self.children: h, w = child.treebb() childMaxHeight = max(childMaxHeight, h) childTotWidth += w ret = childMaxHeight+self.textBox.bb[0], max(childTotWidth, self.textBox.bb[1]) return ret def __init__(self, textBox): self.textBox = textBox self.children = [] def boxlines(node, boxHeight, boxWidth): oh, ow = node.textBox.bb # this node top text box bb th, tw = node.treebb() # minimal child tree bb incl text box at top render = ['']*boxHeight ofmt = '|%%%ds|'% (ow-2) render[0] = ('+'+'-'*(ow-2)+'+').center(boxWidth) iLine=1 for line in node.textBox.text.splitlines(): render[iLine] = (ofmt%line).center(boxWidth) iLine += 1 render[iLine] = render[0] iLine += 1 if node.children: availSepSpaces = boxWidth - tw nch = len(node.children) sep = nch>1 and availSepSpaces//nch or 0 childBoxes = [] for child in node.children: chh, chw = child.treebb() childBoxes.append(child.boxlines(boxHeight-oh-1, sep and chw+sep or boxWidth)) cbhs = map(len, childBoxes); assert max(cbhs)==min(cbhs) # all child boxes same ht for iChildline in xrange(cbhs[0]): iLine += 1 render[iLine] = ''.join( [childBox[iChildline] for childBox in childBoxes] ).center(boxWidth) for iLine in range(boxHeight): if not render[iLine]: render[iLine] = ' '*boxWidth return render def __str__(self): return '\n'.join(self.boxlines(self.PageHeight, self.PageWidth)) def showInPage(self, pageHeight=6*11, pageWidth=78): return '\n'.join(self.boxlines(PageHeight, PageWidth)) def test(): n0 = Node(TextBox("""n0 1 2 3 0 1 2 3 4 1 2 1 5 1 2 1 1 4 3 2 2 4 3 2 7 2 3 2 3 2 3 2 9 """)) n1 = Node(TextBox("""n1 1 2 3 0 1 2 3 4 1 2 1 5 1 2 1 1 ---------- 1 1 0 0 """)) n2 = Node(TextBox("""n2 4 3 2 2 4 3 2 7 2 3 2 3 2 3 2 9 ---------- 0 1 1 0 """)) n1a = Node(TextBox("""n1a 1 2 1 5 1 2 1 1 ---------- 1 1 1 0 """)) n1b = Node(TextBox("""n1b 1 2 3 0 1 2 3 4 ---------- 1 1 1 0 """)) n2a = Node(TextBox("""n2a 2 3 2 3 2 3 2 9 ---------- 1 1 1 0 """)) n2b = Node(TextBox("""n2b 4 3 2 2 4 3 2 7 ---------- 1 1 1 0 """)) n0.children.extend([n1, n2]) n1.children.extend([n1a, n1b]) n2.children.extend([n2a, n2b]) print n0 if __name__ == '__main__': test() ================================================================= Regards, Bengt Richter From ianb at colorstudy.com Mon Jul 7 16:01:12 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 07 Jul 2003 15:01:12 -0500 Subject: Python vs PHP In-Reply-To: <3F094FA4.9030800@ploiesti.astral.ro> References: <3F094FA4.9030800@ploiesti.astral.ro> Message-ID: <1057608071.5348.320.camel@lothlorien> On Mon, 2003-07-07 at 05:47, Catalin wrote: > Can Python replace PHP? > Can I use a python program to make an interface to a mysql 4.X database? > If that's possible where can I find a tutorial? Unlike PHP, Python does not have a single model for creating web pages. See http://www.python.org/cgi-bin/moinmoin/WebProgramming for a slightly intimidating list of options. If you feel comfortable with PHP, I would advise using a similar system in Python, probably Spyce. Webware also has a PSP component, which is slightly more like JSP than ASP (and PHP is more like ASP). I believe mod_python will have a PSP option (but I don't know where or if it's finished). What you should remember when moving away from PHP, is that you no longer have to use the server-page metaphor -- most of your application logic should be in plain Python modules. Then you'll use your PSP (or similar) page to present that code and respond to user input. Python has good database access, look for MySQLdb, and the DB-API documentation applies as well. There's several wrappers to make database programming easier, see: http://www.python.org/cgi-bin/moinmoin/HigherLevelDatabaseProgramming For MySQL there's my own wrapper, SQLObject, as well as MiddleKi, PyDO, and dbObj. For something a little lighter you might want to try SQLDict for ll.sql -- I think you will find even these simple wrappers will take a huge weight off your program compared to normal PHP MySQL usage. Ian From jeremy at alum.mit.edu Tue Jul 8 08:54:44 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 08 Jul 2003 08:54:44 -0400 Subject: urllib2 for HTTPS/SSL In-Reply-To: <153fa67.0307080233.2f7abdf5@posting.google.com> References: <153fa67.0307080233.2f7abdf5@posting.google.com> Message-ID: <1057668883.2342.17.camel@slothrop.zope.com> On Tue, 2003-07-08 at 06:33, Kylotan wrote: > The documentation on this module doesn't seem very clear to me... > there's an 'HTTPSHandler' object documented, but it just lists the > "https_open" function without giving an example of its use. And the > urllib2 examples page shows a totally different way to create an HTTPS > connection (just by making a Request object). There is a lot of talk > about deriving new classes, but is that necessary if I just want to > make HTTPS GET requests? > > I have no idea how (or if) to use the 'HTTPSHandler' object, or what > the correct way for me to request an SSL connection is. Does anybody > have any hints? And additionally, is there any chance of the official > documentation on this useful-looking module being improved? Unless I misunderstand your intent, you don't need to use the Handler object directly. HTTPS support is provided automatically, so long as your local Python has SSL support. (It should.) Here's an example: f = urllib2.urlopen("https://sf.net/") buf = f.read() f.close() The module is included in the standard library docs. They are brief, but do provide some examples: http://www.python.org/dev/doc/devel/lib/urllib2-examples.html Jeremy From tomas at fancy.org Tue Jul 15 18:16:40 2003 From: tomas at fancy.org (Tom Plunket) Date: Tue, 15 Jul 2003 15:16:40 -0700 Subject: anything like C++ references? References: Message-ID: Stephen Horne wrote: > std::string x = "123"; > std::string y = x; > > // At this point, in most implementations, x and y are bound to the > // same object due to a lazy copy optimisation. Actually, that isn't the case these days. I'm sure there are some who do this optimization still, but it is incredibly hard to do so in a thread-safe manner so all of the heavies as far as I know don't do it anymore. -tom! -- There's really no reason to send a copy of your followup to my email address, so please don't. From nushin2 at yahoo.com Mon Jul 28 22:33:36 2003 From: nushin2 at yahoo.com (nushin) Date: 28 Jul 2003 19:33:36 -0700 Subject: How to disable output messages of the child process, in spawnv( )? References: <3f1eddc9$0$160$a1866201@newsreader.visi.com> <1059059614.658900@yasure> Message-ID: Thanks Donn. I resolved the issue. If i do the following the output of the child process is disabled: os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python hello.py >/dev/null &')) but, if some one needs to see the output of the child process spawned by parent, then this does it: os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) (I believe in Python tricks :-) Regards, Nushin "Donn Cave" wrote in message news:<1059059614.658900 at yasure>... > Quoth nushin2 at yahoo.com (nushin): > | Is there any trick to disable the output of a child process spawned by > | spawnv( ) API? > > No. > > | I believe in Python and i am sure there's a way around it. Correct me > | if i am wrong. > > You believe in tricks, is the problem. Read what people are telling you. > You can redirect output of a command, you can do it Python, but the only > way to do it in spawnv is to make spawnv execute a shell command. > > Donn Cave, donn at drizzle.com > > | grante at visi.com (Grant Edwards) wrote in message news:<3f1eddc9$0$160$a1866201 at newsreader.visi.com>... > |> In article , nushin wrote: > |> > I'd like to disable the output of the process spawned by spawnv( ) > |> > API, but the catch is that i *have to* see the output of the parent > |> > process making the spawnv( ) call. Has anyone done that? I have some > |> > pointers that by using dup2( ) API i might be able to do that, any > |> > ideas how? Also, i have to spawn as an asynch call, using P_NOWAIT, > |> > e.g.,: > |> > > |> > os.spawnv(os.P_NOWAIT,'/usr/bin/python',('python','hello.py'),('>/dev/null &')) > |> > |> Nope. > |> > |> The ">" and "&" are things that a shell (like bash or ksh) > |> handles. The python interpreter has no idea what to do with > |> them. If you want to use ">" and "&", then spawn a shell, and > |> pass it a command to run the python program with output > |> redirected. From fredrik at pythonware.com Wed Jul 9 04:10:24 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Jul 2003 10:10:24 +0200 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: Fernando Perez wrote: > For barcodes, use png, tiff or even gif (the patents expired recently). note that PIL's GIF generator uses run-length encoding, so the Unisys LZW patents won't matter here. From tim.one at comcast.net Mon Jul 7 00:41:27 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 7 Jul 2003 00:41:27 -0400 Subject: anything new on the ternary operator? In-Reply-To: <5.2.1.1.0.20030706171559.02597288@66.28.54.253> Message-ID: [Bob Gailer] > Last I heard it was killed by Guido, Confirmed (I asked him; he answered ). > which makes me wonder why we spent so much time discussing and voting. If he had accepted it, people who were opposed to it may have wondered the same thing. IOW, the specific outcome doesn't appear to have anything to do with the gist of what you're saying, here or below. > If he did not want it I wish he had killed it at the start. Likewise, if he did want it, I wish he had accepted it at the start. But he said at the start that he was neither opposed nor in favor, so neither form of this conditional gets off the ground. > I thought the vote was to determine the best choice, and I was looking > forward to having it. There were many creative interpretations of the vote counts, but none of them showed the consensus Guido said at the start would be needed for adoption. > Makes me wonder about the whole PEP process. Voting isn't a normal part of the PEP process. This was the second vote in Python's history. The first was to pick whether "i" or "j" would be used to denote imaginary literals (another case where Guido had no preference). The "i" camp still complains about that one too <0.9j wink>. > Why bother! For you with perfect hindsight, or for Guido with perfect foresight, there wouldn't have been any point. Given that the outcome wasn't known in advance, there was some point at the time. From egbert.list at hccnet.nl Thu Jul 24 17:44:57 2003 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Thu, 24 Jul 2003 23:44:57 +0200 Subject: Don't want to do the regexp test twice Message-ID: <20030724214457.GA874@mirk.lan> While looping over a long list (with file records) I use an (also long) if..elif sequence. One of these elif's tests a regular expression, and if the test succeeds, I want to use a part of the match. Something like this: pat = re.compile(r'...') for line in mylist: if ... : .... elif ... : .... elif pat.search(line): mat = pat.search(line) elif ... : ... else ...: ... Is there a way to to do this job with only one pat.search(line) ? Of course I can do this: for line in mylist: mat = pat.search(line) if ...: .... elif ...: .... elif mat: ... but the test is relevant in only a relatively small number of cases. And i would like to know if there exists a general solution for this kind of problem. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From andersjm at dancontrol.dk Tue Jul 29 11:41:06 2003 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Tue, 29 Jul 2003 17:41:06 +0200 Subject: variable assignment in "while" loop References: Message-ID: <3f2695ca$0$76124$edfadb0f@dread11.news.tele.dk> "Aahz" wrote: > > Peter usually gives a good answer, but this time there's a better > answer: With a bug, but if we combine Peter's answer with yours we get an even better answer: def fetch_iter(mydbcursor): while 1: info = mydbcursor.fetchone() if not info: break yield info - Anders From steve at ferg.org Fri Jul 4 11:46:03 2003 From: steve at ferg.org (Stephen Ferg) Date: 4 Jul 2003 08:46:03 -0700 Subject: Python Code Snippets References: Message-ID: http://www.ferg.org/grimoire/grimoire.html From vincent_delft at yahoo.com Sun Jul 13 11:22:58 2003 From: vincent_delft at yahoo.com (vincent delft) Date: 13 Jul 2003 08:22:58 -0700 Subject: CGIHTTPserver looze PYTHONPATH Message-ID: <5c184570.0307130722.2c74879c@posting.google.com> I'm using Python 2.2.2 the standard cgihttpserver (example given in the python doc). All HTML and CGI work. BUT by writing a simple python-cgi script like this : " #!/usr/bin/env python import os print "%s" % os.environ " I've discover that the environement variable are lost. For example PYTHONPATH is no more present. Can you explain me why ? Does this is a bug ? How can I keep my PYTHONPATH variable across my python-cgi ? (I don't want to add os.putenv on top of each python-cgi script) Thanks From sschwarzer at sschwarzer.net Sat Jul 26 15:46:47 2003 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 26 Jul 2003 21:46:47 +0200 Subject: Standard behaviour of a getSomething method In-Reply-To: References: Message-ID: Mike Rovner wrote: > Batista, Facundo wrote: > >> When I want to know about a attribute (e.g.: myAttrib) of an object, I >> should use the specific method (e.g.: getMyAttrib). > > Python don't enforce nor encourage attribute hiding, > so don't do it unless you have a good reason. > Plain access to attributes is simple: > myObject.myAttribute I think, you should hide an attribute if it doesn't refer to the object's abstract interface but instead merely depends on the implementation. In that case, you shouldn't provide any means to access the attribute directly, be it via direct attribute access or accessor methods. Somewhat, I dislike the sometimes recommended __getattr__/__setattr__ approach. I wouldn't like to have something like def __getattr__(self, name): if name == '...': ... elif name == '...': ... ... else: raise AttributeError("%s has no attribute %s" % (self.__class__, name)) but prefer modifying only the corresponding get/set method(s). But, if I had lots of get/set methods, I would surely use the __getattr__/__setattr__ approach or generate the get/set methods "automatically", with a function like make_accessors.make_accessors(cls, "foo bar baz spam eggs") which would generate def foo(self): return self._foo def set_foo(self, new_foo): self._foo = new_foo and the other accessor methods, if they are not yet defined otherwise. This can be done easily with Python. In one project, we use a similar method to generate accessor methods for persistent objects to be stored in a database. Here, the accessors (which correspond to the "public" database columns in a table row) are a bit more complicated. >> Considering that this attribute is always another object (everything >> is an object in Python), what should getMyAttrib do? >> >> 1) Return the object >> 2) Return a copy of the object Because returning a copy is seldom needed, I prefer returning the object itself. If it's an immutable object, the difference doesn't matter, anyway. If it's a mutable object, you should note the access semantics in the docstring, as someone else pointed out. Stefan From tomas at fancy.org Mon Jul 14 20:48:31 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 17:48:31 -0700 Subject: anything like C++ references? References: Message-ID: sismex01 wrote: > > What I specifically want is a way to have a "second-level > > binding", e.g. a reference to a reference (assuming that the > > terminology is correct by saying that all Python variables are > > references). > > What for? What would be the practical use for such a thing? "Why would you want a bike when you have a car?" I would say that I wanted it because I thought it would be the most straight-forward solution to the problem, so I thought I'd ask. I saw the weakref docs, but it didn't seem to do what I expected it to do, so I asked the question. ;) At this point, I'm not entirely sure what use weakref has, since it seems to only provide the same mechanism that exists already through assignment. > To rebind a name remotely? It's not very consistent with the > rest of the language. hmm. def fn(b): b.val = 4 class MyClass: pass a = MyClass() a.val = 3 fn(a) print a.val This name was rebound remotely. I'm not trying to be difficult, but this does seem like much the same thing if not a bit more heavy-weight than what I'm asking about. > To have functions which rebind a name in a hidden way seems > to me like a veritable fountain of possible bugs. Explicit > is better than implicit and all that. and OO will never take hold, either. ;) Just look at all of the behind-the-scenes that's going on! > Those operations might have sense in a language where a variable > name is directly related to a storage location, a memory address; > but Python is not like that, and trying to program in that style > in Python is quite painful. That's why I'm not trying to program in that style, but in a new style that seems to me to be in the Python way, if not (yet? ) supported by the language. > I find Python to be quite clear and powerful, and never have needed > such functionality in all the different type of projects I've done, > small-to-medium, but varied: SQL parsers, XML parsers, email > messaging systems, GUI frontends, RPC servers and clients, > text-formatting utilities, etc... I've never found a single > instance where I would have needed such that. I've never needed the subtraction operator, myself. Every time I used it, I could have used a negate and an add, but I used the subtraction operator instead. Just because functionality isn't strictly needed doesn't mean it's not useful. -tom! From Marco.LaRosa at csiro.au Mon Jul 28 21:49:28 2003 From: Marco.LaRosa at csiro.au (Marco.LaRosa at csiro.au) Date: Tue, 29 Jul 2003 11:49:28 +1000 Subject: 2 questions: py2exe with chaco AND dendrograms Message-ID: Hi all, 1st question: Has anyone used py2exe on an app which chaco - if yes, were there any problems? 2nd question: Does anyone know of a python routine/package for calculating/displaying dendrograms Cheers, Marco -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sat Jul 26 20:47:58 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 01:47:58 +0100 Subject: emacs python-mode questions: C-c C-c and broken docstring fill Message-ID: <87ptjwre0x.fsf@pobox.com> 1. Why do I get this in my minibuffer when I do C-c C-c in a python-mode buffer containing the following valid Python code? Wrong type argument: sequencep, cpython ----START #!/usr/bin/env python print "hello, world" ----END 2. A while ago I 'upgraded' to a version of python-mode (from somewhere on sourceforge, I think -- perhaps Python CVS, don't remember) which somebody here claimed was able to fill comments without needing blank lines before and after the comment. It does do that, but the new version also breaks filling text in docstrings (under particular circumstances which I haven't figured out, but which occurs very frequently). I get something like: "The parameter start is not the beginning of a python string". Where does the latest python-mode live, and is this fill bug with docstrings fixed? John From fredrik at pythonware.com Wed Jul 16 05:00:44 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2003 11:00:44 +0200 Subject: hex check References: <3F150135.8030708@is.lg.ua> Message-ID: Ruslan Spivak wrote: > Does anybody have a hint how to check if input hex number > is in correct hex format? not unless you define what a "correct hex format" is, of course. but one of these might work: import re if not re.match("[0-9a-fA-F]+$", number): print "oops" import re if not re.match("0x[0-9a-fA-F]+$", number): print "oops" try: int(number, 16) except ValueError: print "oops" (etc) From fabsk+news at free.fr Wed Jul 30 05:11:14 2003 From: fabsk+news at free.fr (Fabien SK) Date: Wed, 30 Jul 2003 11:11:14 +0200 Subject: Embeding Python, COM crash Message-ID: <3f278bf0$0$24554$626a54ce@news.free.fr> Hi, I wrote a plugin for Visual C++ 6 that uses Python 2.2 (it worked perfectly for months). I just installed Python 2.3, and recompiled my plugin, and now it crashes. My plugin do the following things: Py_Initialize(); LoadLibrary("pythoncom23.dll"); typedef PyObject* (*CONVERT_PROC)(IUnknown *punk, REFIID riid, BOOL bAddRef); CONVERT_PROC proc = 0; proc = (CONVERT_PROC)::GetProcAddress(m_hDll, "PyCom_PyObjectFromIUnknown"); PyObject *pvc = proc(punk, __uuidof(IUnknown), FALSE); // boom and I have a "null pointer" crash with python 2.3. I remove the installation of 2.2, so there are no old header or library. I am using Visual C++ 6. Am I doing something wrong, or did something change with Python 2.3 ? Note: I am using the lastest python installer and win32all-155.exe. Thank you for your attention Fabien From bgailer at alum.rpi.edu Tue Jul 1 15:22:17 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 01 Jul 2003 13:22:17 -0600 Subject: remove special characters from line In-Reply-To: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Message-ID: <5.2.1.1.0.20030701131355.01a490e0@66.28.54.253> At 10:03 AM 7/1/2003 -0500, Chris Rennert wrote: >If I have a line like this > >?blah blah blah blah blah > >I know I could do a slice like this [1:] to pull everything but the special >character, but what if I have several lines in a file. >I am not sure how I would detect a special character like that. I would >just like to pull everything from those lines (and the special character >always appears as the first character, but not on every line) except for the >special characters. >I hope I have enough detail for someone to help me. Please define "special character". You have given us one example, but that's not sufficient to guess your meaning. One way to do this is to create a string with all acceptable characters, then see if the first character of each line is in that string. Consider string.printable: >>> import string >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' If you don't want the control characters at the end, use string.printable[:95] for line in file(filename).readlines(): if line[0] not in string.printable: del line[0] ... process line Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From oren-py-l at hishome.net Tue Jul 8 03:51:10 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 8 Jul 2003 03:51:10 -0400 Subject: Merlin, a fun little program In-Reply-To: References: <3F08CFDF.6050603@earthlink.net> Message-ID: <20030708075110.GA14337@hishome.net> On Mon, Jul 07, 2003 at 02:05:28PM -0700, Ron Stephens wrote: > I guess the bigger question is; is there anything wrong with web > scraping? I surely never meant any harm in it, and certainly no money > is involved. But maybe I should give it up and do other things? I don't think there's anything fundamentally wrong with web scraping but you have to consider the fact that a single script can easily consume resources that cost real money and would otherwise serve thousands of human users. If a provider installs mechanisms to detect scripts and block them this can quickly become a cat-and-mouse game where the scrapers try to fool these mechanisms, it starts to get ugly and everybody suffers. I think Google handled this very well - defusing most of the problem by letting people have what they want while keeping things under control. I generally find the way Google handles the issues that come with their dominant market position quite "Pythonic". Oren From cpl.19.ghum at spamgourmet.com Sun Jul 6 17:39:50 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 6 Jul 2003 23:39:50 +0200 Subject: python blogging software Message-ID: which one should I use? Recommendations? Harald From ark at acm.org Tue Jul 15 08:47:14 2003 From: ark at acm.org (Andrew Koenig) Date: Tue, 15 Jul 2003 12:47:14 GMT Subject: Securing the Pyton Interpreter? References: Message-ID: Stephen> I'm looking for a way to install Python on a UNIX machine in Stephen> a way such that any user on the system can use it, but only Stephen> to execute scripts that are located in a certain directory. Why? If I were a user on that machine and wanted to execute Python scripts in a different directory, how would you stop me from installing Python on my own and using it for those scripts? -- Andrew Koenig, ark at acm.org From doug.hendricks at tnzi.com Thu Jul 17 01:29:58 2003 From: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) Date: 16 Jul 2003 22:29:58 -0700 Subject: Connecting Oracle8i to Python References: Message-ID: doug.hendricks at tnzi.com (the_rev_dharma_roadkill) wrote in message news:... > Hello, > I'm a newbie to Python. In order to get much use out of it at my > site, I must be able to connect it to Oracle8i databases. I'm running > Python 2.2.2 on Tru64 (osf1 V5.1a). > > First question: > What do you recommend? > DCOracle2? Note that I am not running Zope or any other web software. > cx_Oracle? > Other? > > Second question (important only if you recommend DCOracle2) > I can "make" DCOracle2, but I don't see any hints anywhere on how to > install it on a non-zope system. If I try any obvious thing, like cp > -r to lib/python2.2/site-packages, at BEST I get: > > > python > Python 2.2.2 (#1, May 9 2003, 14:15:51) [C] on osf1V5 > Type "help", "copyright", "credits" or "license" for more information. > >>> import DCOracle2 > Traceback (most recent call last): > File "", line 1, in ? > File "DCOracle2/__init__.py", line 37, in ? > from DCOracle2 import * > File "DCOracle2/DCOracle2.py", line 104, in ? > import dco2 > ImportError: dlopen: DCOracle2/dco2.so: symbol "OCILobIsTemporary" > unresolved > I actually can get past this now using libocijdbc8 but now I get: >>> import DCOracle2 Traceback (most recent call last): File "", line 1, in ? File "DCOracle2/__init__.py", line 91, in ? import DA File "DCOracle2/DA.py", line 90, in ? from db import DB File "DCOracle2/db.py", line 89, in ? import DCOracle2, DateTime ImportError: No module named DateTime How many other non-standard modules do I need to install to get DCOracle2 working in a non-zope vanilla environment? From not.valid at address.org Thu Jul 17 21:40:07 2003 From: not.valid at address.org (YoTuco) Date: Fri, 18 Jul 2003 01:40:07 GMT Subject: Looking For A Wildcard File Name Parser Message-ID: I've been looking for a good wildcard file name parser. That is, some module in Python or something someone has made that can take a file name with the '*' or '?' wildcards in it, parse a list[] and give back the matches. It seems like a common enough task that one would be around? Or do I just have to roll up my sleeves, dig-in and learn RE? Thanx in advance for your input. --YoTuco From alf at fayauffre.org Fri Jul 25 08:04:04 2003 From: alf at fayauffre.org (Alexandre Fayolle) Date: Fri, 25 Jul 2003 12:04:04 +0000 (UTC) Subject: LGPL and Java, and Python? Message-ID: Hello, Reading Debian Weekly News, I learnt that there seem to be a problem when importing an LGPL'd java library (this forces the importer to be LGPL'd too), making the LGPL license equivalent to the GPL for Java programs. Here are a few references taken from DWN: http://slashdot.org/developers/03/07/17/2257224.shtml http://article.gmane.org/gmane.comp.jakarta.poi.devel/5900 http://linuxintegrators.com/hl30/blog/general/?permalink=LGPL+clarification.html http://www.rollerweblogger.org/page/roller/20030716#for_java_lgpl_is_viral http://www.intertwingly.net/blog/1519.html http://radio.weblogs.com/0122027/2003/07/16.html#a56 I'm by no way a license expert, but it seems to me that the import mechanism in python is closer to Java's than what is allowed to use a python LGPL'd library in a non GPL/LGPL program. Could anyone confirm or infirm this impression? -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From theller at python.net Wed Jul 23 02:44:54 2003 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jul 2003 08:44:54 +0200 Subject: py2exe command line window problem References: <1ee79758.0307220827.78f8571@posting.google.com> <5a4226f0.0307221641.49c96703@posting.google.com> Message-ID: kevin at cazabon.com (Kevin Cazabon) writes: > instead of using "python setup.py py2exe" try "pythonw setup.py > py2exe" from your application. No, it should not matter how the build process itself is run. > prashsingh at yahoo.com (Prashant Singh) wrote in message news:<1ee79758.0307220827.78f8571 at posting.google.com>... >> I'm using py2exe to create a standalone executable from a Python >> script, and I would like the script to run invisibly, i.e. without a >> console window and without any interactive GUI. The script is a helper >> app, which simply downloads and runs some other program. >> >> I've tried passing the -w flag to the script, and I've also tried >> renaming it with a .pyw extension, but when the executable is run an >> empty console window opens with the title "C:\WINNT\system32\cmd.exe". >> I've checked, and there are no print statements, which might cause >> py2exe to assume it's still a console app. Could it be that the DOS-box is not opened from the standalone executable, but from the programs Prashant starts from it? Thomas From bignose-hates-spam at and-zip-does-too.com.au Sat Jul 19 14:10:05 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 20 Jul 2003 04:00:05 +0950 Subject: __getitem__ and arguments References: <10eb079f.0307190110.30deb5b9@posting.google.com> Message-ID: On 19 Jul 2003 02:10:25 -0700, KanZen wrote: > I'm trying to understand the difference between __setitem__ and an > ordinary method. For example: (presuming you mean __getitem__) >>>> class A(object): > def __getitem__(self, *args): > print len(args) > def normalMethod(self, *args): > print len(args) > >>>> a=A() >>>> a.normalMethod(1, 2, 3) > 3 >>>> a[1, 2, 3] > 1 The dictionary access syntax you used specifies a key, which forces everything between [] to become a single argument. In this case, it's a tuple, (1, 2, 3). Thus, the args for A.__getitem__() is a tuple of length one, containing the specified key: the tuple (1, 2, 3). That is, args is a tuple containing a tuple. No such coercion occurs for function syntax; the difference is that you didn't invoke __getitem__ with function syntax. >>> class A: ... def normal_method( self, *args ): ... print len( args ) ... print type( args ) ... print args ... def __getitem__( self, *args ): ... print len( args ) ... print type( args ) ... print args ... >>> a = A() >>> a.normal_method( 1, 2, 3 ) 3 (1, 2, 3) >>> a[ 1, 2, 3 ] 1 ((1, 2, 3),) >>> > For __getitem__() the arguments become a tuple. Yes, because you've specified a key, which by definition is a single argument. -- \ "He may look like an idiot and talk like an idiot but don't let | `\ that fool you. He really is an idiot." -- Groucho Marx | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From jennyw at dangerousideas.com Fri Jul 11 12:57:26 2003 From: jennyw at dangerousideas.com (jennyw) Date: Fri, 11 Jul 2003 09:57:26 -0700 Subject: Reading a DOS text file and writing out Mac Message-ID: <20030711165726.GA29760@dangerousideas.com> Is there a way to set the EOL character that Python recognizes? For example, I'd like to set it to cr/lf (okay, that's eol characters) when reading a file (DOS text) and set it to just cr when writing out (Mac). Is there a way to do this? Thanks! Jen From pablo at bogus.domain.org Sun Jul 20 17:29:12 2003 From: pablo at bogus.domain.org (Pablo) Date: Sun, 20 Jul 2003 23:29:12 +0200 Subject: classes References: Message-ID: > Sure it does. Allowing that is the purpose of the "staticmethod" > call in Dan's example. Yes You're right and Dan as well. I just didn't know that that 'staticmethod' existed and tried to do "Java style" static method which obviously didn't work The trick with __new__ is usefull. I must read some more about classes in Python. Thanks to Pedro for a link. Cheers Pablo From gh at ghaering.de Wed Jul 2 08:06:34 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 02 Jul 2003 14:06:34 +0200 Subject: splitting a string into 2 new strings In-Reply-To: References: Message-ID: Mark Light wrote: > Hi, > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 > strings > 'C H O' and '6 12 6'. I have played with string.split() and the re module - > but can't quite get there. So what's the rule for splitting? Always split on position 4? That'd be too easy, I suppose: >>> s = "C6 H12 O >>> s[:4], s[4:] ('C6 H', '12 O6') -- Gerhard From ben-public-nospam at decadentplace.org.uk Sun Jul 6 10:24:43 2003 From: ben-public-nospam at decadentplace.org.uk (Ben Hutchings) Date: Sun, 6 Jul 2003 15:24:43 +0100 Subject: Collective memory References: <3f06af11$0$49113$e4fe514c@news.xs4all.nl> <3f071e0c.4620472@news.ocis.net> Message-ID: In article <3f071e0c.4620472 at news.ocis.net>, Gene Wirchenko wrote: > Irmen de Jong wrote: > >>Charles Shannon Hendrix wrote: >> > if >> > >> > >> > >> > >> > Is part of the if statement, or did someone with different >> > tab settings from the author make a mistake and align it accidentally? >> >>To catch such mistakes, Python has the -tt command line option: >>-t : issue warnings about inconsistent tab usage (-tt: issue errors) > > What is inconsistent about the tab usage above? That is, why > would it be flagged? If the above used only tabs for indentation, there could be no question about how the statements were meant to be grouped. Similarly, if it used only spaces for indentation, there could be no question. The problematic case that CSH is worried about is where the code uses a mixture of spaces and tabs (this is what is meant by "inconsistent"), e.g.: if : In a text editor misconfigured to use 4-space tabs this appears as: if : but since Python uses 8-space tabs it really means: if : So there is a risk here, and it's probably worth adopting a rule of not using tabs in Python code. If you think a colleague broke the rule, the -t flag will alert you to any potential problems. -- Ben Hutchings | personal web site: http://womble.decadentplace.org.uk/ Man invented language to satisfy his deep need to complain. - Lily Tomlin From m at moshez.org Wed Jul 16 08:25:53 2003 From: m at moshez.org (Moshe Zadka) Date: 16 Jul 2003 12:25:53 -0000 Subject: XML <=> database In-Reply-To: <20030716171311.A3783@cs.unipune.ernet.in> References: <20030716171311.A3783@cs.unipune.ernet.in>, <20030716170049.A3736@cs.unipune.ernet.in> Message-ID: <20030716122553.6759.qmail@green.zadka.com> On Wed, 16 Jul 2003, vivek at cs.unipune.ernet.in wrote: > Can someone please post a sample code for doing this.. Depends on the mocl-SQL XMLish language...and I, for one, am not going to try and find "XML Integrator"'s DTD. > Actually we trying to show the students how to use XML+Web+Database as it is > one of the hottest technology in the market :-) Then you're better off with Java. Java is much better at being a hot technology, and if this is the motivation, then it's better the students will not know how to program in Java than for them to not know how to program in Python. [My immediate take on XML+Web+Database is to use the database to store a counter, to use the xml for stringification and destringification and then to show that counter. Or maybe I should not say that, because someone might implement it...] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From BPettersen at NAREX.com Tue Jul 22 21:14:09 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 22 Jul 2003 19:14:09 -0600 Subject: 'int' object is not callable Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE46E4@admin56.narex.com> > From: JW [mailto:jkpangtang at yahoo.com] > > Hi, > > Suppose I have the following python method: > > def foo(aTuple): > print len(aTuple) #line 1 [...] > > I get the following error at line 1: > 'int' object is not callable > > If i remove line 1, then my foo() method does print out > correct value for aTuple[0]. [...] Did you assign an int to the variable "len" somewhere? -- bjorn From afriere at yahoo.co.uk Thu Jul 10 01:51:50 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 9 Jul 2003 22:51:50 -0700 Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: <38ec68a6.0307092151.21ba077a@posting.google.com> Behrang Dadsetan wrote in message news:<3F0C8AC3.5010304 at dadsetan.com>... > > def isAcceptableChar(character): > return charachter in "@&" > > str = filter(isAcceptableChar, str) > > is going to finally be what I am going to use. Might 'return character not in "@&"' work better? From abelikov72 at hotmail.com Fri Jul 11 14:08:57 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Fri, 11 Jul 2003 18:08:57 GMT Subject: Python in Excel References: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> <873chm9w7o.fsf@pobox.com> <37ee60c8.0307110716.74f7c4c9@posting.google.com> Message-ID: On 11 Jul 2003 08:16:33 -0700, ofnap at nus.edu.sg (Ajith Prasad) wrote: >This looks very useful to Excel users who would like to tap the power >of Python. However, not knowing enough about VBA syntax it was not >possible to proceed beyond step(a). Is it possible to provide an >Idiot's guide to steps (b), (c),(d) and (e)? In other words, what is >the explicit VBA code/steps need to do (b) and (c) and could simple >(even trivial) examples be given of steps (d) and (e). Thanks in >advance. Global sc As New MSScriptControl.ScriptControl Public Function os_getcwd() sc.Language = "python" sc.ExecuteStatement ("import os") os_getcwd = sc.Eval("os.getcwd()") End Function With this you can set your Excel formula to =os_getcwd() For me it returns "C:\Documents and Settings\Administrator\My Documents", which I needed to know at the time so I didn't have to screw around with the ever annoying pythonpath. You can put the first two lines of the function in the Workbook_Open hook, but I don't know where that is. I hope to use more Python in Excel soon. Hmm, actually, I suppose you can put those first two lines of the function after the Global declaration as well. I know just about zero VBScript and didn't get a chance to do anything else beyond proof of concept yet. I figured I would write something dynamic which allowed more transparent access to Python, maybe allowing formula like =py("os.getcwd()"), etc. -AB From domma at procoders.net Fri Jul 4 11:50:48 2003 From: domma at procoders.net (Achim Domma) Date: Fri, 4 Jul 2003 17:50:48 +0200 Subject: loading objects from ZODB Message-ID: Hi, I'm playing around with ZODB but I don't understand when objects are loaded from the DB. Assume I have an object containing a list of other objects. If this object is loaded from ZODB, when is the list filled? Only on demand? I think yes, because otherwise reading the top node would result in loading the whole database. But I wanted to be sure! regards, Achim From achrist at easystreet.com Mon Jul 28 16:34:09 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Mon, 28 Jul 2003 13:34:09 -0700 Subject: Any Software can Python <-> Delphi ? References: <_icVa.1123902$ZC.164425@news.easynews.com> Message-ID: <3F2588C1.8FE0C79B@easystreet.com> Joe Francia wrote: > > PythonMan wrote: > > Any Software can change Python source code to Delphi ? > > thx > > > > You might find an easier time of it to embed your Python in Delphi, or, > even better, write a Python extension with Delphi: > > http://www.atug.com/andypatterns/pythonDelphiTalk.htm > http://membres.lycos.fr/marat/delphi/python.htm > Anyone have any ideas about how to package one of these pythondelphi apps to be easy to deploy and be convenient to the end user? I'm guessing that since python isn't on top, McMillan's installer and py2exe won't handle it. TIA Al From nobody at nowhere.com Sat Jul 26 21:09:54 2003 From: nobody at nowhere.com (Grumfish) Date: Sun, 27 Jul 2003 01:09:54 GMT Subject: Seeing next character in an file Message-ID: Is there a way to see the next character of an input file object without advancing the position in the file? From gradha at titanium.sabren.com Sat Jul 12 07:08:01 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sat, 12 Jul 2003 13:08:01 +0200 Subject: ANN: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. Message-ID: <20030712110801.GA12963@pedos.es> DESCRIPTION The module provides two classes: Mailbox, a file-like object which allows you to iterate through the contents of a mailbox, and Email, an object which holds the individual emails returned by Mailbox. Mailbox inherits from Mailbox_base, but usually you don't need to even know about this class. Mailbox_base implements the file like mailbox reading part of the class, and the Email object creation. Use the Mailbox class in your code, which will always maintain the same API for backwards compatibility. This module has been written with simplicity in mind, and low memory consumption. Unless you do something bad, I estimate maximum memory consumption as twice the memory required by the largest email of the opened mailbox. But I'm guessing, maybe it is lower, like one time your biggest email. DOWNLOAD http://gradha.sdf-eu.org/program/mailbox_reader.en.html http://www.vex.net/parnassus/ http://freshmeat.net/ LICENSE GPL -- Please don't send me private copies of your public answers. Thanks. From intentionally at blank.co.uk Tue Jul 15 18:21:33 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 23:21:33 +0100 Subject: anything like C++ references? References: Message-ID: On Tue, 15 Jul 2003 15:16:40 -0700, Tom Plunket wrote: >Stephen Horne wrote: > >> std::string x = "123"; >> std::string y = x; >> >> // At this point, in most implementations, x and y are bound to the >> // same object due to a lazy copy optimisation. > >Actually, that isn't the case these days. I'm sure there are >some who do this optimization still, but it is incredibly hard to >do so in a thread-safe manner so all of the heavies as far as I >know don't do it anymore. Ah - makes sense. Bugger. There goes my nice neat 'but they can do it' argument :-( From schuffenhauer at iwq.de Tue Jul 1 03:18:01 2003 From: schuffenhauer at iwq.de (Gina Schuffenhauer) Date: Tue, 1 Jul 2003 09:18:01 +0200 Subject: Python 2.0 / Python 2.2 Message-ID: Hallo newsgroup, I have some questions concerning Python 2.2. First question: I try to port source code from Python 2.0 to Python 2.2.The following source code works with Python 2.0. If I compile it with Python 2.2, the modul "tci" is not imported. "tci" is a python module written by us. How can I change the source code to get it working with Python 2.2.? Py_Initialize(); PyStr = Py_BuildValue("s", TCIHome); PyModule = PyImport_ImportModule("sys"); PyList = PyObject_GetAttrString(PyModule, "path"); PyList_Insert(PyList, 0, PyStr); if (PyErr_Occurred()) return 0; TCIModule = PyImport_ImportModule("tci"); Second question: I want to embed Pythonwin in a C++-Application. Where can I find a win32uiHostGlue.h to access win32ui.pyd version 2.1.0.152? -- Mit freundlichen Gr??en / best regards Gina Schuffenhauer schuffenhauer at IWQ.de From Scott.Daniels at Acm.Org Sat Jul 19 22:15:20 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 19 Jul 2003 19:15:20 -0700 Subject: Strange(?) list comprehension behavior In-Reply-To: References: Message-ID: <3f19e98d$1@nntp0.pdx.net> George Henry wrote: > Never mind, my result was due to a typo. Have you ever typed "<" rather > than "," ... and structured your code in such a way that the error > escpaed your notice on casual perusal? So ... [ "s1", ... "sj"< "sk", > ... "sn"] does indeed produce an int. One way that I reduce these problems is defining longer lists like this: ops = '~ ! @ + - | || < << > >> ...'.split() -Scott David Daniels Scott.Daniels at Acm.Org From klappnase at freenet.de Sat Jul 19 19:16:14 2003 From: klappnase at freenet.de (klappnase) Date: 19 Jul 2003 16:16:14 -0700 Subject: Executing a program References: Message-ID: <9a410299.0307191516.3a4481e6@posting.google.com> Eirik wrote in message news:... > Greetings! > > How can I run a program from within Python? > > I have tried the exec* family of functions, but I get these strange > errors, like this: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1300, in __call__ > return apply(self.func, args) > File "./PPP", line 9, in run_app > os.execvp("home/eirik/ppp-skript", argument) > File "/usr/lib/python2.2/os.py", line 298, in execvp > _execvpe(file, args) > File "/usr/lib/python2.2/os.py", line 324, in _execvpe > apply(func, (file,) + argrest) > OSError: [Errno 2] No such file or directory Hi, if you want to run an external program with a bash command (seems like that's what you're trying to do) exec is not the right function for you; with exec you can run python modules. Try something like: os.system("home/eirik/ppp-skript --argument") instead or if you want to get the output of your program try xyz = commands.getoutput("home/eirik/ppp-skript --argument") Did that help (maybe I have not really understood your problem)? Cheers Michael From fredrik at pythonware.com Mon Jul 14 16:33:01 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Jul 2003 22:33:01 +0200 Subject: some questions References: <3f12f613$0$8731$9b622d9e@news.freenet.de> <3f130110$0$31819$9b622d9e@news.freenet.de> Message-ID: Andreas Bauer wrote: > Could anybody tell me how to hide a varibale e.g. in a url > Example > > for i in (0,5): > u = urllib.urlopen("http://www.versionxzy.com/page > - here the variable e.g page1,page2,page3.html here's one way to do it: for i in range(1, 5): u = urllib.urlopen("http://www.versionxzy.com/page%d.html" % i) more here: http://www.python.org/doc/current/tut/node9.html http://www.python.org/doc/current/lib/typesseq-strings.html (reading the entire tutorial won't hurt, of course) From peter at engcorp.com Thu Jul 10 12:31:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 12:31:06 -0400 Subject: Executing scripts References: Message-ID: <3F0D94CA.38C71FFC@engcorp.com> Ken Fettig wrote: > > I am having a problem executing scripts from python. The script is located > at C:\Python22\learn and is named more.py. This is an example from the > Programming Python book by Mark Lutz published by O'Reilly. I have tried how > the author outlines to execute the script but it doesn't work. I am on a > Windows 2000 machine. > The example shows to, at the command line, enter C:\Python22\learn>python > more.py more.py. I get the following output: > >>> C:\Python22\learn>python more.py more.py > File "", line 1 > C:\Python22\learn>python more.py more.py > ^ > I have tried many combinations all unsuccessfully. Can someone please help > me???? You are not at the right command line. The >>> indicates you have already run Python, but are trying to execute a DOS command line at the *Python* prompt. See http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp -Peter From rnd at onego.ru Tue Jul 8 00:39:38 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 8 Jul 2003 08:39:38 +0400 (MSD) Subject: getting a submatrix of all true In-Reply-To: Message-ID: On Wed, 2 Jul 2003, John Hunter wrote: >1 0 0 0 1 >0 0 0 0 0 0 0 0 0 0 >0 0 0 0 0 0 0 0 0 0 candidate submatrix has 15 elements >0 0 0 0 0 0 0 0 0 0 >0 0 1 0 0 I think you can explore two ways to solve your problem. I have not read all the replies in this thread, but these two ways are: - look at the matrix as a representation for the graph and try to understand how can you rearrange it to drop all missing values (you will easily find ready-maid algorithms for rearranging sparse matrices to the optimal (for your case) form by searching in the library and/or Internet - try to use algorithms or modify existent ones to allow for missing values. You can also make some conditioning or making a vector (see below) And also: I do not believe that values you drop are all of equal significance. For example, if you have time series data where time is on the X axis, then dropping several consequent columns can make more damage than dropping a row. In most cases you better interpolate values. Overall, every item of data is usually valuable for the accuracy. Sometimes it's better to rework the model than drop any values. For example, you can try make a matrix 1-column one (vector): 0 0 0 0 0 1 1 0 0 0 0 0 - then just drop missing elements. Of course, this will be a novel view of your model and probably other matrices of your model will become 100 bigger. But computer power is cheaper each day. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From BPettersen at NAREX.com Fri Jul 25 20:34:20 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 25 Jul 2003 18:34:20 -0600 Subject: Static typing Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE473C@admin56.narex.com> > From: Aahz [mailto:aahz at pythoncraft.com] > > In article , > Shane Hathaway wrote: > > > >Well, here's a pattern I've been trying out for this > purpose: use assert > >statements at the top of the function. > > > >def foo(bar, baz): > > assert isinstance(bar, int) > > assert isinstance(baz, str) > > > >I'm quite happy with the pattern, although there are a couple of > >negative points that I can think of: > > > >- It's a bit verbose, although that verbosity enables you to perform > >bounds checking and operate with other type systems like > Zope's interfaces. > > > >- You can't specify the type of the return values this way. > > You skipped the crucial negative: it breaks Python's name-based > polymorphism. If someone creates a class that works just > like a string but doesn't derive from the str class, your > program breaks for no good reason. And just for completeness... If you absolutely want a static type system, that preserves Python's name-based polymorphism, google for "bounded parametric polymorphism" or "constraint based polymorphism". Algol/C(++)/Pascal/Java type-declarations are not nearly expressive enough. -- bjorn (e.g. http://www.cis.ohio-state.edu/~gb/cis888.07g/Papers/p388-litvinov.pdf gives an introduction to the commonly raised issues/examples in the context of Cecil). From richie at entrian.com Mon Jul 28 07:54:57 2003 From: richie at entrian.com (Richie Hindle) Date: Mon, 28 Jul 2003 12:54:57 +0100 Subject: Seeing next character in an file In-Reply-To: References: Message-ID: [Keith] > def peek(self, cnt): > data = self.read(cnt) > self.seek(cnt * -1, 1) > return data > > def peekline(self): > pos = self.tell() > data = self.readline() > self.seek(pos, 0) > return data [Bengt] > if you're going to seek/tell, best to do it in binary, and deal with the platform dependent EOLs. seek() works perfectly with text-mode files as long as you only seek to places given to you by tell(). So if Keith's peek() function had used tell() and then seek()ed (sought()? 8-) back to that point like his peekline() does, there would be no problem. -- Richie Hindle richie at entrian.com From peter at engcorp.com Fri Jul 4 23:22:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 23:22:21 -0400 Subject: Google's netnews speed (was Re: pyBoards.com) References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3F05C39D.3F65B89C@engcorp.com> <3F05FFFE.DB98BF44@engcorp.com> Message-ID: <3F06446D.739C42DC@engcorp.com> Aahz wrote: > > Peter, you're thinking less clearly than usual. ;-) My point was that > the delay does *not* come from the time it takes to propagate to Google, > but from the delay required to index and publish the index. (Slapping forehead...) Of course! Indexing, right... that. :-) I was picturing Groups as nothing more than a big web interface to Usenet. Indexing it, too, well that just smacks of overkill, now, doesn't it? ;-) Thanks for the head-straightener. -Peter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 11 14:01:47 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 11 Jul 2003 20:01:47 +0200 Subject: Embedding Python, threading and scalability In-Reply-To: <7xvfu983ip.fsf@ruckus.brouhaha.com> References: <7xvfu983ip.fsf@ruckus.brouhaha.com> Message-ID: <3f0efb8a$0$49110$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > aahz at pythoncraft.com (Aahz) writes: > >>Not particularly. Most threading at the application level is done for >>one or more of three purposes: >> >>* Allowing background work and fast response in a GUI application >> >>* Scalable I/O >> >>* Autonomous sections of code for algorithmic simplicity (e.g. >>simulations) > > > Um, concurrent access by multiple clients for server applications? Exactly, that is what I use threads for in Pyro. Without threads, each of the client's remote method invocations has to wait in line before being accepted and processed (there can be many clients for one server object). --Irmen From aahz at pythoncraft.com Fri Jul 11 10:39:18 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 10:39:18 -0400 Subject: Nice presentation of Dana Moore on Oscon References: <3F0E63AA.4000107@embeddedsystems.nl> Message-ID: In article <3F0E63AA.4000107 at embeddedsystems.nl>, Gerrit Muller wrote: > >A very nice presentation. I do have one small comment: Python is >characterized as "weakly typed", which should be "dynamic types", or >what people often mean to say "not static typed". Unfortunately, Bruce Eckel has been perpetuating that terminology. I'm in the process of writing a rebuttal. http://www.artima.com/intv/typing.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From ratman at nmt.edu Mon Jul 14 16:58:22 2003 From: ratman at nmt.edu (Jason Trowbridge) Date: 14 Jul 2003 13:58:22 -0700 Subject: =?ISO-8859-1?Q?Python_Mystery_Theatre_--_Episode_2:__As=ED_Fue?= References: Message-ID: <8f35dab2.0307141258.3da9b9d4@posting.google.com> I didn't look at docs or try out the code until after trying to solve the problem. I'm using Python 2.2.1. I did not solve Act I or Act III, and tried them out directly. Act I I didn't know that python formatting could do that! I've always treated it like C's printf-style of statements, as that seems to be what it's primarily based off. I've always used two string substitutions to first replace the formatting parts, then actually insert the real substitutions! Eg: >>> print ('%%%if' % (10,)) % (0.5,) 0.500000 Now to find I can do: >>> print '%*f' % (10, 0.5) 0.500000 In some respects, moving from C/C++ to Python is a bit like moving from Linux to Mac OS X. I use the basic screwdriver, since I know how and where it is, and don't see the nifty cordless power screwdriver placed nicely in the cabinet. Luckily, I have browsed through the entire module index at least once, so I don't miss the jackhammers and use a trowel instead. Act II Again, there's behavior here that I didn't expect. I first assumed that the results would be: print int('0100') -> 100 (Correct) print 16, int('0100', 16) -> 16 256 (Correct) print 10, int('0100', 10) -> 10 100 (Correct) print 8, int('0100', 8) -> 8 64 (Correct) print 2, int('0100', 2) -> 2 4 (Correct) print 0, int('0100', 0) -> ? print -909, int('0100', -909) -> ? print -1000, int('0100', -1000) -> ? print None, int('0100', None) -> None 100 (Wrong, TypeError occurs) The interesting thing is when I tried it out: >>> int('0100', 0) 64 >>> int('0100', -909) 100 >>> int('0100', -1000) Traceback (most recent call last): File "", line 1, in ? ValueError: int() base must be >= 2 and <= 36 I am using Python 2.2.1. According to the doc for int(x, radix), the part about the radix behaviour is as follows: The radix parameter gives the base for the conversion and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. That explains the 0 radix and the exception caused by the -1000 radix. So why does it work with a radix of -909? I presume a bug (which probably got fixed in later versions of Python). I'll have to see if this behavior is present under Python 2.3b at home. Act III Ick. Lambda's. Skipping for now. Act IV I would guess that it would print: 'Now there are three' Since the environmental variable one is 'Now there are', and the environmental variable two is 'three'. My bad. Upon running, I get: 'Now there are None' Apparently, os.putenv() doesn't work like I thought. Ah! os.putenv() updates the environment, but not the os.environ dictionary. It looks like os.getenv() retrieves the environmental variables from os.environ, and just assumes that it is up to date. Since it defaults to None if the environmental variable doesn't exist in os.environ[], that's what I get. Hmm, so os.getenv() and os.putenv() are not symmetric. This isn't mentioned in the Python 2.2.1 documentation, as os.getenv() is listed as: Return the value of the environment variable varname if it exists, or value if it doesn't. value defaults to None. This misleads that it is getting the value from the actual environment, not the os.environ[] variable. Nasty and subtle, too! Act III Ick. Lambda's. Oh well, here's a stab at it. funcs is a list of functions. flim is a list of unnamed functions that call the functions in funcs. flam is a list comprehension of lambda's that call the functions in funcs. flim and flam should be functionally equivalent (2/3 pun intended). The output should be: 1 2 3 1 2 3 Since they are just calling the functions listed in funcs (once, twice, thrice). Hmm, the output is really: 1 2 3 3 3 3 That's odd. Why is this the result here? >>> print [ f.__name__ for f in funcs] ['once', 'twice', 'thrice'] So, f is updating correctly to the next value. >>> for test in [ lambda x: f.__name__ for f in funcs]: print test(1), id(test) ... thrice 135971068 thrice 136291772 thrice 135757396 Okay, so the lambda's being created are unique, yet are being mapped to the third function. >>> def fourth(x): return 4*x ... >>> f >>> f = fourth >>> f >>> flam[0](1) 4 Aha! So the lambda is looking up f in the current scope when it is executed! Instead of binding to the actual function object being iterated over in the list comprehension, the lambda is binding to the variable 'f' itself? Ick! Ick! Ick! Bad touch! (Hey, these are fun!) _ () () Jason Trowbridge | "... but his last footer says 'page ( ' .~. Generic Programmer | 3 of 2', which leads me to believe \ = o = | something is wrong." ---"`-`-'"---+ ratman at nmt.edu | --Scott Bucholtz From aahz at pythoncraft.com Wed Jul 9 16:16:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2003 16:16:15 -0400 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: In article , A.M. Kuchling wrote: > >That reminds me: there was also a proposal to revive the Web-SIG. Ian, >anything moving on this front? (My offer to host a list still stands.) I'd suggest putting it on python.org, so that anyone who who looks at the mailing lists will find it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From bgailer at alum.rpi.edu Wed Jul 2 17:01:59 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 02 Jul 2003 15:01:59 -0600 Subject: does lack of type declarations make Python unsafe? In-Reply-To: <9a6d7d9d.0307020959.634ceb4e@posting.google.com> References: <3064b51d.0306151228.22c595e0@posting.google.com> <1055736914.49032@yasure> <3064b51d.0306170436.2b31f9e@posting.google.com> Message-ID: <5.2.1.1.0.20030702145436.0234ab18@66.28.54.253> At 10:59 AM 7/2/2003 -0700, Aaron Watters wrote: >David Abrahams wrote in message >news:... > > Duncan Booth writes: > > > > I'm not saying that Python isn't a wonderful language -- it is. It's > > great to have the flexibility of fully dynamic typing available. All > > the same, I'm not going to pretend that static typing doesn't have > > real advantages. I seriously believe that it's better most of the > > time, because it helps catch mistakes earlier, makes even simple code > > easier to maintain, and makes complex code easier to write. I would > > trade some convenience for these other strengths. Although it's very > > popular around here to say that research has shown static typing > > doesn't help, I've never seen that research, and my personal > > experience contradicts the claim anyway. > >I'm somewhere on the fence. I've seen static typing catch errors, >but I've also seen static typing (in java, say) make the use of a >hash table into an exercise in code obfuscation. I'd really like some >sort of compromise where you could harden types incrementally. Also >static typing can make it more difficult for bad programmers to do >stupid things... > >I'd like to see research either way. I've heard of rumored research >in both directions. Personally, I suspect the widely repeated statement >"90% of programming errors are typing errors" can be traced back to the >60's when engineers wrote programs on graph paper-like sheets and >handed them to TYPISTS who then TYPED THEM WRONG onto punch cards. Except, of course, they were not typists, they were key punch operators, and they key-punched. There is of course some skill set overlap, but key punching was an art of its own. (former key punch operator, though strictly for my own programs). In addition to the key punch there was also a "verifier" which looked for all practical purposes like a key punch. You fed it punched cards, keyed what was supposed to be on each card, and the verifier would complain if there was a mismatch. There was, also, as I recall, an "interpreter" which would read cards and print the value of each column on the top of the card. The really skilled operators also were experts at programming the little drum that specified what was allowed or not in each column, and tab stops for skipping to the next input column. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From mike at nospam.com Wed Jul 30 15:45:27 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 30 Jul 2003 12:45:27 -0700 Subject: PyXPCom References: <3f27e5a8$0$13798$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > has anyone examples, docs, binaries, urls, etc???? just 'google PyXPCom' gives you: ASPN : Komodo : PyXPCOM PyXPCOM. Description XPCOM is an acronym for "Cross Platform COM". ... See this page for information on how to build PyXPCOM from source. ... www.activestate.com/ASPN/Downloads/Komodo/PyXPCOM/ - 19k - Cached - Similar pages Getting started with PyXPCOM ... programming in Python. This first part covers installation of PyXPCOM. IBM, Skip to main content, ... Getting started with PyXPCOM, e-mail it! ... www-106.ibm.com/developerworks/webservices/ library/co-pyxp1.html - 35k - Cached - Similar pages Getting started with PyXPCOM, Part 2 ... This second part covers the use of PyXPCOM as a client to XPCOM objects. IBM, Skip to main content, ... Getting started with PyXPCOM, Part 2, ... www-106.ibm.com/developerworks/components/ library/co-pyxp2.html - 38k - Cached - Similar pages [ More results from www-106.ibm.com ] Mike From bogus at antispam.com Mon Jul 21 00:47:34 2003 From: bogus at antispam.com (Alex) Date: Mon, 21 Jul 2003 00:47:34 -0400 Subject: Stopping a loop with user input. in curses References: <20030720110941.09823.00000321@mb-m11.aol.com> Message-ID: Hello Ray, After trying the code, I got the same problem which prompted me to post to the newsgroup. The clock would properly display but it wouldn't update every second. If I hit the up-arrow key (or any other key besides 'q'), the program would then update the time. I would have to continuously hit a key to get the clock to update every second. I have a theory about programming in curses which I've described to yet another Ray within the same thread. Please read it and tell me if I'm completely out to lunch here or not (I'm hoping I'm wrong). Thanks, Alex From stephan.diehl at gmx.net Wed Jul 30 08:36:32 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Wed, 30 Jul 2003 14:36:32 +0200 Subject: python in parallel for pattern discovery in genome data References: Message-ID: BalyanM wrote: > Hi, > > I am new to python.I am using it on redhat linux 9. > I am interested to run python on a sun machine(SunE420R,os=solaris) > with 4 cpu's for a pattern discovery/search program on biological > sequence(genomic sequence).I want to write the python code so that it > utilizes all the 4 cpu's.Moreover do i need some other libraries. > Kindly advice. > > Thanks > > Sincerely, > > Manoj > Just a normal python interpreter won't help any, because of the GIL (Global Interpreter Lock). Just from your description, the following module might be something for you: http://poshmodule.sourceforge.net/ It allows object sharing between differnet python processes. As I have never worked with it, I can't say, if it's any good. Stephan From sschwarzer at sschwarzer.net Sat Jul 26 14:54:29 2003 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 26 Jul 2003 20:54:29 +0200 Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Paul Paterson wrote: >> Of course, if you have a better name for your container, that's even >> better. Think of Ian's Point example. :-) > > I think you may have missed my original post; I am writing a generic VB > to Python converter so generating good names based on code intent would > be pretty tough! Perhaps in v2.0 ;) I didn't miss the post, just this specific thing, the _generic_ converter. ;-) Stefan From max at alcyone.com Tue Jul 15 01:08:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 22:08:29 -0700 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: <3F138C4D.F73F08D4@alcyone.com> Stephen Horne wrote: > If people are routinely faking the abstraction, maybe that is because > it is a useful abstraction to have. Maybe it would be better to > support it explicitly instead of forcing people to use tricks and > hacks. But the issue I'd raise is why you think that modification of an object in a mutable container is "faking the abstraction." C and C++ have the concept of a pointer, and that's well and good for those languages. Python doesn't, and doesn't need it. If you want the effect of a C or C++ pointer in Python, you can get it through very simple means. The reason why it's not necessary is that, as has been pointed out, essentially _all_ "variables" in Python are references/pointers -- they refer, perhaps non-uniquely, to objects which have identity beyond the references that have them. This isn't the best way to explain how Python's variable system works to newbies, because it introduces confusion (it's not quite call by value and it's not quite call by reference; it's call by value where the values are references), but any variable "points" to a reference. The equivalent concept to what you're getting at is one of mutability, and that is handled utterly distinctly than it is in C or C++. Someone familiar with Python might argue that it's C++ that's "faking the abstraction," not the other way around. They're very different ways of doing things; insisting that the square peg should be rounded worries people who liked the square hole just fine. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The actor is not quite a human being -- but then, who is? \__/ George Sanders From eddie at holyrood.ed.ac.uk Fri Jul 25 12:35:38 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 25 Jul 2003 16:35:38 +0000 (UTC) Subject: Don't want to do the regexp test twice References: Message-ID: Egbert Bouwman writes: >While looping over a long list (with file records) >I use an (also long) if..elif sequence. >One of these elif's tests a regular expression, and >if the test succeeds, I want to use a part of the match. >Something like this: >pat = re.compile(r'...') >for line in mylist: > if ... : > .... > elif ... : > .... > elif pat.search(line): > mat = pat.search(line) > elif ... : > ... > else ...: > ... >Is there a way to to do this job with only one pat.search(line) ? >Of course I can do this: >for line in mylist: > mat = pat.search(line) > if ...: > .... > elif ...: > .... > elif mat: > ... >but the test is relevant in only a relatively small number of cases. >And i would like to know if there exists a general solution >for this kind of problem. Unless I'm missing something (as usual), how about: def lookup_func (line, pat, mat): x = re.search (...) if x: mat.append (x) return x mat = [] for line in mylist: if ...: .... elif ...: .... elif lookup_func (line, pat, mat): # data is in mat[-1] mat = [] # for next time el... ie you abstract out the code that gets the match data and get it to tell you whether it succeeded or not. Depending on your requirements it may be able to handle several such operations with the one lookup function. Eddie From mcherm at mcherm.com Thu Jul 17 08:43:54 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 17 Jul 2003 05:43:54 -0700 Subject: anything like C++ references? Message-ID: <1058445834.3f169a0a81670@mcherm.com> Adam Ruth writes: > You are correct in that there are times when pointer semantics would be > somewhat useful, but they're never necessary. His statement was that > there are time that "you really can't avoid pointers". That's not true. > I definitely went a little overboard, and it sounds like I'm saying, > "not only are pointers not necessary, they're never desirable". My tone > was a bit more knee jerk than was prudent. So it sounds like we ALL agree: (1) pointers are never *necessary*, and (2) they're sometimes useful. Adam Ruth writes: > Your code example isn't really about pointers, though, as the C++ > version doesn't use pointers. You're right... poor example. In my effort to simplify (and remember) the example, I left out the fact that the function "makeNewComplexObject" in this case) was responsible for incrementing i and sometimes didn't increment it. Frankly, it was a messy piece of C++ code and I wouldn't have done it that way in Python except that it was useful to translate more-or-less directly from the working C++. And I used it as an example because it was the only time I could think of (in real code) where I used the "one-item-list as a fake pointer" idiom in Python. (Although I've needed it in Java quite often.) Which goes to support your point that Python's design makes the pointer thing useful much less often. Adam Ruth writes: > I would be interested in seeing a more complex example where something > would be substantially cleaner with pointers. I have to acknowledge the > possibility that they exist, I don't know everything... yet :) Good point. I think you should be granted a default judgement... it's now up to pointer proponants (who are they?) to show a case where "pointers" really are useful in Python.[1] I tried, and my example hasn't even convinced myself. -- Michael Chermside [1] Python with Horne-style parameter passing obviously needs pointers, but that's not the question here, since that language doesn't exist! From peter at engcorp.com Fri Jul 18 19:12:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Jul 2003 19:12:20 -0400 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> <1058561410.563105@smirk> Message-ID: <3F187ED4.6179CDDD@engcorp.com> "James T. Dennis" wrote: > > Sean 'Shaleh' Perry wrote: > > >> If my english was better I would love to help improve the python > >> documentation, most modules in the standard libraries lack good > >> examples how to *use* them with just a simple description. And a > >> short motivation for the design of a module if possible like "just > >> copied the C API" or "Because of efficiency ..." or "We use a class > >> framework here because ...". A gigantic task. The PSL book by effbot > >> is great but it's a book. And it needs a new version. > > > part of the reason why the docs are not but so great is that most of the > > library is Python code which means any questions can be answered by reading > > the source. I find myself doing this quite often. > > That's BS! > > As a dabbler in programming I have to say that poor documentation is not > excused by the availability of sources. True, but poor documentation *is* excused quite nicely by the LACK of availability of _re_sources, specifically the human resources and time required to make them better. Or was your flame an indirect offer to assist with improving the documentation of Python? If so, thank you! (It's not like you've paid anything for the privilege of whining...) -Peter From ebolonev at rol.ru Fri Jul 4 05:19:32 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 20:19:32 +1100 Subject: enumerate example References: Message-ID: Hello, Andreas! You wrote on Fri, 04 Jul 2003 10:30:56 +0200: Thanks! AJ> 0 a AJ> 1 b AJ> 2 c AJ> --On Freitag, 4. Juli 2003 18:19 Uhr +1100 Egor Bolonev AJ> wrote: ??>> Hello, All! ??>> ??>> Any useful example for enumerate, please. ??>> ??>> With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] ??>> ??>> -- ??>> http://mail.python.org/mailman/listinfo/python-list With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From aes at demnet.ubi.pt Tue Jul 8 18:21:47 2003 From: aes at demnet.ubi.pt (aes) Date: 8 Jul 2003 15:21:47 -0700 Subject: pymat in windows 98 Message-ID: Hi I'm trying to interface Python with MatLab. But I'm have the following problem whem I try to import PyMat module. >>> import pymat Traceback (most recent call last): File "", line 1, in ? import pymat ImportError: DLL load failed: Um dispositivo ligado ao sistema n?o est? a funcionar. Who Can help me please!? Best regards AES From dgallion1 at yahoo.com Tue Jul 8 09:58:30 2003 From: dgallion1 at yahoo.com (Darrell) Date: 8 Jul 2003 06:58:30 -0700 Subject: win32security.LogonUser Message-ID: On windows 2000 I tried to use winprocess.py with the login option. In an effort to run as a diffrent user. It didn't work and lots of searching didn't help. This was my best hit. http://www.faqts.com/knowledge_base/view.phtml/aid/4466 Worked around the problem using runas.exe This is as far as I got. The following code tries to give me every Privilege it can then fails. pywintypes.error: (1314, 'LogonUser', 'A required privilege is not held by the client.') --Darrell import win32con, os, sys sys.path.append(os.sep.join(win32con.__file__.split(os.sep)[:-2])+os.sep+"demos") import winprocess from ntsecuritycon import * import ntsecuritycon, win32security, win32api def AdjustPrivilege(priv, enable = 1): print priv # Get the process token. flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY |TOKEN_DUPLICATE| TOKEN_IMPERSONATE #flags= TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) # Get the ID for the privilege. try: id = win32security.LookupPrivilegeValue(None, priv) except: print 'Fail' return # Now obtain the privilege for this process. # Create a list of the privileges to be added. if enable: newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] else: newPrivileges = [(id, 0)] # and make the adjustment. win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) # now set the rights if 1: for k, v in ntsecuritycon.__dict__.items(): if k.find("SE_")==0 and isinstance(v, str): print k, AdjustPrivilege(v) AdjustPrivilege(SE_CHANGE_NOTIFY_NAME) AdjustPrivilege(SE_TCB_NAME) AdjustPrivilege(SE_ASSIGNPRIMARYTOKEN_NAME) SE_INTERACTIVE_LOGON_NAME = "SeInteractiveLogonRight" #AdjustPrivilege(SE_INTERACTIVE_LOGON_NAME) if __name__ == '__main__': # Pipe commands to a shell and display the output in notepad print 'Testing winprocess.py...' import tempfile timeoutSeconds = 15 cmdString = """\ REM Test of winprocess.py piping commands to a shell.\r REM This window will close in %d seconds.\r vol\r net user\r _this_is_a_test_of_stderr_\r """ % timeoutSeconds cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile() cmd.write(cmdString) cmd.seek(0) print 'CMD.EXE exit code:', winprocess.run('cmd.exe', show=0, stdin=cmd, login=".\nuser\nuser1",#administrator\n", stdout=out, stderr=out) cmd.close() print 'NOTEPAD exit code:', winprocess.run('notepad.exe %s' % out.file.name, show=win32con.SW_MAXIMIZE, mSec=timeoutSeconds*1000) out.close() From tim.harford at rogers.com Sun Jul 6 19:59:17 2003 From: tim.harford at rogers.com (Tim) Date: Sun, 06 Jul 2003 23:59:17 GMT Subject: help! - cmd line interpreter gone "dumb" References: Message-ID: Yes, reboot or have the programmer give his head a shake. ;-) I love this language, but getting used to the little set up details I guess...Half of it was my own ignorance, but it's not obvious. For the record... if I don't define any paths for Python, it naturally knows were to go for the core + libraries. but, if you define the PYTHONPATH in the environment--only those directories are searched. It was probably the late night that had me forget when I changed things (funny--its seemed to work for a long while, but the changes may not have been reflected if I had the same command window open the entire evening (this was the case, I think). It makes sense... Tim "Gerhard H?ring" wrote in message news:mailman.1057524309.16869.python-list at python.org... > Tim wrote: > > Maybe I've been working too long, but has anyon had their python interpreter > > stop taking commands. > > > > The IDLE version works fine, but under Windoze: > > > > 1) execute "python" in teh command shell > > 2) ...interpreter comes up fine > > 3) type in anything and you get "SyntaxError: invalid syntax" > > > > Literally, you could type in "import sys" or anything common and you get the > > same results. > > I've seen that when I used os.spawn* (or was it os.execv*?), apparently > in a wrong way. > > > Any help greatly appreciated--thanks. > > Typical Windows answer: reboot and try again ;-) > > -- Gerhard > From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 17 05:30:12 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 17 Jul 2003 10:30:12 +0100 Subject: Jython classpath question In-Reply-To: References: Message-ID: <200307171030.13174.mfranklin1@gatwick.westerngeco.slb.com> On Thursday 17 July 2003 03:29, Tennessee James Leeuwenburg wrote: > Hi all, > > Sorry for the newb question, but Googling and FAQing didn't work. Is it > correct that Jython can only access Java classes which are inside JAR > archives in the JYTHON_HOME directory? IT doesn't seem to be documented. I > ask because I want to do groovy prototyping using Jython, and save myself > a lot of coding overhead to try something a little out-of-the-box. > No you can import a java .class file. Just make sure it's on the python path (sys.path) if both .py and .class files are in the same directory then you need do nothing... if not then you could add the directory containing the java class files to python sys.path like so: import sys sys.path.append("/path/to/java/class/files") for more information / alternative suggestions look at :- http://www.jython.org/docs/registry.html Regards Martin From edreamleo at charter.net Wed Jul 16 11:23:26 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 16 Jul 2003 10:23:26 -0500 Subject: Nice presentation of Dana Moore on Oscon References: <3F0E63AA.4000107@embeddedsystems.nl> Message-ID: Many thanks for your rebuttal. My picture of the situation is this: the Python interpreter is in effect placing assert statements after (inside) every Python statement. This makes Python in practice much more safe and convenient than any static language. No, this doesn't directly relate to types. However, IMO the real issues aren't about types, they are about safety and convenience. Python crushes any static language as far as convenience goes. This much is obvious. Theoretically all languages are unsafe. Python programs can throw uncaught exceptions just like C++ asserts can fail. In practice, though, the Python interpreter makes development so much safer that one can just "blast away" without worrying too much about the kinds of things compilers typically worry about. And my Python programs have been much more robust than the equivalent C++ programs, even without pychecker's help. This is probably all obvious to Pythonists, and incomprehensible to others. Oh well... :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From theller at python.net Fri Jul 4 07:33:27 2003 From: theller at python.net (Thomas Heller) Date: Fri, 04 Jul 2003 13:33:27 +0200 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: Message-ID: <7k6yh6go.fsf@python.net> "Francesco Bochicchio" writes: > Hi all, > > I was wondering if it would be possible to make a module which allows to > do something like that: > > import c_interface > math_lib = c_interface.load('math.so', 'math.h' ) > sin_f = math_lib.get_function('sin') > print "sin(3.14) = %f" % sin_f (3.14) > > The idea would be to make a module that allows to use any C dynamic > library ( I used an hypothetical math.so only as example ) without > the need of a specific wrapper module. > > I've given some thought to this idea, but I was blocked by the theoric (?) > impossibility to correctly call a C function without knowing its prototype > at compile time. > > Did anybody ever attempted to do something like this? Yes, it already exists (to some degree). http://starship.python.net/crew/theller/ctypes/ Thomas From bokr at oz.net Sat Jul 19 11:44:13 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 15:44:13 GMT Subject: The definition of an object in Python References: <94af9c5a.0307130919.1ab63400@posting.google.com> Message-ID: On 19 Jul 2003 01:52:56 -0700, wesc at deirdre.org (Wesley J. Chun) wrote: [...] >> Wesley says that every Python object must possess the following >> three characteristics: 1) an identity, which can be retrieved >> by the function id(); 2) a type, which can be retrieved by >> the function type(); and 3) a value. > >again, this is also (still) true. (1) the identity is what makes an >object unique from every other object currently in the interpreter. ^^^^^^^^^ This should perhaps be emphasized. E.g., these results are not guaranteed, but they can happen: >>> idvalue = id(123) >>> idvalue, id(456) (7952152, 7952152) >>> idvalue == id(456) 1 I.e., the value of id(x) is not valid beyond the lifetime of x, which is obviously ok, but mistaken reuse of id-like numbers (e.g., such as you get from file('somefile').fileno()) is a traditional source of bugs, and I imagine naive use of id() could lead to similar ones. >some people view this as a "memory address" altho you wouldn't >use it as such since Python handles the memory management 4 u. >you are just guaranteed that any other object in the system will >NOT have the same id. (2) the type of an object defines what its >characteristics (i.e., what methods and attributes it has, etc.) are, >and (3) the value goes without saying. Re (3): until, perhaps, you start taking about copying or pickling? ;-) Regards, Bengt Richter From tim at gerla.net Thu Jul 10 15:57:59 2003 From: tim at gerla.net (Tim Gerla) Date: 10 Jul 2003 12:57:59 -0700 Subject: treeview / pygtk problem In-Reply-To: References: Message-ID: <1057867079.12251.7.camel@redwall.ofsloans.com> On Thu, 2003-07-10 at 11:53, Andre Lerche wrote: > Hi list, > > I am quite new to Python and try to learn Python with a small pygtk > program. I am facing a problem which I am unable to solve for myself. > I think I have read the documentation and some samples, but however > I cannot find my mistake, so hopefully someone can help me with a > short hint. This is a small sample application which demonstrates > my problem: > > import gtk as g > import gobject > > window = g.Window () > window.connect ('delete_event', g.mainquit) > scrolledwin = g.ScrolledWindow () > renderer = g.CellRendererText () > col1 = g.TreeViewColumn ("col 1", renderer, text=1) > col2 = g.TreeViewColumn ("col 2", renderer, text=1) ----^ That's your problem right there: text= expects a sequence from 0 to n. So try: col1 = g.TreeViewColumn ("col 1", renderer, text=0) col2 = g.TreeViewColumn ("col 2", renderer, text=1) That should solve your problem! -Tim tim at gerla.net From vze4rx4y at verizon.net Sat Jul 19 19:23:25 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 19 Jul 2003 23:23:25 GMT Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> Message-ID: [Michele Simionato] > > >>I often feel the need to extend the string method ".endswith" to tuple > > >>arguments, in such a way to automatically check for multiple endings. > > >>For instance, here is a typical use case: > > >> > > >>if filename.endswith(('.jpg','.jpeg','.gif','.png')): > > >> print "This is a valid image file" [Jp] > > > extensions = ('.jpg', '.jpeg', '.gif', '.png') > > > if filter(filename.endswith, extensions): > > > print "This is a valid image file > > > > > > Jp [Irmen] > > Using filter Michele's original statement becomes: > > > > if filter(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > > print "This is a valid image file" > > > > IMHO this is simple enough to not require a change to the > > .endswith method... [Michele] > I haven't thought of "filter". It is true, it works, but is it really > readable? I had to think to understand what it is doing. > My (implicit) rationale for > > filename.endswith(('.jpg','.jpeg','.gif','.png')) > > was that it works exactly as "isinstance", so it is quite > obvious what it is doing. I am asking just for a convenience, > which has already a precedent in the language and respects > the Principle of Least Surprise. I prefer that this feature not be added. Convenience functions like this one rarely pay for themselves because: -- The use case is not that common (afterall, endswith() isn't even used that often). -- It complicates the heck out of the C code -- Checking for optional arguments results in a slight slowdown for the normal case. -- It is easy to implement a readable version in only two or three lines of pure python. -- It is harder to read because it requires background knowledge of how endswith() handles a tuple (quick, does it take any iterable or just a tuple, how about a subclass of tuple; is it like min() and max() in that it *args works just as well as argtuple; which python version implemented it, etc). -- It is a pain to keep the language consistent. Change endswith() and you should change startswith(). Change the string object and you should also change the unicode object and UserString and perhaps mmap. Update the docs for each and add test cases for each (including weird cases with zero-length tuples and such). -- The use case above encroaches on scanning patterns that are already efficiently implemented by the re module. -- Worst of all, it increases the sum total of python language to be learned without providing much in return. -- In general, the language can be kept more compact, efficient, and maintainable by not trying to vectorize everything (the recent addition of the __builtin__.sum() is a rare exception that is worth it). It is better to use a general purpose vectorizing function (like map, filter, or reduce). This particular case is best implemented in terms of the some() predicate documented in the examples for the new itertools module (though any() might have been a better name for it): some(filename.endswith, ('.jpg','.jpeg','.gif','.png')) The implementation of some() is better than the filter version because it provides an "early-out" upon the first successful hit. Raymond Hettinger From gregbrunet at NOSPAMsempersoft.com Tue Jul 1 22:09:58 2003 From: gregbrunet at NOSPAMsempersoft.com (Greg Brunet) Date: Tue, 1 Jul 2003 21:09:58 -0500 Subject: Howto: extract a 'column' from a list of lists into a new list? References: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Message-ID: "Max M" wrote in message news:3f013fb1$0$97259$edfadb0f at dread12.news.tele.dk... > Greg Brunet wrote: > > but I expect that one of those fancy map/lamda/list comprehension > > functions can turn this into a list for me, but, to be honest, they > > still make my head spin trying to figure them out. Any ideas on how to > > do this simply? > > fields = [ > ('STOCKNO', 'C', 8, 0), > ('DACC', 'C', 5, 0), > ('DEALERACCE', 'C', 30, 0), > ('D-ACCRTL', 'C', 9, 0), > ('D-ACCCST', 'C', 9, 0) > ] > > > # The "old" way to do it would be: > NAME_COLUMN = 0 > results = [] > for field in fields: > results.append(field[NAME_COLUMN]) > print results > > > # But list comprehensions are made for exactly this purpose > NAME_COLUMN = 0 > results = [field[NAME_COLUMN] for field in fields] > print results Max: Thanks for that clarification of list comprehensions. Now there's a better "Greg comprehension" of the subject. [groan - I know that was bad, but it's been a rough couple of days of programming, & it usually brings that type of comment out, sorry ;) ] Thanks for your help, -- Greg From egbert.list at hccnet.nl Sun Jul 27 10:41:22 2003 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Sun, 27 Jul 2003 16:41:22 +0200 Subject: Tools for reading Dr Dobb's Python-URL In-Reply-To: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> References: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> Message-ID: <20030727144122.GA1689@mirk.lan> On Sun, Jul 27, 2003 at 01:48:55PM +0200, Irmen de Jong wrote: > > Open the message in your news reader. > Click on an URL in the message. > > Sorry, couldn't resist. I'm not sure what you want to > do, really? My mail reader is the text-based Mutt, which: - doesn't react to mouse clicks - does show url's in a different color - seems not to do anything useful with them The Mutt-documentation says that in order to read the document an url refers to, you have to pipe the e-mail into another program, eg. urlview. But that program only shows a list of all the url's in the e-mail-message, without context, and that is not very illuminating, especially not if many of them refer to googled [mailman] groups. So I am am looking for something better. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From abelikov72 at hotmail.com Tue Jul 8 11:56:58 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 08 Jul 2003 15:56:58 GMT Subject: Python vs PHP References: Message-ID: On Mon, 07 Jul 2003 13:47:00 +0300, Catalin wrote: >Can Python replace PHP? >Can I use a python program to make an interface to a mysql 4.X database? >If that's possible where can I find a tutorial? > I recommend Spyce, Webware, or Quixote depending on your requirements, but Draco, SkunkWeb, RoadKill are worth looking into as well. Spyce is really the best (for PHP-ness) in my opinion, after you actually get past the fact that it supports your old fashioned notion of what embedded delimiters should look like, as well as a new CTS-friendly alternative. Spyce is the closest thing to PHP, but also provides some features PHP does not. However, I think you will find some people, like myself, who are still unable to make the switch from PHP to Python for web development, because of a lot of little things. These people know Python is better and may even know their non-web PHP applications are hell compared to their Python re-implementations. However, they still use PHP for web development and feel they have to. They may have even written out all the requirements and received vague responses to them. Python web development is fragmented. Mod_python CVS now contains the work of what used to be mod_psp by Sterling Hughes, a PHP warlord, I'm sure he'll reply. This possibly soon to be official 'PSP' is not much in my opinion and should probably not be folded into mod_python. Others agree: http://www.modpython.org/pipermail/mod_python/2003-June/003200.html Another big problem with Python web development is the lack of good shared hosting support. Primarily the lack of anything resembling PHP's safe mode. Mod_python has no equivalent of this safe mode, but Apache 2's 'Perchild MPM' is supposed deprecates this need. However, this still requires an httpd.conf edit and a restart of Apache for every user added, very annoying, especially to a shared hosting service. http://apache.slashdot.org/apache/02/12/02/1346206.shtml?tid= http://httpd.apache.org/docs-2.0/mod/perchild.html http://www.modpython.org/pipermail/mod_python/2001-November/001705.html A couple other slight issues : * catch-all error handling not as flexible or non-existent * no equivalent to php_value auto_prepend_file "_header.php" * no equivalent to php_value auto_append_file "_footer.php" * not as intelligent form value handling * white space sensitivity is a unique problem when embedding The best options for me are currently : * use PHP * use Spyce * fork Spyce (creating more fragmentation) * embed python straight into my favorite platform (quite funny) * write my own mod_python-based platform (more fragmentation) * find the holy grail (i must have missed it) I've been handling this dilemma for months. I've even benchmarked quite a few possible solutions, with pleasing results in those which I thought were well done, and pleasing results for Python over PHP in general. -AB From pipen at beast_tu_kielce.pl Sun Jul 13 12:46:45 2003 From: pipen at beast_tu_kielce.pl (Artur M. Piwko) Date: Sun, 13 Jul 2003 16:46:45 +0000 (UTC) Subject: wxPython - question References: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> Message-ID: In the darkest hour on Sat, 12 Jul 2003 21:55:39 -0700, Tim Roberts screamed: >>How can I remove program entry from taskbar (not tray)? > > PLEASE resist the temptation to built Yet Another Tray Application. Win32 > programmers seem to use the tray icons as a sign of their guruness, and > every one of them seems to think that his application is so studly that it > must occupy permanent real estate on my desktop. I've seen some trays that > bloat to 20 or 30 icons. > > Don't do it. Your application just isn't that important. If you need to > notify me of something, I find nothing wrong with a good old-fashioned > dialog box. > I am writing Jabber/others messenger. In this case, tray icon is not a sign of guruness, but user friendliness. Artur -- Before the Goat of Mendes... we all must take our turn | Artur M. Piwko Into the magic circle... where still the fire burns | mailto:s/_/./ We're spinning round and round... until one takes a fall | -- Mercyful Fate The fallen one will not return, the fallen one must burn | "Witches' Dance" From shalehperry at comcast.net Thu Jul 17 10:15:25 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Thu, 17 Jul 2003 07:15:25 -0700 Subject: IMAP examples In-Reply-To: References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: <200307170715.25697.shalehperry@comcast.net> > > If my english was better I would love to help improve the python > documentation, most modules in the standard libraries lack good > examples how to *use* them with just a simple description. And a > short motivation for the design of a module if possible like "just > copied the C API" or "Because of efficiency ..." or "We use a class > framework here because ...". A gigantic task. The PSL book by effbot > is great but it's a book. And it needs a new version. part of the reason why the docs are not but so great is that most of the library is Python code which means any questions can be answered by reading the source. I find myself doing this quite often. Many modules have a little blurb at the top that gives an example of their usage. from imaplib.py: Instantiate with: IMAP4([host[, port]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 port). All IMAP4rev1 commands are supported by methods of the same name (in lower-case). All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. If necessary (the string contains any non-printing characters or white-space and isn't enclosed with either parentheses or double quotes) each string is quoted. However, the 'password' argument to the LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the 'flags' argument to STORE) then enclose the string in parentheses (eg: "(\Deleted)"). Each command returns a tuple: (type, [data, ...]) where 'type' is usually 'OK' or 'NO', and 'data' is either the text from the tagged response, or untagged results from command. From tjreedy at udel.edu Mon Jul 28 11:30:32 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jul 2003 11:30:32 -0400 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> <3f210717$0$76049$edfadb0f@dread11.news.tele.dk> <6f03c4a5.0307280705.6a4ab103@posting.google.com> Message-ID: <28Kdncq1IrIE3LiiXTWJgA@comcast.com> "Rim" wrote in message news:6f03c4a5.0307280705.6a4ab103 at posting.google.com... > "Terry Reedy" wrote in message > > So to answer the OP's question, the problem solved is that directly > > assigning a function as an instance attribute binds the function as a > > function, which means no *automatic* access to the instance and its > > other attributes. > I don't understand why you say "no automatic access". Re-read the sentence again. The key point is 'assign ... as instance attribute'. > If you examine > the following, I have access to the attributes defined in the class, > without doing anything special: > > >>> class a: > ... def __init__(self,name): > ... self.msg = "hi" > ... self.name = name > ... > >>> def f(self): > ... print "hello" > ... print self.msg > ... print self.name > ... > >>> a.f = f a is the class, not an instance, making the new class attribute f a method just as if it has been part of the class statement. > >>> b=a("Joe") > >>> b.f() > hello > hi > Joe Try b.f = f instead and then call b.f() and b.f(b). Now try b.f = new.instancemethod(f) and then call b.f() and b.f(b). The results should answer your questions. Terry J. Reedy > >So to answer the OP's question, the problem solved is that directly > >assigning a function as an instance attribute binds the function as a > >function, which means no *automatic* access to the instance and its > >other attributes. If such access is needed, the instance must be > >passed explicitly, as in > >a1.f = lambda self: repr(self) > >a1.f(a1) > > > >Instancemethod adds the option of wrapping instance-specific functions > >as bound methods getting the instance as an automatic first (self) > >paramater, just like with class-wide methods. In the 'hi' example From duncan at NOSPAMrcp.co.uk Wed Jul 16 10:29:21 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 14:29:21 +0000 (UTC) Subject: <> and != References: <3F154B63.3060503@hotmail.com> <3F154BBD.2060304@hotmail.com> <3jlahv8o1fcu2j0oij2p31c32nftnb3er8@4ax.com> <3F155B6D.8000205@hotmail.com> Message-ID: hokiegal99 wrote in news:3F155B6D.8000205 at hotmail.com: > Thank you, that is what I thought. What's the reason for having two > symbols mean the same thing? > Originally Python only had '<>' for the not-equal comparison. Version 0.9.3 added a bunch of C like syntax, such as C's shifting and masking operators. It also added C style '==' and '!=' comparison operators. The original '<>' remains valid for backwards compatibility. -- 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 http Mon Jul 28 18:23:40 2003 From: http (Paul Rubin) Date: 28 Jul 2003 15:23:40 -0700 Subject: Fastest way to count your iterations? References: Message-ID: <7xsmoqguj7.fsf@ruckus.brouhaha.com> tracer at axiomfire.com (Tracy Ruggles) writes: > def counter(items, f, sep=1000): > i = 0 > for item in items: > f(item) > i += 1 > if i % sep == 0: > print i How's this, if items is a sequence: def counter(items, f, sep=1000): for i in xrange(0, len(items), sep): map(f, items[i:i+sep]) if i > 0: print i From sabu at pure-elite.org Fri Jul 4 06:55:36 2003 From: sabu at pure-elite.org (Xavier) Date: Fri, 4 Jul 2003 06:55:36 -0400 Subject: Gathering variable names from within a function. Message-ID: <004001c3421a$ccb3e370$6401a8c0@boxen> Greetings, I was wondering if there was a way to get a list of all the variables which were executed/created/modified within a function? Here is a simple example that comes to my mind: def getVars(func): ... ... ... def modVar(arg, arg2): Var1 = arg Var2 = arg2 Var3 = arg+arg2 return Var3 def main(): print getVars(modVar('test', 'test2')) # end naturally, "Var1", "Var2" and "Var3" should be printed to the user. Any idea? -- Xavier oderint dum metuant From vze4rx4y at verizon.net Wed Jul 2 12:49:53 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 02 Jul 2003 16:49:53 GMT Subject: Newbie advice for string fromatting References: Message-ID: "gt" wrote in message news:f9b7c11d.0307020642.7231cd82 at posting.google.com... > O.k., four days into playing with python > and I have a little problem that I would like > to get some feedback on. > ( as far as the best way to go about it ) > > Basically, just a little Mad-Libs type script. > > Something like: > > libs = ["adverb", "noun", "verb", "tool"] > words = {a:j, n:j, v:j, t:j} > for x in libs: > print "Enter a ", x, ": ", > words[j] = raw_input() > print "The %s %s %s with a %s." % (a, n, v, t) > > What is the most efficient way to do something like this? You're on the right track. Using dictionaries with the % formatting operator is efficient. Subclassing a dictionary with a question asker is an approach that keeps the code simple and separates it from the actual madlib strings. So, here is version to get you started: >>> farmtale = """ At %(name)s farms, we drive a %(machine)s over the %(vegetable)s crops and feed %(food)s to our %(animal)s.""" >>> class Madlib(dict): def __getitem__(self, key): return raw_input("Enter a %s: " % key) >>> print farmtale % Madlib() Enter a name: Donald Enter a machine: clock Enter a vegetable: squash Enter a food: pizza Enter a animal: snake At Donald farms, we drive a clock over the squash crops and feed pizza to our snake. Raymond Hettinger From intentionally at blank.co.uk Mon Jul 14 22:59:53 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:59:53 +0100 Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: On Tue, 15 Jul 2003 02:26:58 GMT, "Bryan" wrote: >> >> In maths, a variable binds to a value. In Python, a variable binds to >> an object in a way that does no correctly implement binding to a value >> unless the object happens to be immutable. >> > >this sentence is completely FALSE because python does not have the concept >of variables that bind to values. The term 'variable' is defined by mathematics and computer science. The fact that Python has arbitrarily redefined it is the cause of very real confusion and errors. > therefore it's impossible for python to >incorrectly implement binding variables to values like in math. python does >not have the concept of variables. instead, as has been pointed out several >times, python has what you can call "names" that bind to objects. Bogus. Read the Python tutorial. I think you'll find the first use of the word 'variable' in the file node4.html ("Using the Python Interpreter"). Actually, there are earlier uses but they allow plausible deniability in the interpretation. This is the first time when the tutorial specifically refers to a variable existing... """ When known to the interpreter, the script name and additional arguments thereafter are passed to the script in the variable sys.argv """ > two >completeley different concepts. i think a lot of this argument is based on >this false premise that python has true "slot" variables and incorrect >comparisons are being made. No. The point requires a certain amount of pedanticism, but that doesn't mean it isn't real or important. In mathematics and computer theory, variables bind to values. In a computer language, that binding can be implemented in various ways. The Python way, however, does not respect the original definition. The binding to objects has side-effects which do not respect the principle of binding to values. From gh at ghaering.de Wed Jul 9 06:50:51 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Jul 2003 12:50:51 +0200 Subject: Why Python In-Reply-To: <3f0be9ac@news.comindico.com.au> References: <3f0be9ac@news.comindico.com.au> Message-ID: <3F0BF38B.1070201@ghaering.de> Tony Steward wrote: > Hello All, > I am looking for a programming language to use to write a database type > application to run on windows machines. Is python for me or pls suggest what > is. Python is excellent for database work. > Is there a page that explains in simple terms what Python can do on windows? No single page, but with the win32 extensions, Python can access Windows-specific stuff like COM and the win32 API just fine. > Is there an IDE? There are, but if you're into thin GUI clients like VB6, there is no direct equivalent. It's a lot more common to create GUIs from code without form designers under Python. > Is the windows api pre wrapped? Sure. Part of the win32 extensions. http://starship.python.net/crew/mhammond/ Alternatively, you can use the Python distribution from ActiveState which contains win32all already, plus some additional goodies like a package management system and Python docs in Windows Help format. -- Gerhard From duncan at NOSPAMrcp.co.uk Wed Jul 16 10:59:44 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 14:59:44 +0000 (UTC) Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> <20030716081550053-0600@news.xmission.com> Message-ID: Adam Ruth wrote in news:20030716081550053- 0600 at news.xmission.com: >> Initialisation uses '=', assignment uses ':='. Note that the constant >> is defined as a real and initialised with one, but the variable is a >> reference to a real and initialised with a storage location. The last >> example is not initialising x with the value, it is implicitly >> initialising x with a location then assigning the value into that >> location. >> > > That's interesting. What does it use for an equality operator? > Tricky question that. It uses the equals symbol which might, or might not be spelled '=' or 'EQ'. Sorry, my pedantry is trying to get the better of me. Algol68 defines its syntax in terms of the tokens that it accepts, it doesn't really force you to spell its tokens any particular way. The language definition uses bold face for symbols such as 'real', and the implementation might choose to recognise REAL, .real., 'real, or some special [real] symbol in your character set. Case stropping, which I think was commonest, uses upper case. The language is quite clear on this giving as an example that various typefaces of begin could be used to represent the begin symbol including a combination of hole on a punch card. In particular, although the symbol used for equality testing in the language definition looks like =, the other operators look more like the appropriate mathematical symbols than, say, <=, and the implementation may decide how the symbols are to be represented. See http://www.fh-jena.de/~kleine/history/languages/Algol68- RevisedReport.pdf -- 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 jocsch at phreaker.net Sun Jul 6 16:13:39 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Sun, 06 Jul 2003 22:13:39 +0200 Subject: Search for mapping solution References: Message-ID: > > lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] > costs = {} > for name,number,price in lines: > costs[name] = costs.setdefault(name,0)+float(price) > print costs > thanks it works. But maybe I can complicate the example a little bit (because in real world it's more complicated): What if I every list in lines has 20 or more entries and I have only the index number to access the name, e.g. lines = [['elem1','elem2','fred','elem3',.......;'elem 17','333','elem18','0.10'],[...],[...]] what I want to say: I can't be sure that the name is always on the third position. That's dynamic. I know it before I parse the list, but I can't say for elem1,elem2,name,.... cause it can also be for elem1,name,elem3 .... Thanks for the answer, Markus From kbass1 at nc.rr.com Sun Jul 6 20:08:08 2003 From: kbass1 at nc.rr.com (Kevin Bass) Date: Sun, 6 Jul 2003 20:08:08 -0400 Subject: Newbie Question: Abstract Class in Python References: <00ec01c34050$49ab4bb0$6401a8c0@boxen> Message-ID: <007001c3441b$d8eb7060$2a523942@homebass1> Hello: I am new to Python and want to know how to implement an abstract class? I have read through different books and I have no found this information. Thanks! Kevin From hst at empolis.co.uk Tue Jul 22 05:49:41 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 22 Jul 2003 10:49:41 +0100 Subject: Python Mystery Theatre -- Episode 3: Extend this Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4DD@hendrix.empolisuk.com> Raymond Hettinger wrote: > > Here are few more mini-mysteries for your amusement > and edification. > > Again in this episode, the program output is not shown. > Your goal is to predict the output and, if anything > mysterious occurs, then explain what happened > (in blindingly obvious terms). > > This time, the extra credit is for picking-out the three > that surfaced as errors in my own, real code over > the past few years (the example context below may be > different, but the type of error occurred in real code). > > Try to solve these without looking at the other posts. > Let me know if you learned something new along the way. > > > Enjoy, > > > Raymond Hettinger > > > ACT I --------------------- > def real(z): > return hasattr(z, 'real') and z.real or z > def imag(z): > return hasattr(z, 'imag') and z.imag or 0 > for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L: > print real(z), imag(z) > I guess this was a real error. print real(z), imag(z) will give 6j, 6 as z.real is 0, therefore the result of the first expression is z which is 6j > ACT II --------------------- > uniq = {} > for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0): > uniq(k) = 1 > print len(uniq) > Assuming it should read uniq[k] = 1, the answer is three as there are only three unique keys - 10, 'Ten' and 'ten' > ACT III --------------------- > s = 'abracadabra' > for i in [3, 2, 1, 0]: > print s[i:], s[-i:] > as -0 is the same as 0, I presume the trap is that s[-i:] when s == 0 gives 'abracadabra', whereas the three preceding values are 'bra', 'ra' and 'a' > ACT IV --------------------- > pets = list('cat ') > pets += 'dog ' > pets.extend('fish ') > print pets + 'python' > I guess this was a real error as I've done it myself. pets is a list of characters, initially ['c', 'a', 't'], which is then extended by += 'dog ' and .extend('fish') The print statement is trying to concatenate a string to a list, which isn't allowed. I suppose this is why some people don't like augmented assignment as the results are sometimes unexpected. > INTERMISSION (with output included, oh yeah! ------------ > >>> import operator > >>> 1 - reduce(operator.add, [1e-7]* 10**7) > 2.4983004554002264e-010 Is this just the rounding error on a particular machine in evaluating 1e-7* 10**7? > > ACT V --------------------- > class Bin: > numitems = 0 > contents = [] > > def add(self, item): > self.numitems += 1 > self.contents += [item] > > laundry = Bin() > groceries = Bin() > > laundry.add('shirt') > groceries.add('bananas') > groceries.add('nuts') > laundry.add('socks') > groceries.add('pretzels') > > print laundry.numitems, laundry.contents > print groceries.numitems, groceries.contents I guess this was a real error due to the unintended use of class variables. the two print statements yield identical results with 5 items in each. > > > ACT VI ----------------------------------------- > print "What is the technical name for this algorithm or > transformation?" > a = range(0, 100, 10) > import random > random.shuffle(a) > print "Input:", a > swaps = 0 > for i in range(len(a)): > for j in range(i+1, len(a)): > if a[i] > a[j]: > i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1 > print "Output:", a > print "Workload;", swaps > > It's a quick and dirty bubble sort. Not sure what's wrong without running the code, but it looks wrong to mess around with the loop indices. Perhaps the swapping line should read a[i], a[j], swaps = a[j], a[i], swaps+1. BTW isn't there an indentation error in the code? > Interesting set of puzzles. _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From jude-venn at blueyonder.co.uk Mon Jul 21 08:42:33 2003 From: jude-venn at blueyonder.co.uk (Jude Venn) Date: Mon, 21 Jul 2003 12:42:33 +0000 Subject: pythonic malloc References: Message-ID: <20030721124233.18f56047.jude-venn@blueyonder.co.uk> how about something like: retpacket = "\xf0\x00\x02\x00"+socket.gethostname() retpacket += chr(0) * (25 - len(retpacket)) On Mon, 21 Jul 2003 09:15:26 GMT kjockey wrote: > I have some simple UDP code that does: > s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr) > > This is OK, except that I'd like to change the text in the middle ("rachel", > which is the hostname FWIW), and the NUL padding needs to go out to make > the length 25 bytes (so the padding depends on the length of the name). > > So I could do something like: > retpacket = "\xf0\x00\x02\x00"+socket.gethostname() > while len(retpacket) < 26: > retpacket += "\x00" > s.sendto(retpacket, addr) > > But that feels "wrong". And Python in a Nutshell says its a bad idea - > "anti-idiom". > > Can anyone show me the true path? > > Brad From jjl at pobox.com Tue Jul 1 13:17:06 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Jul 2003 18:17:06 +0100 Subject: Question regarding naming convention References: <1056988215.49928.0@iris.uk.clara.net> <1057062415.13616.0@doris.uk.clara.net> Message-ID: <87adby88vh.fsf@pobox.com> michael writes: [...] > Yeah, thanks for the quote. Unfortunately, this still leaves me with > syntax that's a bit unfriendly. Taking the StringIO class as an > example, I can either write: > > import StringIO > s = StringIO.StringIO() > > or: > > from StringIO import StringIO > s = StringIO() > > Both of the above seem to overcomplicate the syntax. Of the two, I Well, one is simpler when you only use StringIO.StringIO once or twice, and the other is simpler when you use it lots of times. Really, there are two issues, I suppose. First, the second form has the convenience of shorter names. Second, the first form is useful where somebody reading your code would otherwise have to keep referring to your imports to see where names came from, or might be confused by similarly-named classes in different modules. Third, ease of switching names -- sometimes it's convenient to be able to swap from StringIO import StringIO to from cStringIO import StringIO And have your code work unchanged. OK, three issues. A fourth issue is that it's nice not to mix the two styles, to avoid confusing readers. > prefer the second, but I'm sure I've read on c.l.py that the > from..import.. version is not a preferred way of doing things. Nothing un-preferred about 'from foo import bar'. What is discouraged is 'from foo import *' (that's a literal *, if you haven't seen that syntax before -- see the tutorial). It is useful sometimes, though. In PyQt, for example. > Is there no way to write a class, such that the statement: > > import MyClass > > would dynamically import the MyClass class from MyClass.py ? Well, maybe (I'm vaguely aware that there's an import hook of some kind). *Nobody* would thank you for it, other than as a joke. > It just surprises me that there isn't a neater way around this, as > Python seems to encapsulate most everything else in a simple way. Modules are useful, and explicit is better than implicit. John From guettler at thomas-guettler.de Tue Jul 1 09:38:43 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Tue, 01 Jul 2003 15:38:43 +0200 Subject: Unicode problem.... as always References: <631aeedc.0307010420.685500e9@posting.google.com> Message-ID: Todd Jenista wrote: > I have a parser I am building with python and, unfortunately, people > have decided to put unicode characters in the files I am parsing. Maybe this helps you. It converts a latin1 byte to unicode and then converts it to utf8. >>> s="?" >>> s_u=unicode(s, "latin1") >>> s_utf8=s_u.encode("utf8") You need to know the encoding of the input (utf8, utf16) . thomas From gmuller at worldonline.nl Mon Jul 28 14:40:46 2003 From: gmuller at worldonline.nl (GerritM) Date: Mon, 28 Jul 2003 20:40:46 +0200 Subject: default import path References: <3f24c37e@news.maxnet.co.nz> Message-ID: "Peter" schreef in bericht news:3f24c37e at news.maxnet.co.nz... > > > How can I edit the default import path for Python under Windows? > > I want to use the piddle module. So far, I've copied the unzipped contents > of the zip file to c:\prog~1\python\lib\site-packages, but how do I set it > so this is automatically on the python path? > > (I don't want to have to manually add that directory every time.) > > TIA > > Peter > create a piddle.pth file in the main Python directory (c:\prog~1\python in your case?), with the pathname of piddle as line of text in the file: c:\prog~1\python\lib\site-packages\piddle (check the last part, this is the directory on my machine) kind regards, Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From shane at zope.com Fri Jul 25 20:41:47 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 25 Jul 2003 20:41:47 -0400 (EDT) Subject: Static typing In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E2019202CE473B@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E2019202CE473B@admin56.narex.com> Message-ID: On Fri, 25 Jul 2003, Bjorn Pettersen wrote: > However, the only way said programmer can do that is by looking at > _your_ code, and then changing _your_ code. Wouldn't: > > def foo(bar, baz): > """... > Expects: > bar: integer in the range (0..65535) > baz: string (used as binary data) > ... > """ > > be much more useful for said programmer? Afterall, we're all adults > here. It depends on the context and intent. Type checking is useful in several ways, even in Python: - When you're evolving new code, function signatures change often, and you can use type checks as a safety belt. You can save time this way if you apply it in moderation. (The problem with statically typed languages is that they usually mandate this technique to the point that it becomes a large burden.) - If you're writing secure code, you can't trust the inputs. Of course, in this case you need stronger checks than assert statements. - If you're translating Python to a lower level language, you can use type checks as reliable hints for the translator. - When you're working with a large codebase, many developers, and many parts changing simultaneously, type checks can enhance your functional and system testing strategies. There have been several articles and interviews lately saying that type checking is a distraction and that testing is the right way to go. I agree that unit tests should come first, but type checks remain a useful tool that increases productivity when used in moderation. Shane From abbeflabbe at InospamIhotmail.com Sat Jul 12 04:41:27 2003 From: abbeflabbe at InospamIhotmail.com (Linkages) Date: Sat, 12 Jul 2003 08:41:27 GMT Subject: FTP search Message-ID: im new with python.. im trying to do a script to find a file in a FTP ...the script is supposed to work with a recursive function that search in the FS entering in each DIR until the file is found... more or less something similar... Function read_directory( directory_start ) { list allfilespresentintheDIR if (fileX) is present END else for each DIR in [directory_start] { read_directory( newdirectory_start ); // ricorsion } Next; } i dont know how to translate for each DIR in (directory_start) using ftplib i know how to list files ... to list dirs... but i dont know how to point at each dir... suggetions ? bye linkages From mcfletch at rogers.com Sun Jul 20 10:55:35 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 20 Jul 2003 10:55:35 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: Message-ID: <3F1AAD67.8010005@rogers.com> Aahz wrote: >In article , >Mike C. Fletcher wrote: > > >> * finally, stores the value >> o tries to do what would have been done if there were no >> descriptor (with the new, coerced value) >> o does *not* create new names in the object's namespace (all >> names are documented w/ descriptors, there's not a lot of >> '_' prefixed names cluttering the namespace) >> o does *not* require a new dictionary/storage-object attribute >> for the object (the descriptor works like any other >> descriptor, a *stand-alone* object that replaces a regular >> attribute) >> >> > >But this is a recipe for name clashes. If you follow the first bullet, >it's a normal attribute, but everything else says you want a property. >Properties are themselves objects that are attached to names in an >object. You can't have the same name bound to two different objects. > > It's true that: * your class has a namespace, and there are objects stored in that namespace o the objects stored in that namespace often are descriptors o they are available to the instances which do not shadow them (as I said, I can deal with this, and it's cleaner anyway). + if they are descriptors, they modify instance access to attributes * you can't have a property object in the class namespace if you're storing the meta-class property-value there o *unless* the value is the property (perfectly reasonable value to store for the meta-class property) * the metaclass properties are stored in the metaclass' dictionary, so they don't conflict with metaclass instances' values for the properties * the metaclass instance's property *values* would be stored in the metaclass instance's dictionary, just as is normally done (the metaclass' property *descriptors* would be stored in the metaclass' dictionary), there's no new conflicts created here, everything just works like it does now, a lookup would look something like this: >>> x.y x doesn't have a __getattribute__, so see if it has a descriptor for 'y' get type(x).y type(x) doesn't have a __getattribute__, so see if it has a descriptor for 'y' get type(type(x)).y -> this is just a simple descriptor, as there's no higher-level descriptor, has a __get__ method, calls it to retrieve type(x).y returns the currently stored entry 'y' in type(x)'s dictionary, which happens to be a descriptor has type(x).y, a descriptor with a __get__ method, calls it, gets back value stored in instance's dictionary returns the value of y stored in the instance dictionary You wind up with some names that are not available for use *as properties* on instances *iff* you set a simple value for the properties of the meta-class instance, but you solve that the regular way, by making the value stored by the meta-class instance's property a descriptor, rather than a simple value. That's just the way classes work. Yes, it's a "name clash", but everything in classes/instances is name clashes . Not a problem I can see in the problem I outlined just yet, there's still no low-level value-setting mechanism exposed, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bdesth.nospam at removeme.free.fr Thu Jul 10 19:15:34 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 10 Jul 2003 23:15:34 +0000 Subject: Parsing References: Message-ID: <3F0DF396.6030409@removeme.free.fr> Simon Bayling wrote: > whatsupg21 at hotmail.com (Michael) wrote in > news:e5fb8973.0307100938.13fcea56 at posting.google.com: > >>I have been assigned a project to parse a webpage for data using >>Python. I have finished only basic tutorials. Any suggestions as to >>where I should go from here? Thanks in advance. >> > (snip) > > If the data to find is more complicated, or you need to parse the HTML as > well, you should look at more string methods, maybe regular expressions > (import re)... Or the HTML or SGML parsers that are part of the standard library... Bruno From buzzard at urubu.freeserve.co.uk Mon Jul 28 09:38:21 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 28 Jul 2003 14:38:21 +0100 Subject: urn scheme Message-ID: Hello, I'm currently doing some simulations where I need to sample without replacement from a list of counts. (Actually it's a Numeric array, but I'm currently converting the array to a list, using the following function and converting back to an array.) I *desperately *need to speed this up (simulations currently take over 24 hours). This sampling is a real bottleneck, and accounts for about 90% of the time cost. If I can get a 10-fold speed up I might be in business, and a 100-fold speed up might even allow me to meet a deadline. Using psyco appears to give me no speed up whatsoever (that can't be right, can it?). I am currently working on reducing the number of function calls to urn(), but the biggest speed up will still come from improving the performance of this function. Any ideas for a significant speed up? TIA. Duncan ----------------------------------------------------------- import random def urn(bins, draws, drawn=0, others=0): """Bins is a sequence containing the numbers of balls in the urns. 'drawn' and 'others' define how the contents of the bins should be updated after each draw in draws. The default arguments correspond to sampling with replacement. e.g. drawn = -1 corresponds to sampling without replacement""" len_bins = len(bins) res = [0] * len_bins cum_bins = [bins[0]] + [0] * (len_bins-1) for i in range(1, len_bins): cum_bins[i] = cum_bins[i-1] + bins[i] for i in range(draws): balls = random.random() * cum_bins[-1] adj = 0 for j in range(len_bins): if adj == 0 and cum_bins[j] > balls: res[j] += 1 cum_bins[j] += drawn adj = 1 else: cum_bins[j] += (j - adj) * others + adj * drawn return res ---------------------------------------------------------------- e.g. >>> urn((0,2,5,3,4), 10, -1) [0, 1, 4, 1, 4] >>> From missive at frontiernet.net Sun Jul 20 18:56:03 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 20 Jul 2003 22:56:03 GMT Subject: Newbie! I'm a newbie! What's wrong with this program? References: <5da8e4b3.0307191800.48dc0a6d@posting.google.com> Message-ID: > import math ##loads the math modual > ########Start created Functions######### > ##Function for converting minutes to hours## > def minHour(x): > min = 60 > hour = min * x > print hour > ##Function creates a new line## > def newLine(): > print > #######End created Functions######## > ###Start Variables#### > x_hours = 5 > ###End Variables#### > newLine(); > print "There are", minHour(x_hours), "minutes in", x_hours, "hours"; > newLine(); > print "Program Terminated."; > newLine(); # mi.py import math import sys def minutes_per_hour(hours): MIN_PER_HOUR = 60 return hours * MIN_PER_HOUR def print_minutes(hours): minutes = minutes_per_hour(hours) print "There are %s minutes in %s hours" % (minutes, hours) print if __name__ == '__main__': hours = float(sys.argv[1]) print_minutes(hours) # >python mi.py 5.2 There are 312.0 minutes in 5.2 hours >python mi.py 5 There are 300.0 minutes in 5.0 hours >python mi.py 5.25 There are 315.0 minutes in 5.25 hours From sholden at holdenweb.com Tue Jul 1 23:49:39 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 02 Jul 2003 03:49:39 GMT Subject: Python-2.3b1 bugs on Windows2000 with: the new csv module, string replace, and the re module References: Message-ID: "Daniel Ortmann" wrote in message news:hc6el19am1o.fsf at mhbs.lsil.com... > These problems only happen on Windows. On Linux everything works fine. > Has anyone else run into these bugs? Any suggestions? > > Where do I find out the proper bug reporting process? > http://sourceforge.net/tracker/?atid=105470&group_id=5470&func=browse regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From clifford.wells at comcast.net Sun Jul 13 01:48:00 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 12 Jul 2003 22:48:00 -0700 Subject: new in town In-Reply-To: References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: <1058075280.2220.67.camel@devilbox.homelinux.net> On Sat, 2003-07-12 at 20:27, David McNab wrote: > One more thing Elaine - I may offend others on this list in saying this, > but if you're doing GUI applications, I strongly suggest that you dive in > and familiarise yourself with Tkinter. It could well be the only GUI you > ever need in Python. > > Don't be intimidated if the Tkinter docs you come across urge you to > approach it from a Tk viewpoint- there's an excellent guide at: > http://www.astro.washington.edu/owen/TkinterSummary.html > > I argue for Tkinter over another popular Python-accessible GUI, wxWindows, > because Tkinter is smaller, faster and far less buggy, and has a really > nice 'feel' within the Python environment. Everyone is welcome to prefer whatever toolkit they like. However, please don't use false reasons to justify your preference. Smaller? Probably. Faster? I suspect the reverse is true, but I'd love to see your benchmarking methodology. Less buggy? Very arguable, but I'd be willing to concede that point if you concede that the reason for that state is because wxWindows more actively developed than Tk . Some *valid* reasons for choosing Tkinter over wxPython would be: 1. de facto standard for Python (and several other languages) 2. More widely ported 3. Somewhat simpler to learn Reasons to choose wxPython over Tkinter: 1. More diverse widget set (hence the size difference) 2. More flexible framework (hence the higher learning curve) Regards, Cliff -- Now as the petals are no more, a corroded shrinking stalk remains -Bauhaus From mwilson at the-wire.com Sun Jul 20 13:07:50 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 20 Jul 2003 13:07:50 -0400 Subject: object as a reserved keyword References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: >In article , >Lawrence Oluyede wrote: >> >>Does it worth to make "object" keyword a reserved one? > >Maybe. Python strives for a minimal syntax. Many identifiers that >would be keywords in other languages are simply names in the builtin >namespace. Plus it's not impossible that somebody could export a name in the set of standard names from a module or a class and accomplish something useful. I'm having trouble finding a convincing example, but consider class Debate: ... def agree (self, *args): pass # or some real code def object (self, *args): pass # usw. Regards. Mel. From akineko at pacbell.net Tue Jul 8 16:57:32 2003 From: akineko at pacbell.net (Aki Niimura) Date: 8 Jul 2003 13:57:32 -0700 Subject: Accessing Web site contents from a Python script (with use of Cookie) References: Message-ID: Ian Bicking wrote in message > On Mon, 2003-07-07 at 23:50, Aki Niimura wrote: > > I'm currently having a problem completing my script because the contents > > I would like to access in the Web site is a dynamic content and it is > > generated based on the Cookie contents which are set in another page. > > You should use ClientCookie: > http://wwwsearch.sourceforge.net/ClientCookie/ Thank you for getting me know such interesting Python module is available. I made my script working using HTTPResponse.getheader('Set-Cookie') and HTTPResponse.putheader('Cookie', cookie). Using ClientCookie would make such process hidden. I should use it next time. Thanks! Aki Niimura From newsgroups at jhrothjr.com Sun Jul 13 11:24:21 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 13 Jul 2003 11:24:21 -0400 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: "Fredrik Lundh" wrote in message news:mailman.1058088861.14670.python-list at python.org... > John Roth wrote: > > > > Read the source, Luke. > > > > I haven't gotten into the Python source, and my name > > is not Luke. > > And life's to short to waste on movies... Depends on what your goals in life are. > > On reading this over, it does sound a bit more strident than my > > responses usually do, but I will admit to being irritated at the > > assumption that you need to read the source to find out the > > answer to various questions. > > Well, you obviously didn't bother to read the documentation for > os.environ, so pointing you to the source sounds like a reasonable > idea. Not particularly. I might be one of that not inconsiderable number of people that doesn't know C. I'm not, but the number of people who use Python and who don't know C is not zero. I like Python because, for the most part, it's much more understandable than many languages I know, and that makes it much more productive. What I've learned in this conversation is that os.environ fails to handle one of the major corner cases in a Windows NT/2000/XP environment. So if I need that corner case, I'm going to have to use the Windows API call. Not a big deal, but also not something that I regard as one of the language's strengths. John Roth > From selwyn at home.net.nz Sun Jul 13 07:41:51 2003 From: selwyn at home.net.nz (selwyn) Date: Sun, 13 Jul 2003 23:41:51 +1200 Subject: timeout on os.popen3? Message-ID: hi all, I would like some advice on how I can include a timeout for a scanning operation using unzip on linux and os.popen3. I am scanning through about 30g of rescued zip files, looking for xml extensions within those files. What I have put together 'works', but only for what appears to be properly reconstructed files. Unfortunately, some aren't AND for some reason no standard error messages are being triggered. This causes my script to hang indefinitely. What I would like is for the script to move on to the next file, after say a 10sec period of inactivity, but am unsure how this could be included. I have googled around and think the select module may be helpful, but after reading the docs I am still confused :-( Here is what I have so far: #!/usr/bin/python import os,sys, time, string filesscanned=0 possibles=0 nonzips=0 files=[] a = os.listdir(sys.argv[1]) for i in a: print i stdin, stdout, stderr = os.popen3('unzip -l %s%s' % (sys.argv[1], i)) if stderr.read()=='': zippedfiles = string.lower(stdout.read()) if zippedfiles.find('xml')!= -1: os.system("""cp '%s%s' candidates"""% (sys.argv[1], i)) possibles +=1 print 'found a candidate:- %s%s'% (sys.argv[1],i) files.append(i) else: os.system("""cp '%s%s' nonzips"""% (sys.argv[1], i)) nonzips +=1 print 'found nonzip or broken file:- %s' %i filesscanned +=1 Any help gratefully received. cheers, Selwyn. From dave at nullcube.com Wed Jul 30 01:11:58 2003 From: dave at nullcube.com (Dave Harrison) Date: Wed, 30 Jul 2003 15:11:58 +1000 Subject: -shared option in distutils Message-ID: <20030730051157.GA28595@dave@alana.ucc.usyd.edu.au> afternoon pythonic gurus, quick question about distutils. Im compiling on solaris 9 and am having problems with the linking (I loathe solaris these days ;-), and if I call gcc by hand and remove the -shared flag and replace it with -G it works. But I just cant find where I need to change this in the distutils package for my install of python2.1.1. Where can I find it ? cheers Dave From exarkun at twistedmatrix.com Fri Jul 11 19:13:05 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Fri, 11 Jul 2003 19:13:05 -0400 Subject: socket problem In-Reply-To: <24472.1057964727@www25.gmx.net> References: <24472.1057964727@www25.gmx.net> Message-ID: <20030711230938.GA22310@intarweb.us> On Sat, Jul 12, 2003 at 01:05:27AM +0200, Gordon Wetzstein wrote: > Hello everyone, > > I have a problem with python sockets. I broadcast a lot of pickled objects > with socket. sendto(...), that works. Ireceive them on the other site with > socket.recvfrom(16384) The pickled objects are smaller (like 10000 bytes) > than the max bytes. > > The problem appears if I send too many pickled objects very quickly one > after another, then I only receive a part of the sent objects. I print > them before I send them, they are there but they never reach the > destination. When I do a time.sleep(0.1) (but not lesser than 0.1) after > socket.send() all is good but it's too slow! > > Does anyone know what the problem is? And maybe a solution! > UDP is an inherently unreliable protocol. If you require reliable data transmission, consider using TCP. Jp -- http://catandgirl.com/view.cgi?44 From detlev at die-offenbachs.de Sat Jul 5 05:16:47 2003 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 05 Jul 2003 11:16:47 +0200 Subject: ANN: Eric 3.2 released Message-ID: Hi Trolls, I am pround to announce, that eric3 3.2 has been released today. It is available via http://www.die-offenbachs.de/detlev/eric3.html This version includes a Subversion interface, possibility to simply run a script/project, to profile it and to determine code coverage statistics. The editor supports autocompletion and calltips and a whole bunch of additional lexers. For details see the history file in the distribution. What is it? ----------- Eric 3.2 (or short eric3) is a Python IDE written using PyQt and QScintilla. It has integrated project management capabilities, it gives you an unlimited number of editors, an integrated Python shell, an integrated debugger and much more. Please see for yourself by visiting the a.m. page (it contains a picture of Eric our mascot as well). Please report bugs, feature wishes or code contributions to eric-bugs at die-offenbachs.de Help wanted!! ------------- I really need some support in the area of more translations and user documentation. Any volunteers out there? Just let me know. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From LogiplexSoftware at earthlink.net Thu Jul 3 18:00:50 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 03 Jul 2003 15:00:50 -0700 Subject: function overloading In-Reply-To: References: Message-ID: <1057269649.16862.24.camel@software1.logiplex.internal> On Wed, 2003-07-02 at 23:33, Jere Kahanpaa wrote: > Hi. > > Mirko Koenig wrote: > > I serached around the web and some tutorials but i can't finds any > > documentation about function overloading in python. > > > I want to have 3 functions: > > def setPos( x, y ): > > def setPos( pos ): > > def setPos( object ): > > ( pos and object are classes i wrote ) > > The normal Pythonic way is probably as follows: > > def setPos(position): > """ > Set Position. > > The 'position' argument should be one of > * a tuple of coordinates (x,y) > * a instance of class Pos > * a instance of class Object > """ > > if type(positions) is types.TupleType or type(positions) is types.ListType: > x,y = positions > ... > else if: > ... identify object type and process Or you could implement something like this, if think you "need" overloading so badly that the horrific overhead added to each function call is tolerable: class overload(object): def __init__(self, *args): self._funcs = {} for f, p in args: self._funcs[tuple([type(a) for a in p])] = f def __call__(self, *args): f = self._funcs[tuple([type(a) for a in args])] return f(*args) def f_noargs(): print "noargs" def f_int(a, b): print "ints", a, b def f_str(a, b): print "str", a, b def f_strint(a, b): print "strint", a, b f = overload( [ f_noargs, () ], [ f_int, (int(), int()) ], [ f_str, (str(), str()) ], [ f_strint, (str(), int()) ] ) f() f(1, 2) f('a', 'b') f('c', 3) > It's hard to think outside the box when you ARE the box. Or if the box is full of Chicken McNuggets. Mmmm. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From kirk at eyegor.jobsluder.net Wed Jul 2 02:48:23 2003 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Wed, 02 Jul 2003 06:48:23 GMT Subject: Good code patterns in Python References: Message-ID: Will Stuyvesant wrote: > If you know that your source code is going to be used > later by others, then I feel that code with the pattern: > > if some_condition: > some_name = some_value > else: > some_name = other_value > > is often a mistake. Much better, safer, would be: > > some_name = some_value > if not some_condition: > some_name = other_value > > Why? My personal opinion is that it depends on context. The first idiom is more clear when you are dealing with some kind of a switch. The second idiom works better if you have a default value that needs to be overridden in some cases. > Because those people reusing your code might decide to > change or adapt the "if" part of the first example. Or > the "else" part for that matter. And then they could end > up with "some_name" being undefined, crashing other code > maybe 1000's of lines away. This could happen for example > because they use exceptions in the "if" part that jump out > of it, etc. Of course, another alternative is to combine both approaches by setting a default value: #set default for some_value some_value = [] if condition1: some_value = function1() else: some_value = function2() And then if you really want to be safe the functions using some_value should do reality checks as well. def function3(some_value=[]): if len(some_value): do something else: do something else. I think that an argument for the readability of if-else is that because the logic is made more clear, it can be more effectively replaced. > There is the small overhead of assigning something twice > to some_name in the safer example, so if performance is > *that* important then the first example is better, but I > feel there should be comments with warnings around it: > **CREATING A NEW OBJECT REFERENCE HERE!** Hmm, now that > makes code ugly :-) The problem here is that ***creating a new object reference*** is not only ugly, but its ambiguous as well. (What kind of object, what is it used for?) If indeed some_name is an important variable in your program, then provide a full description. #some_value (string) is used to hold the widgit that will #be passed to a wadget and eventually passed #to standard output. -- Kirk Job-Sluder http://www.jobsluder.net/~kirk/ From rimbalaya at yahoo.com Thu Jul 3 01:19:42 2003 From: rimbalaya at yahoo.com (Rim) Date: 2 Jul 2003 22:19:42 -0700 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <6f03c4a5.0307022119.4cbcf66b@posting.google.com> > Do they not understand that '=' binds a name to an object? Are They do understand the binding to the object, but there are objects that do not need explicit casting, like integers. As you know you can say "name = 18" and name will become an int, but int was not explicitely specified, it was infered by the interpreter, but as soon as I extend int to myint, I suddenly have to do "name = myint(18)", which I find annoying, but if that's the way it is so be it. Thanks! - Rim From mickey at tm.informatik.uni-frankfurt.de Tue Jul 1 13:56:36 2003 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 1 Jul 2003 17:56:36 GMT Subject: PyQT and Mandrake 9.1 References: Message-ID: Politics and polemics aside - how 'bout an attempt to help the OP? Did you install libqt3-devel ? :M: From bokr at oz.net Tue Jul 1 22:07:21 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Jul 2003 02:07:21 GMT Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: On Tue, 1 Jul 2003 09:22:03 -0600, Steven Taschuk wrote: >Quoth Rim: > [...] >> The idea is to separate the value assignment from the type assignment, >> by introducing a new operator, let's say the ':=' operator. >> >> '=' remains what it is, assigns type and value at the same time >> ':=' assigns only the value > >That's a peculiar way of speaking. '=' does not assign type and >value to a variable; it assigns an object to a name. > > [...] >> In reality, := would just coerce the return type of the RHS of := to >> the type of the variable on the LHS of the :=, preserving the value(s) >> as best as it can. > >"The type of the variable" is not a meaningful phrase in Python: >names do not have types; objects do. I assume you meant "the type >of the object the name on the lhs is presently bound to". > >Coerce how? Do you want a new __magicmethod__ for this operation? > >Would ':=' mutate the object presently bound to the lhs name >create a new object and rebind the lhs name? To be concrete: > One thought would be that it wouldn't change the current binding. E.g., x := y could be a spelling of x.__update__(y) and would be an *expression* with potential side effects. By convention, a reference to the updated same object would be returned. I.e., x.__class__ would have to have def __update__(self, other): return self For starters, you could just let AttributeError get raised if there's no __update__ method. > a = whatever > b = a > a := 7 > assert a is b > >Should that assertion succeed or fail, in general? (Note that it >fails in general if the ':=' is replaced with '=', even if >whatever == 7.) For the above, it should succeed, since the binding will have been unchanged > >Would ':=' support chaining? That is, would > a := b := >work? If so, would it be equivalent to Yes, it should work, but no, it wouldn't be equivalent to > _tmp = > a := _tmp > b := _tmp working left to right, it would presumably be equivalent to a.__update__(b).__update__() >(except for the namespace pollution), to match the semantics of >chained '='? (Note that the assignments happen left to right.) > >Would use of a name on the lhs of a ':=' cause that name to be >considered local, as such use with '=' does? No, because it would be a named object reference for the purpose of looking up the __update__ attribute in the non-sugar spelling of a:=b (which is a.__update__(b)) -- i.e., it's an expression, not really an assignment statement. > >> If the type of the variable was still undefined, ':=' would behave >> like '='. It might create confusion in future code, but does not break >> old code. > >Yikes. Why not raise NameError if the name on the lhs of ':=' is >not yet bound? Yes. > >> I think it would be a nice feature to have. Comments? > >Your example > a = Currency(6) > a := 7 >is highly strange. (Even if we ignore the question of *which* >currency is being represented; the example could easily be >restated with, say, FixedPoint or Rational or some such.) > I don't know that I would totally dismiss the usage. It could be a concise notation for a possibly polymorphic update operation. w = Widget(blah, blah) w := ('blue','white') # changes fg/bg colors w := (20,40) # changes position w := Font('Times Roman', size=24) w := 'some text appended to a text widget' Of course, you could use a property very similarly, e.g., w.p = 'text ...' I guess it's a matter of what kind of sugar you like ;-) >How is it that your users are happy to write Currency(...) when >first assigning to a name, but not happy doing so when assigning >later? > >Do they not understand that '=' binds a name to an object? Are >they C programmers who think of assignment as copying a value from >one location in memory to another? Do they think of the first >assignment as a type declaration for the name? (If any of these >three are true, they need to be better educated -- they're all >fundamental misconceptions about Python.) True, but if they did understand that a=b binds but a:=b updates?? > >Do they need a language with syntactic support for Currency >objects? I'm not sure what that would mean. OTOH, a:=b might lead to analogies with a+=b and other a=b and then where would we be ;-) Let's see... a+:=b => a.__update__(a.__add__(b)) ?? ;-) Regards, Bengt Richter From paulpaterson at users.sourceforge.net Fri Jul 25 22:25:20 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sat, 26 Jul 2003 02:25:20 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: Shane Hathaway wrote: > Paul Paterson wrote: > >> I am trying to find a way to mimic by-reference argument passing for >> immutables in Python. I need to do this because I am writing an >> automated VB to Python converter. >> >> Here's an example of the VB code: >> >> Sub Change(ByVal x, ByRef y) >> x = x+1 >> y = y+1 >> End Sub >> >> x = 0: y = 0 >> Change x, y >> ' Now x should be 0 and y should be 1 > > > I might put all of the "ByRef" variables in a dictionary that gets > passed back to the caller through a hidden argument. > > def change(x, y, _byref): > x = x + 1 > y = _byref['y'] = y + 1 > > x = 0; y = 0 > __byref = {'y': y}; change(x, y, __byref); y = __byref['y'] > The problem here is that you still have the delayed change to 'y' in the caller's scope. Other posts in this thread have made me wonder whether this is a problem sepcific to the ByRef topic. The interesting thing about your approach is that you have an explicit step for transmitting changes to y back to the calling scope - which is quite nice. In an automated translation, having this explicit is a good sign-post for the user to let them know that something important is going on. > At least this relies on nothing magical. One thing that's still wrong, > though, is that you can't embed the change() call in an expression. > AFAIK, in Python, assignment to a local variable absolutely requires a > statement. You can get around this by splitting apart the expression > and storing the result of the call in another hidden temporary variable. > > Even if you do that, though, exceptions will behave differently in > Python than they do in VB. Matching VB's exception behaviour is my worst nightmare - but that's another story ... > If an exception occurs in change() after a > value has been assigned to 'y', the outer code won't get the value, and > it just might affect the behavior of the outer code. You could fix that > with a try: / finally: > > __byref = {'y': y} > try: > change(x, y, __byref) > finally: > y = __byref['y'] > > Suddenly it's awfully verbose and ugly, but if variables by reference > are rare (as they should be), maybe it's not so bad. :-) Unfortunately (and to my shock), it seems that ByRef is the *default*! It may be the case that using the implications of ByRef are rare and it may be possible for me to detect when this is occuring. > You could go the extreme route and store all variables in dictionaries > rather than use local variables, which would allow "true" references, > but then you'd kill speed and readability. Better not do that. At the end of the day (see my response to Ian) this may in fact be the safest approach if you want to match the exact behaviour of the original VB code. There will almost certainly be a switch where you can turn this off, but then it is up to the programmer to go and fix things which get broken. Hopefully it will be possible to try to identify likely hot spots automatically. Paul From vze4rx4y at verizon.net Tue Jul 29 21:51:32 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 30 Jul 2003 01:51:32 GMT Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> <6%CVa.59$cI2.38@nwrdny01.gnilink.net> Message-ID: > I understand why it works as inverse when * creates a argument list of > list element. But don't understand why * works that way in this context. > Does ** do this for maps and keywordargs, too? Hey, this is python - lets > try: > >>> def foo(a=None, b=None): > ... pass > ... > >>> foo(a=10, b=20) > >>> foo(**{'a':10, 'b':20}) > >>> > > Coooool. Where is that documented? Never stumbled across it so far! http://www.python.org/dev/doc/devel/ref/calls.html Raymond Hettinger From intentionally at blank.co.uk Tue Jul 15 00:20:48 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 05:20:48 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> <9iu6hv4r968o9s1n5fh887u2j7an94de4e@4ax.com> Message-ID: On Mon, 14 Jul 2003 20:57:44 -0700, Tom Plunket wrote: >Stephen Horne wrote: > >> >Are they really technicalities, though? I mean, a mutable object >> >can be changed. It's the same object, just changed. Immutable >> >objects, however, can't be changed. You can get something that >> >appears like changing it, but it's actually building a new thing >> >and binding the label to that new thing. >> >> Yes. But the thing being changed *is* an object, *not* a value. Values >> are always immutable - basic fact of mathematics. > >Sure, but we're not modelling pure mathematics, we're modelling a >level of abstraction that's appropriate for the problem that >we're solving. If that were true, the abstraction would not regularly be causing confusion and errors, and it would not be a recurring issue on this newsgroup. >class Chameleon: pass > >a = Chameleon() >b = a > >now, a and b represent the same thing. Say it's a chameleon out >in the woods. > >If I say: > >a.ClimbTree() > >then I expect > >b.GetColor() > >to return some brown color, since a and b are referring to the >same critter. All this tells me is that you have got used to the current Python way. Personally, I think that if you want indirect references to objects you should ask for them explicitly. That way there's no confusion. >I don't agree, because Python is a language that allows us to >model objects in a way that is comfortable to us. If I wanted to >use a more mathematically pure language, I would, but that >language would likely not be suited to the problems I'm trying to >solve. Comfortable to those who are used to it, perhaps. But again, the fact of regular confusion and errors, and of the issue regularly reappearing in the group, shows that this 'comfort' is a very long way from being universal. From wayne at mishre.com Sat Jul 12 15:43:25 2003 From: wayne at mishre.com (Wayne Pierce) Date: 12 Jul 2003 12:43:25 -0700 Subject: Any pure-python relational databases? References: Message-ID: <2a897f11.0307121143.4a37113b@posting.google.com> David McNab wrote in message news:... [sniped] > 1) Any pure-python interface to MySQL? or If you cannot get the MySQL specific interface working, have you tried a generic database interface? http://www.python.org/topics/database/DatabaseAPI-2.0.html > 2) Any kind of relational DBMS written in pure python that'll run on > 1.5.2? While not relational, have you looked at Metakit? http://www.equi4.com/metakit/python.html Wayne From frobozz_electric at hotmail.com Wed Jul 9 11:17:09 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 9 Jul 2003 15:17:09 GMT Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: "Anton Vredegoor" wrote in message news:beh8ad$dm0$1 at news.hccnet.nl... > Importing the math module should also make a big difference for the > standard deviation routine :-) Also stddev was only used by the > sigmascaling code, which was unreachable ... Thank you! I tacked on the fitness proportional stuff (roulette selection, sigma scaling, expected values) on at the end to try to make the offering more well-rounded, but I only did a couple of quick runs on one problem to test. It looked fine, so I went ahead. I won't do that again - heh. I had *no* idea that the sigma scaling was unreachable. I'm stunned and embarassed. Thank you for making me aware the problem. I've done the imported math module fix but, as for the sigma scaling, that will be resolved in the newer version I'm working on: refactoring, renaming, redesigning, reworking, that sort of thing. That version should be available on my site sometime in early August. I already prefer it over the old version, and I'm not quite finished :) > However, this is a very > nice module and I especially like the graphical TSP-solver that is in > the other package on your website. > I'm glad you like it. I enjoyed watching it try to solve problems too. Seeing where it would get stalled, trying to fiddle with the parameters to make it work faster, better. Unfortunately, I did that display for a course, so it was a matter of "just meet the deadline" code production. So, for instance, the builtin scaling mechanisms are poorly designed - you can't easily introduce a TSP problem that is different from the one provided and have it display well. I don't know if I'll get around to fixing that soon - I have other things to work on at the moment. > I had been looking at it before but I failed to comprehend what you > were doing. There's a lot there. I'm a bit torn. I wanted to give people some examples of operators that you may not find in other Genetic Algorithm code, but I also think there's just a bit too much code there. When I post the next version, I'm thinking I will just post a kernel of the system with a few interesting tidbits, and then make the entire module available on my site. That way it will be easier to read on the recipe page, and you can still get more if you like. We'll see. > Anyway, maybe seeing your code used and *changed* will give enough of > a jolt to start working on it some more (which I would welcome :-) Wait til you read the next version ;) It has 3 whole classes! (heh). Thanks again for making me aware of the bugs in this code. I was hoping people might get some benefit from this code, and I'm glad that someone has. I'm just sorry it's not better. From peter at engcorp.com Thu Jul 24 09:15:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Jul 2003 09:15:00 -0400 Subject: Reading Keyboard Scan Codes References: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4706@admin56.narex.com> Message-ID: <3F1FDBD4.F38948CB@engcorp.com> Francois Pinard wrote: > > [Fran?ois Pinard] > > > [...] I do not know if reading scan codes or key codes is easily done > > within X, nor on MS-Windows. I would like finding or discovering recipes > > in this area. So, please share your tricks in this area, if any! :-) > > [Bjorn Pettersen] > > > I'm assuming you can use the msvcrt module: > > > >>> def getch(): > > ... import msvcrt > > ... while not msvcrt.kbhit(): pass > > ... return msvcrt.getch() > > ... > > >>> getch() > > 'a' > > >>> > > This does not give scan codes (or key codes of some sort). I would like > being able to detect, for example, if Ctrl is being held while Keypad-5 > is entered, or any other such (possibly unusual) combination of keys. I'm not sure about your specific case with Ctrl-Keypad-5 (is that a valid combination?), but the above will return 0 or 224 plus another code for the special keys (such as function keys, and the numeric keypad keys, and those values are different when Ctrl is held down. For example, Home on the numeric keypad is (0, 71), while Ctrl-Home is (0, 119). The other Home key comes back as (224, 71), and with Ctrl it is (224, 119). Experiment a bit and you'll figure it out. -Peter From bokr at oz.net Sun Jul 6 17:50:40 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Jul 2003 21:50:40 GMT Subject: Using Loops to track user input References: Message-ID: On Sun, 06 Jul 2003 16:32:37 -0400, hokiegal99 wrote: >I don't understand how to use a loop to keep track of user input. Could >someone show me how to do what the program below does with a loop? > >Thnaks! > >---------------------------- >#Write a program that reads 10 numbers from the user and prints out the >sum of those numbers. > >num0 = input("Enter a number: ") >num1 = input("Enter a number: ") >num2 = input("Enter a number: ") >num3 = input("Enter a number: ") >num4 = input("Enter a number: ") >num5 = input("Enter a number: ") >num6 = input("Enter a number: ") >num7 = input("Enter a number: ") >num8 = input("Enter a number: ") >num9 = input("Enter a number: ") > >num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9 > >print num >---------------------------------- > >>> num = 0 >>> for i in range(10): ... prompt = 'Enter %s%s number: '%(i,i<4 and 'thstndrd'[2*i:2*i+2] or 'th') ... while 1: ... try: ... num += int(raw_input(prompt)) ... break ... except Exception,e: ... print ' Error: %s' % e ... Enter 0th number: 100 Enter 1st number: 10 Enter 2nd number: x Error: invalid literal for int(): x Enter 2nd number: 2 Enter 3rd number: 3 Enter 4th number: 4.5 Error: invalid literal for int(): 4.5 Enter 4th number: 4 Enter 5th number: 5 Enter 6th number: 6 Enter 7th number: 7 Enter 8th number: 8 Enter 9th number: 9 >>> print num 154 Regards, Bengt Richter From noah at noah.org Sat Jul 12 20:05:22 2003 From: noah at noah.org (Noah) Date: 12 Jul 2003 17:05:22 -0700 Subject: How do I have a client shutdown a win32 COM server? References: Message-ID: Bob Gailer wrote in message news:... > >"Noah" wrote in message > > > > > Hi, > > > > > > How do I shutdown a win32 COM server? > > > > > If that does not do it try: > comobject.Quit() > Bob Gailer That was it! Too simple... Thanks! Noah From cben at techunix.technion.ac.il Wed Jul 30 15:20:23 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Wed, 30 Jul 2003 22:20:23 +0300 (IDT) Subject: streams (was: Re: Itertools) In-Reply-To: References: Message-ID: Ronald Legere wrote on 2003-07-29: > The new itertools stuff is pretty cool. One thing that bothers me > though is that there seems to be no way to copy an iterator. How > does one work around this? Is there a trick that I am missing? > > Without being able to 'split' an iterator, I can't think of how to > do some of the cool things you can do with lazy lists in Haskell. It > seems quite often you want to be able to do this 'splitting', and if > I had more coffee I would post an example :) The ones I can think of > are also defined recursively, which is another kettle of fish. > Strange, the need seems to come up more freqeuntly since I implemented it ;-). Or is it just me paying more attention to it? After a couple of design iterations, I've got: http://www.technion.ac.il/~cben/python/streams.py [NEWS: The last changes were addition of __nonzero__ methods, clued by discussion on c.l.py , and a `.force(count=None)` method to force computing values.] I concluded that it's best to separate the two abstractions, providing ability to convert both ways: - An iterable immutable (but lazily computed) linked list, with O(1) tail access and ability to cons in front of it. - An iterator object whose `.next()` method is necessarily destructive, on another hand. Turns out the most flexible implementation of the iterator is simply a pointer to a linked list; this way you can split the iterator and even "unyield" values back onto it. See the module for more details. In general it's most clean to separate iterables from iterators. Iterables should be changed by iterating. Any feedback welcome. I'd like to make it as Pythonic as possible. An perhaps make it standard. Particular open questions: - Terminology. There are too many names for the same things ;-). - The linked lists are called "streams" by me because they are lazy and that's what such beasts are called in functional languages. But I still have many refernces to them as linked lists, especially w.r.t. the `Cons` class which happens to be the base class of `Stream`. So `Stream` is defined as a lazy linked list node. Should I try to squash refences to "linked lists", treating them as "stream nodes which are already computed" to reduce confusion with Python lists? - car/cdr vs. first/rest vs. head/tail. I chose head/tail. car/cdr would be opaque to people without lisp background. first/rest are of different length :-). - `Cons` still requires lisp background but I don't know any name that would be recognizable to non-lispers anyway. And it's not a bad name. - Is `StreamIter` the best name? - I called the operation for creating new iterator from same place "forking". Alternative names: `split`, `copy`, `clone`, `dup`, "lookahead", etc. What's best? - Consing in front of a StreamIter's stream is called `.unyeild`. The point is that it's the opposite of the ``yield`` statement but the name is a brave new invention. Alternatives: `prev` (antonym of `.next()`, probably misguided since it doesn't return the previous value but rather takes it from you), `pushback`, `unread`, `stuff`, etc. - Functionality: - Should the operations (`.head`/`.tail`, indexing) on the underlying stream be proxied by `StreamIter` or should the programmer have to spell out e.g. ``iterator.stream.head`` as now? - What to do about __repr__ and __str__? The streams could well be infinite and forcing lookahead for even a few values is unacceptable as this could be expensive. - What to do about __hash__ and __eq__? - Should I weakly memoize the `Stream` for each given iterable? That would reduce the risk of wrapping a destructive iterator twice with distinct streams, so that each produced item is seen by only one stream, with access-order-dependant interleaving, violating the functional intent of the laziness. OTOH, this would make the programmer less aware of the risk. Besides, I'm not sure what to return on the second attempt to wrap same iterator after some of it has already been consumed since the first time. - Would some convenience operations for lookahead, e.g. `.startswith()` be useful? - Anything else anybody needs? -- Beni Cherniavsky Put a backslash at the evening to continue hacking onto the next day. From skip at pobox.com Mon Jul 7 15:56:46 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 7 Jul 2003 14:56:46 -0500 Subject: [Spambayes] mail.generator examples - anyone kknow where I can find them? In-Reply-To: References: Message-ID: <16137.53374.3816.265404@montanaro.dyndns.org> python-list instead of python-dev would be a better place to post your request. John> I've been trying to understand the email.generator class. There John> are virtually NO examples showing how to "generate" an Email John> message. You might try poking around the Mailman 2.1 source code for examples: % find . -name '*.py' | xargs egrep -i generator ./admin/www/MMGenerator.py:"""Generator for the Mailman on-line documentation. ./admin/www/MMGenerator.py:class MMGenerator(Skeleton, Sidebar, Banner): ./Mailman/Handlers/Scrubber.py:from email.Generator import Generator ./Mailman/Handlers/Scrubber.py:# We're using a subclass of the standard Generator because we want to suppress ./Mailman/Handlers/Scrubber.py:# sub-Generators will get created passing only mangle_from_ and maxheaderlen ./Mailman/Handlers/Scrubber.py:class ScrubberGenerator(Generator): ./Mailman/Handlers/Scrubber.py: Generator.__init__(self, outfp, mangle_from_=0) ./Mailman/Handlers/Scrubber.py: Generator._write_headers(self, msg) ./Mailman/Handlers/ToDigest.py:from email.Generator import Generator ./Mailman/Handlers/ToDigest.py: g = Generator(mboxfp) ./Mailman/Handlers/ToDigest.py: g = Generator(plainmsg) ./Mailman/ListAdmin.py:from email.Generator import Generator ./Mailman/ListAdmin.py: g = Generator(fp) ./Mailman/ListAdmin.py: g = Generator(outfp) ./Mailman/Mailbox.py:from email.Generator import Generator ./Mailman/Mailbox.py: # Create a Generator instance to write the message to the file ./Mailman/Mailbox.py: g = Generator(self.fp) Skip From john at landahl.org Thu Jul 24 19:03:24 2003 From: john at landahl.org (John Landahl) Date: 24 Jul 2003 16:03:24 -0700 Subject: Cluster Node Auto Discovery References: Message-ID: codepunk at codepunk.com (Codepunk) wrote in message news:... > > I have written a specialized server in python and now I wish to look > at making it scalable. To do this I wish to include automatic > discovery of peer nodes operating on my network. Can anyone provide me > a pointer as to how I do such a thing? By how to do it I mean how does > something like that work at the network level? > > ping scan the ip range? > some sort of broadcast packet? > udp request to entire ip range? > > I am not asking for code just how is something like that typically > done? It depends on what you mean by "peer nodes". Do you mean *any* node in your local network? Or do you mean other nodes running your software? If the former, ping scanning would probably be sufficient. You might want to make use of the nmap tool (http://www.insecure.org/nmap/) to simplify the job. However, if by "peer nodes" you mean only other nodes running your software, you might want to use Service Location Protocol (SLP, defined by RFC 2608). Take a look at OpenSLP (http://www.openslp.org/) for an open source implementation. There's a Python wrapper (available in the "misc" directory of the distribution, IIRC) which works quite well, and which condenses all the C code to a .so for use by Python. The advantage there is that you don't need to distribute the entire OpenSLP package separately, you only need to distribute the Python OpenSLP code itself (which can easily be turned into a tarball via "python setup.py bdist"). From missive at frontiernet.net Tue Jul 22 17:38:23 2003 From: missive at frontiernet.net (Lee Harr) Date: Tue, 22 Jul 2003 21:38:23 GMT Subject: Newbie question about strings References: Message-ID: In article wrote: > Hi, > > I have been tasked to Integrate Inktomi Search (now Verity of course) > with our website. I am fairly new to Python. The way the search > engine is setup is that it has embedded python in a html document. > After looking at the html code for a day or so, I was able to pin > point the place where I need to make a change but I am having a hard > time. > > I am assuming > > &$self.text(dbcol[docdb].pretty_name); > > prints something in HTML but I am trying to figure out it's > equivalent > in Python. I am assuming this is a string and I need to check it's > value against another string say 'XXY' if it is equal then go ahead > and print that value otherwise skip to the next item in the > list/array. > > > This is what I had before and it worked > > , Test< &$self.text(dbcol[docdb].pretty_name); >Test > > when run this prints > > Test< XXY >Test, Test< ABCD >Test > > I want it to print only when the string is equal to XXY. otherwise > skip to the next string. This is the edited code that I have so far. > > > , Test< &$self.text(dbcol[docdb].pretty_name); >Test > > > I get the following error when I run the program. > > exceptions.SyntaxError: invalid syntax (line 86) > Line 86 > if dbcol[docdb] == wlines.append(u' '); > > Any help would be greatly appreciated. > Do you know python? It might be a good start to go through the python tutorial... http://python.org/doc/current/tut/tut.html From bhv1 at psu.edu Sun Jul 13 20:36:39 2003 From: bhv1 at psu.edu (Brian Victor) Date: Mon, 14 Jul 2003 00:36:39 GMT Subject: Distutils gcc error Message-ID: I am attempting to distribute my wxPython program with the aid of distutils. I have one C++ module that needs to built on the user's machine. When I run "./setup.py build", the following appears on the terminal: gcc -DNDEBUG -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fno-strict-aliasing -fPIC -Isrc -I/usr/include/python2.2 -c src/bwaa.cc -o build/temp.linux-ppc-2.2/bwaa.o -I/usr/local/lib/wx/include/gtk-2.4 -DGTK_NO_CHECK_CASTS -D__WXGTK__ -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES [snip] /usr/local/include/wx/setup.h:15: #error No __WXxxx__ define set! Please define one of __WXBASE__,__WXGTK__,__WXMSW__,__WXMOTIF__,__WXMAC__,__WXQT__,__WXPM__,__WXSTUBS__ That error message is consistent with failure to define __WXGTK__. However, that macro is clearly defined on the command line, and copying and pasting that line into the terminal causes the build to succeed. Why would that be? This is how I have the extention defined in my setup.py file: wxlibs = commands.getoutput("wx-config --libs") wxcxxflags = commands.getoutput("wx-config --cxxflags") bwaaext = Extension("bwaascalec", ["src/bwaa.cc", "src/bwaascale.cc"], include_dirs=["src"], extra_link_args=[wxlibs], extra_compile_args=[wxcxxflags]) [snip] ext_modules=[bwaaext]) If anyone can point me to a fix, I would appreciate it. Thanks in advance! -- Brian From and-google at doxdesk.com Tue Jul 22 08:08:24 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 22 Jul 2003 05:08:24 -0700 Subject: PEP 304, and alternative Message-ID: <2c60a528.0307220408.73c6e740@posting.google.com> Evening all, haven't seen much discussion on PEP 304 recently, what's its current status? As I'm currently writing something that also allows configuration of where bytecode files go, I finally got around to reading the PEP, and I'm really not convinced I like the approach it takes. It's so broad-brush; PYTHONBYTECODEBASE can only really be set per-user, and is likely to cause the same problems PYTHONPATH did (before site-packages and .pth files made all that easier). The problems with user rights also look really horrid. Say bytecodebase is /tmp/python/. All users must have write access to /tmp/python/home, so they can store PYCs for PYs in their home directory; however if user A hasn't yet run a PY from his home directory, user B can create /tmp/python/home/A and put a booby-trapped PYC in, that could be run when user A executes a script of the same name from /home/A. The only way I can see of getting around problems like this in 304 is to create a complete skeleton of the existing filesystem, owned by the same users as in the main filesystem, and keep it updated. Which is impractical. I'd instead like to do it by having a writable mapping in sys somewhere which can hold a number of directory remappings. This could then be written to on a site-level basis by sitecustomize.py and/or a user or module-level basis by user code. eg. sys.bytecodebases= { '/home/and/pylib/': '/home/and/pybin/', '/www/htdocs/cgi-bin/': '/www/cgi-cache/' } and so on. Filenames of .py files could be compared by string.startswith to see if they match each rule. If they match more than one, the rule with the longest key is used. If a match is made, its key is replaced by the value, and 'c' or 'o' added to the filename. An attempt is made to makedirs the parent directory if it doesn't exist. IMO such a mapping, if it occurs, should replace rather than augment the original directory as in 304. The need to look in the same directory regardless of bytecodebase seems to come from the need to keep the process of finding standard library modules unchanged; a selective remapping like this would avoid the problem by not touching the standard modules (unless you really want it to). Also it avoids the problem of what to do on multi-root filesystems like that of Windows, as only string matching is required. (O)bjections, (T)houghts, (A)buse? -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From anton at vredegoor.doge.nl Sun Jul 13 07:33:32 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 13 Jul 2003 13:33:32 +0200 Subject: The "intellectual property" misnomer References: Message-ID: "Tim Peters" wrote: >> -- there may be no patents, but with the statement they assert that >> either there are no patents or they hold them. > >The PSF doesn't know of any patents associated with Python. It's possible >that the PSF will apply for some, though, and I like using "intellectual >property" because it covers (in the common understanding) all stuff of this >nature. It's probably better to "think outside the box" and stop using the term altogether. After reading this: http://old.law.columbia.edu/my_pubs/anarchism.html I get the feeling that many of the things said in there are true, but still the conclusion to fight the law using the law as per the GPL must be wrong. For example: http://www.negativland.com/albini.html suggests that the legal system does little for creators of music and is mainly used to protect the interest of the music companies. Probably nothing good can come from using it. I am not saying that it cannot be used to prevent something bad, but that it's probably better to try to do something good ... Another problem with the IP term is that it feels like a "contradictio in terminis". It is very hard (impossible even ?) to delineate ones own contribution to a piece of software because if an idea has any quality it almost always depends on the ideas of a lot of other people. Therefore ideas are very unlikely to be "undivided" property, unless the intellectual level is very low. Anton -- If I have seen farther than others, it is only because I was standing on the shoulders of giants From LogiplexSoftware at earthlink.net Tue Jul 8 14:53:11 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 08 Jul 2003 11:53:11 -0700 Subject: path module In-Reply-To: <1057687291.8459.71.camel@lothlorien> References: <1057687291.8459.71.camel@lothlorien> Message-ID: <1057690391.5396.68.camel@software1.logiplex.internal> On Tue, 2003-07-08 at 11:01, Ian Bicking wrote: > Interesting, but I think a bad idea. I don't believe Python has been > ported to Tops-20, and I'm not sure if there's a viable VMS port > either. Most filesystems don't have the complexity that the Lisp > pathname encapsulates. If someone was using VMS paths, I would assume > they would subclass path for that OS, adding the portions that applied. > I think it's unreasonable to expect people programming on normal > platforms to pay attention to components like version, so even including > it in a structured manner is asking for trouble. There is talk that Windows will have versioning in its next filesystem (WinFS). It would surprise me if there weren't similar plans on the Linux side. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From Ax10 at gmx.de Sat Jul 5 03:12:56 2003 From: Ax10 at gmx.de (Mike Abel) Date: Sat, 5 Jul 2003 09:12:56 +0200 Subject: tkFileDialog without a parent window References: Message-ID: Stephen Boulet wrote: > How can I do this without an empty tk window popping up and hanging around > after the dialog is closed? Thanks. Well i think this is probably a problem in your script not a problem from tkFileDialog. Mike From dave at pythonapocrypha.com Sun Jul 13 07:50:46 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 13 Jul 2003 05:50:46 -0600 Subject: anything like C++ references? In-Reply-To: References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <200307130550.46624.dave@pythonapocrypha.com> On Sunday 13 July 2003 01:41 am, Tom Plunket wrote: > Dave Brueck wrote: > > Your response above (that the normal thing to do in Python is > > just return the modified value) made me wonder if most people are > > asking about pass-by-reference not because they want pass-by- > > reference, but because in C it's generally a nuisance to return > > stuff from functions, especially multiple values, so you end up > > learning about pointers and/or pass-by-reference. > > In C++ it's trivial to return multiple values Trivial but non-intuitive until you convince yourself "that's the way it is", perhaps. :) What I mean is this: when you're just starting out you learn that functions can return values like this: int foo(int a, int b) { return a + b; } But the method for returning more than one thing is not a simple progression from this pattern. Instead you learn and shift to a *completely* different mechanism. In Python, however, you *can* continue along the original route as well: def foo(a, b, c): return a+b, b+c > > IOW, if you could erase the influence of previous languages would > > this FAQ become "how can I return multiple things from a > > function" more often than it would become "how can I modify an > > object from inside a function"? > > That's a good idea, although I would have to say that multiple > return values typically means that your function is doing too > many things. ;) Far from it: lastName, firstName = line.split('\t') (there are many, many, many such examples). This is also an example of what I mean by "in C it's genreally a nuisance to return multiple values": void split(char *pLine, char **ppLastName, char **ppFirstName) {} Sadly, it's not uncommon to see one-off structures defined whose sole purpose in life is to act as a go-between for functions. Ugh. -Dave From mail at cheesch.de Tue Jul 15 03:48:54 2003 From: mail at cheesch.de (Carsten Heesch) Date: Tue, 15 Jul 2003 09:48:54 +0200 Subject: Need help: Compiling Python-Code Message-ID: Hi, I wrote some little python programs which run without problems. Now I'd like to compile them into byte-code. What do I have to do? Platform: SuSE Linux 8.2 Thx in advance. Carsten From exarkun at intarweb.us Wed Jul 2 23:34:04 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 2 Jul 2003 23:34:04 -0400 Subject: anything like a "pointer" in python? In-Reply-To: <20030703014105.16688.qmail@sina.com> References: <20030703014105.16688.qmail@sina.com> Message-ID: <20030703033329.GA30078@intarweb.us> On Thu, Jul 03, 2003 at 09:41:05AM +0800, stevenswan wrote: > I want to open a file in python and read something and process the file in c++ moduel, but there is no "pointer" in python, > so how can I pass the arg(file buffer) between python and c++ modules? fileObj.fileno() Or, you could just open the file in your extension module. Or, you could pass the PyFileObject* (fileObj) to the extension module and call PyFile_AsFile() on it. Jp From bkelley at wi.mit.edu Wed Jul 30 11:50:03 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 30 Jul 2003 11:50:03 -0400 Subject: graph libraries In-Reply-To: References: Message-ID: <3f27e8d3$0$3945$b45e6eb0@senator-bedfellow.mit.edu> Hi Andrew! A couple more to pepper your list: Graph Template Library http://www.infosun.fmi.uni-passau.de/GTL/ Seems to have some fairly decent algorithms but I can't say much more than that. GNU Goblin Graph Library http://www.math.uni-augsburg.de/opt/goblin.html Good editors and layout support (not for molecules, of course). Uses TCL/TK to script but I think a python port would be minimal. And of course, vflib has their own internal model that I have wrapped. You can download it from http://frowns.sourceforge.net/ We could then go into the commercial libraries: LEDA and it's java equivalent yWorks. They also distribute BALL http://www.algorithmic-solutions.com/enballbeschreibung.htm a molecular modelling environment for protein prediction/docking and the like. Good academic license but pricey otherwise. Tom's Graph Library -> great layout routines. Brian. From sross at connectmail.carleton.ca Thu Jul 10 13:03:35 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 10 Jul 2003 13:03:35 -0400 Subject: for in sequence problem... possible new operator to add to python References: <3a8fc6c5.0307100816.634c83a3@posting.google.com> Message-ID: <5_gPa.8878$ru2.867718@news20.bellglobal.com> "Adam Gent" wrote in message news:3a8fc6c5.0307100816.634c83a3 at posting.google.com... > I was fooling around subclassing a dictionary object and noticed that > when > I do the standard "for in :" that I have no > control on how python gets that sequence. [snip] > However I want b to be the values with out doing: > for b in bl.values() You can do it as follows: class Blah(dict): def __iter__(self): return iter(self.values()) b = Blah() b.update({'hello':'world', 'how':'are', 'you':'today'}) for v in b: print v # OUTPUT: # are # today # world Just be aware that you are introducing surprising behaviour - other Python programmers will expect for v in b: to iterate thru the keys of b, not the values. It's up to you whether you want this behaviour more than you want your code to be easily understood. From tom at liveDELETE-MElogix.com Thu Jul 3 09:57:10 2003 From: tom at liveDELETE-MElogix.com (Tom Locke) Date: Thu, 03 Jul 2003 13:57:10 GMT Subject: Emacs + py-mode + tkinter problem Message-ID: Hi All, I'm having trouble with the python shell within emacs. It's hanging when I use tkinter. Setup is: Windows XP emacs 21.3 py-mode 4.6 Recipe: >From a python-mode buffer, launch the python shell (C-c !), then in the shell >>> import Tkinter >>> root = Tkinter.Tk() >>> 1+2 And that's all folks. I get precisely one prompt after creating the root, and then it hangs. I've had a trawl around and it seems a few have run into this, but so far no fix. One tip was try running python with -u, but then I get syntax errors with anything I type - seems like a CR/LF issue. Help! :( Tom. From afriere at yahoo.co.uk Thu Jul 31 22:24:32 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 31 Jul 2003 19:24:32 -0700 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <38ec68a6.0307301841.dfb951a@posting.google.com> Message-ID: <38ec68a6.0307311824.1f17b2d0@posting.google.com> "Keith Jones" wrote in message news:... > > If you use vim remember to put 'set expandtab' (or if you wanna be fancy > > 'au BufRead,BufNewFile *.py set expandtab' ) into your .vimrc (or .exrc) > > file. This way you can use '[Ctrl]-[T]' and '[Ctrl]-[D]' to in- and > > un-dent in insert mode, as well as '>>' and '<<' in command mode, > > without fear of hard tabs being inserted. (Though the way vi(m) mixes > > tabs and spaces is consistent enough that you wouldn't usually get into > > any trouble with it.) > > > Oh, yeah, forgot to mention expandtab; I did not know about >>, <<, > Ctrl+T, and Ctrl+D, however; so thanks for those. I had mapped and > to : s/^/ / and : s/^ / for command mode, which I > guess I won't have to use anymore. [ctrl]-[t] and [ctrl]-[d] also exist in vanilla vi, but are much more nicely implemented in vim. In vi you have to make sure you are at the front of the line, or else you indent will be inserted into your line (which is hardly ever what you would want). In vim it doesn't matter where in the line your cursor is, the commands will move the line as a unit, much like your mappings would. I should perhaps also mention the very useful ex versions of this command as well. ie '>' for a single indent, '>>' for two indents, '<<<' for three dedents, etc, which like ex commands generally are especially useful when you want to move a bunch of lines at a time. Thanks for that resource file listing, that is going to up a whole new vista of vim/python usage for me. From tim at remove_if_not_spam.digitig.co.uk Wed Jul 16 06:16:39 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Wed, 16 Jul 2003 11:16:39 +0100 Subject: hex check References: Message-ID: On Wed, 16 Jul 2003 10:39:33 +0300, Ruslan Spivak wrote: >Hello. > >Does anybody have a hint how to check if input hex number is in correct >hex format? could always try: num = raw_input("Enter hex number"): try: int(num, 16) print "Yes, that was hex!" except: print "Doesn't look like hex to me!" I'm sure someone else here can do better. From skip at pobox.com Wed Jul 23 11:40:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jul 2003 10:40:11 -0500 Subject: python assignment In-Reply-To: <3F1E964E.BFD7513F@engcorp.com> References: <3f1e92bc$0$161$a1866201@newsreader.visi.com> <3F1E964E.BFD7513F@engcorp.com> Message-ID: <16158.44123.73600.679465@montanaro.dyndns.org> >> > The examples you gave showed that integers share identity with other >> > integers of the same value, while floats do not. >> I believe that's only true for small integers, isn't it? Peter> Google finds "LOADI - a fast load instruction for small positive Peter> integers (those referenced by the small_ints array in Peter> intobject.c)" LOADI was an instruction I implemented a few years ago when investigating bytecode optimization. It was never added to the Python virtual machine (ceval.c). Skip From max at alcyone.com Mon Jul 14 21:07:57 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 18:07:57 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> Message-ID: <3F1353ED.4111EC1D@alcyone.com> Stephen Horne wrote: > 99 out of 100 times, true. But not always - especially in discrete > maths. > > For example, if I write... > > [forall] x . f(x) = y > > It's hard to interpret that '=' as an assertion. Similar applies to a > range of maths operators. How is that not an assertion, anymore than [exists] x [~ (x = y)] or s = (1/2) a t^2 ? I don't mean this as an insult, but it seems to me that much of your comments on Python in these threads come down to, "The way this works is not something I would have given this name to." While that's completely legitimate, it's hard to see it as very compelling, since your distinctions seem to me to be fairly arbitrary (x = y is assertion but ALL x [f(x) = y] isn't?). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Does the true light / Of love come in flashes \__/ Sandra St. Victor From m.stenzel at allanime.de Mon Jul 7 20:07:07 2003 From: m.stenzel at allanime.de (Markus Stenzel) Date: Tue, 08 Jul 2003 02:07:07 +0200 Subject: Reverse Engineering of Windows Distribution In-Reply-To: <3F099651.5D3C74D1@engcorp.com> References: <3F098251.426DB151@engcorp.com> <3F099651.5D3C74D1@engcorp.com> Message-ID: The exe was compiled using py2exe. I have identified a set of well known initials "PK" (Phil Katz, author of the legendary PKZIP software) - and in fact there was a ZIP embedded in the executable at position 9000C. Unpacking this zip resulted in a bunch of .pyc files which I'm currently running through the beta version of the decompyle package. Wonder if that will work ;) Thanks for your help Peter. Markus Peter Hansen wrote: > The packaging process used might be useful to know: was it py2exe, or the > Macmillan Installer? > > Note, in case you weren't aware, that you won't actually get back the > *source*, such that you could easily modify it and recompile. You'll > get back the compiled (bytecode) file, which you could put into a .pyc > file and run in place of the "bad" .py file which you have... at least > in theory. > > Retrieving the source itself is even more involved. It requires > decompiling (see "decompyle"), although if you go that route you should > get back something very close to the original. Maybe even enough for you > to do a "diff" and patch the latest version to work again? > > Sounds like a lot of work though. Wouldn't it be easier to work with > the author to fix the problem in the supported versions, and use them? > > -Peter From plasser at hexagon.at Thu Jul 3 07:19:24 2003 From: plasser at hexagon.at (Juergen R. Plasser) Date: Thu, 03 Jul 2003 13:19:24 +0200 Subject: libxml2 Python bindings error Message-ID: <12307667.1057238364@[192.168.123.98]> Hi, I have installed libxml2-2.5.7, libxslt-1.0.30 from source and the bindings libxml2-python-2.5.7. Everything seems to compile fine, but when I try to import the libxml2 library in python I get the following error: Python 2.1.3 (#1, Feb 10 2003, 10:37:44) [GCC 2.95.3 20010315 (SuSE)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import libxml2 Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.1/site-packages/libxml2.py", line 1, in ? import libxml2mod ImportError: /usr/local/lib/python2.1/site-packages/libxml2mod.so: undefined symbol: xmlNewTextReaderFilename How can I get rid of this error? I need this libs for a Zope product called CMFOODocument, so I am depening on python 2.1.3. Thanx, Juergen From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 8 14:08:44 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 08 Jul 2003 20:08:44 +0200 Subject: unconventional path syntax (was Re: path module) In-Reply-To: References: Message-ID: <3f0b08ac$0$49109$e4fe514c@news.xs4all.nl> Skip Montanaro wrote: > Hallvard> It's a long time since I used anything like that, but I think > Hallvard> Tops-20 filename paths looked like this: > > Hallvard> device:file.ext;version > > Hallvard> where most components were optional. > > which is (not too surprisingly) very similar to VMS: > > device:[dir.dir.dir]file.ext;version > > Skip Which the Amiga's version borrows (borrowed) heavily from: device:dir/dir/dir/file (no filename extensions) The nifty part was that the could be the name of a physical device (such as "DF0:" meaning "floppy drive 0", or a user-defined logical device (such as "LIBS:"). The latter was usually called an "assign", and you could let it point to *multiple* locations in your filesystem *at once*. Sorry--way off topic here, but the above path syntax brings back some good memories ;-) --Irmen de Jong From andy at wild-flower.co.uk Wed Jul 23 18:27:56 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Wed, 23 Jul 2003 23:27:56 +0100 Subject: help... In-Reply-To: <000a01c3514d$3bbed680$6c00a8c0@ab.hsia.telus.net> References: <000a01c3514d$3bbed680$6c00a8c0@ab.hsia.telus.net> Message-ID: <200307232327.56525.andy@wild-flower.co.uk> On Wednesday 23 Jul 2003 8:04 pm, HostDomains.ca- A Division of FordWeb.Inc wrote: > we get the following error message when we try to login to our control > panel for ensim....can you help > > key > Traceback (innermost last): > File C:\Program Files\Zope\lib\python\ZPublisher\Publish.py, line 162, in > publish File C:\Program Files\Zope\lib\python\ZPublisher\BaseRequest.py, > line 427, in traverse File .\base\AccessControl\CommonAccessControl.py, > line 235, in validate (Object: RoleManager) > File .\base\AccessControl\CommonAccessControl.py, line 296, in > _authenticate (Object: RoleManager) > File .\published\webhost\WebHostAccessControl.py, line 78, in > userAuthenticate (Object: RoleManager) > File .\base\serverman\current\registrymgr.py, line 54, in value2dict > NameError: key The error is that the word 'key' is not a valid python statement: the file concerned is probably corrupted/truncated or has been modified by gremlins or inept users... Open up file .\base\serverman\current\registrymgr.py, and post the surrounding code found near line 54 - then we'll have some context to work from. Is this a custom app or part of Zope itself? Have you asked anyone on any of the Zope mailing lists or forums? hth -andyj From daniel.dittmar at sap.com Tue Jul 22 09:39:02 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 22 Jul 2003 15:39:02 +0200 Subject: Where can one get Python 1.4 and Pythonwin 1.0? References: <41dqhv43pp8d8kb76r2u2sm3bnbbkic4cm@4ax.com> Message-ID: Richard Lee wrote: > Hi. I need to test and document some really old software. For that, I > have to install P 1.4 and Pwin 1.0 (the latter which is based on > P1.4). http://www.python.org/windows/pywin14.html Daniel From grante at visi.com Thu Jul 17 15:31:20 2003 From: grante at visi.com (Grant Edwards) Date: 17 Jul 2003 19:31:20 GMT Subject: Python Quiz References: <3F156952.AD24AAB8@engcorp.com> <3f156c23$0$166$a1866201@newsreader.visi.com> Message-ID: <3f16f988$0$159$a1866201@newsreader.visi.com> In article , Terry Reedy wrote: >> Yup. I found a lot of things in FORTRAN surprising. Python is >> so much nicer in that respect. Though I was recently surprised >> that the remove() method for lists uses "==" and not "is" to >> determine what to remove. It's documented that it works that >> way. But, it wasn't what I excpected, and it took me a while to >> figure out that it was using my class's __cmp__ method rather >> than the object ID. > > Given ints = [9, 99, 999, 9999] would it not surprise you even more if > ints.remove(99) worked and ints.remove(999) did not, or even worse, if > the behavior of ints.remove(99) depended on the implementation? Yes, it would. > (Similar examples apply to strings, where the implementation of > interning and hence behavior based on identity *has* changed!) I'm not claiming it's right, or even rational, but for user-defined objects, I expected it to use "is". Now I know better, and am more careful when I impliment __cmp__. I had expected to be able to have two different objects that compared equal. And I also expected to be able to use list.remove() to remove a specified object. I had to give up one or the other. -- Grant Edwards grante Yow! ... he dominates the at DECADENT SUBWAY SCENE. visi.com From tomg at em.ca Wed Jul 16 20:04:36 2003 From: tomg at em.ca (Tom Goulet) Date: Thu, 17 Jul 2003 00:04:36 -0000 Subject: hex to signed integer Message-ID: Hello, My question basically is: What is the opposite of the following? | "%08X" % -1 I want to convert a string of hexadecimal characters to the signed integer they would have been before the statement converted them. How do I do this in such a way that is compatible with Python versions 1.5.2 through 2.4, and not machine-dependent? This is my current best: | struct.unpack("!l", \ | chr(string.atoi(hexbit[0:2], 16)) + \ | chr(string.atoi(hexbit[2:4], 16)) + \ | chr(string.atoi(hexbit[4:6], 16)) + \ | chr(string.atoi(hexbit[6:8], 16))) Thanks in advance. -- Tom Goulet, tomg at em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html From vincent_delft at yahoo.com Sat Jul 26 19:01:45 2003 From: vincent_delft at yahoo.com (vincent_delft) Date: Sun, 27 Jul 2003 01:01:45 +0200 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> Message-ID: <3f230835$0$280$ba620e4c@reader0.news.skynet.be> Irmen de Jong wrote: > vincent_delft wrote: > >> Is there a site who list the main charateristics of each of those Web >> tool kit ? > > Check out http://www.python.org/cgi-bin/moinmoin/WebProgramming > > --Irmen de Jong Waouuuww... So many different tools .... Can I get some "guidelines" ? My needs are : - Build pages via templates (easy to split content and layout) - My pages will be defined with "boxes". I would like to have a tool that can manage easely such "object". - I will use PostgreSQL as backend. - possibility to build very simple web site (<10 users) but big web sites too ( > 1000 users). So I don't need a Apache/mod_Python, ... for small web sites. CGIHTTPserver is enough. But CGIHTTPServer will not be able to manage very high load. From mis6 at pitt.edu Fri Jul 18 08:54:40 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Jul 2003 05:54:40 -0700 Subject: Co-routines References: Message-ID: <2259b0e2.0307180454.2e03f3a4@posting.google.com> If really you want to play tricks with the source code, as Micheal Spark is suggesting, you can avoid generators all togheter and "merge" the two functions by hand: import inspect def f1(): print "1-1" print "1-2" print "1-3" def f2(): print "2-1" print "2-2" print "3-3" def merge(f1,f2): s1=inspect.getsource(f1).splitlines()[1:] s2=inspect.getsource(f2).splitlines()[1:] lines=['def mergedfunction():\n'] for line1,line2 in zip(s1,s2): lines.append(line1+'\n') lines.append(line2+'\n') dic={}; exec ''.join(lines) in dic return dic['mergedfunction'] f=merge(f1,f2) f() Output: 1-1 2-1 1-2 2-2 1-3 3-3 Exercise left for the reader: show the pittfalls of this approach. Michele From _NOSPAM_nabugoon at moor.pe.kr_NOSPAM_ Sun Jul 27 14:28:00 2003 From: _NOSPAM_nabugoon at moor.pe.kr_NOSPAM_ (nabugoon) Date: Mon, 28 Jul 2003 03:28:00 +0900 Subject: wxPython wxListBox problem Message-ID: How can I add 100000 lists in wxListBox? When I tried, it stop because of overhead. In demo application, Some Grid Control handles 1000000 data. So I think it is possible that I add 100000 lists. Do I have to use another control? Any idea? TIA. From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 24 10:52:51 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 24 Jul 2003 15:52:51 +0100 Subject: Python scripting with Paint Shop Pro 8.0 In-Reply-To: References: Message-ID: <200307241552.51201.mfranklin1@gatwick.westerngeco.slb.com> On Thursday 24 July 2003 3:14 pm, Marc Wilson wrote: > In comp.lang.python, Martin Franklin > (Martin Franklin) wrote in > > :: > |On Monday 21 July 2003 12:29, Marc Wilson wrote: > |> In comp.lang.python, Martin Franklin > |> (Martin Franklin) wrote in > |> > | > |# PIL IMPORTS > |import Image, ImageEnhance > | > |im = Image.open("gnome-mixer.jpg") > | > |enhancer = ImageEnhance.Sharpness(im) > |eim = enhancer.enhance(2.0) > |eim.save("gnome-mixer-sharp.jpg", "JPEG") > | > |eim.thumbnail((10, 10)) > |eim.save("gnome-mixer-thumb.jpg", "JPEG") > | > | > |And this is the first time I've used PIL. > > Wow. I've now knocked up a script that can be called in "batch" mode to > convert and sharpen the image, and produce a thumbnail from it. > > All I need to do now is resize the image (to a fixed width) and we're > laughing. I'll press on. > > Oh, and- is there a way to overwrite text onto an image? The site is a > house-sales site, and we want to overwrite "SOLD" across the thumbnail once > a property is sold. It looks like I can do this with the ImageDraw module, > but I can't see how to replicate what we do now with Image Robot, which is > to write "SOLD" across the image diagonally (using the Add Watermark > feature). Any ideas? > > Marc, Looks like there could be (at least) two ways to do it... The ImageDraw class allows you to draw onto an existing image like so:- im = Image.open("gnome-mixer.jpg") draw = ImageDraw.Draw(im) draw.text((5, 5), "SOLD", fill="black") I have not investigated how (and if) you can rotate the text - I know you can change it's font etc... The second way would be to paste a SOLD image onto the original image im = Image.open("gnome-mixer.jpg") im.paste(Image.open("sold.jpg"), (5, 5)) HTH Martin From intentionally at blank.co.uk Sun Jul 13 17:08:07 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 22:08:07 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: On 13 Jul 2003 14:48:09 -0500, Ian Bicking wrote: >On Sun, 2003-07-13 at 12:51, Stephen Horne wrote: >> On 13 Jul 2003 12:19:08 -0400, aahz at pythoncraft.com (Aahz) wrote: >> >> >Whether one can mutate a specific object is simply an >> >attribute of that object, rather than requiring a different syntax. >> >Trying to focus on the mutable/immutable distinction is what causes the >> >mental blowup -- keep your eye on the objects and bindings and you're >> >fine. >> >> That's exactly it - you have to focus on whether an object is mutable >> or immutable for that exact reason. > >No you don't! Mutable and immutable objects act the same with respect >to assignment. However, because you cannot change a immutable object in >place, to get a different value you must rebind. You must *use* mutable >and immutable objects differently -- but that is not surprising, because >they are obviously very different objects! You have to use integers and >lists differently in part because one is mutable and the other isn't -- >but mostly because one is a number and the other is a list. Different >objects are different! > >Python is not novel in the way it deals with variables. Scheme and >Smalltalk, for instance, act exactly the same, as do many other >dynamically typed languages (though there are different opinions on >whether strings should be mutable -- but it's agreed there has to be >some immutable string-like type, e.g. symbol). The reason you are >getting this reaction is that anyone that comes from those backgrounds >thinks you are crazy, as does anyone who has embraced the Python model. >This isn't a funny little feature, this is the way all strong, >dynamically typed languages work. In computer science, a variable is a named binding to a value. Operations on that variable may rebind it to a different value, but values don't change behind your back. A pointer is, in effect, a value which indirectly refers to another (possibly anonymous) variable. A pointer is something you specifically request, and by doing so you allow that the 'variable' being indirectly referenced may be modified by something else that has no direct access to your pointer value (via your named variable or via copys or pointers-to your pointer held elsewhere). Python should respect that. If you claim that it does, then the values to which we currently associate the type name 'list', 'dictionary' and 'class instance' are badly named. They should be called 'pointer to list', 'pointer to dictionary' and 'pointer to class instance'. And if you want to call those references and make the dereferencing implicit, fine. Equally, if you want to implement variable binding using references and using copy-on-write to implement lazy copying (which does not violate the standard computer-theory semantics of the binding to values - only the binding to the implementation of values ie memory locations) then equally fine. However, even if the names included the 'pointer to' prefix so that they actually described the real behaviours of the values, this still raises two important questions... 1. Why are the values of mutable objects always forced to be accessed via a pointer (or reference or whatever)? Note that I am referring to a computer science, semantic pointer/reference/whatever - not to any pointers or references that may be used in the implementation of the binding of variables to values. The use, behind the scenes, of lazy copying as an optimisation is irrelevant to the computer science principles. 2. Why is there no way to reference an immutable object via a pointer, other than stuffing it into a mutable object designed for some purpose other than simple pointer behaviour? The truth is that this system is arbitrary, and that therefore this excuse is invalid. >The problem you have is you are still thinking of variables as slots, >which is not correct. Variables in Python are bindings. Assignment >never copies anything, or creates anything except for changing the >variable to point to a different address location. *Every* Python >assignment (a=b) is like the C assignment (a=&b). The problem is that you are confusing implementation with semantics. The meanings of 'variable', 'value', 'assignment' etc are defined by computer science. Whether you arbitrarily change the meaning of 'assignment' or whether you arbitrarily change the meaning of 'variable', it amounts to the same thing. > >> Tell me one case where it is sensible for a function to behave such >> that whether the caller sees a change in a variable it passed as its >> argument should depend on the type. > >Generally a function takes either immutable values (e.g., ints and >floats) or mutable values for a certain argument. > >However, there is a class of operations which are generally operate in >an immutable manner, that is, create copies of the objects instead of >changing them in place. So even though lists are mutable, list >concatenation does not mutate, and in general adding two things (with +) >will not mutate either object. Immutable values, by design, do not have >the same methods and operations as the mutable counterparts (or at least >the mutating methods of those mutable objects). *That* would be a >design bug. You miss my point. Your argument would equally apply to the need for an integer-specific division operator, for instance. Its all about how one function reacts in response to varying input. If you pass a mutable value to a function which expects an immutable one, you get an error. If you pass an immutable value to a function which expects a mutable one, you get an error. There is no good reason for a function to react to the distinction as evidenced by your own observation that what actually happens (and what should happen) is that you have two distinct variants of the function. >> Tell me one case where an object storing values should care about >> callers mutating values it holds *only* for certain types. > >Objects don't *store* values, they *refer* to values. You are still >thinking like you're in C (or C++). This is why you are having a >problem. No it is not. I'm thinking in terms of computer science, in which terms like 'variable', 'value' and 'assignment' are abstract concepts independent of the way in which they are implemented in a programming language. One way or the other, Python is currently choosing not to respect the computer science definition of those terms. It may have historic and backward-compatability reasons, but that does not change the facts. This deviation from computer science definitions, whatever the excuse, is arbitrary, confusing and error prone. That is my problem. From skip at pobox.com Wed Jul 2 17:13:22 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 16:13:22 -0500 Subject: Remote db connections possible with DCOracle2? Message-ID: <16131.19186.190625.679324@montanaro.dyndns.org> Connections to remote Oracle databases doesn't seem possible with DCOracle2. I have no problem making remote connections using Perl's DBI::Oracle package, so I know it's possible in theory. Is this capability available in DCOracle2 but just not documented perhaps? Thx, Skip From tjreedy at udel.edu Tue Jul 29 17:18:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2003 17:18:20 -0400 Subject: inverse of the zip function References: <9sBVa.12998$o%2.6289@sccrnsc02> Message-ID: "David C. Fox" wrote in message news:9sBVa.12998$o%2.6289 at sccrnsc02... > Is there a function which takes a list of tuples and returns a list of > lists made up of the first element of each tuple, the second element of > each tuple, etc.? > > In other words, the the inverse of the built-in zip function? Go to http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.python enter 'zip inverse', and check search Python only. TJR From mmuller at enduden.spam.filter.com Fri Jul 25 13:19:36 2003 From: mmuller at enduden.spam.filter.com (Michael Muller) Date: Fri, 25 Jul 2003 13:19:36 -0400 Subject: Static typing Message-ID: Is there currently any plan to introduce static typing in any future version of Python? (I'm not entirely sure that "static typing" is the right term: what I'm talking about is the declaration of types for variables, parameters and function return values). I know there was a "types SIG" which introduced several proposals, but it expired quite a while ago, and I was wondering whether whether some consensus has been reached on the subject or if it has just been shelved indefinitely. -- Remove the spam and filter components to get my e-mail address. From peter at engcorp.com Thu Jul 3 11:32:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 11:32:45 -0400 Subject: Reading an image file data......... References: Message-ID: <3F044C9D.CE43D5F4@engcorp.com> Egor Bolonev wrote: > > [Sorry, skipped] That's twice I've seen you use this... what does it mean? From grobinson at transpose.com Wed Jul 30 10:08:27 2003 From: grobinson at transpose.com (Gary Robinson) Date: Wed, 30 Jul 2003 10:08:27 -0400 Subject: bisect uses __cmp__()? Message-ID: [Tim Peters] > Well, it doesn't use __cmp__ directly now, and never has: it uses Python's > infix "<" operator. While not documented, it's deliberate that bisect > *only* uses "<", so that instances of a class implementing only __lt__ can > use bisect. OK, but why is it undocumented that bisect uses it, and that CPython's list.sort() uses it? I still don't know if I can write code that is based using __lt__ to define a sort order and be justified in assuming it will work in the future. I can't see much downside in making that behavior well-defined in the docs...? --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From hokiegal99 at hotmail.com Tue Jul 22 09:45:49 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 22 Jul 2003 09:45:49 -0400 Subject: Search for a string in binary files In-Reply-To: References: Message-ID: Fran?ois Pinard wrote: > import glob > for name in glob.glob('*.xls'): > if file(name, 'rb').read().find('Microsoft Excel') >= 0: > print "Found in", name > Thanks for the example guys. One last question: does grep actually open files when it searches them? And, would it be more efficent (faster) to just call grep from python to do the searching? From sybrenUSE at YOURthirdtower.imagination.com Wed Jul 30 02:43:31 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 30 Jul 2003 06:43:31 GMT Subject: while (assignment): References: Message-ID: John Roth enlightened us with: > For most purposes, there is. Just use a for loop! As long as the > source behaves like an iterator, the for loop will automatically > assign each result. How's that for performance? I guess I'll have to take a look at the MySQLdb package source code to see how the resultset code functions. I hope it calls fetchone() on each call to next() - AFAIK that's more efficient (let the DB ponder what the next row will be while my program ponders what to do with the information, and then exchange the new tuple) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From giva at users.sourceforge.net Wed Jul 30 20:52:38 2003 From: giva at users.sourceforge.net (Gisle Vanem) Date: Thu, 31 Jul 2003 02:52:38 +0200 Subject: How to get Windows physical RAM using python? References: Message-ID: <3f2868d9$1@news.broadpark.no> "Dan Bishop" wrote: > The easiest way is to parse the output from $WINDIR/system32/mem.exe . > > memTotals = os.popen('mem | find "total"').readlines() > conventionalMemory = int(memTotals[0].split()[0]) > extendedMemory = int(memTotals[1].split()[0]) Duh! That program reports the memory available to 16-bit programs. --gv From aahz at pythoncraft.com Fri Jul 18 09:09:25 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Jul 2003 09:09:25 -0400 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: In article <0tRRa.212$vD1.8077 at nnrp1.ozemail.com.au>, Graeme Matthew wrote: > >I just cannot seem to find any documentation that shows an example of >using the factory method Event() in threads. I have a thread pool and >if there are no jobs in a Queue I want them to wait for something to >be inserted. When a job is inserted I want to send an Event, the first >thread that picks it up runs with the job the rest wait for another >insert Event. Given that you're already using a Queue, there is no, repeat NO, reason for using an Event. Just have your threads block on the Queue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From p-abel at t-online.de Tue Jul 29 17:00:56 2003 From: p-abel at t-online.de (Peter Abel) Date: 29 Jul 2003 14:00:56 -0700 Subject: while (assignment): References: Message-ID: <13a533e8.0307291300.be1423a@posting.google.com> Sybren Stuvel wrote in message news:... > Hi there, > > Is it possible to use an assignment in a while-loop? I'd like to do No I guess. This is typical C, to use an assignment and work with its result in the same statement. One famous representative is the following which is the reason for many faults: if (a=somethting) { ... } what means in pyhton: a=something if a: ... > something like "loop while there is still something to be read, and if > there is, put it in this variable". I've been a C programmer since I > was 14, so a construct like: > > while info = mydbcursor.fetchone(): > print "Information: "+str(info) > The following should work: info = mydbcursor.fetchone() while info: print "Information: "+str(info) info = mydbcursor.fetchone() > comes to mind. Unfortunately, this doesn't work. Is there a similar > construct in python? > > Sybren Regards Peter From duncan at NOSPAMrcp.co.uk Thu Jul 17 11:37:23 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 17 Jul 2003 15:37:23 +0000 (UTC) Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: wrote in news:pBxRa.308$fF.9875 at nnrp1.ozemail.com.au: > OK. Thanks. I was just giving some simple examples...but I hope this > is better: > > From the python grammar: > > funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite > > I want the statements in to be executed on a statement by > statement basis, with no particular restrictions on *what* those > statements are. It's the execution stepping I'm interested in... the > I/O in my example was just that. I understand that there will be all > the problems on contention/race etc (just like if the functions were > going in separate threads) The only way I can think to implement this 'easily' would be to use the parser module to parse your source code, then walk the parse tree looking for statements inside one of your functions and add a yield_stmt after every other statement. Then compile the tree into bytecode and execute it. Of course your users may be surprised to find that they cannot directly call any of their functions from another function. You could do a further rewrite on the tree to convert obvious calls to your users' functions into for loops. Why? -- 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 ricardo.b at zmail.pt Thu Jul 17 21:59:39 2003 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Fri, 18 Jul 2003 02:59:39 +0100 Subject: Unicode question References: <65m1yubd.fsf@python.net> Message-ID: On Fri, 18 Jul 2003 02:07:13 +0200, Gerhard H?ring wrote: > Thomas Heller wrote: >> Gerhard H?ring writes: >> >> >>> >>> u"???" >>>u'\x84\x94\x81' >>> >>>(Python 2.2.3/2.3b2; sys.getdefaultencoding() == "ascii") >>> >>>Why does this work? >>> >>>Does Python guess which encoding I mean? I thought Python should >>>refuse to guess :-) >> >> >> I stumbled over this yesterday, and it seems it is (at least) partially >> answered by PEP 263: >> >> In Python 2.1, Unicode literals can only be written using the >> Latin-1 based encoding "unicode-escape". This makes the programming >> environment rather unfriendly to Python users who live and work in >> non-Latin-1 locales such as many of the Asian countries. Programmers >> can write their 8-bit strings using the favorite encoding, but are >> bound to the "unicode-escape" encoding for Unicode literals. >> >> I have the impression that this is undocumented on purpose, because you >> should not write unescaped non-ansi characters into the source file >> (with 'unknown' encoding). > > I agree that using latin1 as default is bad. If there's an encoding > cookie in the 2.3+ source file then this encoding could be used. > -- Gerhard You can use string literals in any encoding like this: 'string in my favorite encoding'.decode('my favorite encoding'). Note that the lack of the u prefix. Not very confortable though.. u'string' ends up doing the same as 'string'.decode('latin1'). It doesn't work for docstrings though.. I'm not sure for what you mean about encoding cookie, but I like the idea of each source file having some element that defines the encoding used to process string literals. Either that or we define the Python code must be written in UTF-8. But that would break lots of code.. :D -- Ricardo From donn at drizzle.com Wed Jul 16 00:01:41 2003 From: donn at drizzle.com (Donn Cave) Date: Wed, 16 Jul 2003 04:01:41 -0000 Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> Message-ID: <1058328099.572993@yasure> Quoth Adam Ruth : ... | In Python, there is no situation where "you really can't avoid pointers". That's trivially true, no such situation can exist because that Python can't be coded. I'll repeat an example that I proposed a couple days ago, though: user implemented sequences could be implemented with a single simple indexing function, returning a pointer/target/whatever; Python could assign directly to that, making "seq[i] = x" the same kind of operation as and automatically symmetrical with "x = seq[i]". It can't be done without pointers, as far as I can see. You may not care if it can be done, but I think you'd agree that "there is no situation that I care about where you really can't avoid pointers" would be kind of a lame version of your assertion. Donn Cave, donn at drizzle.com From heikowu at ceosg.de Mon Jul 28 14:43:10 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 28 Jul 2003 20:43:10 +0200 Subject: Python on a USB storage device? In-Reply-To: References: Message-ID: <1059417790.623.17.camel@d168.stw.stud.uni-saarland.de> On Mon, 2003-07-28 at 19:27, Kevin Altis wrote: > Does anyone have experience running Python from a USB storage device? I don't have experience running Python from an USB storage device, but I've been using a 1GB USB-Stick to carry around a Knoppix distribution with me, for those PCs which can boot from USB and don't have a CD-ROM drive (there are quite a few where I work as sys-admin). USB works well here, so I guess if you use USB to carry around a Python installation, this should work well too. USB 2.0 doesn't matter, as the USB-sticks I know of don't even support it (the normal transmission speed of those sticks is an average 5 MB/s, and that's way below USB 1.1 max speed of 11 MB/s). So, I guess you should be successful with a stick for running Python too... Just my 5 cents. Heiko Wundram. From vze4rx4y at verizon.net Wed Jul 30 04:25:40 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 30 Jul 2003 08:25:40 GMT Subject: variable assignment in "while" loop References: Message-ID: <8iLVa.2654$Jz2.2272@nwrdny02.gnilink.net> > >>Spot on, with one (minor) correction. With a for loop you have to > >>iterate over the results of a call to a method on the cursor, e.g.; > >> > >>for info in mydbcursor.fetchall(): > >> print "Information:", info > >> > >>You could replace fetchall() with fetchmany() or, if you are feeling > >>contrary, fetchone() ;-) > > > > > > Are you sure about this? Because, if you have to iterate > > through .fetchall() (for example), then the cursor isn't > > actually an iterable object, the result of fetchall() is > > (it's a list, which is iterable), same goes for fetchmany(); > > BUT, if you iterate over the results of fetchone() then > > you're gonna do a columnwise iteration over a single row. > > > > So... anyone... do cursors have an __iter__() method? > > I don't have a DB module at hand to check it out... > > Technically, cursor objects are not iterators, and the DB-API > specification has this to say about the various methods that return data; > > """ > .fetchone() > > Fetch the next row of a query result set, returning a > single sequence, or None when no more data is > available. Remember, the second form of the iter() function makes it easy to build a real iterator here and a fast one too: for row in iter(mydbcursor.fetchone, None): print row > .fetchall() > > Fetch all (remaining) rows of a query result, returning > them as a sequence of sequences (e.g. a list of tuples). > """ > > Which means that the cursor object itself is not an iterator, and the > methods need only return a sequence (or sequence of sequences). Right, so if you want iterator performance (just-in-time production, minimal memory consumption, better cache utilization, etc), then use fetchone wrapped in iter() as shown above. Raymond Hettinger From piet at cs.uu.nl Sat Jul 12 06:43:49 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 12 Jul 2003 12:43:49 +0200 Subject: Maxmium bufsize using open2? References: Message-ID: >>>>> Maurice (M) wrote: M> Dear all, M> I've a problem using popen2 when using large files. M> When I use small input files everything works well but when I feed large M> inputfile to the pipe nothing happens. Is there a maximum bufsize for using M> the pipe. The code I use is written down here below. Do I need to specify a M> waittime between line 4 and 5 ? M> o,i =popen2('command ')) M> fh=open(os.path.join(self.dirname, self.filename),'r') M> i.write(fh.read()) M> i.close() M> self.StringData=o.read() M> o.close() With popen2 (and popen3 and popen4) you can manage yourself in a deadlock. This is apparently happening to you. The problem is that the O.S. has only a limited buffering in the pipes. Now when the command generates much output and the buffer is full, the command blocks until you have read some of its output. But you are still busy feeding it more input. A waittime doesn't solve it. The only solutions are: using different threads for input and output, or redirecting either stdin or stdout to a file. I don't think the buffersize parameter will solve it, because this specifies the in-process buffer, not the O.S. buffer (I think). The in-process buffer will be flushed by i.close() so you are back to the situation without buffer. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From donn at u.washington.edu Wed Jul 16 17:33:07 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jul 2003 14:33:07 -0700 Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> <20030716123907246-0600@news.xmission.com> <20030716142716509-0600@news.xmission.com> Message-ID: In article <20030716142716509-0600 at news.xmission.com>, Adam Ruth wrote: > In Donn Cave wrote: > > In article <20030716123907246-0600 at news.xmission.com>, ... > > OK, there really aren't any situations where you can't avoid > > pointers ... so you're ready with a solution to the problem > > I posed above? ... > As for your problem on the subscript operator, I think my solution is: > there's no problem. Having the get and set asymetric is preferrable, in > my view. For example, I use it in a number of places where I cache the > set operation: So after all it should be "there aren't any situations that I care about where you can't avoid pointers." That's fine, it's really where we all come down in the end - life is too short to worry about solving problems you don't care about. One should be clear about it, though. Donn Cave, donn at u.washington.edu From mcfletch at rogers.com Sun Jul 20 12:10:45 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 20 Jul 2003 12:10:45 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <2259b0e2.0307200652.131ed45e@posting.google.com> References: <2259b0e2.0307190640.56266017@posting.google.com> <2259b0e2.0307200652.131ed45e@posting.google.com> Message-ID: <3F1ABF05.8030505@rogers.com> Michele Simionato wrote: >"Mike C. Fletcher" wrote in message news:... > > >As others before me, I am not sure of what you are trying to do >and why you are doing so. I use descriptors in this way: > >class o(object): > class p( object ): # descriptor class > def __set__( self, client, value, *args, **named ): > print '__set__', self, client, value, args, named > self.v=value > def __get__(self,obj,cls): > return self.v > v = p() > You are aware that you have just created a class-attribute, rather than an instance attribute? The property/descriptor object exists within the class 'o' namespace, not the instance namespace. Try creating two instances of your o class and setting v on both of them. There is one 'p' instance "self" to which you are assigning/retrieving an attribute for all instances of o. Creating class variables is certainly a valid use for descriptors, but I'm not sure if that's really what you were trying to do. What I'm looking for, in terms of your code, is a method/function which would do the proper thing instead of using "self.v=value", (or rather client.__dict__['v'] = value (i.e. store the value in the client dictionary)) for all of the major built-in types, such as object-instances, classes (and object-instances with slots would be nice). To the best of my knowledge, such a function does not exist within Python; for instances, simply doing instance.__dict__[ key ] = value is sufficient, but classes do not have a method exposed AFAIK which allows an equivalent setting of a value *without* triggering the descriptor machinery for the given key. I'm creating a slightly more involved pattern, by the way: class plugin( type ): someHelperClass = common.ClassByNameProperty( "someHelperClass", """Documentation for this meta-property""", defaultValue = "some.package.module.ClassName", setDefaultOnGet = 0, ) class MyWorkingPlugIn( myBaseImplementation ): __metaclass__ = plugin instance = MyWorkingPlugIn() Where the properties of the plugin meta-class are providing all sorts of services for the MyWorkingPlugIn class, such as allowing it to find "someHelperClass" related to the plug-in system while allowing that property to be set manually if desired, or automatically calculating a global identifier if the plug-in doesn't currently have a global identifier. The value is primarily that the meta-class will use exactly the same mechanisms as the rest of the system, and so will be readily dealt with by the property-based meta-application system. There are certainly other ways to get around the particular problem (I have already done that), I'm looking for the *elegant* solution to the *general* case. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From gsmatthew at ozemail.com.au Thu Jul 3 08:24:27 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Thu, 3 Jul 2003 22:24:27 +1000 Subject: Python is a gem, you need to keep pushing it .... Message-ID: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Hi all, I just wanted to tell someone :-) I was previously a perl programmer and have been a visual basic frustrated developer for a number of years, only for the reason that corporates are so obsessed with using proprietary marketing focused computer languages and not using true computer science oriented solutions written by computer science engineers and not a marketing panel. The amount of frustration I have experienced using visual basic is unbelievable and most of these programs could have been easily written in python and solved in half the time. I looked at ruby, it is a beautiful language too but there are still too many scarce libraries compared to python. Perl, I still like perl but its syntax requires a photographic memory when coming back to some old code. I have now taken on a large project outside of work for another company, initially they, yes wait for it, wanted a VB client / server solution. It took me lot of hard motivation and they have now totally changed their focus, a web based python solution it now is ! who said one cannot market linux, python and mysql ? I hope to have the project completed in 6 months and I am looking forward to adding it to one of python's success stories. So the whole point of this email is that if a lot of you are hitting the same frustration as myself where managers (and people who think Microsoft invented everything well except a watch you need to recharge every 2 days :-) keep on insisting on developing in the basket case Microsoft Languages such as VB (I am not mentioning C or C++ as it does not fall into this bracket) then dont give up, keep up the evangelism, as someday they will give in .... and let you prove it too them Cheers From tim.one at comcast.net Tue Jul 15 19:15:16 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 15 Jul 2003 19:15:16 -0400 Subject: FCNTL module deprecation warning In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1302644476@its-xchg4.massey.ac.nz> Message-ID: [Tony Meyer] > My question is then why the 2.3b2 Windows binary bothers installing > the FCNTL.py file. Because it would be enormously more bother to special-case it. The Wise script that generates the installer simply specifies that *.py should be copied from the Lib directory in my build tree. The only way to exclude FCNTL.py would be to explicitly list every other .py file in the Wise script. That would never remain in synch with new .py files that should be included, so "screw it" is my Professional Judgment . > fnctl isn't available on Windows anyway (going by > the docs and that there isn't a fnctl.py file installed). > > Shouldn't the correct behaviour be to raise an ImportError if a > windows user tries to import fcntl or FCNTL? It does for me: >>> import fcntl Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fcntl >>> import FCNTL C:\CODE\PYTHON\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) Traceback (most recent call last): File "", line 1, in ? File "C:\CODE\PYTHON\lib\FCNTL.py", line 11, in ? from fcntl import * ImportError: No module named fcntl >>> I get that under Python 2.2.3 and 2.3b2. From skip at pobox.com Fri Jul 11 08:21:46 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Jul 2003 07:21:46 -0500 Subject: Python Documentation In-Reply-To: <221d8dbe.0307110252.7d44b63a@posting.google.com> References: <221d8dbe.0307110252.7d44b63a@posting.google.com> Message-ID: <16142.43994.777263.353053@montanaro.dyndns.org> srijit> I do not see any discussion of new style classes in tutorial srijit> section of Python 2.3b1 core documentation. I hope that I have srijit> not missed any section. The extra features available in new-style classes don't really strike me as introductory material. The tutorial is not meant to be an exhaustive introduction to the language. In addition, new-style classes are a very new feature of the language. It will take some time for the tutorial to catch up. If you'd like to update it, feel free. Skip From udo.gleich at web.de Tue Jul 29 04:03:51 2003 From: udo.gleich at web.de (Udo Gleich) Date: Tue, 29 Jul 2003 10:03:51 +0200 Subject: mixin class References: <3F24F8D2.E1ADFB08@web.de> <2259b0e2.0307281355.34725f83@posting.google.com> Message-ID: <3F262A67.57E4762C@web.de> Hi, > Why not simply > > class K1(object): > pass > > class K2(object): > pass > > mixed = type("K1_K2", (K1, K1), {}) > new_instance = mixed() > > print new_instance > almost. If K1 has a constructor that takes arguments you get an error when you call the constructor of the derived class without an argument. Why do I want to do that? Usually one would say that I should know the arguments of the constructor of the derived class. What I want to do is take *two objects*, derive from both their classes, make a new object and combine the state of the old objects. I dont know if that is a good idea. I would appreciate comments on the following solution. Especially the use of the dummy_init function as an empty constructor looks not quite right to me. --------------------------------------------------------------------- def dummy_init(self): pass class Mixin: __shared_state = {"classes":{}} def __init__(self): self.__dict__ = self.__shared_state def mix(self, original_instance, mixin_instance): original_class = original_instance.__class__ mixin_class = mixin_instance.__class__ name = original_class.__name__ + '_' + mixin_class.__name__ mixed = self.classes.get(name, type(name, (mixin_class, original_class), {"__init__": dummy_init})) new_instance = mixed() new_instance.__dict__.update(mixin_instance.__dict__) new_instance.__dict__.update(original_instance.__dict__) try: new_instance.late_init_original() except AttributeError: pass try: new_instance.late_init_mixin() except AttributeError: pass return new_instance class K1(object): def __init__(self, a): self.a = a class K2(object): def late_init_mixin(self): self.b = self.a + 1 mixer = Mixin() new_instance = mixer.mix(K1(3), K2()) print new_instance print new_instance.a, new_instance.b ------------------------------------------------------------------------- From sfb at alysseum.com Mon Jul 28 14:01:03 2003 From: sfb at alysseum.com (Simon Bayling) Date: Mon, 28 Jul 2003 18:01:03 +0000 (UTC) Subject: Debugging Python ? References: Message-ID: PythonWin and Boa Constructor both have step-through debuggers. > I'd be happy to hear your techniques to debug python programs. > Is there any interactive debugging environment by any chance ? > Simon. From usenet at soraia.com Mon Jul 21 13:13:00 2003 From: usenet at soraia.com (Joe Francia) Date: Mon, 21 Jul 2003 17:13:00 GMT Subject: global variable In-Reply-To: References: Message-ID: Tom wrote: > Hi, > > I have one "master" program which calls a small program. In this small > program I want to work with a value from the "master" program. But I > always get this error: NameError: global name 'T' is not defined > > How can I define a global variable? > > Thanks for your help. > Regards, Tom You can't (well, there is a way, but you probably don't want to be messing with that). By "program" I assume you mean "module". You can do something like: #master.py T = 'Some value' #small.py import master doSomething(master.T) However, if master.py is also importing small.py, you'll get a circular reference, which may cause hard to track bugs, in which case it's best to have a third module for common (global) variables (and functions, if you'd like), and have both master.py and small.py import that. jf From me at home.net Thu Jul 3 19:19:21 2003 From: me at home.net (J-P) Date: Thu, 03 Jul 2003 19:19:21 -0400 Subject: Why so many references to global variables? In-Reply-To: References: Message-ID: <0S2Na.6305$bD1.721957@news20.bellglobal.com> Alexander Schmolck wrote: > J-P writes: > > >>It appears that every time the interpreter tests for >>the value of 'myflag', it keeps a reference to it. > > > What makes you think so? This seems rather unlikely to me (not that the > references themselves should eat your memory anyway!). Well, sys.getrefcount() does tell me there are 3 millions references to it and other globals. Even though this doesn't eat up all my memory (how large is a reference object in Python?), I definitely think there's something fishy with keeping that many references to global variables that appear here and there in the script. > Chances are, the C extension code doesn't work correctly (C extensions to > python code have to do memory management by hand; increasing and decreasing > reference counts for the python objects they deal with as appropriate; so if a > bit of code forgets to decrease the refcount, the object will stay alive > forever; my guess would be that this it what happens here). Might be, but the ref count for the objects interacting with the C library are pretty much what I expect them to be, i.e. a few dozens. I don't think there are other memory leaks in the bindings to the library. I've passed it through Purify a couple of times and everything seems clean. J-P From hokiegal99 at hotmail.com Wed Jul 9 10:50:03 2003 From: hokiegal99 at hotmail.com (Tubby Tudor) Date: Wed, 09 Jul 2003 10:50:03 -0400 Subject: regexp and filenames In-Reply-To: <3F0BF9B4.7186537C@hotmail.com> References: <3F0BF9B4.7186537C@hotmail.com> Message-ID: Alan Kennedy wrote: > Another poster has shown how to navigate directory hierarchies, so > I'll leave it to you to combine the two code snippets. Thanks for the advice Alan. I've learend a lot. Python is turning out to be more flexible than I thought it would be. From paul at boddie.net Fri Jul 4 06:14:09 2003 From: paul at boddie.net (Paul Boddie) Date: 4 Jul 2003 03:14:09 -0700 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: <23891c90.0307040214.776f31f@posting.google.com> "Max Khesin" wrote in message news:... > > I am not sure where we disagree. This is exactly my point. The statement > " > Engineering Lessons > ------------------- > 1. C/C++ is no longer a viable development language > " > is pure rubbish. C++ is still great for certain kinds of projects, and there > are lots of open-source and proprietary projects to prove this. I wouldn't agree with you unreservedly here. In many respects, the choice of C++ for projects is often an educational problem with the developers - people choose it because it's what they know, potentially not very well in many cases. So one could say that it's really something they just know something about - it seems like the right/safe choice, presumably because their peers/acquaintances who are just as badly informed tell them so. Those of us who are used to more high-level languages would think twice about writing a large application using a language/library combination without decent (ie. modern) support for memory management, for example. I can imagine that many developers find it challenging and even rewarding to think up interesting schemes for allocating and freeing memory - perhaps they even think that this (and lots of other unnecessary wheel reinvention) is what programming is all about. Personally, I'd rather get on with implementing the actual system concerned. So, I'd rephrase the original statement: C/C++ are frequently suboptimal choices for application development. Why? Poor support for near-essential features found in contemporary languages combined with the absence of timely, effective standardisation of useful library functionality. Paul From raims at dot.com Sun Jul 20 06:11:22 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 20 Jul 2003 12:11:22 +0200 Subject: object as a reserved keyword References: <3F1A633B.98456C76@alcyone.com> Message-ID: On Sun, 20 Jul 2003 02:39:07 -0700, Erik Max Francis wrote: >If someone wants to be abusive, he can. The idea behind Python is that >everyone will behave like adults, so there's little need to worry about >these kinds of things. Yeah, thanks. Is this kind of idea that I'm not used to -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com rhymes at NOSPAMmyself.com From alanmk at hotmail.com Fri Jul 25 08:09:31 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 25 Jul 2003 13:09:31 +0100 Subject: Tokenize References: <8%VTa.133$313.72262@news.uswest.net> <3F203257.AD0A4B30@hotmail.com> Message-ID: <3F211DFB.FDC54852@hotmail.com> Andrew Dalke wrote: > Another option is the little-known 'shlex' module, part of the standard > library. [snip] > Also, with __iter__ in newer Pythons, if these module were useful > then it would be nice if "for token in shlex..." worked. Python 2.3b1 (#40, Apr 25 2003, 19:06:24) >>> import shlex >>> import StringIO >>> s = StringIO.StringIO("""ls -lart "have space.*" will travel""") >>> for ix, tok in enumerate(shlex.shlex(s)): ... print "%d: %s" % (ix, tok) ... 0: ls 1: - 2: lart 3: "have space.*" 4: will 5: travel >>> Thanks to Gustavo Niemeyer, who is credited in the code for "Lib/shlex.py" as follows # Posix compliance, split(), string arguments, and # iterator interface by Gustavo Niemeyer, April 2003. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From lol at lolmc.com Wed Jul 16 17:57:16 2003 From: lol at lolmc.com (Rogue9) Date: Wed, 16 Jul 2003 22:57:16 +0100 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? Message-ID: <3f15ca92@shknews01> Hi, I?m trying to retrieve an item from a list using a reference called ?draw?' (which is an integer from 1 to 792 in a while loop) using:- draw = 1 while 1: if draw == 792: break b1 = someOtherList[draw-1] r1 = b1[draw] draw = draw+1 However,the item I expect is not being retrieved i.e. a zero is the result of the retrieval rather than the integer in the list I was expecting. Furthermore,when I substitute an integer for draw e.g. r1 = b1[12],I do get the expected result. Can anyone enlighten me as to why and how to get over this please? Thanks Lol McBride From ianb at colorstudy.com Wed Jul 16 23:56:02 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Jul 2003 22:56:02 -0500 Subject: list() coercion In-Reply-To: References: Message-ID: <1058414161.19240.1423.camel@lothlorien> On Wed, 2003-07-16 at 22:04, Greg Ewing (using news.cis.dfn.de) wrote: > Ian Bicking wrote: > > However, list() seems to call the object's > > __len__, > > > > Is there a way I can keep this from happening? > > Give your object an __iter__ method that returns > itself. I'm not clear on how that will help...? It already does have an __iter__ method, but it returns a separate iterator. Ian From mail2jinu at yahoo.com Tue Jul 15 06:08:44 2003 From: mail2jinu at yahoo.com (Jinu) Date: 15 Jul 2003 03:08:44 -0700 Subject: zope xml error Message-ID: <517bf874.0307150208.3faf9bf0@posting.google.com> while i worked with xml in zope using python i got the following error. Error Type: AttributeError Error Value: documentElement i've installed pyxml,xmllib ,xmldocument . can anyone shed some light thanks in advance Jinu my python script is as follows import string doc=getattr(context,'addressbook.xml') #doc=context.objectvalues('addressbook.xml') book=doc.documentElement # here the error is generated. print "Number of items",len(book.childNodes) names=[] for item in book.childNodes: name=item.firstChild names.append(name.firstChild.nodeValue) print "Names",string.join(names,",") return printed addressbook.xml Bob
2118 Wildhare st
Randolf
13 E. Roundway
From mickey at tm.informatik.uni-frankfurt.de Wed Jul 2 19:22:24 2003 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 2 Jul 2003 23:22:24 GMT Subject: PyQT and Mandrake 9.1 References: Message-ID: fwiw, mandrake-cooker now contains pyqt-3.6 as rpms. :M: From aahz at pythoncraft.com Thu Jul 31 11:43:47 2003 From: aahz at pythoncraft.com (Aahz) Date: 31 Jul 2003 11:43:47 -0400 Subject: RELEASED Python 2.3 (final) References: <3F28EA71.6A863E7@hotmail.com> Message-ID: In article , Robin Becker wrote: > >1) SyntaxWarning: assignment to None > eg for None, name in colorNamePairs: > what is the preferred way to do this nowadays? It's fairly > trivial to go through and change these to for notUsed, x in .... > but is there a nicer way. Some people use "_". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From CousinStanley at hotmail.com Wed Jul 30 08:15:51 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 30 Jul 2003 05:15:51 -0700 Subject: Thank you developers for 2.3 References: Message-ID: | You must really trust us. | The benchmark compares the speed | but doesn't check to see if the answers are the same Python 2.2.1 Python 2.3b1 k ..... 26991000000 k ..... 26991000000 et .... 108.370000005 et .... 51.4100000858 Answers look OK and 2x speed improvement seems to prevail for slower processors as well .... Using Win98 @ 250 MHz .... -- Cousin Stanley Human Being Phoenix, Arizona From gh at ghaering.de Thu Jul 17 20:07:13 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jul 2003 02:07:13 +0200 Subject: Unicode question In-Reply-To: <65m1yubd.fsf@python.net> References: <65m1yubd.fsf@python.net> Message-ID: <3F173A31.1030404@ghaering.de> Thomas Heller wrote: > Gerhard H?ring writes: > > >> >>> u"???" >>u'\x84\x94\x81' >> >>(Python 2.2.3/2.3b2; sys.getdefaultencoding() == "ascii") >> >>Why does this work? >> >>Does Python guess which encoding I mean? I thought Python should >>refuse to guess :-) > > > I stumbled over this yesterday, and it seems it is (at least) partially > answered by PEP 263: > > In Python 2.1, Unicode literals can only be written using the > Latin-1 based encoding "unicode-escape". This makes the programming > environment rather unfriendly to Python users who live and work in > non-Latin-1 locales such as many of the Asian countries. Programmers > can write their 8-bit strings using the favorite encoding, but are > bound to the "unicode-escape" encoding for Unicode literals. > > I have the impression that this is undocumented on purpose, because you > should not write unescaped non-ansi characters into the source file > (with 'unknown' encoding). I agree that using latin1 as default is bad. If there's an encoding cookie in the 2.3+ source file then this encoding could be used. I stumbled on this when giving another Python user on this list a pointer to the relevant section in the Python tutorial (http://www.python.org/doc/current/tut/node5.html#SECTION005130000000000000000) where Guido uses u"???" in an example. As this is BAD the tutorial should probably be changed. I'll file a bug report. -- Gerhard From skip at pobox.com Sun Jul 27 16:02:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 27 Jul 2003 15:02:58 -0500 Subject: GET/POST Data Array in Python? In-Reply-To: <7b454334.0307271134.771de1ce@posting.google.com> References: <7b454334.0307271134.771de1ce@posting.google.com> Message-ID: <16164.12274.833025.917517@montanaro.dyndns.org> faizan> I am making a simple Pythong CGI script that collects data from faizan> a form. When the Python CGI Script is called, I wish to gather faizan> all the POST variables and display all their values. So, I was faizan> wondering if all the POST data is collected in an array like in faizan> PHP where I just go through all keys and display their values? Sure. For an example, visit: http://www.musi-cal.com/~skip/python/ and search for "CGI Environment Printer". Skip From oren-py-l at hishome.net Sun Jul 13 09:38:01 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 13 Jul 2003 09:38:01 -0400 Subject: anything like C++ references? In-Reply-To: References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <20030713133801.GA92658@hishome.net> On Sun, Jul 13, 2003 at 10:58:13PM +1200, David McNab wrote: > On Sat, 12 Jul 2003 13:53:35 -0700, Tom Plunket paused, took a deep > breath, then came out with: > > > I want to do something along the lines of the following C++ code: > > > > void change(int& i) > > { > > i++; > > } > > > Is there any way to do references like this in Python? > > > In Python, basic types like strings and numbers are a weird exception to > the 'everything is an object' rule. > > When you pass any other object in a function, the function gets a ref to > that object. > > But when you pass a string or numeric object, the whole thing (not a ref) > gets passed. Numbers and strings are objects just like everything else in Python and are passed by reference. The only difference is that they are *immutable* objects so their value cannot be changed through that reference in a way that will be visible to others who reference the same object. Under most circumstances a reference to an immutable object is nearly indistingishable from a value. But the id() builtin function or the 'is' operator quickly reveal the difference. There is no weird exception to any rule here. Some objects are mutable, some are not. That's all. Oren From andreas.kuntzagk at mdc-berlin.de Wed Jul 2 06:56:18 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 02 Jul 2003 12:56:18 +0200 Subject: os.fork() different in cgi-script? References: Message-ID: Sorry, forgot: this is Python 2.2.1, apache 1.3.26 on SuSE 8.1 Andreas From adechert at earthlink.net Sun Jul 20 16:43:27 2003 From: adechert at earthlink.net (Alan Dechert) Date: Sun, 20 Jul 2003 20:43:27 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested Message-ID: In the world of voting technology experts, I'm known as the guy that has proposed to use commodity PCs as voting machines running open source software with a printer to generate the paper ballot. While I have been pushing the idea since Dec of '00, I haven't gotten any project funded yet. Back then, I was just a crank with an idea. Now people are starting to take it more seriously. I have some computer scientists and some students interested in producing a demo of the system I have described. Primarily, this demo is intended to introduce the idea to the public. Lots of ideas for which language to use for the demo have been tossed around. I would like to get some feedback on whether or not you think Python would be good for this and why. This will be throw-away code. It will be pure coincidence if we end up using any of it when the real [funded!] project gets underway. We will be demonstrating to some reporters the look and feel of our voting machine -- and by extension to the public, especially since we plan to have a demo on the web that anyone with an Internet connection can try out. Some have suggested HTML or XML but I'm not sure this will give us fine enough control over the page layout. Here are some requirements for the demo: 1) The display will be for 1280 x 1024 resolution. While other resolutions may be supported in the final product, the demo will only support this resolution (the large screen is a critical usability advantage). Here is a mock up of the on-screen ballot image: http://home.earthlink.net/~adechert/ballot-mockup3.gif Pretty much, I want pixel-for-pixel control over what goes on the display. 2) The demo on-screen ballot will have pale background colors initially. I'm thinking the columns will be alternating shades of pale yellow to help delineate them. We might also have the tiles (each contest is displayed in a tile) with contrasting shades. Once a contest is voted on, the colors will change. For example, when the voter selects a president/vice president pair, the background will change; the non-selected pairs will be greyed while the selected pair will be highlighted (very brightly -- should light up like a Christmas tree). The selected pair will also swell in size (maybe 10 %). The target next to the names looks something like a radio button but I'm thinking we may want a box. On selection, a large red checkmark will appear in the box (and maybe extending outside the box). In any case, it will be stupendously obvious who was selected and who was not. 3) When "WRITE-IN CANDIDATE" is selected, a large widow (maybe the full screen) will pop up with a QWERTY keyboard in the upper half. This keyboard will have only three rows with the alpha keys (no punctuation or numbers needed except for perhaps the hyphen... no shift, all CAPS). We'd include a backspace key and a space bar. Under the QWERTY keyboard (and space bar) we'll have a two-row keyboard with the letters arranged alphabetically. Large instruction text that tells the voter to select letters from either keyboard to build the string for the write-in. When the voter selects "DONE," s/he is returned to the original screen with the write-in selected. 4) The first button in the INSTRUCTIONS tile is for selecting a different language. The button label (now has Spanish and French text that says, "To select a different language...") will have maybe one other language on it. Upon selection, the voter will be given a list of languages from which to choose. I one is selected, the voter is returned to the original screen with the text now in the selected language. For the demo, maybe one other language will actually be selectable and used in the display. 5) If the second button in the INSTRUCTIONS tile ("FOR LARGER TYPE") is selected, we go from a one page ballot to multiple pages. The button will change to say "FOR NORMAL TYPE" and will have arrows appended to the left and right of the button for previous and next pages. Each contest will then be displayed one a page of its own with larger text (maybe twice the size). If we have the time, we may also include the option to make the text even larger. This paginated ballot style will require a summary screen that will show all the selections made for all the contests: the "PRINT MY BALLOT" option will appear only on the summary screen. 6) The CAT CATCHER contest illustrates how vote-for-n will look. Once the voter has made three selections, the rest get grey-ed out and cannot be selected. De-selecting one of the selected candidates reactivates the others. 7) The County Commissioner race illustrates how ranked preference voting would look. When the voter selects the first one, the button in the "1" column is filled and the text "1st" will appear in the space between the row of buttons and the candidate name. When the next selection is made, the corresponding button in the "2" column is filled and "2nd" appears, and so on. There is a "CLEAR CHOICES" button in case the voter wants to start over. 8) The printout is intended to come from a personal laser printer located in the voting booth. For the demo, we'll probably use the HP Laserjet 5L. 9) In our set up for the media, we'll have one touch screen system using a flat panel screen something like this one (maybe exactly this one). http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=2742571869&category=29502 We'll have one or more other non-touch screen systems that will work exactly the same way except with a mouse. The displays will be horizontal -- sitting in some custom made cradle we come up with (maybe made from wood). The Australians have done something similar in a pilot project: http://www.softimp.com.au/evacs.html 10) The PCs used will be trailing-edge -- maybe 300-450 MHz PII or PIII. 11) The demo will be advertised to show a new system that will potentially cost a fraction of what dedicated voting machines (ES&S, Sequoia, Diebold, et al, DREs typically cost $3,000 - $4,000 ea) cost. With Measure 41 in California ($200 million) and the Help America Vote Act ($3.9 billion) a lot of public funds are being wasted on outrageously expensive hardware that will be obsolete in a very few years. Trailing edge PCs cost next to nothing. We can afford to put some extra money into the displays and still have a system that is much cheaper. 12) Besides the standalone system, we'll have a web based version so others can try it out. We anticipate that writers will discuss the demo in their articles and will include a URL for readers that want to go try it out. The web version will be hosted at one of the University of California campuses (probably UC Santa Cruz, fyi). BTW, we are not proposing that you will be able to vote from home via Internet. We are proposing that Internet voting be used instead of the usual absentee voting methods, but this will be done at attended voting stations (where the voter can be positively identified). The Remote Attended Internet Voting scheme we propose has the advantage that the on-screen ballot image will be exactly the same for poll site and Internet voting. The printout will also be exactly the same (mailed from the remote location instead of dropped in the ballot box). The electronic record of the vote will also be in the same format. 13) I am pulling together faculty and students from quite a few universities around the country. However, this is designed as mainly a University of California project. Several UC campuses are now involved. UC will be the eventual owner of the software. The complete [funded] project will involve much more than just some voting machine software -- all the software needed for conducting elections will be created. We anticipate having quite a few non-academics involved too. For example, Roy Saltman is probably the best known voting technology expert and he's not an academic. I'm not an academic either. 14) In our system, the printout represents the authentic vote -- it's what the voter sees and personally verifies. The printout will include the ballot number printed in each corner (upside down at the bottom). The selections will be bar coded in a strip on the left edge. Probably, write-in candidate names will be in a separate bar code. The printout will list the voter's selections in text that can be easily read by humans and scanners. Blind voters will use the system wearing headphones and using a hand held device to register selections. Blind voters will take the printout from the printer and place it in a privacy folder. They will be able to verify the contents of the printout and maintain a secret ballot by going to a poll worker and exposing just the edge of the printout with the bar code so that it can be read by a scanner. The blind voter will then be able to hear the selections read back via headphones. 15) Here is some background information on the project proposal in case you're interested: Here's a copy of the first page of our UC Berkeley proposal for California: http://home.earthlink.net/~adechert/src_proposal.html This proposal was recommended for funding more than once: http://home.earthlink.net/~adechert/perata3.jpg U of Iowa CS professor, Doug Jones, is my main co-author for the current draft of our nationwide proposal: http://home.earthlink.net/~adechert/ucvs-proposal.rtf More recent information is available: http://home.earthlink.net/~adechert/ ******************** So, please let me know what you think about using Python for this demo. Also, if you are a Python expert and would like to help as a volunteer (we're all volunteers until the project gets funding), please contact me ASAP. We want to have a demo running very soon! -- within a few weeks. --Alan Dechert 916-791-0456 adechert at earthlink.net From JoeyTaj at netzero.com Mon Jul 14 16:33:38 2003 From: JoeyTaj at netzero.com (Paradox) Date: 14 Jul 2003 13:33:38 -0700 Subject: Python Image Conversion with PIL Message-ID: <924a9f9c.0307141233.6d894f7a@posting.google.com> I am trying to convert some group 4 Tif images to JPG. I can load the image fine and can read attributes but every method I call raises this error (IOError: decoder group4 not available). Is there any extra package that I am needing. I searched the PDF help and the PIL website and can't find any reference to anything like that. From tdelaney at avaya.com Wed Jul 16 20:25:39 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 17 Jul 2003 10:25:39 +1000 Subject: Augmented Assignment question Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE8D3D44@au3010avexu1.global.avaya.com> > From: Doug Tolton [mailto:dtolton at yahoo.com] > > I mis-spoke, lists are not included. You cannot do augmented > assignments on tuples or multiple targets. This is still incorrect. You correct thing to say is that you cannot do an augmented assignment on something which does not have a name, or which explicitly forbids it. > >>> a,b = 0,0 > >>> a,b += 1,1 > SyntaxError: augmented assign to tuple not possible >>> l = [] >>> l [] >>> id(l) 8289204 >>> l += [1,] >>> l [1] >>> id(l) 8289204 >>> l += ['foo',] >>> l [1, 'foo'] >>> id(l) 8289204 >>> t = () >>> t () >>> id(t) 7966916 >>> t += (1,) >>> t (1,) >>> id(t) 8261268 >>> t += ('foo',) >>> t (1, 'foo') >>> id(t) 8133748 Note how the ID of `l` (list) does not change, but the id of `t` (tuple) does. This is because a tuple is immutable, and so: t += (1,) is equivalent to: t = t + (1,) whereas a list is mutable, and: l += [1,] is equivalent to: l.extend([1,]) Every class can decide how to implement augmented assignment, using the __iadd__, etc magic methods. Tim Delaney From LogiplexSoftware at earthlink.net Tue Jul 15 14:24:30 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 15 Jul 2003 11:24:30 -0700 Subject: How to crash Python in 1 easy step (python 2.2.2) In-Reply-To: References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <1058293470.1563.16.camel@software1.logiplex.internal> On Tue, 2003-07-15 at 03:17, Gavrie Philipson wrote: > pwmiller1 at adelphia.net (Paul Miller) wrote in message news:<2e363c08.0307130944.4c470bc3 at posting.google.com>... > > I'm not sure if this is a python bug or a bug in an associated > > library, and I'm not even sure how to correctly report it, but here is > > Anytime python is accepting keyboard input, whether it's with > > raw_input, or sitting on the command line waiting for the user to type > > code, you can crash python by holding ctrl+shift and then pressing > > enter. > > > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > > everything about the system is standard except for what's been updated > > by RedHat itself. If anyone who has the time and ability to track > > down this bug needs more information, please email me. > > I'm seeing the same effect on RH9, using KDE's "konsole" terminal > emulator. > When pressing Ctrl-Shift-Enter, it actually sends the ^[OM characters > (Escape, O, M). > Manually sending the key sequence Esc-O-something also crashes Python. Yep, here (RH9, Py2.2.2) it is as well under gnome-terminal (sending Esc-O-M). I'm amazed no one saw it sooner . -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From shawn at thekompany.com Wed Jul 30 00:59:09 2003 From: shawn at thekompany.com (Shawn Gordon) Date: 29 Jul 2003 21:59:09 -0700 Subject: PyQt Help and Advice References: Message-ID: ilyak at red.seas.upenn.edu (Ilya Knizhnik) wrote in message news:... > Dear All, > > I am fairly new to Python. I have found it an easy language to learn and > a very usefull one for many tasks. Currently I am working on a python > project that involves a GUI and it was suggested that PyQt is the best way to > design that GUI. > However since PyQt is rather new, I have not found much documentation on > it, or examples in it. The only useful tutorial/book I have found is at > www.opendocspublishing.com/pyqt/ but it is not always clear for someone > with almost no GUI experience. > Does anyone have any suggestions? > > Ilya We have a product called PyQtDoc that provides a very nice and convenient interface for all the PyQt information. You can see information on it at http://www.thekompany.com/products/pyqtdoc/ Best, Shawn From mis6 at pitt.edu Thu Jul 24 17:06:55 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Jul 2003 14:06:55 -0700 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: <2259b0e2.0307240536.425f837d@posting.google.com> After some thinking, and having read the suggestion in this thread, I see that the source of my problem was the following: whereas an empty list or an empty tuple has a truth value of False, an empty iterator has a truth value of True. It is easy to fix, anyway, with a function which works as "iter", but return an empty list (or tuple) when the iterator is empty: import itertools def iter_(seq): i=iter(seq) try: first=i.next() except StopIteration: return [] return itertools.chain([first],i) Maybe not very elegant, but it works: it=iter_('xyz') for c in it: print c if iter_(it): print "non empty" else: print "is empty" BTW, the fact that an empty iterator is True is somewhat strange, considering that [],() and "" are False; on the other hand, generic objects are True, so the point can be debated ... Michele From fredrik at pythonware.com Tue Jul 29 10:47:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Jul 2003 16:47:43 +0200 Subject: gzip HTTP results problem References: <003401c355c1$cb6949f0$6400a8c0@EVOD31> Message-ID: Bill Loren wrote: > I've encountered a problem trying to decode gzip data > returned from an HTTP server I communicate with (I use urllib2). > I've tried to use both the gzip and zlib come-along python libraries but > alas. > > Have anyone of you ppl succeeded in talking gzip with an HTTP > server ? this might help: http://effbot.org/zone/consumer-gzip.htm (that piece of code is used in production code, so it should work...) From roy at panix.com Fri Jul 11 07:46:13 2003 From: roy at panix.com (Roy Smith) Date: Fri, 11 Jul 2003 07:46:13 -0400 Subject: How to get all IP addresses in python? References: Message-ID: "Yun Mao" wrote: > Hi. I did a little homework on google for this question. The answer was: > >>> import socket > >>> hostname = socket.gethostname() > >>> ip = socket.gethostbyname(hostname) > >>> print ip > 192.168.55.101 > But what if I have several interfaces, say eth0, eth0:1, eth1, etc. How to > get all of them? It would be a little undesirable if people suggest to parse > the result of ifconfig because I in particular want the code to be cross > platform. Thanks a lot! You might try using gethostname() as above to get the canonical host name for your machine, then using one of the various Python DNS modules to look up all the A records for that name. Not perfect, but a start. From simonb at webone.com.au Fri Jul 4 21:40:04 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 05 Jul 2003 11:40:04 +1000 Subject: ANN: hYPerSonic-1.0 Message-ID: hYPerSonic allows one to build and manipulate signal processing pipelines from python scripts. It is designed for real-time control. It includes objects for oscillators, filters, file-io, soundcard and memory operations. It is low-level: every byte counts. Source code, examples, docs, here: http://arrowtheory.com/software/hypersonic/index.html Runs on Linux and OSX, with python2.2 or 2.3. I'd like to know what you think of it. Simon Burton. From gh at ghaering.de Fri Jul 25 13:37:04 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 25 Jul 2003 19:37:04 +0200 Subject: CGI "download" prompt? In-Reply-To: <3f215bef$0$49107$e4fe514c@news.xs4all.nl> References: <77dd287a.0307240632.40c6c309@posting.google.com> <3f205f06$0$49115$e4fe514c@news.xs4all.nl> <77dd287a.0307250619.7c2ec441@posting.google.com> <3f215bef$0$49107$e4fe514c@news.xs4all.nl> Message-ID: <3F216AC0.3010004@ghaering.de> Irmen de Jong wrote: > Gerhard H?ring wrote: > >> Erhm. Let's suppose you want to send an RTF file and have the browser >> pop up a save dialog with a certain filename preconfigured: >> >> Then send these headers: >> >> Content-Type: application/rtf >> Content-Disposition: attachment; filename=mydocument.rtf > > I didn't know about Content-Disposition! If this works, > that's very nice-- especially if the filename part of that > header is actually used by the web browser. That's what it is about. See http://www.faqs.org/rfcs/rfc2183.html for details :) -- Gerhard From letezo at fw.hu Thu Jul 10 11:47:38 2003 From: letezo at fw.hu (=?iso-8859-2?B?TOl0ZXr1?=) Date: Thu, 10 Jul 2003 17:47:38 +0200 Subject: Number Theory modules for Python Message-ID: <001601c346fa$9add2b60$8800a8c0@sirius> Hi! I searched the Net and found several Number Theory (NT) related Python extension modules. Some of them may be used to do some research but unfortunately almost all promising modules disappeared from the Net, so I wasn't able to download them. I'm sure, that it's my fault and NT packages are actually exist and downloadable - somewhere. Please send me any known NT related materials/URLs can be used to do NT research. Thanks: Complex From jarausch at skynet.be Mon Jul 14 16:13:08 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 14 Jul 2003 22:13:08 +0200 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= In-Reply-To: References: Message-ID: <3F130ED4.2030804@skynet.be> Raymond Hettinger wrote: > ACT III ---------------------------------------------------- > def once(x): return x > def twice(x): return 2*x > def thrice(x): return 3*x > funcs = [once, twice, thrice] > > flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)] > flam = [lambda x:f(x) for f in funcs] > > print flim[0](1), flim[1](1), flim[2](1) > print flam[0](1), flam[1](1), flam[2](1) OK, I believe to know why the last line print '3' three times, since only a reference to 'f' is stored within the lambda expression and this has the value 'thrice' when 'print' is executed. But how can I achieve something like an evaluation of one indirection so that a reference to the function referenced by 'f' is stored instead. Thanks for hint. (this references only model of Python is a bit hard sometimes) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From peter at engcorp.com Wed Jul 9 09:15:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 09:15:00 -0400 Subject: Python Global Constant References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: <3F0C1554.DFBE1601@engcorp.com> Christoph Becker-Freyseng wrote: > > >>*** module any *** > >>import dirs; > >>def CheckDir(Dir): > >> if Dir=dirs.Const_Up: xxx > > > > > > This code should work fine, although you might want to follow > > the Python conventions ........ > > What about using __builtins__ wouldn't make this the constant really global? A module is already global, in the sense that if you do "import xxx" you will get a reference to a singleton module object (generally from xxx.py), which provides a nice clean namespace for a set of names such as constants. This makes it easy for someone reading the code to see where a constant is defined, and it provides a necessary level of organization. Putting something in __builtins__ is not only stylistically a bad idea for most things, but it also hides the source of the name and anyone reading the file will be at a loss to figure out where it came from unless every reference to it is preceded by a big comment:: # WARNING! The author of this code chose the silly approach # of storing a reference to this constant in the __builtins__ # namespace, which is why you can't find where it is defined. # This reference was stored in the initialization code that # is in init.py, and instead of just leaving the name there # so you could call it "init.CONSTANT", it was slipped in # through the back door to let the author save five keystrokes, # at the expense of readability, but with this comment everything # will be okay. x = CONSTANT How is that better than using the proper approach of storing constants in a module, such as "constant.py"? ;-) -Peter From inyeol.lee at siimage.com Tue Jul 15 18:06:03 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 15 Jul 2003 15:06:03 -0700 Subject: String Manipulation In-Reply-To: References: <2c6431ab.0307151223.4173c4ee@posting.google.com> Message-ID: <20030715220603.GA7138@siliconimage.com> On Tue, Jul 15, 2003 at 01:58:09PM -0700, Cousin Stanley wrote: > | I need a piece of code that takes a string like this > | string1 = "aaa/bbb/ccc/dd" and extracts a string containting > | the character after the last "/" > | > | So for this example the result would be "dd" > | ... > > lamar_air ... > > Here is one way ... > > > >>> str_in = 'aaa/bbb/ccc/dd' > >>> > >>> list_in = str_in.split( '/' ) > >>> > >>> last_element = list_in[ -1 ] > >>> > >>> print last_element > dd > >>> > > > -- > Cousin Stanley > Human Being > Phoenix, Arizona > In Unix, >>> os.path.basename("aaa/bbb/ccc") 'ccc' Inyeol From ask at me.com Thu Jul 10 16:24:15 2003 From: ask at me.com (Greg Krohn) Date: Thu, 10 Jul 2003 20:24:15 GMT Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: "Steve Pinard" wrote in message news:6cd58b6.0307101214.34e99f2a at posting.google.com... > (Got a comm error trying to post first time, sorry if this > is a duplicate) > > New to Python, so please bear with me. > > >>> import sys > >>> print sys.modules.keys() # works fine > ['code', ...snip... ] > >>> print sys.modules.keys().sort() # returns None, why? > None > > According to my reference (Nutshell), keys() returns a > "copy" of the dict keys as a list, so I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? > > TIA, > - Steve > You said it yourself. It's an IN PLACE sort, so it won't return anything (well, None, but that doesn't count). Try this: **UNTESTED** >>> mykeys = sys.modules.keys() >>> print mykeys [...a list of keys...] >>> mykeys.sort() #Note it's IN PLACE. Nothing is returned, so there's no need to assign anything >>> print mykeys [...a SORTED list of keys...] Greg From tzot at sil-tec.gr Sun Jul 27 20:10:44 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 28 Jul 2003 03:10:44 +0300 Subject: Python 2.3C1 Fails to build ? References: Message-ID: On Fri, 25 Jul 2003 02:01:10 -0400, rumours say that "Tim Peters" might have written: >> PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) >> ^ >> >> Total errors detected in Objects/obmalloc.c: 2 >> make: *** [Objects/obmalloc.o] Error 1 >> ~~~~~~~~~~~~~~ >> >> Any ideas what is going on? > >I'm surprised this hasn't triggered a (bogus) error on some other platform >before! This does trigger a warning on SGI MIPSPro compilers: cc-1167 cc: WARNING File = Objects/obmalloc.c, Line = 371 Pointer points outside of underlying object. PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) ^ I never bothered to report it as a Python bug (or a patch: see later) since things work fine; I am sure other Irix users noticed that too. As Martin says, the macro PT(0) expands to twice PTA(0): ((poolp )((uchar *)&(usedpools[2*(0)]) - 2*sizeof(block *))) C defines that a[i] == *(a+i) {btw: == *(i+a) == i[a] but it's irrelevant} so, assuming that MIPSPro don't like returning addresses before the one usedpools points to, I just tried #define PTA(x) ((poolp )((uchar *)(usedpools+2*(x)) - 2*sizeof(block *))) ie I used (a+i) instead of &(a[i]), just in case I could fool the compiler. No success, of course, the warning was still thrown, because usedpools *is* an array pointer --it's not just a pointer-- and PT(0) points to memory *before* usedpools. Anyway, the source comments declare that PT(0) is indeed an "invalid" address, so the programmer is aware. MIPSPro and UNICOS cc aren't that mistaken in giving a warning/error, but it's a bug only if usedpools[0] or usedpools[1] ever get used as pointers; it seems they are not (guessing by Python working correctly). Now, Holden: although there could be some connection between Cray and SGI C compilers, I am afraid I can't help more; you could try cc options about what is an error and what is a warning... the manuals should be your friend. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From aahz at pythoncraft.com Tue Jul 15 10:47:09 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2003 10:47:09 -0400 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= References: <3F140F34.1030401@mitretek.org> Message-ID: In article <3F140F34.1030401 at mitretek.org>, Chris Reedy wrote: > >Aside: I have to admit that the ((42,) * 2) did confuse me at first. I'm >so used to doing 2 * (42,) when I want to repeat a sequence that I >hadn't thought about the reversed form. My experience is that most people do it the way Ray did, * . -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From alanmk at hotmail.com Fri Jul 18 15:25:39 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 18 Jul 2003 20:25:39 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F17C1D4.1A70703A@hotmail.com> Message-ID: <3F1849B3.ED989E2@hotmail.com> Brian McErlean wrote: > I saw the same as you with that URL, but viewing the thread in > google, or going to the link it gave for "View this article only": > http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3F172442.2040907%40v.loewis.de > > displayed OK (Using Mozilla firebird 0.6) > > The key difference seems to be the "oe=UTF-8" argument in the URL. > Adding this to your URL displays it correctly. Yep, we're definitely not in ASCII-land anymore. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From edreamleo at charter.net Thu Jul 17 16:52:22 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 17 Jul 2003 15:52:22 -0500 Subject: wxPython questions Message-ID: I am considering switching from Tk to wxPython; the demo is just so cool. Here are my questions: How reliable is wxPython? This is the big one. In more than two years of Tkinter development I've taken exactly one core dump in Tk. I can get wxPython's demo.py to take memory faults with the Unicode enabled version of wxPython on XP. About half the time clicking on the Generic Buttons demo yields: "Unhandled exception in python.exe (WXMSW24UH.DLL)" The wxTimeControl demo also throws AttributeError exceptions. Not a big deal, and one wonders... Tk does a lot of checking; wxWindows apparently does little or none. I don't really mind hard crashes during development; core dumps for my users must never ever happen. How difficult is it in practice to get all the core dumps out of a medium-sized wxPython app? Presumably many of the wxWindows helper classes aren't needed in wxPython. Besides the actual widget classes, what other wxWindows classes must a wxPython app use? Any others besides wxColor, wxIcon and wxFont? What about strings? I'd much rather use Python strings instead of wxString. Is it possible to have an app that creates multiple windows without using wxDoc and allies? My app presently creates a hidden TK root window, and manages all other Tk windows by hand. Is something like this possible in wxPython? Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From pyth at devel.trillke.net Thu Jul 3 05:01:45 2003 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 3 Jul 2003 11:01:45 +0200 Subject: Clever One Liners In-Reply-To: <20030703022716.62264.qmail@web20514.mail.yahoo.com>; from woooee@yahoo.com on Wed, Jul 02, 2003 at 07:27:16PM -0700 References: <20030703022716.62264.qmail@web20514.mail.yahoo.com> Message-ID: <20030703110145.E6906@prim.han.de> Curly Joe wrote: > I agree with you, especially since the compiler, in > most cases, must break everything down into single > steps anyway. Take for instance a very simple > example: > x = a + b/c > The compiler would execute this as: > x = b/c > x += a to be more precise, the compiler would *compile* x = a + b/c to some bytecode like LOAD_FAST 0 (a) # get var and put on valuestack LOAD_FAST 1 (b) # get var and put on valuestack LOAD_FAST 2 (c) # get var and put on valuestack BINARY_DIVIDE # take 2 stack values and put # the devision of them on valuestack BINARY_ADD # take 2 stack values and put # the sum on the value stack STORE_FAST 3 (x) # store last stack item into "x" and the interpreter would execute this bytecode. > Michael Chermside wrote: > I'm not picking on you in particular, there have been > several people > doing this lately, but I'd like to ask folks to please > lay off the > quest for one-liners. What about going for writing bytecode-assembler instead of language-level oneliners :-) ? cheers, holger From steve at ferg.org Tue Jul 22 15:51:02 2003 From: steve at ferg.org (Stephen Ferg) Date: 22 Jul 2003 12:51:02 -0700 Subject: Python & Perl in Wall Street Journal References: Message-ID: Ooops. Make that "E and J sources". From flanagan at hotmail.com Wed Jul 9 02:26:38 2003 From: flanagan at hotmail.com (Flanagan) Date: Wed, 09 Jul 2003 06:26:38 GMT Subject: format discs. Message-ID: hello to all somebody can say to me whereupon I modulate of python I can format discs. thanks flanagan From wright at esrf.fr Fri Jul 4 14:16:41 2003 From: wright at esrf.fr (Jon) Date: 4 Jul 2003 11:16:41 -0700 Subject: getting a submatrix of all true References: Message-ID: <52fe159d.0307041016.4dcb4a5c@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > On Wed, 02 Jul 2003 14:16:57 -0500, John Hunter wrote: > >I am currently using a hack that works, but it makes me wonder if > >there is an optimal solution. I define optimal as the removal of rows > >and columns such that there are no missing values and > >max(numRows*numCols). There must be! For each missing entry you can choose to drop either the row or the column - giving a maximum of 2^N possible ways for N missing elements. Given that the order in which the rows/columns are deleted is unimportant the number of possibilities to test is less than that, but the difficulty is that your decision about row or column for one element affects the decision for other elements if they share rows or columns. Graph theoretic approaches probably help - it's similar to reordering matrix elements to avoid fill in when decomposing sparse matrices. Depending on N, you might be able to test all possibilities in a reasonable time, but I have a nasty feeling you need to check all 2^M to be sure of an optimal solution, where M is the subset of N which either a share a row or column with another problematic element. > >Another way of formulating the question: for a sparse boolean matrix > >(sparse on True), what is the optimal way to remove rows and columns > >so that the total number of elements in the matrix is maximal and > >there are no True values left. Sadly I can only give you a method which is certainly not optimal, but at least finds something which is probably not too bad, and fairly quickly. Uses the Numeric module to speed up, so that a few thousand by a few hundred is quickly computable. I'm curious to know if it does much better or worse than other algorithms. Interesting problem! Cheers, Jon ===================================================================== from Numeric import * def pickrcs(a,debug=0): b=array(a,copy=1) # local copy of array is modified dr=zeros(b.shape[0]) # Arrays to note deleted rows... dc=zeros(b.shape[1]) # ... and columns sizeleft=[b.shape[0],b.shape[1]] # Remaining dimensions while 1: # Keep deleting till none left sr=sum(b,1) # Column scores = ij's to remove sc=sum(b,0) # Row scores mr=argmax(sr) # index highest row score mc=argmax(sc) # index highest column score if sr[mr]==0 and sc[mc]==0 : break # stop when nothing to delete # pick the row/column to delete fewest useful elements if sizeleft[1]-sr[mr] > sizeleft[0]-sc[mc]: b[:,mc]=0 # Zero out column dc[mc]=1 # tags column as deleted sizeleft[1]-=1 else: b[mr,:]=0 # Zero out row dr[mr]=1 sizeleft[0]-=1 # end of deletions loop - should be no missing elements now # # paranoia!, check if anything was left after deletions if sum(dr) Message-ID: <3f01d0d1@news.swissonline.ch> > Hi, I need to get a sort of DOM from an HTML page that is declared as XHTML > but unfortunately is *not* xhtml valid.. If I try to parse it with I use mx.Tidy in such cases, with great success. Cheers Franz "Alessio Pace" schrieb im Newsbeitrag news:3GbMa.4404$FI4.118833 at tornado.fastwebnet.it... > Hi, I need to get a sort of DOM from an HTML page that is declared as XHTML > but unfortunately is *not* xhtml valid.. If I try to parse it with > xml.dom.minidom I get error with expat (as I supposed), so I was told to > try in this way, with a "forgiving" html parser: > > from xml.dom.ext.reader import HtmlLib > reader = HtmlLib.Reader() > dom = reader.fromUri(url) # 'url' the web page > > FIRST ISSUE: > It seemed to me, reading the source code in > $MY_PYTHON_INSTALLATION_DIR/site-packages/_xmlplus/dom/ext/reader/ , > that these are 4DOM APIs , so from what I know of python distributions, they > are extra packages, or not? I would like to use *only* libs that are > available in the python2.2 suite, not any extra. > > SECOND ISSUE: > If the above libs were included in python (and so I would continue using > them), how do I print a string representation of a (sub) tree of the DOM? I > tried with .toxml() as in the XML tutorial but that method does not exist > for the FtNode objects that are involved there... Any idea?? > > Thanks so much for who can help me > > -- > bye > Alessio Pace From mwilson at the-wire.com Wed Jul 30 14:08:36 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 30 Jul 2003 14:08:36 -0400 Subject: Syntax: pointers versus value References: <3F27F673.3000801@mathstat.concordia.ca> <3F280475.3000500@mathstat.concordia.ca> Message-ID: In article <3F280475.3000500 at mathstat.concordia.ca>, Danny Castonguay wrote: >Tino Lange wrote: >> Use: >> listB = listA[:] > >-------------------------------------------------------------------- >In the example I have given, it does solve the problem. However, for >some reason I don't understand, it doesn't work in the next example: > >def ps_of_missing_edges(initial_graph, missing_edges): > num_m_e = len(missing_edges) #number of missing_edges > num_e_pset = 2**num_m_e > graphs = [] > for i in range(0,num_e_pset): #iteration will stop at 2^num-1 > temp_i = i #use temp_i to find i's bit values > new_graph = initial_graph[:] > print 'initial_graph is ' + str(initial_graph) > for j in range (0,num_m_e): > if temp_i%2 == 1: > new_graph[missing_edges[j][0]-1].append(missing_edges[j][1]) > temp_i = temp_i >> 1 > graphs.append(new_graph) > return graphs > >-------------------------------------------------------------- > >the output when I call: > ps_of_missing_edges([[2,3],[1],[1]], [[2,3],[3, 2]]) >is: > initial_graph is [[2, 3], [1], [1]] > initial_graph is [[2, 3], [1], [1]] > initial_graph is [[2, 3], [1, 3], [1]] > initial_graph is [[2, 3], [1, 3], [1, 2]] > >-------------------------------------------------------------- >Therefore, somehow initial_graph's value changes even though the >assignment is new_graph = initial_graph[:] > >Assuming that the assignment does it's job, then I don't see how >initial_graph's value changes. I don't know, but I think you'd better try copy.deepcopy instead. Looks like initial_graph and new_graph are sharing mutable elements. Regards. Mel. From max at infobahn.ch Tue Jul 8 10:00:07 2003 From: max at infobahn.ch (Zcam) Date: 8 Jul 2003 07:00:07 -0700 Subject: PyIrc module References: <20030707225250.7171.qmail@cs06.tgv.net> <200307072005.17077.shalehperry@comcast.net> Message-ID: Jp Calderone wrote in message news:... > On Mon, Jul 07, 2003 at 08:05:17PM -0700, Sean 'Shaleh' Perry wrote: > > On Monday 07 July 2003 15:52, sylvain HELLEGOUARCH wrote: > > > Hello everyone, > > > > > > This is my first message round here :) > > > > > > Well, my message is more or less an announcment of my pyirc module for > > > Python (uh uh surprise this is the right place :)). > > > > > > This module tries to implement both RFC 1459 and 2812 about IRC protocol. > > > I've decided to code my own module as Python has a lack of IRC ones. > > > Generally speaking, either they are not up-to-date anylonger or they are > > > written for a specific GUI. > > > > > > > not to downplay your work, but have you looked at Twisted? > > http://twistedmatrix.com/products/twisted > > > > Forget Twisted: > > http://python-irclib.sourceforge.net/ > > http://sourceforge.net/projects/pyirclib/ > > http://sk.nvg.org/python/irc_uninett/ > > http://tarken.lyrical.net/programming/python/irclib_py.php > > http://linux.duke.edu/projects/kibot/contents/doc/kibot/kibot.irclib.html > > But hey, I guess everyone's entitled to write at least one IRC library... > > Jp > > PS - Not to downplay etc I dont know about Twisted, but the other existing python irc implementations do not follow the rfc's specifications (not entirely). Nice peace of work Sylvain . From intentionally at blank.co.uk Mon Jul 14 00:07:21 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 05:07:21 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: On 13 Jul 2003 21:43:41 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >Stephen Horne wrote: >> >>In computer science, a variable is a named binding to a value. >>Operations on that variable may rebind it to a different value, but >>values don't change behind your back. A pointer is, in effect, a value >>which indirectly refers to another (possibly anonymous) variable. A >>pointer is something you specifically request, and by doing so you >>allow that the 'variable' being indirectly referenced may be modified >>by something else that has no direct access to your pointer value (via >>your named variable or via copys or pointers-to your pointer held >>elsewhere). >> >>Python should respect that. > >That's why I (and others) prefer to use "name" and "target" instead of >"variable". Would that assuage your ire? Not really, for reasons defined elsewhere. The problem isn't theoretical - it is practical, as shown by the fact that people do trip over it time and time again. I'm just saying that the problem arises out of peoples intuition of how variables should work - an intuition that matches very well with theory. If there is a clear concept of the right thing expressed in theory which happens to match common intuitions, and if the wrong thing tends to lead to subtle errors in functions that act differently depending on whether the values passed in happen to be of mutable or immutable types, all I can do is refer back to the arguments used against me back in PEP238 when the majority *wanted* to make the massively incompatible change on the grounds of theory, intuition and reliability. From BPettersen at NAREX.com Wed Jul 23 18:29:56 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 23 Jul 2003 16:29:56 -0600 Subject: Reading Keyboard Scan Codes Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4706@admin56.narex.com> > From: Fran?ois Pinard [mailto:pinard at iro.umontreal.ca] > > [Michael Bendzick] > > > Is there a simple way in python to read a keyboard scan > > code? I'm working on a shell script that interfaces > > with a proprietary keyboard device (extra buttons) and > > need to be able to distinguish between those keys. > > Within Linux in console mode, you merely do: [...] > However, I do not know if reading scan codes or key codes is > easily done within X, nor on MS-Windows. I would like finding or > discovering recipes in this area. So, please share your tricks > in this area, if any! :-) [...] I'm assuming you can use the msvcrt module: >>> def getch(): ... import msvcrt ... while not msvcrt.kbhit(): pass ... return msvcrt.getch() ... >>> getch() 'a' >>> -- bjorn From bokr at oz.net Thu Jul 31 21:13:25 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Aug 2003 01:13:25 GMT Subject: How to get Windows physical RAM using python? References: Message-ID: On Fri, 01 Aug 2003 09:02:03 +1000, Mark Hammond wrote: >Why not submit that as a patch to win32all ? > >Mark. > You mean just posting to c.l.py doesn't go anywhere? ;-) Anyway, don't know how to submit path to win32all. Plus how do you test something like that? Already the 0 for percentage of memory in use that I got seemed funny, but maybe it's a percentage of total possible maxed-out page file virtual. Seems like it needs a little ageing at least? I thought someone might spot something. I meant to look into win32all, but this is all the further I got ;-/ 03-05-31 16:24 3,971,152 E:\DownLoad\Python\win32all-152.exe Regards, Bengt Richter From mike at nospam.com Wed Jul 30 20:02:42 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 30 Jul 2003 17:02:42 -0700 Subject: Dict to "flat" list of (key,value) References: Message-ID: Nicolas Girard wrote: > Forgive me if the answer is trivial, but could you tell me how to > achieve the following: > > {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] [list(i) for i in d.items()] Mike From hwlgw at hotmail.com Tue Jul 22 02:38:12 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 21 Jul 2003 23:38:12 -0700 Subject: How to save web pages for offline reading? References: Message-ID: > [Sybren Stuvel] > do "man wget" and you'll soon find out that there is an option to > download all required files. Hint: > > --page-requisites > This option causes Wget to download all the files that are necessary > to properly display a given HTML page. This includes such things as > inlined images, sounds, and referenced stylesheets. There is no "man wget" on Windows :-) And unfortunately the GNU Windows port of wget I have (version 1-5-3-1) does not have that --page-requisites parameter. I thought this whole thing would be easy with all those Python internet modules in the standard distro: httplib, urllib, urllib2, FancyURLxxx etc. Being able to download a "complete" page *from Python source* would be very nice for my particular application. -- Behold the warranty ... the bold print giveth and the fine print taketh away. From paulpaterson at users.sourceforge.net Fri Jul 25 22:01:33 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sat, 26 Jul 2003 02:01:33 GMT Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: <1ilUa.102161$XV.6096085@twister.austin.rr.com> Steven Taschuk wrote: > Quoth Paul Paterson: > [...] > >>Does anyone have any alternative strategies for trying to achieve the >>objective? A "Pythonic" approach such as, >> >>def change(x, y): >> x = x + 1 >> y = y + 1 >> return y >> >>x = 0; y = 0 >>y = change(x, y) >> >>Works in a single threaded environment but, because the value of 'y' >>changes at the wrong time, with multiple threads there is a possibility >>that two users of 'y' could dissagree on its value. > > > Even if the simple > y = y + 1 > could change the caller's binding, there would be a race condition > -- you'll need a lock anyway. (I'd be a bit surprised if this > were not so in VB as well. Are statements atomic in VB?) > AFAIK in VB, if 'y' is a global (or in some other way accessible via two threads) then concurrent changes are managed behind the scenes by VB - presumably either some locking is occuring or the assignment statement is atomic. To be honest though, I'm not sure. Threading usually occurs either by using timers or COM. I have seen issues where you have to manually implement semaphores when using timers and COM together. That asside, you make an excellent point. The thread safety and ByRef issues are probably orthogonal and I should probably look for two complementary solutions. From Nicolas.nospam.Girard at removethis.nerim.net Wed Jul 30 15:26:19 2003 From: Nicolas.nospam.Girard at removethis.nerim.net (Nicolas Girard) Date: Wed, 30 Jul 2003 21:26:19 +0200 Subject: Dict to "flat" list of (key,value) Message-ID: Hi, Forgive me if the answer is trivial, but could you tell me how to achieve the following: {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] The subtle point (at least to me) is to "flatten" values that are lists. Thanks in advance, Nicolas ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From g2h5dqi002 at sneakemail.com Thu Jul 24 02:55:55 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 24 Jul 2003 18:55:55 +1200 Subject: How to link a C extension module on Mac OS X? In-Reply-To: References: Message-ID: Gerhard H?ring wrote: > Two words: Use distutils. And it turns out that, rather unintuitively, the way distutils does it is that it *doesn't* try to create a dynamic library, just an ordinary object file named with a .so suffix... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aahz at pythoncraft.com Wed Jul 16 16:51:38 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 Jul 2003 16:51:38 -0400 Subject: Augmented Assignment question References: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: In article <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com>, Doug Tolton wrote: > >I did some reading and it seems that an augmented assignment is >specifically verboten on tuples and lists. Is there a clean way to >accomplish this? Really? >>> l = [] >>> l+=[1] >>> l [1] >>> l+=['foo'] >>> l [1, 'foo'] -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From pythonguy at Hotpop.com Tue Jul 29 09:14:06 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 29 Jul 2003 06:14:06 -0700 Subject: Voting Project Needs Python People References: <5ab0af73.0307211623.6e12f807@posting.google.com> Message-ID: <84fc4588.0307290514.54d68563@posting.google.com> I am ready to join this project. As for knowing python I guess I do. Before you take my word for it take a look at my homepage at http://members.lycos.co.uk/anandpillai. I dont need money, just free beer and pizza ;-) (joking) ~Anand "Alan Dechert" wrote in message news:... > "Matt Shomphe" wrote in message > news:5ab0af73.0307211623.6e12f807 at posting.google.com... > > "Alan Dechert" wrote in message > news:... > > > > > We have an excellent team together. We're looking for a few good Python > > > coders willing to volunteer for this free open source project. It will > be > > > on sourceforge.net later today. > > > > Are there any prerequisites for joining the team? > > > It would be nice if you know some Python. Do you? > > BTW, I'm told it will take a day or two to get the project going on > sourceforge.net. > > Alan Dechert From rastm2 at aol.commorespam Sun Jul 20 14:49:19 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 18:49:19 GMT Subject: ANN: zip-ls -- Zip file listing program References: Message-ID: <20030720144919.18124.00000263@mb-m15.aol.com> Dave writes: >I've implemented a Zip file listing program that gives me some of >the listing and formatting options that I've wanted from "unzip >-l" and "unzip -Z". It's written in Python using the zipfile >module from the Python standard library. Dave, you might like to mention the fact that Python2.3 can now import from zip files. zipimport - import modules from zipfiles, implemented in C by Just van Rossum based upon earlier code by James Ahlstrom. (New in 2.3a2: several serious bugs discovered in 2.3a1 fixed.) --Ray St.M Proudly stating the obvious since birth >You can find it here: > > http://www.rexx.com/~dkuhlman/#zip-ls > http://www.rexx.com/~dkuhlman/zip-ls.html > http://www.rexx.com/~dkuhlman/zip-ls.zip From jaraco at nospamsandia.gov Wed Jul 2 11:52:16 2003 From: jaraco at nospamsandia.gov (Jason R. Coombs) Date: Wed, 2 Jul 2003 09:52:16 -0600 Subject: Win32 Extensions: problem with ADO.Command.Execute() options Message-ID: I'm hoping this is a coding error on my part, but I've encountered a problem with parameters that I cannot understand. Perhaps someone out there might be willing to assist me with some suggestions. First, here is some VB code that correctly does what I want to do: --------------------------- begin cmdtest.vbs Dim cn Dim rs Dim cmd Set cn = CreateObject( "ADODB.Connection" ) cn.Open( "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=Environmental Monitoring;Integrated Security=SSPI" ) Set rs = CreateObject( "ADODB.Stream" ) rs.Open() Set cmd = CreateObject( "ADODB.Command" ) cmd.ActiveConnection = cn cmd.Properties("Output Stream").Value = rs cmd.CommandText = "SELECT * FROM [Sources] for XML AUTO" cmd.Execute , , 1024 'adExecuteStream rs.Position = 0 WScript.Echo rs.ReadText() --------------------------- end cmdtest.vbs Here is partial output I get: C:\>cscript cmdtest.vbs Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. ... Now, if I attempt to do the same thing in python, it returns no output. ------------------------- begin cmdtest.py import ADO, sys cn = ADO.Connection() cn.Open( "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=Environmental Monitoring;Integrated Security=SSPI" ) rs = ADO.Stream() rs.Open() cmd = ADO.Command() cmd.ActiveConnection = cn cmd.Properties("Output Stream").Value = rs cmd.CommandText = "SELECT * FROM [Sources] for XML AUTO" cmd.Execute( Options = ADO.constants.adExecuteStream ) rs.Position = 0 sys.stdout.write( rs.ReadText() ) # prints nothing ------------------------- end cmdtest.py If I pass no parameters to cmd.Execute in the VBScript verison, I get no output. Other tests have further led me to conclude that the constant value 1024 is not being properly passed to ADO.Command.Execute in the Python version only. Here are some other points of information: a.. Using the literal 1024 in the Python code instead of the constant reference make no difference. b.. The VBScript code does not recognize adExecuteStream by name. c.. Using win32com.client.Dispatch( 'ADODB.*' ) to create the objects (instead of ADO.py created from make PY) yields the same results. d.. Using a different PROVIDER in the connection (such as SQLXMLOLEDB) will yield different results, but still indicates that the 'adExecuteStream' is not being set proprly. e.. I'm using "Microsoft ActiveX Data Objects 2.8 Library" for the ADO. I've tried using v2.5, but get identical results. f.. The first parameter to ADO.Command.Execute appears to be an [out] parameter, but the documentation is confusing and I haven't seen the first parameter used anywhere. Any insight into this problem would be most appreciated. Regards, Jason R. Coombs Sandia National Laboratories -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Mon Jul 7 11:48:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 11:48:33 -0400 Subject: Reverse Engineering of Windows Distribution References: <3F098251.426DB151@engcorp.com> Message-ID: <3F099651.5D3C74D1@engcorp.com> Markus Stenzel wrote: > > Product : Experimental BitTorrent Client (c)Bram Cohen > Modified: Eike Frost http://ei.kefro.st/projects/btclient/ > License : MIT > Source : Available (3.1-CVS-4, 3.2-1, 3.2.1b-1, 3.2.1b-2) > > The Experimental BitTorrent is a GUI upgrade of the well known > BitTorrent file swarming application (c)Bram Cohen and released under > the MIT license. > > Eike Frost modified the software to allow "bandwidth capping" to be > selected from the GUI to allow ACK messages to pass the upstream during > normal operation thus increasing overall efficiency. > > However all versions mentioned above in the line starting with "Source" > _DO NOT_ run on Linux. 3.1-CVS-3, 3.2-1 and 3.2.1b-1 produce error > messages due to a few bugs handling the command line parameters. > > The 3.2.1b-2 client DOES work on Linux but is running slowly and works > for single files only. When working with "batch torrents" it routinely > hangs during operation (even if it's not touched after it's launch) > > The author Eike Frost doesn't offer the pre-3.1-CVS-3 source. > > The windows version we have installed on Win32 is a pre 3-1-CVS-4 > version. Now guess what.. ;)) > > > Technically it is possible, but it's not trivial, and seems like > > a pretty bizarre thing to do if the author didn't intend it to > > be used on Linux in the first place. (Which we can infer from the > > choice of distribution method.) > > I hope the additional background info might make you giving a few little > hints? *hopes* So basically the problem is that the versions for which source is available do not work, but you have a version which works, so you'd like to try getting it running under Linux. (?) If that's so, maybe you can isolate the problem to a single file? Extracting a single .pyc file from the .exe might be relatively easy, even if you had to basically do it manually. The packaging process used might be useful to know: was it py2exe, or the Macmillan Installer? Note, in case you weren't aware, that you won't actually get back the *source*, such that you could easily modify it and recompile. You'll get back the compiled (bytecode) file, which you could put into a .pyc file and run in place of the "bad" .py file which you have... at least in theory. Retrieving the source itself is even more involved. It requires decompiling (see "decompyle"), although if you go that route you should get back something very close to the original. Maybe even enough for you to do a "diff" and patch the latest version to work again? Sounds like a lot of work though. Wouldn't it be easier to work with the author to fix the problem in the supported versions, and use them? -Peter From alan.gauld at btinternet.com Thu Jul 10 17:21:54 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Jul 2003 21:21:54 GMT Subject: no python mode for my gvim References: <3097082.1057868612@dbforums.com> Message-ID: <3f0dd87c.269088789@news.blueyonder.co.uk> On Thu, 10 Jul 2003 20:23:32 +0000, pygeek wrote: > "E370: Could not load library python21.dll > I have Python 2.2.2 running and what concerns me is that, > I only have the file 'python22.dll' in C:\Windows\System32 and not > 'python21.dll' as > required by gvim. How do i go about loading the .dll file for gvim? I guess you need to install a copy of Python 2.1 somewhere. You can delete all the docs and samples if space is tight... [ Or you might try finding the call to load the DLL (loadlibrary()?)and change the name if its hard coded, but I dunno if that will work, its probably too simple! ] Alan g. Alan g. http://www.freenetpages.co.uk/hp/alan.gauld/ From nhodgson at bigpond.net.au Fri Jul 25 19:36:20 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 25 Jul 2003 23:36:20 GMT Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: Shane Hathaway: > Well, here's a pattern I've been trying out for this purpose: use assert > statements at the top of the function. > > def foo(bar, baz): > assert isinstance(bar, int) > assert isinstance(baz, str) The Wing IDE will read assertions of the above form and provide more assistance than with identifiers it knows nothing about: http://wingide.com/psupport/wingide-1.1/node5.html#SECTION005800000000000000 00 Neil From JWellington at wbta.org Tue Jul 22 09:36:48 2003 From: JWellington at wbta.org (Jim Wellington) Date: Tue, 22 Jul 2003 09:36:48 -0400 Subject: Quick question. Message-ID: <200307221337.h6MDb1N26314@elton.siteprotect.com> Can you help? I am trying to find a good list broker and also need some email appending done. I did a quick search and understand that you provide or might be able to refer me to a good provider. Can you take a second to add this information to our supplier database? I will then follow-up and contact that person. Below is the form. Thank you in advance. Regards, Jim Wellington WBTA "The national association of CEOs and Training Executives" JWellington at wbta.org www.wbta.org IMPORTANT: FIRST OPEN THIS MESSAGE IN A NEW WINDOW (OUTLOOK PREVIEW PANE NOT RECOMMENDED) Service: List Broker Email Appending Other First: Last: Company: Email: Web Site: Phone: -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyth at devel.trillke.net Tue Jul 15 03:07:53 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 15 Jul 2003 09:07:53 +0200 Subject: path module In-Reply-To: <182bcf76.0307141319.7b6fed7a@posting.google.com>; from paul.moore@atosorigin.com on Mon, Jul 14, 2003 at 02:19:37PM -0700 References: <1057651068.5348.386.camel@lothlorien> <182bcf76.0307141319.7b6fed7a@posting.google.com> Message-ID: <20030715090753.M6906@prim.han.de> Paul Moore wrote: > holger krekel wrote in message news:... > > I agree that something like Jason Orendorff's path module should go into > > the standard library. I've coded a similar module and i think that > > a discussion about certain design decisions would probably improve our > > approaches. > > Is it available anywhere? It would be nice to be able to try both, for comparison. sorry, not right now. I'll try to make a release soonish. holger From bokr at oz.net Tue Jul 22 01:09:18 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2003 05:09:18 GMT Subject: Flat file to associative array. References: Message-ID: On Mon, 21 Jul 2003 01:02:49 -0400, "Alex" wrote: >Hello, > >What would be the best way to convert a flat file of products into >a multi-dimensional array? The flat file looks like this: > >Beer|Molson|Dry|4.50 >Beer|Molson|Export|4.50 >Shot|Scotch|Macallan18|18.50 >Shot|Regular|Jameson|3.00 > >I've managed to read the file properly and get the individual lines >into a list, but I've got to turn this list into something that can >be stored in memory like a dictionary / associative array so I can >properly display the data. > The problem is 'way underspecified AFAICS. Imagine a magic black box that loads the data into itself, never mind how represented. What do you want to ask of the black box? (I was going to do an OO approach, but just tweaked your code a bit ;-) What does "properly display" mean? All the data at once? Selected? How selected? What do you want displays to look like? Why do you say multi-dimensional array? Is the input a tree/outline, the way it appears to be? >Here's the code I have so far: > Suggest upgrade to 2.2.2 or better ... >[Code] >#! /usr/bin/python > >import string \_won't need__ > >file = open("definitions", "r") infile = file('definitions') # file is new name for creating file objects, 'r' is default > ___________________ / >while 1: > line = file.readline() > if not line: > break > else: \____________________ # replace above by products = {} # root directory for line in infile: > data = string.split(line, '|') data = line.split('|') ... etc see below ___________________________________________ / > item = dict([('product', data[0])]) > print "You want a " + item['product'] + > ". What kind? " + data[1] + " for $" + > data[3] + " ... right?" > \___________________________________________ ??? >file.close() >[/Code] > ====< flat2tree.py >========================================= import StringIO infile = StringIO.StringIO("""\ Beer|Molson|Dry|4.50 Beer|Molson|Export|4.50 Shot|Scotch|Macallan18|18.50 Shot|Regular|Jameson|3.00 This line should be rejected. Beer|Virtual|c.l.py|Priceless ;-) """) # infile = file('definitions') # file is new name for creating file objects, 'r' is default def makeTree(infile): products = {} # root directory for line in infile: data = line.strip().split('|') if not data: continue if len(data)<2: print 'Rejecting data line: %r'%line continue currnode = products for kind in data[:-2]: currnode = currnode.setdefault(kind, {}) currnode[data[-2]] = data[-1] # assumes unique kind->price at end of lines return products # print sorted outline ? def pso(node, indent=0): if not isinstance(node, dict): print '%s%s'% (' '*indent, node) else: nodenames = node.keys() nodenames.sort() for name in nodenames: print '%s%s'% (' '*indent, name) pso(node[name], indent+1) if __name__ == '__main__': import sys print if sys.argv[1:]: infile = file(sys.argv[1]) products = makeTree(infile) infile.close() print '\nSorted product outline:' pso(products) print '\n---- the product dict -----\n', products ============================================================= Maybe this will give you a start. Running it makes this result: [22:09] C:\pywk\clp>flat2tree.py Rejecting data line: 'This line should be rejected.\n' Sorted product outline: Beer Molson Dry 4.50 Export 4.50 Virtual c.l.py Priceless ;-) Shot Regular Jameson 3.00 Scotch Macallan18 18.50 ---- the product dict ----- {'Beer': {'Virtual': {'c.l.py': 'Priceless ;-)'}, 'Molson': {'Dry': '4.50', 'Export': '4.50'}} 'Shot': {'Regular': {'Jameson': '3.00'}, 'Scotch': {'Macallan18': '18.50'}}} [22:09] C:\pywk\clp> Note that the prices aren't converted to actual numbers, they are still in string form. Regards, Bengt Richter From paoloinvernizzi at dmsware.com Tue Jul 15 04:45:45 2003 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Tue, 15 Jul 2003 10:45:45 +0200 Subject: path module In-Reply-To: <20030715090753.M6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <182bcf76.0307141319.7b6fed7a@posting.google.com> <20030715090753.M6906@prim.han.de> Message-ID: holger krekel wrote: > Paul Moore wrote: > >>holger krekel wrote in message news:... >> >>>I agree that something like Jason Orendorff's path module should go into >>>the standard library. I've coded a similar module and i think that >>>a discussion about certain design decisions would probably improve our >>>approaches. >> >>Is it available anywhere? It would be nice to be able to try both, for comparison. > > > sorry, not right now. I'll try to make a release soonish. > > holger > I cannot access the path.py module from http://www.jorendorff.com/articles/python/path/ Someone can be so kind to email it to me? Thanks in advance! --- Paolo Invernizzi paoloinvernizzi at dmsware.com From bignose-hates-spam at and-zip-does-too.com.au Thu Jul 10 21:06:05 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 11 Jul 2003 10:56:05 +0950 Subject: Securing 'pickle' References: Message-ID: On Fri, 11 Jul 2003 13:20:48 +1200, David McNab wrote: > I'm writing a web app framework which stores pickles in client > cookies. Sounds like a waste of bandwidth, in addition to the security concerns you raise. Why not store the pickles on the server, and set a session cookie to refer to them? That way, you only send a short session ID instead of the whole pickle, and messing with the cookie doesn't alter the pickles. (Mmm, all this talk of food...) -- \ "I don't know anything about music. In my line you don't have | `\ to." -- Elvis Aaron Presley (1935-1977) | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From jon+usenet at unequivocal.co.uk Tue Jul 8 12:47:35 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 8 Jul 2003 16:47:35 GMT Subject: Python vs PHP References: Message-ID: In article , Afanasiy wrote: >>Try jonpy (http://jonpy.sf.net/), it solves all of the above. >>Also you may find FastCGI (which jonpy supports) helps with your >>"safe mode" problem, although it might require a bit of hackery. > > No, CGI is not an option and I tried jonpy. I kept my notes about it... The only similarity between FastCGI and CGI is the name. FastCGI is just as fast, if not faster, than mod_python in my experience. jonpy lets you use CGI or FastCGI or mod_python interchangeably anyway. From gtalvola at nameconnector.com Tue Jul 15 17:28:40 2003 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Tue, 15 Jul 2003 17:28:40 -0400 Subject: Thread suddenly stops in NT Service Message-ID: <61957B071FF421419E567A28A45C7FE59AF551@mailbox.nameconnector.com> matthew.rapoport at accenture.com wrote: > I'm running an NT service with a thread. The thread performs a > calculation every so often and appends the number to a text file. > Every so often the thread just stops - or so it seems. The text file > stops getting numbers added to it but the service is still running and > no errors have been thrown. I'm quite sure that the code would catch > an error and post it to the event viewer if one were arising. > > The only other relevant points I can think of are that the thread runs > a while 1: loop and is set to run as a Daemon. The service waits only > for the stop command. It doesn't seem to be operating system specific > (happens on both XP and 2000). It doesn't seem to be file size > specific, it stops at various file sizes ranging from 5K - 50K. It > doesn't seem to be time specific - sometimes it'll stop after about a > day. Sometimes it'll stop after two days. > > Any help would be great. Thx. Make sure that you're not intentionally or unintentionally writing to sys.stdout or sys.stderr in your service -- those are not valid file objects. That will definitely cause a traceback, which could crash your thread, but not until you've written enough for it to try to flush its internal buffers, which could be the reason why your service is able to run for a while before it stops. In my service code I usually avoid the problem by adding something like: sys.stdout = sys.stderr = open('nul', 'w') in the __init__ of my service class, perhaps with an option to write to a logfile instead of just throwing away the output. Too bad the service framework doesn't do this automatically... - Geoff From spam at fisher.forestry.uga.edu Thu Jul 17 14:57:27 2003 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 17 Jul 2003 11:57:27 -0700 Subject: scrollback in macpython Message-ID: Is there any way of getting scrollback to work in MacPython 2.3b2? At present, when I try and scroll back to re-issue a past command using the up arrow key, I simply get a series of "^[[A" symbols. Very annoying, Any tips most appreciated. cjf From BPettersen at NAREX.com Fri Jul 25 18:03:56 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 25 Jul 2003 16:03:56 -0600 Subject: Static typing Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4739@admin56.narex.com> > From: Bruno Desthuilliers [mailto:bdesth.nospam at removeme.free.fr] > > Michael Muller wrote: > > Is there currently any plan to introduce static typing in any future > > version of Python? > > AARGGHHHH ! NO !! DON'T DO THAT !!! NEVER AGAIN !!!! > > (sorry, uncontrolable nervous reaction... 3 valiums latter... : ) > > > (I'm not entirely sure that "static typing" is the right > > term: what I'm talking about is the declaration of types > > for variables, parameters and function return values). > > This is the right term. This is also the wrong thing for Python IMHO. Almost. It's "explicit static typing" (vs. e.g. SML which has "implicit static typing"). > > I know there was a "types SIG" which introduced several > > proposals, but it expired quite a while ago, and I was > > wondering whether whether some consensus has been reached > > on the subject > > > Yes : > dynamic typing is good a Good Thing(tm), > static typing is Evil(tm) !-) > who: implicit/explicit/both when: compile-time/run-time/both/neither what: check-all/check-some/check-none choose one from each column'ly y'rs -- bjorn From ambiod at sbcglobal.net Mon Jul 21 16:15:57 2003 From: ambiod at sbcglobal.net (ryan) Date: Mon, 21 Jul 2003 13:15:57 -0700 Subject: encoding error Message-ID: <001501c34fc5$05997300$53fefea9@h5p1n4> 1) i have a function that i made in one of my program's modules named "input_box.py" that uses unicode: def get_key(): while 1: event = pygame.event.poll() if event.type == KEYDOWN: ev_unicode = event.unicode if type(ev_unicode) == types.UnicodeType: if ev_unicode == '': ev_unicode = 0 else: ev_unicode = ord(ev_unicode) value = unichr(ev_unicode).encode('latin1') return (event.key, value) else: pass ------------------ 2) i use py2exe to compile it with the option for encodings, like the docs say: python setup.py py2exe --packages encodings -------- 3) I still get the error: Traceback (most recent call last): File "", line 110, in ? File "", line 82, in main File "handle_keyboard.pyc", line 113, in handle_keyboard File "open_url.pyc", line 126, in open_url File "input_box.pyc", line 53, in ask File "input_box.pyc", line 21, in get_key LookupError: no codec search functions registered: can't find encoding ------ 4) Aren't I only supposed to get the above error "LookupError: no codec search functions registered: can't find encoding" if i did NOT compile with "--packages encodings"? ----- 5) Why am i still getting this error when i run the exe? I do not get it when i just run the source From aahz at pythoncraft.com Mon Jul 14 20:00:45 2003 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2003 20:00:45 -0400 Subject: Which Python Book References: <3F134200.8060708@hotmail.com> Message-ID: In article <3F134200.8060708 at hotmail.com>, hokiegal99 wrote: > >I have an option, I can buy either O'reilly's "Python in a Nutshell" or >"Python Cookbook", but not both. Which book is better? I'm leaning >toward "Python Cookbook" right now, as it seems more applied. A college >professor once told me that Romans liked to build roads while Greeks >liked to talk about *how* to build roads. I'm more of a Roman than a Greek. If you want lots of code, get the Cookbook. If you want a reference-in-a-book, get Nutshell. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From tjreedy at udel.edu Thu Jul 24 16:22:57 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2003 16:22:57 -0400 Subject: How to import hackicon.dll References: <8a5a6d82.0307240417.494caa13@posting.google.com> Message-ID: "Sonia Rovner" wrote in message news:8a5a6d82.0307240417.494caa13 at posting.google.com... > I'm using Python2.2.1 and Tcl/Tk 8.3 running on Win2000. I've been > researching how to change the icon on the title bar and found that > hackicon is the one I should pursue. However, hackicon package uses a > dll. When I run the hi.py, I get an error saying > ImportError: DLL load failed: The specified module could not be > found. > I copied hackicon.dll to various directories in my pythonpath but > nothing happens. Unless hackicon.dll was specifically compiled to by Python importable, the import should fail. You probably need to wrap it. I believe both the calldll and ctypes third-party modules will work. Either google web andor newgroup for more info or wait for more informed answer here. Terry J. Reedy From martin at v.loewis.de Mon Jul 21 18:36:23 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Jul 2003 00:36:23 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> <3F1C5A3F.962BC15E@hotmail.com> Message-ID: Alan Kennedy writes: > http://xhaus.com/?cinn?ide > > If I use the latter, then that's an illegal URI. However, it is a valid IRI. Regards, Martin From toc-01-nospam at blikroer.dk Mon Jul 7 16:38:35 2003 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Mon, 7 Jul 2003 22:38:35 +0200 Subject: win32service problems References: Message-ID: Justin Johnson wrote: > Windows 2000. Aftering searching google for similar problems I'm > beginning to think I hit the dreaded shared section memory problem on > win2k. Ugh... You can't see any differences between the working and not-working servers, like: - domain controller or not - list of members of the local administrators group - other services running Python - ... ------- Tomas From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 18:41:15 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 31 Jul 2003 00:41:15 +0200 Subject: special case loading modules with imp In-Reply-To: References: Message-ID: <3f28498b$0$49105$e4fe514c@news.xs4all.nl> Steven Taschuk wrote: > I was going to suggest StringIO, but it turns out imp.load_module > wants a real file, not merely something file-like. > > However, you can always do it by hand: > > >>> import imp > >>> sourcecode = 'def foo(x): return 11*x' > >>> mod = imp.new_module('foo') > >>> exec sourcecode in mod.__dict__ > >>> mod.foo(16) > 176 Heh, that's cool. That looks like what I'm doing in Pyro to load (and import) 'mobile code' that is sent from one computer to another. However I do it a bit different, partly because it's not always the *source* that gets loaded: if the .pyc bytecodes are available, those are loaded instead. Also, I stuff the modules into sys.modules because they have to be found by regular import statements after they're loaded. So I'm doing: --------- code snippet from Pyro ------------ name="not.yet.existing.module" module= import imp,marshal,new name=name.split('.') path='' mod=new.module("pyro-agent-context") for m in name: path+='.'+m # use already loaded modules instead of overwriting them real_path = path[1:] if sys.modules.has_key(real_path): mod = sys.modules[real_path] else: setattr(mod,m,new.module(path[1:])) mod=getattr(mod,m) sys.modules[path[1:]]=mod if module[0:4]!=imp.get_magic(): # compile source code code=compile(module,'','exec') else: # read bytecode from the client code=marshal.loads(module[8:]) # finally, execute the module code in the right module. exec code in mod.__dict__ --------- end code snippet from Pyro ------------ It works, but I'm not too fond of the bytecode 'tricks'... --Irmen From kahanpaa at gstar.astro.helsinki.fi Thu Jul 3 02:33:38 2003 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 3 Jul 2003 06:33:38 GMT Subject: function overloading References: Message-ID: Hi. Mirko Koenig wrote: > I serached around the web and some tutorials but i can't finds any > documentation about function overloading in python. > I want to have 3 functions: > def setPos( x, y ): > def setPos( pos ): > def setPos( object ): > ( pos and object are classes i wrote ) The normal Pythonic way is probably as follows: def setPos(position): """ Set Position. The 'position' argument should be one of * a tuple of coordinates (x,y) * a instance of class Pos * a instance of class Object """ if type(positions) is types.TupleType or type(positions) is types.ListType: x,y = positions ... else if: ... identify object type and process Jere -- It's hard to think outside the box when you ARE the box. - unknown, alt.religion.kibology From not at home.org Fri Jul 4 03:15:11 2003 From: not at home.org (Dfenestr8) Date: Fri, 04 Jul 2003 16:15:11 +0900 Subject: Some guidance please: A Python multitrack recorder? Message-ID: Hi. I'm no coder. I'm just a working guy who likes to tinker with computers in my spare time. That's my hobby. My passion is: playing instruments. Combining the two, I've made a couple of event driven, GUI controlled progs in Python and tKinter before. I made an abc/midi player, using the timidity, and abc2midi packages. I also did a metronome, using the Snack sound toolkit. My next project is to make my own sound recorder, using Tkinter and the Snack Sound toolkit. I have an idea, that using multiple threads for each recording track, I could eventually develop it into a multitrack recorder. I could use linux SOX to add effects to each track. Does this sound like a stupidly complicated idea for a newby? Also, is the Python interpreter fast enough for this sort of work? Especially on a pII 450Mhz with only 256 meg? Would I be better off just sticking with a single track recorder, until the day I get around to seriously studying a compiler language like C++? Here's the skeleton of the code I'm writing...... #! /usr/bin/python from Tkinter import * from os import popen, popen2 import threading import tkSnack root = Tk() tkSnack.initializeSnack(root) class RecThread(threading.Thread): #this thread accesses the Snack toolkit #and actually does the recording def __init__ (self, master = None): threading.Thread.__init__(self, master) class TrackFrame(Frame): #this frame will contain the controls for running RecThead #including Rec, Play, and Mute Radiobutton contols. def __init__ (self, master = None): Frame.__init__(self, master) class ControlFrame(Frame): #this contains all the arrow keys for controlling TrackFrame #it will have Start, Stop, and Pause buttons def __init__ (self, master = None): Frame.__init__(self, master) class Application(Frame): #this is the layout for all of the above def __init__ (self, master = None): Frame.__init__(self, master) if __name__ == '__main__': root.App = Application() root.App.master.title("Un Recorder") root.App.mainloop() From usenet03q2 at hczim.de Sun Jul 20 08:39:56 2003 From: usenet03q2 at hczim.de (Heike C. Zimmerer) Date: Sun, 20 Jul 2003 14:39:56 +0200 Subject: Tk mainloop() References: Message-ID: "Petr Evstratov" writes: > Hi, I have a question: how do you execute an arbitrary function in Tk fooBar.mainloop()? > > I need to change the contents of a label every second, but I think I will also use some other functions as well... Use the after() method, like in: def periodic() ... do something useful ... widget.after(1000, periodic) ... periodic() ... widget.mainloop() Greetings, Heike From kamikaze at kuoi.asui.uidaho.edu Sun Jul 20 02:26:42 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 20 Jul 2003 06:26:42 GMT Subject: Tkinter PhotoImage or PIL transparent subimages Message-ID: In the new Python game I'm developing, I need to crop out individual tiles from larger tilesets, and maintain transparency. Unfortunately, I've run into major deficiencies in both Tkinter and PIL (PyGame, wxPython, PyQt, etc. are not really suitable for this program, for a number of reasons, and I have zero interest in discussing why right now). Since the Tkinter.PhotoImage.copy() method doesn't allow a region parameter, I have to save the tile to a disk file (write does have a region parameter) and read it back in; this does work correctly, but it's not very fast. Tk's copy() method *does* support a region parameter, but Tkinter inexplicably does not pass it through. It'd probably take someone who can program in C and knows the Tkinter library 30 minutes to fix this, check it in for Python 2.3, and add it to the documentation. HINT HINT. If you want a PEP first, I'll write one, but this just looks like a bugfix to me. PIL has a fast crop() method, but it then throws away the transparency information, making it useless to me. I'm not that familiar with PIL, but the obvious way to use it does not work, the documentation is uninformative on the problem, and according to google, people who've previously asked similar questions have received no answers. I need answers. I'd rather have a fixed Tkinter than PIL, since getting users to install more libraries sucks and I have no need for PIL's other features, but I'll take what I can get. Right now, I have the following code, and my images are all transparent GIFs. Thanks in advance. ---cut here--- def getTileImagePIL(tile): key = getTile(tile) filename, tx, ty = key tx *= TILESIZE ty *= TILESIZE img = IMAGES.get(key) if not img: # get master image bitmap = IMAGES.get(filename) if not bitmap: if DEBUG: Log.log('Loading %s' % filename) bitmap = Image.open(filename) pagename, width, height = getPagedata(filename) bitmapsize = bitmap.size if (width*TILESIZE != bitmapsize[0] or height*TILESIZE != bitmapsize[1]): raise AssertionError, 'Image size mismatch: %s' % filename IMAGES[filename] = bitmap # get one tile from image subimage = bitmap.crop( (tx, ty, tx+TILESIZE, ty+TILESIZE) ) img = ImageTk.PhotoImage(subimage) IMAGES[key] = img return img def getTileImageTkinter(tile): key = getTile(tile) filename, tx, ty = key tx *= TILESIZE ty *= TILESIZE img = IMAGES.get(key) if not img: # get master image bitmap = IMAGES.get(filename) if not bitmap: if DEBUG: Log.log('Loading %s' % filename) bitmap = Tkinter.PhotoImage(file=filename) pagename, width, height = getPagedata(filename) if (width*TILESIZE != bitmap.width() or height*TILESIZE != bitmap.height()): raise AssertionError, 'Image size mismatch: %s' % filename IMAGES[filename] = bitmap # get one tile from image try: bitmap.write('tmp.gif', format='GIF', from_coords=(tx, ty, tx+TILESIZE, ty+TILESIZE) ) except Tkinter.TclError: Log.log('TclError, coords %d,%d-%d,%d in %d,%d' % (tx, ty, tx+TILESIZE, ty+TILESIZE, bitmap.width(), bitmap.height()) ) raise img = Tkinter.PhotoImage(file='tmp.gif') IMAGES[key] = img return img try: import Image, ImageTk PIL = True getTileImage = getTileImagePIL except ImportError: import Tkinter, tkMessageBox PIL = False getTileImage = getTileImageTkinter ---cut here--- -- Mark Hughes "The computer is incredibly fast, accurate, and stupid. Man is unbelievably slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation." -Leo Cherne From donald_rivard at hotmail.com Fri Jul 25 10:07:11 2003 From: donald_rivard at hotmail.com (Don Rivard) Date: Fri, 25 Jul 2003 10:07:11 -0400 Subject: zope ZMySQLDA References: Message-ID: I know get: Error Type: AttributeError Error Value: server_capabilities Traceback (innermost last): a.. Module ZPublisher.Publish, line 49, in publish b.. Module ZPublisher.mapply, line 32, in mapply c.. Module ZPublisher.Publish, line 38, in call_object d.. Module Products.ZMySQLDA.DA, line 102, in manage_addZMySQLConnection e.. Module Shared.DC.ZRDB.Connection, line 58, in __init__ f.. Module Shared.DC.ZRDB.Connection, line 86, in edit g.. Module Products.ZMySQLDA.DA, line 120, in connect h.. Module Products.ZMySQLDA.db, line 179, in __init__ AttributeError: server_capabilities I'm not sure what server_capabilities really means. I will write my own DA for this. Thanks "Thomas G?ttler" wrote in message news:bfobe2$h17es$1 at ID-63505.news.uni-berlin.de... > Don Rivard wrote: > > > zope 2.71b > > ZMySQLDA 2.08 > > MySQL-python-0.9.2 > > mysql 3.23.55NT > > > > When I attempt to connect, by creating a Add Z MySQL Database Connection, > > I set the connection string > > to database user password, and i keep getting the following error > > Site Error > > An error was encountered while publishing this resource. > > > > Error Type: AttributeError > > Error Value: server_capabilities > > Hi, > > If you want to see the stacktrace in error messages put > > in the standard_error_message of Zope. This needs to be done > trough the web and is very handy for debugging. > > The stacktrace shows you the file and the line where > the error occured. Maybe this helps you to find your problem. > > thomas > > From jmfbahciv at aol.com Tue Jul 8 08:43:14 2003 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Tue, 08 Jul 03 12:43:14 GMT Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: In article , shoppa at trailing-edge.com (Tim Shoppa) wrote: >Remember the Dilbert where PHB complains that his programmers are using >way too many semicolons? :-) All RIGHT! That's a good PHB. It was so difficult to distinguish between a semicolon and a colon on the listings. /BAH Subtract a hundred and four for e-mail. From simon_place at whsmithnet.co.uk Sat Jul 5 16:28:43 2003 From: simon_place at whsmithnet.co.uk (simon place) Date: Sat, 05 Jul 2003 21:28:43 +0100 Subject: PEP idea. ( removing __slots__ ) Message-ID: <3f073594$1_2@news1.vip.uk.com> Removing __slots__ ~~~~~~~~~~~~~~~~~~~ To do this nicely requires the renaming of __dict__ to, say, __attribs__ , ( since dict is unnecessarily unspecific, this seem like a small improvement in itself. ) then using the setting of __attribs__ to a non-mutable type (ie tuple of attribute names) to indicate the behaviour of __slots__, rendering it unnecessary, this I think is a good simplification. From stark7 at sbcglobal.net Thu Jul 24 16:56:26 2003 From: stark7 at sbcglobal.net (David Stark) Date: Thu, 24 Jul 2003 20:56:26 GMT Subject: Tkinter and Mac OS X Message-ID: I have Mac OS 10.2 which ships with python. I downloaded TclTkAqua from ActiveState and installed it. Then I get: >>> import Tkinter Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> After digging around on www.python.org I get the impression that I have to download the source and do my own build. Do I really have to go through this? Is the OS X distribution of python different (for a reason)? From tjreedy at udel.edu Fri Jul 25 13:03:13 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2003 13:03:13 -0400 Subject: How safe is modifying locals()? References: Message-ID: "Paul Paterson" wrote in message news:BDcUa.100193$XV.6037947 at twister.austin.rr.com... > I am trying to find a way to mimic by-reference argument passing for > immutables in Python. I need to do this because I am writing an > automated VB to Python converter. > > Here's an example of the VB code: > > Sub Change(ByVal x, ByRef y) > x = x+1 > y = y+1 > End Sub > > x = 0: y = 0 > Change x, y > ' Now x should be 0 and y should be 1 > > One approach that has been suggested is to use locals() and indirect > references to the immutable via the resulting dictionary, > > def change(x, y, refs): > x = x + 1 > refs[y] = refs[y] + 1 > > x = 0; y = 0; > change(x, 'y', locals()) > > The Python documentation gives a warning that modifying the contents of > locals() may not affect local values. Despite the warning, the code > seems to work as desired, at least on Python 2.2. At module scope, locals() == globals(). Within a function, locals() currently is a *copy* of the function's local namespace. So above only works because you made the call from the global (module) context and would not if you tested by making call from within a function. Terry J. Reedy From staschuk at telusplanet.net Thu Jul 31 21:15:38 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 19:15:38 -0600 Subject: Exceptions as New Style Classes In-Reply-To: ; from imbosol@aerojockey.com on Thu, Jul 31, 2003 at 07:54:59AM +0000 References: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Message-ID: <20030731191538.E22513@tibia.amotlpaa.bogus> Quoth Carl Banks: > Steven Taschuk wrote: > > Quoth Carl Banks: [...] > >> Why not give exceptions their own metaclass? So if type(x) is > >> ExceptionMetaclass, it's a class. If type(type(x)) is > >> ExceptionMetaclass, it's an instance. Otherwise, it's illegal to > >> raise it. [...] > > I'm not sure what it gains us, though, over the idea of mandatory > > inheritance from Exception. Am I missing something? > > Probably not much, unless you think you want to raise exceptions that > aren't subclasses of Exception. I would have thought that having to raise instances of classes which are instances of ExceptionMetaclass would be just as onerous as having to raise instances of Exception. class MyRaisable(Exception): # ... class MyRaisable(object): __metaclass__ = ExceptionMetaclass # ... I suppose Exception could have behaviour you don't want, in which case the latter might be preferable. -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From steve at ferg.org Fri Jul 4 11:28:07 2003 From: steve at ferg.org (Stephen Ferg) Date: 4 Jul 2003 08:28:07 -0700 Subject: ANN: Python language slideshow presentation Message-ID: An HTML slideshow on the Python language is now available on the Python Slideshow Presentations page: http://ferg.org/python_presentations/index.html These slides are good for talks on features of the Python language for programmers (as opposed to a management-oriented presentation). In 2000 and 2001, David Beazley gave three presentations on Python, based on his book "Python Essential Reference". Later, he generously released the slides from these presentations under the GNU Public License (GPL). I have combined these slides into a single presentation on the Python language. Note that the slides are not in PowerPoint, but in HTML. All you need to give the presention (other than the files themselves) is a Web browser. I've made very few changes to David's original material. I have removed references to David in his role as presenter, since you (not David) will be giving the presentation. I've updated a few things, such as changing references from Jpython to Jython and bringing the list of Python versions up to 2.3. The main difference is that the slides look different. I've made the navigation links easier to use, and added color through the use of a CSS stylesheet. Information about the slideshow, and a link to download a zip file, are on the Python Slideshow Presentations page: http://ferg.org/python_presentations/index.html You can look at the presentation online at http://ferg.org/python_slides/index.html -- Steve Ferg From taka at net.hr Wed Jul 9 08:19:21 2003 From: taka at net.hr (Taka) Date: Wed, 09 Jul 2003 14:19:21 +0200 Subject: format discs. References: Message-ID: On Wed, 09 Jul 2003 06:26:38 +0000, Flanagan wrote: > hello to all > > somebody can say to me whereupon I modulate of python I can format > discs. > > > thanks flanagan Let's presume you want to format a unix partition and that it is /dev/hda1. The do this: #!/bin/python import os partition = open ('/dev/hda1', 'w') for x in range(os.path.getsize('/dev/hda1'): partition.write ('0') partition.close() :) From adechert at earthlink.net Sun Jul 27 14:09:48 2003 From: adechert at earthlink.net (Alan Dechert) Date: Sun, 27 Jul 2003 18:09:48 GMT Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: "Andrew Dalke" wrote in message news:bfo1k3$n2s$1 at slb6.atl.mindspring.net... > BTW, I don't think you need to distribute a calculator for this. I think > you just need some tables which give values for a few select points, > as in: > I still want a calculator. Here's what Bill Buck ( billbuck at cox.net ) sent me. It turns out there is a BINOMDIST function in Excel. I think it might be what I want. http://home.earthlink.net/~adechert/LOTAcceptanceCalculator.xls Let me try to clarify what I'm after. The paper record should always match the electronic record. So the allowable defects is zero. If there is a mismatch found in the sample, we don't publish the electronic tally: we take all the paper ballots and check them. We are talking about an election conducted with computer-generated paper ballots. The paper ballots represent the actual vote since these ballots are what voters actually saw, verified, and cast. We will have an electronic record obtained from the computers which should match each paper ballot generated. We want to use the electronic record since it will give us an instant result -- but we have to check it against the paper ballots to be sure the election result is correct. So, in this scenario, the electronic count is a prediction (or preliminary tally). So, if by the preliminary electronic tally a candidate won a race by 1 percent, I want to know how many ballots we have to check (random sample) to be certain that the result predicted is true. When I put one million into this Confidence Level Calculator, and Acceptable Quality Level of .01, a sample of 10,000 shows a confidence level of "1." A sample of 2000 give C.L of 0.999999998 Presumably, "1" is really .9999999999+ more 9s. Can we get more decimal places? So I guess the Lot Fraction Defective is analgous to the predicted victory margin. Is that right? I would still like a standalone calculator that doesn't require Excel. Alan Dechert From hokiegal99 at hotmail.com Sat Jul 12 12:14:11 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 12 Jul 2003 09:14:11 -0700 Subject: call one python script from within another References: <3f0f40b9$0$49103$e4fe514c@news.xs4all.nl> Message-ID: <93f5c5e9.0307120814.4a84ca9a@posting.google.com> Irmen de Jong wrote in message news:<3f0f40b9$0$49103$e4fe514c at news.xs4all.nl>... > Tubby Tudor wrote: > > What is the best way to call one python script from within another > > python script? For example: > > > > one.py finishes succesfully and calls two.py which finishes OK and then > > calls three.py > > > > Thanks guys! > > > > one.py: > --------------- > > import two > import three > > > def main(): > .... body of your code here .... > > > main() # run code in one > two.main() # run code in two > three.main() # run code in three > ------------------ > > Will this do? Yes, this works. Thanks for the tip! From tjreedy at udel.edu Thu Jul 17 12:35:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 12:35:48 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> Message-ID: "Stephen Horne" wrote in message news:hub7hvgjjm0prt5p3jn92npmb3gf777mr9 at 4ax.com... > A goal of Python is to be a 'very high level language'. Another is to > 'do the right thing'. At this point, we need to differentiate between Guido's goal for Python, your goal for Python, and anybody else's. The above may by your goals but not necessarily others' (primary) goals. > In my view, the current implementation of Python with respect to > variable binding is against those goals. That may be, for all I know. > Python isn't really a member of that list. ... > It isn't an experimental language. It doesn't obsess on one particular > concept. It is a language for getting things done with very little > fuss. This is, I believe, expresses Guido's goal for Python much better than your two goals above. So, by your own statement, he has met *his* goal pretty well. Terry J. Reedy From bokr at oz.net Sat Jul 19 12:58:57 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 16:58:57 GMT Subject: __getitem__ and arguments References: <10eb079f.0307190110.30deb5b9@posting.google.com> Message-ID: On 20 Jul 2003 04:00:05 +0950, Ben Finney wrote: [...] > >> For __getitem__() the arguments become a tuple. > >Yes, because you've specified a key, which by definition is a single >argument. > But note that it can be more than a simple tuple (or less, if it's an int): >>> class X(object): ... def __getitem__(self, i): print i ... >>> x=X() >>> x[1] 1 >>> x[1:] slice(1, None, None) >>> x[:1] slice(None, 1, None) >>> x[:] slice(None, None, None) >>> x[1, :, 1:, :1, 1:2, 1:2:3, (4,5), 6] (1, slice(None, None, None), slice(1, None, None), slice(None, 1, None), slice(1, 2, None), slice(1, 2, 3), (4, 5), 6) Notice that (4,5) in there also as one of the indices. Regards, Bengt Richter From python-url at phaseit.net Mon Jul 21 05:58:19 2003 From: python-url at phaseit.net (Irmen de Jong) Date: Mon, 21 Jul 2003 09:58:19 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) Message-ID: QOTW: "To 'Tron' fans: yes, you could assign the name TimBit to it [the TimBot] but it's a broken Bit; what's the use of a Bit that's always true?" -- Christos Georgiou "Whether or not I agree with you, you have made me think. That's worth the price of my Internet connection this month." -- Tim Roberts Discussion ---------- Aahz writes a rebuttal to Artima.com, because a recent interview with Bruce Eckel on that site might give the wrong impression regarding Python's type system. The interview with Bruce Eckel is at: Raymond Hettinger intrigues with the second episode of a series of mysterious Python puzzles. Tom Plunket starts a huge thread about the way Python treats objects, names, variables, assignment, references and what not. Various people have different opinions about what would be the best way to do things, but in the end, the QOTW of Tim Roberts (above) kind of says it all. Michele Simionato likes to have an endswith method that accepts a list of strings, instead of a single string argument. But things are not that easy. Alan Kennedy shows what you might do if you need to build a list of database rows (from a query), without allocating the list beforehand because you don't know the size. He uses an iterator to do the trick. Andrew Kuchling has started a mailing list for discussion about Python Web frameworks. This is partly because perhaps Python needs a single 'standard' way to create web applications, as Andy Robinson points out. Announcements ------------- Python 2.3 release candidate 1. This will become Python 2.3 final if no major new bugs are found this week. Gnosis Utils 1.1.0, several Python modules for XML processing, plus other generally useful tools such as pickling and indexing. ZODB3 3.3a1, a set of tools for using the Zope Object Database (ZODB) in Python programs separately from Zope. SC-Track Roundup 0.5.9, an issue-tracking system with command-line, web and e-mail interfaces. PyUNO (in OpenOffice.org1.1rc), a generic bridge between python and OpenOffice.org's component model UNO (Universal Network Objects). dnspython 1.1.0b1, a DNS toolkit for Python. hYPerSonic is a python/c framework for building and manipulating real-time sound processing pipelines. Albatross 1.10, is a small toolkit for developing highly stateful web applications (including a HTML template language). ClientForm 0.0.11 and 0.1.5a, a Python module for handling HTML forms on the client. C=F2nflux Lite 1.0, a web-based groupware and file management application. Quixote 0.6.1, yet another framework for developing Web applications in Python (but focused on the Python developer). SCGI 1.1, a package that implements the SCGI protocol (similar to FastCGI, but easier to implement). ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From candiazoo at mac.com Wed Jul 16 00:41:17 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Wed, 16 Jul 2003 04:41:17 GMT Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> <120720032321075007%candiazoo@mac.com> <3344b1fa.0307140325.67be7b8c@posting.google.com> Message-ID: <160720030041014531%candiazoo@mac.com> I shall check it out! Thanks. Mike J. In article <3344b1fa.0307140325.67be7b8c at posting.google.com>, Peter Wilkinson wrote: > "Michael S. Jessop" wrote in message > news:<120720032321075007%candiazoo at mac.com>... > > [[ This message was both posted and mailed: see > > the "To," "Cc," and "Newsgroups" headers for details. ]] > > > > I tried supplying host as well, same error. :/ Something is hosed. > > I guess I could try reinstalling. I really want to get this to work. > > I am trying to write a maintenance program for my wife, so she can > > remotely modify the database containing information about her artwork, > > distribution lists, etc. > > > > I've just sorted out the problem on my machine and it appeared to be a > set of include files from a previous install of MySQL that were > sitting in /usr/include, once I removed that and rebuilt with setup.py > pointing to the Fink include paths it works fine. > > Peter. From bignose-hates-spam at and-benfinney-does-too.id.au Sat Jul 26 19:00:58 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jul 2003 08:50:58 +0950 Subject: Beginners help with password program! References: Message-ID: On Sat, 26 Jul 2003 18:08:39 -0400 (EDT), tjland at iserv.net wrote: > Their are some errors that i > just cant find, Please show the errors you get, so we know what you're talking about. > and i want some advice on how to do some of these things easier. Here's advice on finding errors: When you encounter an error you don't understand, *don't* try to deal with the whole program. Take a copy, or make a new program (whichever seems simpler at the time) and get to the smallest possible program you can make that still exhibits the error. This will result in several things: you may end up solving the error; otherwise: you may understand the error much better you will know exactly which lines of code are related to the error you will have something suitable to post to this newsgroup. Please don't just post the whole program and say "find my error". That's *your* task. -- \ "I watched the Indy 500, and I was thinking that if they left | `\ earlier they wouldn't have to go so fast." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From robin at jessikat.fsnet.co.uk Tue Jul 8 17:38:33 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 8 Jul 2003 22:38:33 +0100 Subject: anything new on the ternary operator? References: <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com> <40a939c9.0307080622.3118cfd7@posting.google.com> <2UVsCJApkwC$EwTg@jessikat.demon.co.uk> Message-ID: <1XpcCKAZnzC$EwCd@jessikat.fsnet.co.uk> In article , Fredrik Lundh writes ..... >if we'd known that you folks would end up this bitter, we would >have given you one point ;-) > > .... even though I helped in recording the awful 'Puppet On A String' back in the dark ages, not getting any points is a high point in Britain's Eurovision career. With any luck we can consign this awfulness to the dustbin of history. Perhaps we can make Guantanamo part of Europe and send it there for a quickie death sentence. -- Robin Becker From candiazoo at mac.com Wed Jul 16 01:09:28 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Wed, 16 Jul 2003 05:09:28 GMT Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> <120720032321075007%candiazoo@mac.com> <3344b1fa.0307140315.321bb6b2@posting.google.com> Message-ID: <160720030109126017%candiazoo@mac.com> YES! It works. I could kiss you, Peter! Thanks! Mike J. In article <3344b1fa.0307140315.321bb6b2 at posting.google.com>, Peter Wilkinson wrote: > "Michael S. Jessop" wrote in message > news:<120720032321075007%candiazoo at mac.com>... > > [[ This message was both posted and mailed: see > > the "To," "Cc," and "Newsgroups" headers for details. ]] > > > > I tried supplying host as well, same error. :/ Something is hosed. > > I guess I could try reinstalling. I really want to get this to work. > > I am trying to write a maintenance program for my wife, so she can > > remotely modify the database containing information about her artwork, > > distribution lists, etc. > > > > I see exactly the same problem. My install is with MySQL and Python > both via Fink. Trying both 2.2 and 2.3 Python I get the same problem. > > Trying to dig into it a little it looks as though the setup code isn't > populating some of the fields and methods and the error thrown shows > up because self.converter is set to None. > > I'm going to try and figure this out but would be interested in any > insight others might have. > > Peter. From peter at engcorp.com Wed Jul 23 10:06:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Jul 2003 10:06:06 -0400 Subject: python assignment References: <3f1e92bc$0$161$a1866201@newsreader.visi.com> Message-ID: <3F1E964E.BFD7513F@engcorp.com> Grant Edwards wrote: > > In article , Ben Finney wrote: > > >> What I need is an exact and unambiguous algorithm for determining when > >> an assignment will change the id of the variable > > > > As I understand it, this is specific to the implementation of each type. > > The only sensible way to code is as if the identity of an object, on > > assignment, were completely unpredictable. > > > > The examples you gave showed that integers share identity with other > > integers of the same value, while floats do not. > > I believe that's only true for small integers, isn't it? Google finds "LOADI - a fast load instruction for small positive integers (those referenced by the small_ints array in intobject.c)" and checking that file is left as an exercise to the reader. I'm going to blindly assume this is directly related to the issue in question... ;-) -Peter From theller at python.net Tue Jul 29 03:03:25 2003 From: theller at python.net (Thomas Heller) Date: Tue, 29 Jul 2003 09:03:25 +0200 Subject: Any Software can Python <-> Delphi ? References: <_icVa.1123902$ZC.164425@news.easynews.com> <3F2588C1.8FE0C79B@easystreet.com> Message-ID: achrist at easystreet.com writes: > Joe Francia wrote: >> >> PythonMan wrote: >> > Any Software can change Python source code to Delphi ? >> > thx >> > >> >> You might find an easier time of it to embed your Python in Delphi, or, >> even better, write a Python extension with Delphi: >> >> http://www.atug.com/andypatterns/pythonDelphiTalk.htm >> http://membres.lycos.fr/marat/delphi/python.htm >> > > Anyone have any ideas about how to package one of these pythondelphi > apps to be easy to deploy and be convenient to the end user? I'm > guessing that since python isn't on top, McMillan's installer and > py2exe won't handle it. You could write a small, fake module importing the stuff that the library needs. If you then run py2exe with the -k (--keep-temp) option, it doesn't delete its own build tree. You will find there a xxx.zip file, containing all the modules needed (plus a few scripts which you can ignore). If you use Python 2.3, just add the zip-file's name to sys.path, and you are done. Thomas From ben at dadsetan.com Tue Jul 15 15:56:50 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Tue, 15 Jul 2003 20:56:50 +0100 Subject: Waiting for processes to finish under Solaris References: <3F144AB2.10703@dadsetan.com> Message-ID: <3F145C82.6010606@dadsetan.com> Wow.. that is a pretty nice shortcut indeed.. at least for the second step of waiting for the process to end by itself! It is also a very underdocumented feature.. :)) signal.SIG_DFL (0) is documented as """SIG_DFL This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCLD is to simply ignore it. """ Hopefully it will NOT SIGQUIT it... I can only test it tomorrow but if it works it will certainly give it a performance boost. If it does not maybe some other signal is completed ignored... Pity I will have to probably run the watch script as the same user than the process. I guess I will not be able to kill it otherwise. Could you maybe find anything where you would say, could be done a little more pythonic? :) Thanks. Ben. Donn Cave wrote: > Since you apparently already know the PIDs you're looking for, > it would be easier and more reliable to just kill them with 0 - > > Though of course that doesn't retrieve any of the other information > you get from "ps". > > Donn Cave, donn at u.washington.edu From ianb at colorstudy.com Sun Jul 20 06:01:44 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 05:01:44 -0500 Subject: object as a reserved keyword In-Reply-To: References: Message-ID: <1058695303.28092.1367.camel@lothlorien> On Sun, 2003-07-20 at 04:29, Lawrence Oluyede wrote: > Does it worth to make "object" keyword a reserved one? > I'd like to avoid oddities like this: > > Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class c(object): pass > ... > >>> object = 4 > >>> class c(object): pass > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: int() takes at most 2 arguments (3 given) > >>> That's not odd or even bad... so you get an exception. That can happen all the time when you do silly things. Now... class object: pass *That* would be bad, cause later on you'll do... class Whatever(object): ... x = property(get_x, set_x) I can totally imagine going nuts trying to figure out what went wrong with that... Ian From lol at lolmc.com Thu Jul 17 16:57:13 2003 From: lol at lolmc.com (Rogue9) Date: Thu, 17 Jul 2003 21:57:13 +0100 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> Message-ID: <3f170dfd@shknews01> As I put in my reply to your personal email - I asked in the python ng for help with a python program I was writing NOT an opinion on what I was writing. Not replying to the post would have been better than you pushing your opinions on others when not asked. When I posted I didn?t say ?Hey guys,help me and the program I write will guarantee you?ll win the lottery.? I merely asked for help with a programming problem for a personal project - whether it is a fools errand is my business and not for anyone else to gainsay. On Thu, 17 Jul 2003 10:51:41 +0000, Bob Gailer wrote: > At 04:05 PM 7/17/2003 +0100, Rogue9 wrote: > >>After reviewing my question I realised that I should have posted the >>short piece of real code I'm working on and not tried to write some >>pseudo-code to illustrate the problem I'm having.Therefore I have >>printed the listing below which is quite short and hopefully won't annoy >>too many peopleabout the length of my post. >> >>To reiterate: >>The masterList holds the results for the UK lottery > [snip] > I sure hope you are not writing "yet another winning lottery number > predictor". It is a sad commentary on mathematics education when > individuals belive that one can predict the outcome of a truly random > process based on any history. I for one certainly won't support any > effort to further mislead people. > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 > > --- > Outgoing mail is certified Virus Free. Checked by AVG anti-virus system > (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - > Release Date: 7/10/2003 From pedro.werneck at bol.com.br Wed Jul 9 19:37:46 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 9 Jul 2003 16:37:46 -0700 Subject: Application Development in Python References: <3089454.1057738936@dbforums.com> Message-ID: I suggest you to look at Kiwi, in http://www.async.com.br/kiwi... it's a framework for quick application development, based on PyGTK and Glade... the stable version currently only supports GTK 1.2, but I think it's worth a look... indru <____indru_june at yahoo.com____> wrote in message news:<3089454.1057738936 at dbforums.com>... > Hi all, > I am new to Python programming. I am from C,C++,Perl background. I am > quite convinced by the possibilities python as a very high level > language is offering. I am seriously thinking of using python in my > project which is to create a accounting software. First thing came to my > mind was C++ but the time required could be enormous and my people are > not ready to wait that long. The project is a medium sized one but > bigger than something like gnucash and KMyMoney2. Do any body have > experience with application development using python and their > experiences ?. Also please advice me whether Python can be used for > such purposes. > Thanks in advance > Indru From pablo at bogus.domain.org Sun Jul 20 08:30:11 2003 From: pablo at bogus.domain.org (Pablo) Date: Sun, 20 Jul 2003 14:30:11 +0200 Subject: classes References: Message-ID: [cut] >> 2) how to declare a static method > > class HasStaticMethod: > def method(arg0, arg1): # note the lack of "self" > # do something with arg0 and arg1 > method = staticmethod(method) That's not exactly what I wanted. I would prefer something like this: class StaticMethod: __instance = None def __init__(self): if StaticMethod.__instance is None: StaticMethod.__instance = self else: raise Exception("Constructor may be invoked only once") def getInstance(): if StaticMethod.__instance is None: StaticMethod.__instance = StaticMethod() return StaticMethod.__instance m = StaticMethod.getInstance() but Python does not allow to invoke any class method without providing an instance of the class object I've been thinking about Python classes and modules and found out that it is possible in Python to create an object in some module and use a reference to it from other modules. In Java it's not possible to create any object outside of any class. So my problem would be solved if I could create a class which would be seen only in its module (something like private class). Then I could create an object and simply use it across my application. It would behave like a static object since it wouldn't be possible to create another object in other modules (since the class would be visible only it its module), and it also wouldn't be possible to create another object in its module (there is no reason for it). Is it possible to create a class and forbid its use outside its module? Thanks for a usefull reply. Pablo From phil at riverbankcomputing.co.uk Sat Jul 5 14:01:35 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 5 Jul 2003 19:01:35 +0100 Subject: ANN: PyQt v3.7 Released Message-ID: <200307051901.35797.phil@riverbankcomputing.co.uk> PyQt v3.7 has been released and can be downloaded from http://www.riverbankcomputing.co.uk/pyqt/ PyQt is a comprehensive set of Python bindings for Trolltech's Qt GUI toolkit. It includes approximately 300 classes and 5,750 methods including OpenGL, SQL and XML support as well as a rich set of GUI widgets. It also includes a utility to generate Python code from Qt Designer, Qt's GUI builder. PyQt runs on UNIX/Linux, Windows and the Sharp Zaurus. PyQt is licensed under the GPL, commercial, educational and non-commercial licenses. Phil From cedmunds at spamless.rochester.rr.com Mon Jul 14 22:17:32 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Tue, 15 Jul 2003 02:17:32 GMT Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <0vJQa.6944$G%5.4151@twister.nyroc.rr.com> "Allison Bailey" wrote in message news:mailman.1058229111.12248.python-list at python.org... > Hi Folks, > > I'm a brand new Python programmer, so please point me in the right > direction if this is not the best forum for this question.... > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. > > I'm not really sure how to get started with this process. > I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), > using Microsoft Excel 10.0 Object Library, then > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") > > Then, I get errors when I try the following: > sh = wb.worksheets(1) > > > I think I'm missing something fairly fundamental, but I've googled all > over the place and can't seem to find anything very introductory about > opening and using data from MS Excel using Python. Any suggestions, > including places to get more information are welcome. > > Also, do I need to run the makepy utility every time I run my script? > If so, how would I do it from within my Python program, rather than with > the GUI in the IDE? > > Thanks for your help, > > Allison > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Allison Bailey > TerraLogic GIS, Inc. > allisonb at terralogicgis.com > 425-673-4495 > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > Your code worked on my system. However, I have found this interface to be pretty tricky. It often happens that while you are debugging the program you generate an instance of Excel which then makes later operations bomb mysteriously. On XP, hit Ctrl-Alt-Del tp bring up the task manager and then look at the Processes tab. If you have an instance of Excel running you should see it there. Use End Process to get rid of it. You can avoid these problems by making sure that any COM references you make get released properly if an exception occurs. Your script would look like this: import win32com.client xl = win32com.client.Dispatch("Excel.Application") try: wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") try: sh = wb.worksheets(1) try: print sh.Cells(2,3) except: sh = None raise sh = None except: wb.Close() wb = None raise wb.Close() wb = None except: xl = None raise xl = None There are more elegant ways of doing this using classes. However, with this code I think you will never see one of those mysterious Excel instances in your task manager. -- Cy http://home.rochester.rr.com/cyhome/ From gsmatthew at ozemail.com.au Fri Jul 11 08:28:39 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Fri, 11 Jul 2003 22:28:39 +1000 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <_3yPa.251$7d2.10974@nnrp1.ozemail.com.au> Im working on a commercial application for a company to replace their existing system. In python of course. Our aim is to distribute it commercially and if a large number of people upgrade then we are planning on donating some funds to the applicable open source associations. I think that if anyone is going to make a commercial product from open source then the expected bare minimum is to at least offer something for all those involved. "Frank Millman" wrote in message news:246a4e07.0307100613.fc2fc50 at posting.google.com... > Hi all > > I would like some advice, and I hope that the good people on c.l.p > will give me the benefit of their experience. > > I am busy developing an accounting package, using Python and wxPython, > together with PostgreSQL on a Unix platform or SQL Server on a Windows > platform. I am a qualified accountant and have been developing > accounting software, mostly customised, for over 20 years. I have now > got myself into a position financially where I can take a few months > off and write "the perfect system". No, not really, but I have built > up a lot of experience over the years, I have a lot of ideas about > what I would like to see in a system, and I have decided to give > myself the opportunity to see how good a system I can actually write. > > At some point quite soon I will have to start generating some revenue > from my efforts. I have a number of people interested in what I am > doing, and I was planning to start selling it as YAAS (yet another > accounting system) and see how many customers I could get. > > As an alternative, I have been toying with the idea of releasing it > under an Open Source license. Part of my thinking is to put something > back into the Open Source community - I love working with Python, > wxPython, PostgreSQL, etc, and it would be nice to contribute > something. The other part of my thinking is that it should be > possible, with a sound business model, to make a viable income out of > supporting an Open Source product. However, as I have no experience of > this, I was wondering how other people survive financially in the Open > Source world. I have no "big daddy" that will pay me to pursue my > dreams, so whatever I do has to bring in a reasonable income. > > Here are some of my ideas - any comments will by much appreciated. > > The essence of a business model must be that the source code may be > free, but you have to pay for support. I believe that accounting > systems more than most systems need support, and that a sensible > company looking for accounting software would not consider anything > that was not supported. Therefore it is important to decide what kind > of support should be offered, and how to persuade customers to sign up > for it. > > The software must be downloadable and runnable by anyone, and it must > be fully functional, at no charge. I realise that there is an option > to restrict functionality in the free version and make it available > only to licensed users, but then you are into security codes, source > code protection, etc, which would at least partially defeat the > object, so I am not thinking along those lines. There will be full > online help (it will probably start off sketchy, but I will improve it > over time), and maybe there should be an FAQ available. That, I think, > is all that should be free. > > I would like to open a free discussion forum (probably a mailing list) > to discuss the software from a technical perspective. I am an > experienced programmer, but I am nowhere near being a Pythonista, so I > am sure there will be many areas ripe for improvement. I would like to > remain open to as much of this kind of feedback as possible. > > However, any support of the software from a business or accounting > perspective will be available to registered users only. For a monthly > support fee (I am thinking of a range of $50-100 per month - let me > know if it is too high or too low) users will be able to request > support via email, which will be responded to promptly. I have a small > staff at present, and if this idea is successful I will plough money > back into expanding the support infrastructure. > > To retain registered users once their software has settled down, I > have in mind a website restricted to registered users which will > provide sufficiently interesting content to persuade them to keep up > their registration. The main content I can think of is enhancement > requests - it is the nature of accounting software that there is a > continuous demand for enhancements, and I intend to keep on enhancing > and improving the product. I envisage a forum where users can forward > ideas, and others can respond/comment/criticise until there is some > consensus. A roadmap of agreed enhancements can be posted on the free > website, which will hopefully attract more users into signing up so > that they can participate. > > Here are a couple of pitfalls that I can see, and my possible > solutions to them. Firstly, a user will be able to terminate his > support contract at any time, and the software will continue to > function. Therefore some may be tempted to stop paying until they have > a problem, then pay for a month, get an answer, and stop again. My > thinking is that 3 months must be paid up front to activate a support > contract. Secondly, a consultant may use my software to build up a > client base, pay a single support fee, and use that to support all his > clients. I don't think I can (or even want to) prevent that, but I can > restrict it by limiting each contract to a single email address for > replies to support queries. > > These are my thoughts so far. Any comments - suggestions, warnings, > personal experiences - will be much appreciated. > > Many thanks > > Frank Millman From johnfabel at btinternet.com Mon Jul 21 12:59:24 2003 From: johnfabel at btinternet.com (John Abel) Date: Mon, 21 Jul 2003 17:59:24 +0100 Subject: PYConfig.h/_FILE_OFFSET_BITS On Solaris Message-ID: <3F1C1BEC.6060905@btinternet.com> Hi, I have written a Python module in C, for the parsing of /proc. I have written it using the Structured Proc API, as per Sun's documentation/recommendations. However, in order to get it to compile, I have had to define _LP64, include , and then undefine it, to get round the fact, pyconfig.h defines _FILE_OFFSET_BITS. This seems to be forcing everything to support large file support, something that is not allowed for correct parsing of /proc. Does anyone know of a way round this? I've included the code below. I have a pure C version of the script, which works fine. Thanks John #include "Python.h" #include #define _LP64 #include #undef _LP64 #include #include #include static PyObject * psinfo_fullpidinfo(PyObject *self, PyObject *args) { PyObject *queryPid; char procBuf[50]; char argStr[512]; char **argvp; int fdPSInfoFile, fdASFile, counter; struct psinfo psBuf; if (!PyArg_ParseTuple(args, "i:pidinfo", &queryPid) ) { return NULL; } (void)sprintf(procBuf,"/proc/%i/psinfo", (int)queryPid); (void)sprintf(asBuf,"/proc/%i/as", (int)queryPid); if ((fdPSInfoFile = open(procBuf, O_RDONLY)) != -1 ) { if (read(fdPSInfoFile, &psBuf, sizeof(struct psinfo)) == sizeof(struct psinfo) ) { close(fdPSInfoFile); if ((fdASFile = open(asBuf, O_RDONLY)) == -1 ) { printf(" Open Of AS Failed"); } else { printf( "%d", psBuf.pr_argc); argvp=(char **) malloc(sizeof(char *) * (psBuf.pr_argc + 1)); if (lseek(fdASFile, psBuf.pr_argv, SEEK_SET) == -1) { printf ("Initial LSeek Failed" ); return NULL; } if (read(fdASFile, argvp, sizeof(char *) * (psBuf.pr_argc + 1)) == -1 ) { printf( "Read Failed" ); return NULL; } for ( counter=0; counter < psBuf.pr_argc; counter++ ) { if (lseek(fdASFile, argvp[ counter ], SEEK_SET) == -1) { printf( "2nd LSeek Failed"); return NULL; } if (read(fdASFile, argStr, 512) == -1) { printf( "Read Of AS File Failed"); return NULL; } printf( "Got %s.\n", argStr ); } close(fdASFile); } } } return Py_BuildValue( "s", argStr ); } static struct PyMethodDef PSInfoMethods[]={ { "fullpidinfo", psinfo_fullpidinfo, METH_VARARGS, "Display Full Arg Details For A Given PID" }, { NULL, NULL, 0, NULL } }; void initpsinfo(void) { (void)Py_InitModule("psinfo", PSInfoMethods); } From monsterkodi at gmx.net Tue Jul 8 08:38:53 2003 From: monsterkodi at gmx.net (Thorsten Kohnhorst) Date: Tue, 08 Jul 2003 14:38:53 +0200 Subject: SWIG and Python in use? References: Message-ID: <3F0ABB5D.4090800@gmx.net> Hello Alan, I've used SWIG and Python in a game I wrote last year. Python was used for writing the various levels and some aspects of the user interface. It was very easy to export most of my C++ Interfaces to Python 2.x. I experienced no problems and can highly recommend using SWIG for scripting and prototyping C++- applications. If interested, you may find the sources at: http://kiki.sourceforge.net Yours kodi Alan Sheehan wrote: > Hi, > > I am considering scripting a large C++ application. > > In particular I am interested in test driving and end-user scripting > the "application layer" in Python and giving it access to a large > collection of C++ objects and their methods. > > I note that SWIG is a mature tool and refers to supporting Python > v1.x. > > Has/Does anyone use SWIG to bind with Python 2.x ?. > > Does it still work? > Any pitfalls, caveats ? > > Thanks in advance. > > Alan From gh at ghaering.de Fri Jul 18 07:26:59 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 18 Jul 2003 13:26:59 +0200 Subject: "\n" in ASCII-file In-Reply-To: References: Message-ID: <3F17D983.3000806@ghaering.de> Martin P wrote: > Hello, > > for a short exercise-program I have to read the lines in an ASCII-file. > > But every line has a new-line-feed ("\n") at the end of the line. (The > ASCII-file was made with Windows Notepad). > Is this only because I used Windows (and Notepad)? Yes. > And... is there any special method to read lines from a file without "\n"? Most of the time, I want to strip any trailing whitespace and do something like: f = file("/path/to/my/file") for line in f: line = line.strip() # ... Unlike Karl's method, this scales to larger files without needing to read the whole file into memory. Files are iterable since Python 2.2. -- Gerhard From gh at ghaering.de Sun Jul 27 12:00:11 2003 From: gh at ghaering.de (Gerhard Haering) Date: Sun, 27 Jul 2003 18:00:11 +0200 Subject: Tools for reading Dr Dobb's Python-URL In-Reply-To: <20030727144122.GA1689@mirk.lan> References: <3f23bc25$0$49102$e4fe514c@news.xs4all.nl> <20030727144122.GA1689@mirk.lan> Message-ID: <20030727160011.GA847@lilith.ghaering.test> * Egbert Bouwman [2003-07-27 16:41 +0200]: > On Sun, Jul 27, 2003 at 01:48:55PM +0200, Irmen de Jong wrote: > > > > Open the message in your news reader. > > Click on an URL in the message. > > > > Sorry, couldn't resist. I'm not sure what you want to > > do, really? > > My mail reader is the text-based Mutt, which: > - doesn't react to mouse clicks > - does show url's in a different color Mutt is infinitely configurable: color body brightcyan black \ "((ftp|http|https)://|(file|mailto|news):|www\\.)[-a-z at 0-9_.:]*[a-z0-9](/[^][{} \t\n\r\"<>()]*[^][{} \t\n\r\"<>().,:])?" > - seems not to do anything useful with them [...] I highlight the whole URL with the mouse, then middle-click in my GUI browser window to open a URL I see in mutt. Alternatively you could use a terminal program like KDE's konsole that parses URLs itself and makes them clickable. -- Gerhard From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 23 22:17:39 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 24 Jul 2003 12:07:39 +0950 Subject: Cookbook idea - single-shot __init__ References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: On Wed, 23 Jul 2003 19:15:23 -0600, Bob Gailer wrote: > I have at times had the need to initialize some things once at the > class level In Python 2.2 (earlier?) you can define any attribute at the class level, and it will be shared by all instances: class Foo( object ): grumble = 0.1 flibble = {} def __init__( self ): ''' Instance initialisation ''' return This causes the attributes 'grumble', 'flibble', and '__init__()' to be shared by all Foo instances; anything done within __init__() will affect the individual instance only. -- \ "I stayed up all night playing poker with tarot cards. I got a | `\ full house and four people died." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From alanmk at hotmail.com Tue Jul 8 12:44:19 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 08 Jul 2003 17:44:19 +0100 Subject: anything new on the ternary operator? References: <3F09E4B4.FED89C06@alcyone.com>, <3F09252F.9B0F52BD@alcyone.com>, <40a939c9.0307080622.3118cfd7@posting.google.com> Message-ID: <3F0AF4E3.CDBF6C0C@hotmail.com> Alia Khouri wrote: > Sorry, I am confused: isn't Israel in the Middle East? Well, I prefer to avoid the geopolitics, but it is worth noting that Israel enters the Eurovision song contest every year :-) And even wins occasionally! Although not all Israelis were happy with the last Israeli winner, Dana International :- http://news.bbc.co.uk/2/hi/special_report/1998/05/98/eurovision/90279.stm http://www.jewishsf.com/bk980515/ettrans.htm regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From danbmil99 at yahoo.com Thu Jul 24 22:25:36 2003 From: danbmil99 at yahoo.com (dan) Date: 24 Jul 2003 19:25:36 -0700 Subject: python assignment References: Message-ID: er, my example in last post should have been: >>> for x in range(3): ... for y in range(3): ... temp[y] = x+y ... v[x] = temp ... >>> v [[2, 3, 4], [2, 3, 4], [2, 3, 4]] #Surprise! You're in Pythonville #fixed: >>> for x in range(3): ... for y in range(3): ... temp[y] = x+y ... v[x] = temp + [] ... >>> v [[0, 1, 2], [1, 2, 3], [2, 3, 4]] #expected behavior but again the +[] looks funky in the morning light. Can I always assume that an operation of this sort will return a new object, even if it has no effect on one of the operands? I suppose a clearer fix would be v[x] = copy.copy(temp), eh? "Tim Peters" wrote in message news:... > [Tim] > >> It would be very unusual (because bad design) for the __iadd__ > >> method of a mutable type to return a pre-existing object, though. > > [Juha Autero] > > I'm confused. I thought that the idea of __iadd__ is that for > > *mutable* types it modifies existing object instead of returning new > > one. > > Bjorn added more appropriate words -- it would be bad design for the > __iadd__ method of a mutable type to return a pre-existing object other than > self. > > >>> a = [1, 2] > >>> b = [1] > >>> b += [2] > > While "a == b" must be true at this point, it would be a nightmare if "a is > b" could be true at this point. For immutable types it doesn't matter: > > >>> a = (1, 2) > >>> b = (1,) > >>> b += (2,) > > It so happens that "a is b" is not true at this point under any Python > released so far, but it could be true someday without causing harm. > > Sorry for the confusion! From bokr at oz.net Wed Jul 16 01:18:48 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 05:18:48 GMT Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> Message-ID: On Tue, 15 Jul 2003 22:14:20 +0100, Stephen Horne wrote: >On 15 Jul 2003 20:32:30 GMT, bokr at oz.net (Bengt Richter) wrote: > >>On Tue, 15 Jul 2003 02:40:27 +0100, Stephen Horne wrote: >> >>>On Mon, 14 Jul 2003 00:07:44 -0700, Erik Max Francis >>>wrote: >>> >>>>Stephen Horne wrote: >>>> >>>>> Imagine, for instance, changing all assignments and other 'copying' to >>>>> use a copy-on-write system. Then add a pointer type and a 'newcopyof' >>>>> operator. And nick the C-style prefix '*' for dereferencing and add >>>>> '&' as a 'make a pointer to this object' operator (absolutely NOT a >>>>> physical memory address). >>>> >>>>The problem is that this misses the point that Python is not C++. You >>>>shouldn't try grafting syntaxes and approaches that make Python look >>>>more like C++, you should be learning to use Python on its own merits. >>> >>>Not true. >>> >>>If you eliminate all violations of the idea of variables bound to >>>values (basically the whole point of my thread), then mutable >>>containers cannot achieve the same thing. >>> >>>If a copy-on-write scheme is added to Python, you'd get the following >>>results from using mutable containers... >>> >>>>>> a = [1, 2, 3] >>>>>> b = a >>>>>> b[2] = 4 >>>>>> a >>>[1, 2, 3] >>>>>> b >>>[1, 2, 4] >>> >>Yes, but it would be hugely inefficient for the case where, e.g., you are >>modifying lines read from a 20MB log file. Imagine inducing a 20MB copy >>every time you wanted to delete or modify a line. Now you have to invent >>a way to program around what can be done very conveniently and efficiently >>thanks to Python's semantics. > >What makes you say that! > >Copies are only made when they are needed. The lazy copy optimisation, >in other words, still exists. (BTW, don't get hung up on this part, ok? Skip forward to the ==[ code part ]== below if you're going to skip ;-) Ok, so the copy happens at b[2]=4 right? This is still useless copying if the holder of the "a" reference *wants* to have it as a continuing reference to the same single shared list. And you can program that in C++ if you want to, and you presumably would. Except now you have to create pointer variable. Ok now how would you handle the case of multiple copies of that pointer variable? Make it "smart" so that you get copy-on-write of what it points to? That's the discussion we're having about the first level of Python references, ISTM. > >Delete or modify one string in a list of strings, and the same stuff >would happen as happens now. Unless, perhaps somewhere you don't know So a 20MB log file in the form of a string list might be 500,000 lines of 40-byte log entries, which would be 2MB of 4-byte pointers. Cheap copy when you explicitly don't want it, but want to share the same list? >about, the caller of your function who passed that list in to you has >a separate reference they expect to stay unchanged. In that case, the >first changed string triggers a copy of the list - but as the list >only contains references to strings, it doesn't trigger copying of all >the strings. The second line changed doesn't require the list to be >modified again because you already have your separate copy. Sure, but the first unwanted copy cost you. > >C++ uses exactly this kind of approach for the std::string class among >others. Copy-on-write is a pretty common transparent implementation >detail in 'heavy' classes, including those written by your everyday >programmers. Does that mean C++ is slower that Python? Of course not! > It could be, if the unwanted copying was big enough. Except you wouldn't program it like that. You'd program it to share mutable data like Python for a case like that. In any case, the performance is a side issue, however practically important, to the discussion of the language semantics. ===[ code part ]================= I'm a bit disappointed in not getting a comment on class NSHorne ;-) BTW, that was not a faked interactive log. It doesn't have lazy copy, but that could be arranged. Though that's an implementation optimization issue, right? Does that namespace have the semantics you are calling for or not? ;-) If I add a mechanism to create and dereference "pointers" re that namespace, will that do it? Here's a go at that: >>> class NSHorne(object): ... from cPickle import dumps, loads ... class Ptr(object): ... def __init__(self, ns, name): self.ns=ns; self.name=name ... def __getitem__(self, i): return getattr(self.ns, self.name) ... def __setitem__(self, i, v): setattr(self.ns, self.name, v) ... def __setattr__(self, name, val): ... if isinstance(val, self.Ptr): ... object.__setattr__(self, name, val) ... else: ... object.__setattr__(self, name, self.loads(self.dumps(val))) ... def __getitem__(self, name): return self.Ptr(self, name) ... >>> ns = NSHorne() set the value of x: >>> ns.x = [1, 2, 3] make a "pointer" to x >>> ns.px = ns['x'] You can use ordinary Python aliases with the "pointer" >>> p=ns.px You *p dereference it like: >>> p[:] [1, 2, 3] And here's a function that expects such a pointer >>> def foo(bar): ... bar[:] = 'something from bar' # like *bar= ... You can pass it to an ordinary Python function >>> foo(p) And dereference it again to see what happened >>> p[:] #like *p 'something from bar' Or look at what it was pointing to >>> ns.x 'something from bar' or look via the original pointer in ns >>> ns.px[:] # like *px 'something from bar' and alias it some more >>> p2 = p >>> p2[:]=(3,4,5) >>> ns.x (3, 4, 5) Or to play with one of your original examples: >>> ns.a = [1, 2, 3] >>> ns.b = ns.a >>> ns.b[2] = 4 >>> ns.a [1, 2, 3] >>> ns.b [1, 2, 4] Make "pointer: to b: >>> p = ns['b'] >>> ns.b [1, 2, 4] >>> ns.b[0]=-1 >>> ns.b [-1, 2, 4] Now dereference p: >>> p[:] [-1, 2, 4] Use dereferenced pointer to mod value >>> p[:][1]=-1 Check values >>> ns.b [-1, -1, 4] >>> ns.a [1, 2, 3] >>> p[:] [-1, -1, 4] >>> But we can set something else than that list: >>> p[:] = 'something else' >>> ns.b 'something else' IOW, p = &x is spelled ns.p = ns['x'] and *p = x is spelled ns.p[:] = ns.x and y = *p is spelled ns.y = ns.p[:] and you can pass ns.p to a function def foo(bar): and dereference it as bar[:] there Does this give names in ns the "variable" semantics you wanted? Is there any difference other than "semantic sugar?" Explaining the difference, if any, will also clarify what you are after, to me, and maybe others ;-) Regards, Bengt Richter From warkid at hotbox.ru Mon Jul 21 12:25:24 2003 From: warkid at hotbox.ru (Kerim) Date: 21 Jul 2003 09:25:24 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) References: Message-ID: <7c58a0f1.0307210825.b17defa@posting.google.com> Any posted URL of form "http://groups.google.com/groups?..." doesn't work for me;-( From peter at engcorp.com Mon Jul 21 16:45:58 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Jul 2003 16:45:58 -0400 Subject: Python scripting with Paint Shop Pro 8.0 References: <3F1C307E.1A00BBD0@engcorp.com> Message-ID: <3F1C5106.580EBFEA@engcorp.com> Marc Wilson wrote: > > In comp.lang.python, Peter Hansen (Peter Hansen) wrote > in <3F1C307E.1A00BBD0 at engcorp.com>:: > > |Marc Wilson wrote: > |> > |> Groovy. I may become a Python convert. *sigh* I've not finished learning > |> perl yet, and now I've got a new shiny toy. :) > | > |Excellent! You have much less to _un_learn then. :-) > > I'm not here to participate in any religious wars. :) Sorry, I must have misinterpreted your use of the word "convert" then. ;-) From tjreedy at udel.edu Fri Jul 25 13:44:45 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2003 13:44:45 -0400 Subject: Why instancemethod when I can add functions to classes outside class body? References: <6f03c4a5.0307242027.85f195a@posting.google.com> <3f210717$0$76049$edfadb0f@dread11.news.tele.dk> Message-ID: "Anders J. Munch" wrote in message news:3f210717$0$76049$edfadb0f at dread11.news.tele.dk... > "Ben Finney" wrote: > > On 25 Jul 2003 07:18:15 +0200, Martin v. L?wis wrote: > > > rimbalaya at yahoo.com (Rim) writes: > > >> So what problem is the new.instancemethod() trying to solve? > > > > > > It has no side effects on the class it is an instancemethod of. > > > > So what side effects (i.e. what problem) is the new.instancemethod() > > trying to solve? > > Assigning to the class changes the behaviour of all instances of that class. Since changing the behavior of all instances is precisely the purpose of making such an assignment (of function to class as method), that is a feature, not a problem. > new.instancemethod can be used to add a method to an individual instance. > > >>> class A: pass > ... > >>> a1 = A(); a2 = A() > >>> a1.f = new.instancemethod(lambda self: "hi", a1, A) > >>> a2.f() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'f' > >>> a1.f() > 'hi' So to answer the OP's question, the problem solved is that directly assigning a function as an instance attribute binds the function as a function, which means no *automatic* access to the instance and its other attributes. If such access is needed, the instance must be passed explicitly, as in a1.f = lambda self: repr(self) a1.f(a1) Instancemethod adds the option of wrapping instance-specific functions as bound methods getting the instance as an automatic first (self) paramater, just like with class-wide methods. In the 'hi' example above, since the self (psuedo)param is is ignored, a1.f = lambda: 'hi' would have the same net effect. However, a1.f = new.instancemethod(lambda self: repr(self), a1, A) requires the wrapping to avoid having to explicitly pass the instance. Terry J. Reedy From mciperf at cox.rr.com Tue Jul 8 20:29:53 2003 From: mciperf at cox.rr.com (Gerard C Blais) Date: Tue, 08 Jul 2003 20:29:53 -0400 Subject: anygui newbie question Message-ID: <54omgv8rb7p08uct892h6q1qck489gvoph@4ax.com> I'm trying to learn anygui, running on Win98. When I run backend(), I get mswgui. I've typed in the first program from the manual (one button, random sentence in text box on click). Window comes up fine. When I click the button, I get a run-time error and the traceback says my handler function has received an unexpected argument, "source". As far as I can tell, "source" should be expected. I do have a link call (link (btn, handler). Any ideas? Any place to look besides the on-line manual ahd Hetland's Practical Python? Thanks, Gerry From mis6 at pitt.edu Sat Jul 19 09:29:41 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jul 2003 06:29:41 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> Message-ID: <2259b0e2.0307190529.57338b3f@posting.google.com> Irmen de Jong wrote in message news:<3f17f883$0$49107$e4fe514c at news.xs4all.nl>... > Jp Calderone wrote: > > On Fri, Jul 18, 2003 at 05:01:47AM -0700, Michele Simionato wrote: > > > >>I often feel the need to extend the string method ".endswith" to tuple > >>arguments, in such a way to automatically check for multiple endings. > >>For instance, here is a typical use case: > >> > >>if filename.endswith(('.jpg','.jpeg','.gif','.png')): > >> print "This is a valid image file" > >> > >>Currently this is not valid Python and I must use the ugly > >> > >>if filename.endswith('.jpg') or filename.endswith('.jpeg') \ > >> or filename.endswith('.gif') or filename.endswith('.png'): > >> print "This is a valid image file" > > > > > > extensions = ('.jpg', '.jpeg', '.gif', '.png') > > if filter(filename.endswith, extensions): > > print "This is a valid image file > > > > Jp > > > > Using filter Michele's original statement becomes: > > if filter(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > print "This is a valid image file" > > IMHO this is simple enough to not require a change to the > .endswith method... > > --Irmen I haven't thought of "filter". It is true, it works, but is it really readable? I had to think to understand what it is doing. My (implicit) rationale for filename.endswith(('.jpg','.jpeg','.gif','.png')) was that it works exactly as "isinstance", so it is quite obvious what it is doing. I am asking just for a convenience, which has already a precedent in the language and respects the Principle of Least Surprise. Michele From amk at amk.ca Thu Jul 10 10:42:51 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 10 Jul 2003 09:42:51 -0500 Subject: Memory leak ?? References: <3f0d5d3f$0$13154$edfadb0f@dread15.news.tele.dk> Message-ID: On Thu, 10 Jul 2003 14:34:05 +0200, Kim Petersen wrote: > Using python-2.2.2-26 on RH9 (shrike) x86 -fully patched > > The following program slowly eats up more and more memory when run on > large datasets... can anyone tell what the trouble is? Your code uses eval(), which is pretty heavyweight because it has to tokenize, parse, and then evaluate the string. There have been a few memory leaks in eval(), and perhaps you're running into one of them. Try using int() or float() to convert strings to numbers instead of eval. As a bonus, your program will be faster and much more secure (could an attacker tweak your logfiles so you end up eval()ing os.unlink('/etc/passwd')?). In general, using eval() is almost always a mistake; few programs need to take arbitrary expressions as input. --amk From achrist at easystreet.com Fri Jul 4 13:17:29 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 04 Jul 2003 10:17:29 -0700 Subject: Form using HTML on PythonCard References: Message-ID: <3F05B6A9.72935EA8@easystreet.com> You can put panels of widgets into HTML very nicely with wxPython. The version of HTML that the wxHtmlCtrl supports is pretty simple, but it includes a hook for extending it, the WXP tag. This looks something like this embedded in your html: Although the demo that comes with wxPython does something simple like embedding a button, I just about always derive SomeClass from wxPanel, and I use sizers to control the layout of several controls within the panel. The constructor will start like this: class SomeClass(wxPanel): def __init__(self, parent, id=-1, size=wxDefaultSize) wxPanel.__init__(self, parent, id, size=size) IDK how to pass in object references as constructor parameters in the embedded HTML, so these panels seem to often wind up using globals to communicate with the rest of the program. Keep in mind that the constructor for this panel is not called until the HTML actually gets put into the wxHtmlCtrl (by SetPage, etc). The panel also gets automatically destroyed when the next contents get put into the wxHtmlCtrl, so don't hang on to any references to it. IDK if PythonCard supports this control or not. Haven't used pythoncard. I alsways use wxCallAfter to send the next page to the wxHtmlCtrl. That way I don't have to worry about a panel destroying itself while its still running by changing the screen contents. wxCallAfter waits until the current UI event is completely processed before doing whatever it does. This all leads to a pretty convenient style of programming. I throw something at the screen, the user clicks something, maybe this makes me throw something else at the screen, maybe it doesn't. If not, he's still got the same screen to try something else. You don't have to work out a hierarchy of screens where the user is forever drilling down and popping up -- they can have more browser-like freedom. Makes their heads spin. Keep a copy of the HTML and give them a back button. Al From Andreas.Ames at tenovis.com Wed Jul 23 04:31:05 2003 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Wed, 23 Jul 2003 10:31:05 +0200 Subject: How is the execution order of 'x = z'? (also: Python FAQ 4.88 ) Message-ID: <788E231C269961418F38D3E360D1652526C9CD@tndefr-ws00021.tenovis.corp.lan> Hello, "Ulrich Petri" writes: > 1. its not y's reference count that gets (possibly) decremented but > the-object-y-points-to Thanks for the clarification, that's what I wanted to say (but failed to say). > 2. in this example noting will be decremented since y never goes out of > scope. Just by assining y to x you dont ~invalidate~ y. Obviously my sample was somehow ambigous. The assignment I cared about was 'x = z' (like in the subject). I wanted to make the sample clear by the other assignment. Sorry! Below is a more selfcontained sample (assume that x, y and z are not bound before the code is executed): >>> class Foo: ... def __del__(self): ... print '__del__(%#x)' % id(self) ... >>> y = Foo() >>> print '%#x' % id(y) 0x8152e7c >>> z = 0 >>> print '%#x' % id(z) 0x80cbf70 >>> x = y >>> print '%#x' % id(x) 0x8152e7c >>> del y >>> print '%#x' % id(x) 0x8152e7c >>> x = z __del__(0x8152e7c) >>> print '%#x' % id(x) 0x80cbf70 The assignment 'x = z' calls Foo.__del__. What I wanted to know is: Is Foo.__del__ called *before* x refers to an integer object of value 0 or *afterwards*. In other words, does x refer to a possibly (partially) invalid object while Foo.__del__ is executed, or what is the Python FAQ 4.88 referring to (within the final paragraph which begins with 'Note:', dealing with atomicity of operations replacing objects)? TIA, andreas From tebeka at cs.bgu.ac.il Mon Jul 7 08:39:34 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 7 Jul 2003 05:39:34 -0700 Subject: Problems with py2exe for python 2.3 beta References: Message-ID: <33803989.0307070439.6decf52c@posting.google.com> Hello Jamie, > - I've included "-p encodings" in the command line flags, but still get the > "no codec search functions registered" error at runtime. I had the same problem. IIRC adding "import encodings" (and maybe importing the specific encodings as well) did the trick. > - py2exe is now including tcl files as dependencies, whereas these weren't > required in the python 2.2 version. I don't recall it doing that. Maybe some module you're using imports Tkinter. HTH. Miki From m at moshez.org Tue Jul 8 13:38:21 2003 From: m at moshez.org (Moshe Zadka) Date: 8 Jul 2003 17:38:21 -0000 Subject: anything new on the ternary operator? In-Reply-To: <3F0AF4E3.CDBF6C0C@hotmail.com> References: <3F0AF4E3.CDBF6C0C@hotmail.com>, <3F09E4B4.FED89C06@alcyone.com>, <3F09252F.9B0F52BD@alcyone.com>, <40a939c9.0307080622.3118cfd7@posting.google.com> Message-ID: <20030708173821.13840.qmail@green.zadka.com> On Tue, 08 Jul 2003, Alan Kennedy wrote: > And even wins occasionally! Although not all Israelis were happy with > the last Israeli winner, Dana International Well, not all the Israelis were happy when she *won*. Everybody, of course, had a field day when she dropped the award when Israel hosted the competition the next year... -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From ansible at typhoon.xnet.com Thu Jul 31 15:29:34 2003 From: ansible at typhoon.xnet.com (James Graves) Date: Thu, 31 Jul 2003 19:29:34 +0000 (UTC) Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> <38ec68a6.0307301841.dfb951a@posting.google.com> Message-ID: Asun Friere wrote: >If you use vim remember to put 'set expandtab' (or if you wanna be >fancy 'au BufRead,BufNewFile *.py set expandtab' ) into your .vimrc >(or .exrc) file. This way you can use '[Ctrl]-[T]' and '[Ctrl]-[D]' >to in- and un-dent in insert mode, as well as '>>' and '<<' in command >mode, without fear of hard tabs being inserted. (Though the way vi(m) >mixes tabs and spaces is consistent enough that you wouldn't usually >get into any trouble with it.) That's handy. I had known about 'set expandtab' for a while, but I wanted to figure out how to use it for just Python. And now I don't have to. Thanks, James Graves From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 31 18:38:41 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Aug 2003 08:28:41 +0950 Subject: looking for design pattern name References: <87adaud0he.fsf@pobox.com> Message-ID: On 31 Jul 2003 19:17:49 +0100, John J. Lee wrote: > "Andrew Dalke" writes: >> Err, I tangented, didn't I. > > "Verbing weirds language", to quote Calvin. From my sigmonster: "First they came for the verbs, and I said nothing, for verbing weirds language. Then, they arrival for the nouns and I speech nothing, for I no verbs." -- Peter Ellis -- \ "I'm beginning to think that life is just one long Yoko Ono | `\ album; no rhyme or reason, just a lot of incoherent shrieks and | _o__) then it's over." -- Ian Wolff | Ben Finney From sjmachin at lexicon.net Sun Jul 20 20:51:10 2003 From: sjmachin at lexicon.net (John Machin) Date: 20 Jul 2003 17:51:10 -0700 Subject: Strings and Unicode References: Message-ID: madsurfer2000 at hotmail.com (-) wrote in message news:... > I wrote: > > I have a function that takes a string as an input parameter. This > > function then urlencodes the string and sends it to a server with > > telnetlib.Telnet > > > > The problem is that the string gets converted into what seems to be > > Unicode. How can I check to see if the input-string is Unicode and > > convert it to a different character set (in this case ISO-Latin1). > > I see that my question may have been asked in the wrong way, so here's > more details: > > I'm using Python 2.2.2. under Windows XP. The function I was talking > about actually takes two strings, and I send both parameters to the > urlencode function. The urlencode-function I use is imported from > urllib. > > My function: > > def addPOSTParam(self,name,value): insert here: print 'value:', type(value), repr(value) > param = urlencode({name: value}) insert here: print 'param:', type(param), repr(param) > self.POSTParameters.append(param) > > Example: > > client.addPOSTParam("param","abc ?") > > POSTParameters then looks like: > ['param=abc+%C3%A6'] > > Here, the '?' character is converted into what seems to be Unicode Unlikely. U+C3A6 is a Hangul (Korean) syllable. > > I would have expected the following: > ['param=abc+%E6'] So would I. See below. However despite the fact that the last character in your 'value' shows up as "small ae ligature" in MSIE, we would really like to see some code of yours that *minimally* and *unambiguously* shows the problem, and can be executed in the minimal Python environment (i.e. sans gui, command prompt, again: see below). C:\junk>python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >>> import urllib >>> urllib.urlencode({'name':'abc \xe6'}) 'name=abc+%E6' >>> urllib.quote_plus('abc \xe6') 'abc+%E6' >>> From gsmatthew at ozemail.com.au Mon Jul 14 07:35:59 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Mon, 14 Jul 2003 21:35:59 +1000 Subject: How to give a custom object instance a type name ? Message-ID: Hi all, quick one, I hope I am explaining this properly, I am wanting to do some introspection on custom object instances, for example: import md5 >>> m = md5.new() >>> type(m) I can at least test here by doing something like if type(m) == 'md5.md5': Here is a custom Dispatcher class that I have written >>> from BI.System.Controller.Dispatcher import Dispatcher >>> x = Dispatcher() >>> type(x) How do I get the same as with instance 'm' above where the type displays the actual object instance name, however my custom dispatcher instance is just a generic 'instance', is there some builtin where this is set ? many thanks Graeme From http Sun Jul 27 20:40:33 2003 From: http (Paul Rubin) Date: 27 Jul 2003 17:40:33 -0700 Subject: floating point range generator References: Message-ID: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> I needed this for something I was doing just now. It came out pretty enough that I thought I'd post it. It's like xrange, except for floating point values. def frange(start, stop, step=1.0): sign = cmp(0, step) while cmp(start, stop) == sign: yield start start += step >>> for i in frange(3., 4., 0.2): print i ... 3.0 3.2 3.4 3.6 3.8 >>> From w0zhang at ouray.cudenver.edu Wed Jul 30 17:59:59 2003 From: w0zhang at ouray.cudenver.edu (wzhang) Date: 30 Jul 2003 14:59:59 -0700 Subject: (Eclipse/TruStudio) Re: I am so impressed References: <20030726215139.14696.00000526@mb-m04.aol.com> Message-ID: thedustbustr at aol.com (TheDustbustr) wrote in message news:<20030726215139.14696.00000526 at mb-m04.aol.com>... > My only complaint is that it won't let you use control keys in the > interpereter. It's a problem when you put a while 1: in your mainloop and > can't KeyboardInterrupt out of it. > > Great for an editor, as long as you run your apps externally. I downloaded both eclipse and trustudio plugin. Everything was fine except I could not pass a commandline argument to the module. Could anybody tell me how to configure eclipse 'run' so that I can pass a argument. Thanks. wz From intentionally at blank.co.uk Tue Jul 15 02:49:53 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 07:49:53 +0100 Subject: anything like C++ references? References: Message-ID: <3f67hvgi36s7rmtn59rajj2gpir8hhfiph@4ax.com> On 15 Jul 2003 06:56:56 +0200, martin at v.loewis.de (Martin v. L?wis) wrote: >Stephen Horne writes: > >> Write... >> >> x = classname() >> y = x >> >> ... and that would be an error. >[...] >> However... >> >> x = &classname() >> y = x >> >> ... and everything is fine. > >If any kind of implicit reference assignment would be an error, then I >assume > >x = classname() >x.foo() > >would also be an error? because that assigns a reference of the object >to the implicit 'self' parameter of the method? The whole point of 'self' is to act as a name for the object (not the value) so there is no problem in having it behave that way. Its already special because its implicit, so making it special in this way too wouldn't be a big issue. Implementation detail. Not a fundamental problem. > >> > This is completely different from the notion of >> >values in C or C++, where each occurrence of the literal 5 creates a >> >new value whose state is 5. >> >> Not true. Each occurence of the literal 5 creates a new 'symbol' which >> represents the value 5. The immutability of values is preserved in >> C++. > >That is not true. There are no "symbols" in C beyond those that you >use to name functions and global variables. Every occurrence of an >integer literal *does* create a temporary object, every time the >literal is *executed*. I was using the word 'symbol' in the theoretical sense - the sense in which any computer might be called a machine for manipulating symbols. Not in the sense of an identifier. The data stored in RAM (or registers or whatever) may be considered just a bunch of electrical charges or currents that may or may not be present at certain points. But that ignores the fact that these electrical signals have meaning. These electrical signals have meaning because they form symbols which represent integers, or floating point numbers, or strings or whatever. The principle is no different to symbols written on paper in order to form words, numbers or whatever. In C, variables bind directly to precisely that type of symbolic representation of value. If you write... int main (int argc, char *argv []) { int x = 100; int y = x; y = 200; return EXIT_SUCCESS; } ...then it is perfectly true that you wouldn't tend to think of the patterns of bits in memory as symbols, but that is what they are. That is why at the end of the program, the value 100 is still 100 and the value of x is still 100. You have not manipulated values (in a highly pedantic theoretical sense) because values are immutable and cannot be changed. You have simply changed the symbol stored in the memory associated with variable y to one that represents the value 200. These days, symbols representing integers almost certainly uses a twos complement binary notation. But that isn't the only way of representing such values. It could have been a binary coded decimal notation. In COBOL, it could well be an ASCII or EBCDIC string of characters - each of those characters in turn being symbolised by a number and so on. Even with twos complement, it may be big endian or little endian. An integer value can be represented by many symbolic notations, and machines that manipulate symbolic representations (I have seen computers defined in pretty much those words before) have used a number of different symbolic representations for that purpose. The symbol isn't the value - it only represents the value. In general, of course, it is not useful to think in these extremely pedantic terms. From gh at ghaering.de Thu Jul 31 19:48:03 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 01 Aug 2003 01:48:03 +0200 Subject: Python vs. Perl vs. PHP? In-Reply-To: <7b454334.0307311023.28900d57@posting.google.com> References: <7b454334.0307281002.41dae81b@posting.google.com> <7b454334.0307301611.1b40ff11@posting.google.com> <7b454334.0307311023.28900d57@posting.google.com> Message-ID: <3F29AAB3.2050209@ghaering.de> Fazer wrote: > Thanks for the reply! I think I am going to give mod_python a try. > Would I have to be root to install mod_python? Either that or you need to have the privileges to compile Apache + mod_python and run it on a nonprivileged port (> 1024). > Because that's one of > my biggest concerns. I don't have root and I don't want to work on my > windows machine since I am kind of more comfortable working on a Linux > platform. [...] mod_python works on Windows as well. The harder part is finding a web hoster that will host mod_python apps (pythonhosting.com comes to mind). I personally find it much easier to learn about system administration and get my own dedicated server for EUR 39/month. -- Gerhard From iambren at sympatico.ca Mon Jul 21 16:16:53 2003 From: iambren at sympatico.ca (Bren) Date: 21 Jul 2003 13:16:53 -0700 Subject: Problem building extension sample with Python 2.2.3 Message-ID: Hi, I'm trying to build the sample extension file from http://www.python.org/doc/current/ext/simpleExample.html. I get a linker error: Linking... spam.obj : error LNK2001: unresolved external symbol __imp__Py_InitModule4TraceRefs Also, I find it necessary to ignore python22_d.lib and link python22.lib explicitly when I make a Debug build. I'm using MSVC++ 6. Any help appreciated, thanks. From juneaftn at REMOVETHIShanmail.net Wed Jul 2 21:40:22 2003 From: juneaftn at REMOVETHIShanmail.net (Changjune Kim) Date: Thu, 3 Jul 2003 10:40:22 +0900 Subject: When is unit-testing bad? [was: Re: does lack of type...] References: <3EEE1210.3004AB45@engcorp.com> <878ys06tcv.fsf_-_@pobox.com> <87of0pno5s.fsf@titan.staselog.com> Message-ID: "Jeremy Bowers" wrote in message news:pan.2003.07.02.21.14.36.896580 at jerf.org... > On Wed, 02 Jul 2003 15:21:45 +0200, Aur?lien G?ron wrote: > > I'd be interested to know about > > projects where they automate unit tests for GUIs, but I suspect it would be > > just as cumbersome. > > I'm doing one right now. It's designed from the ground up by me, so it's > testable. It almost has to be, since it's fairly complicated and Needs To > Work. > > For the record, I've found Tkinter does *great* with this, because you can > drive the GUI without ever actually starting the event loop. It doesn't > seem perfect but largely works, much better then it has any right to. > > wxPython doesn't work at all without an event loop, so I never did get it > tested, which has contributed to me dropping it. ;-) (I'm gonna guess that > never entered into anybody's head when they were designing toolkits...) > > > In all those cases, I much prefer having a human being go out and do the > > unit tests manually. > > The thing is, they won't. We've got about 50 years of collective > experience backing that up. UnitTesting GUI is not that difficult. UnitTesting multi-threaded programs is not that difficult. UnitTesting database programs is not that difficult. I have experiences in all of them, of which the degree and depth might vary. For example, I follow a sequence(as in Christopher Alexander's style) for TDDable GUI program: Principles: 1. Test everything that is in P and M. Don't test V. 2. There is no GUI framework API call in P and M. 3. In V, there are stuffs that you can have enough confidence even without testing. 4. No duplication. 5. Keep the cycle. Sequence: 1. Start from one chunk. Think about what should be shown from the abstract level, what concepts(M) should be there. Don't use GUI API calls. 2. You can take M and P apart. How it should be shown goes into P. What goes into M. 3. P uses the interfaces of V. Firstly, test P with mock-V. Put into V only those that can be considered as "need not tests, really sure" in GUI aspects. 4. As mock-V getting its form, implement real-V along with it. 5. If there is anything you feel not confident pass it over to P. These are what I get after years of experience in TDDing GUI programs. see also(all highly recommended): * http://martinfowler.com/articles/separation.pdf * http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf * http://www.sdmagazine.com/documents/sdm0206b/ * http://www.object-arts.com/EducationCentre/Overviews/ModelViewPresenter.htm Best wishes, June From mertz at gnosis.cx Sat Jul 12 02:25:50 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 12 Jul 2003 02:25:50 -0400 Subject: The "intellectual property" misnomer References: Message-ID: Ben Finney wrote previously: |The term he used doesn't explain anything, and only confuses. It would |have been *less* confusing to say "The PSF holds something unspecified |for Python". At least there is no pretence of explanation there. This is flatly disingenuous. There is not one reader of c.l.py in a hundred who does not know that IP consists of copyrights, trademarks, patents, and--to an extent--trade secrets. Yes, those things are different from each other, but that's what the category includes. There is no more ambiguity in the phrase "intellectual property" than there is in the phrase "African countries" or "scripting languages". Both of those latter phrases include a number of things that differ significantly between each other; and both even have some borderline cases. But I'm not going to stop using any of the terms, nor should Guido. Just because you think (correctly) that IP is *bad*, it doesn't mean the term doesn't denote. ... Then some more bluster and whatnot: PSF has copyrights; hopefully Python is not patent-restricted, but who knows; it's hard for an open source project to have any trade secrets; I don't think the name "Python" is trademarked, but were it to be, the PSF should hold the trademark. Duh! Yours, Lulu... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From skip at pobox.com Fri Jul 25 12:46:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Jul 2003 11:46:54 -0500 Subject: path module In-Reply-To: <20030725163757.N6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725163757.N6906@prim.han.de> Message-ID: <16161.24318.327345.674356@montanaro.dyndns.org> holger> IMO you'll almost never use the following string-methods on a holger> 'Path' object: holger> capitalize center count decode encode holger> expandtabs find index isalnum isalpha isdigit holger> islower isspace istitle isupper holger> ljust lstrip rjust splitlines startswith holger> swapcase title translate zfill In practice, I rarely use the above methods on string objects. The only exception is startswith. ;-) Skip From fumingw at tom.com Thu Jul 17 08:28:49 2003 From: fumingw at tom.com (Fuming Wang) Date: 17 Jul 2003 05:28:49 -0700 Subject: Accessing and updating global variables among several modules References: Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:... > On 11 Jul 2003 20:38:48 -0700, fumingw at tom.com (Fuming Wang) wrote: > > >Hi, > > > >I have several modules that need to access global variables among > >them. I can do that by import modules: > > > >module A: > >gA = 'old' > > > >module B: > >import A > >print A.gA > >>>> 'old' > > > >change gA in module A after some initialization: > >def init_fuct(): > global gA # w/o this line, gA is just a local variable, and init_fuct() is well named ;-) > > gA = 'new' > > > (I assume the above function was in module A, and either invoked from there or as A.init_fuct() > from somwhere else). > > >no change in module B: > >print A.gA > >>>> 'old' > With the code above, there was no change in A either ;-) > > > >However, when I modify these global variables in one module, the other > >modules would not see the changes. Any one has any suggestions? ( I > >don't want to use from A import *) > > > Just make sure you actually change A.gA and you should be able to see the change from B as A.gA. > Unless I am missing something. > > Regards, > Bengt Richter Hi, Thanks for the replies. I have actually found a solution to the problem. The problem is caused by Python creating two copies of the module that is passed to the interpreter. Here is a short report of what the problem is and how to avoid it. Hope this can be of help for others. Fuming P.S. I am running Python 2.3 b2 on Windows2000 ******************************************** It started out as a simple desire to have communications between two modules that import each other (circular imports). It turns out to be quite a gotcha,which I thick could catch many experience Python user by surprise. You can now avoid this pitfall and gain some insights in how module imports are handles. So here it goes. ------ File A.py ---------- import B a = object() def printa(): print 'a from A:', a def printb(): print 'b from A:', B.b if __name__ == '__main__': printa() printb() B.printa() B.printb() ------ File B.py ---------- import A b = object() def printa(): print 'a from B:', A.a def printb(): print 'b from B:', b Run it from Python interpretor >python A.py a from A: b from A: a from B: b from B: If you look at the addresses of the printed objects carefully, you will find that the same object b in module B can be seen by both modules (0x..3C0), while object a seems to be totally different objects seeing from module A and B (0x..3C8, 0x..3B8). Why are module A and B are seeing different objects from the same object a? We will find out after the following experiment. Let's add the following two lines to file A.py and B.py seperately: print 'init module A:', a, __name__ print 'init module B:', b, __name__ This line will tell us when each module is created/initialized/loaded/imported. Let's run the script once again. We will have the following results. init module A: A init module B: B init module A: __main__ a from A: b from A: a from B: b from B: Haaa! There are two copies on module A. One is called 'A', the other is called '__main__'. Functions in module A is seeing module __main__.a (0x..3C8),while functions in module B is seeing module A.a (0x..3B8). No wonder they are seeing two different object. Knowing the cause of this problem, we can devise many solutions. Some are more proper than others. Let's discuss the proper one first. The only reason module A is created twice is because it is invoked by the interpreter. We only need to write another short module C as following, and the problem is solved. --------- file C.py ---------------- import A import B if __name__ == '__main__': A.printa() A.printb() B.printa() B.printb() Improper solutions including: change in A.py if __name__ == '__main__': ----> if __name__ == 'A': or change in B.py import A ----> import sys; import sys.modules['__main__'] From johnroth at ameritech.net Tue Jul 1 17:17:01 2003 From: johnroth at ameritech.net (John Roth) Date: Tue, 1 Jul 2003 17:17:01 -0400 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: "John Roth" wrote in message news:vg3eghr5kj1sd8 at news.supernews.com... > > "Rim" wrote in message > news:6f03c4a5.0306301931.3f15fbb7 at posting.google.com... > > Hi, > > > > I have been thinking about how to overload the assign operation '='. > > In many cases, I wanted to provide users of my packages a natural > > interface to the extended built-in types I created for them, but the > > assign operator is always forcing them to "type cast" or coerce the > > result when they do a simple assign for the purpose of setting the > > value of a variable. > > Use a property. Changing the semantics of the assignment > statement (NOT assignment operator) is not going to happen. > > Properties are new in Python 2.2 (which is around a year > old by now.) They enable you to have getter and setter > methods with an interface that looks like an instance > variable. > > John Roth I usually don't reply to my own posts, but I thought it might be nice if I put up a skeletal example of how to do it. I'm assuming that what you want is a way of insuring, in a class named Foo, that the variable fooBar is always bound to a class instance of Bar, regardless of what the user tries to assign to it. Most of what follows is documented in "What's New in Python 2.2," section 2: Peps 252 and 253: Type and Class Changes. The information on the __new__ method is in the document under 2.5: Related Links. The way to do this is: 1. Both Foo and Bar have to inherit from a built-in type. That's usually "object", but it can be any built-in type. 2. Refactor Foo so that all references to self.fooBar now refer to self._fooBar. (It can be any name; the underscore is a convention that means "private." 3. Insert the following code in Foo: def _getFooBar(self): return self._fooBar def _setFooBar(self, parm): self._fooBar = Bar(parm) _fooBar = property(_setFooBar, _getFoobar, None, "doc strings swing") 4. In class Bar, use the __new__ method to check if the parameter is an instance of class Bar. If it is, return that instance, otherwise call your superclass's __new__ method to create a new object and return it. 5. In class Bar, do whatever type determination you need to in the __init__ method to build your new Bar object. Most of this is documented in "What's New in Python 2.2," section 2: Peps 252 and 253: Type and Class Changes. The information on the __new__ method is in the document under 2.5: Related Links. HTH John Roth > > From tgerla at outsourcefinancial.com Wed Jul 16 13:54:20 2003 From: tgerla at outsourcefinancial.com (Tim Gerla) Date: 16 Jul 2003 10:54:20 -0700 Subject: Replacing rexec Message-ID: <1058378060.5034.13.camel@redwall.ofsloans.com> (I apologize if I've dug up a long-dead horse, but I haven't found any posts in the archive on this that really explain what I'm asking.) We are looking to use plpython in PostgreSQL, but it's being downgraded to "untrusted" and/or being completely removed because Python's rexec went away. Why did rexec go away, specifically? I know it had security issues, but couldn't these have been fixed? Did the module just have too many integral flaws in the design to be worth saving? Is anyone working on a replacement? If not, why not? Even if plpython isn't very widely used, I think it's still important for advocacy. I'd much rather write Python than PL. Anyway, I'm looking for a summary of specific reasons why rexec went away without a replacement. I understand completely that it had flaws and was insecure; I'm only confused as to why these flaws were insurmountable. Given a bit more assurance that a replacement would be useful and possible, we potentially have the resources to do so. Having a working and trusted plpython is valuable to both my own organization and, IMHO, the Python world itself. Thanks, Tim Gerla -- Outsource Financial Services, LLC. tgerla at outsourcefinancial.com From klappnase at freenet.de Mon Jul 28 10:14:44 2003 From: klappnase at freenet.de (klappnase) Date: 28 Jul 2003 07:14:44 -0700 Subject: How to stop screensaver from starting up Message-ID: <9a410299.0307280614.444cc2b2@posting.google.com> Hello everyone, does anyone know a way to stop the screensaver under linux from starting up while a certain process is running? I need this because I experience a memory leak while recording wav-files every time the screensaver starts. It is a Tkinter application, btw. Any help would be very appreciated. Thanks Michael From ebolonev at rol.ru Fri Jul 4 02:20:02 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 17:20:02 +1100 Subject: File information?? References: Message-ID: Hello, Stan! You wrote on Fri, 04 Jul 2003 05:59:10 GMT: SC> Is there a way to get the file size and modified date of a file? os.stat() =========Beginning of the citation============== import os,glob a=glob.glob('c:\\*')[0] print os.stat(a)[6],os.stat(a)[8] =========The end of the citation================ With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From bgailer at alum.rpi.edu Tue Jul 1 15:47:57 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 01 Jul 2003 13:47:57 -0600 Subject: (Numeric) should -7 % 5 = -2 ? In-Reply-To: <010720031119590501%pecora@anvil.nrl.navy.mil> References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> Message-ID: <5.2.1.1.0.20030701134327.01a49fc0@66.28.54.253> At 11:19 AM 7/1/2003 -0400, Louis M. Pecora wrote: >In article <3g32gvcolis4485956egtc35akm6lh3uq5 at 4ax.com>, Tim Roberts > wrote: > > > >Hmmm... "remainder" makes sense. But "%" is mod, right. IIRC from my > > >abstract algebra days (only 30 yrs ago :-) ) The "X mod n" function > > >maps onto the postive integers from 0 to n-1. So sounds like numeric > > >contradicts the math texts. Not good since it's a math module. > > > > That's a bit harsh. > >You may be right. I got to work and checked my old Abstract Algebra >book. The defintion is, > >We write a=b mod m if m divides (a-b) (i.e. no remeinder). > >The defintion does not say how to compute the mod, rather it is an >expression of a relationship between a and b. Hence, writing -2=-7 mod >5 appears to be OK. >[snip] To quote from "Number Theory and its History" by Oystein Ore, page 213f: "When an integer a is divided by another m, one has a = km + r where the remainder is some positive integer less than m. Thus for any number a there exists a congruence a (is congruent to) r (mod m) where r is a unique one among the numbers 0, 2, 1, .... m-1" Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From baas at ira.uka.de Fri Jul 18 14:12:55 2003 From: baas at ira.uka.de (Matthias Baas) Date: Fri, 18 Jul 2003 20:12:55 +0200 Subject: installing python library modules (general question) References: <79ad5955.0307122013.6780fc53@posting.google.com> <79ad5955.0307131400.696226ce@posting.google.com> Message-ID: On 13 Jul 2003 15:34:36 -0700, juliagoolia301 at hotmail.com (Julia Goolia) wrote: >you so much. just so i know... adding something to /etc/ld/so/conf is >different than setting LD_LIBRARY_PATH? The result should actually be the same. Maybe there was a typo when you set the path in LD_LIBRARY_PATH, this can easily happen (see above, the config file is actually /etc/ld.so.conf.... ;-) By the way, if you want to know how loading libraries works, have a look at this HOWTO (section 3): http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Program-Library-HOWTO.html (this and more documentation can be found at "The Linux Documentation Project": http://www.tldp.org/) >what do you do if you don't ave root access? Then you actually do use LD_LIBRARY_PATH. - Matthias - From cben at techunix.technion.ac.il Sun Jul 20 05:20:54 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Sun, 20 Jul 2003 12:20:54 +0300 (IDT) Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: <2259b0e2.0307190640.56266017@posting.google.com> Message-ID: Mike C. Fletcher wrote on 2003-07-19: > * finally, stores the value > o tries to do what would have been done if there were no > descriptor (with the new, coerced value) > o does *not* create new names in the object's namespace (all > names are documented w/ descriptors, there's not a lot of > '_' prefixed names cluttering the namespace) > o does *not* require a new dictionary/storage-object attribute > for the object (the descriptor works like any other > descriptor, a *stand-alone* object that replaces a regular > attribute) > > It's that last part that I'd like to have a function/method to > accomplish. That is, store (and obviously retrieve as well) attribute > values for objects, instances, types, classes, __slot__'d instances, > etceteras under a given name without triggering any of the __setattr__ > machinery which defers to the __set__ method of the associated descriptor. > > I can work around the problem by violating either of those two bullet > points under "finally, stores the value", but I'm looking for something > that *doesn't* violate them. See below for responses to particular > points... > I didn't grasp your precise problem but I've been having some similar problems (without metaclasses however). Two tricks: - Insert a dummy class into you heirarchy between object (or whatever other superclass that doesn't have the properties yet and the class where you install the properties. Then you might be able to use this class to access the underliying class dict without being intercepted by the properties. [I recall some problems with properties vs. super, didn't follow them closely]. - If you use __slots__, they are also implemented as properties. So if you define properties with the same name in the same class, you lose all access to the raw slots. The solution is similar: define __slots__ in a superclass, hide them with properties in a sublass. See http://www.technion.ac.il/~cben/python/streams.py for an example. HTH, Beni Cherniavsky From tim.one at comcast.net Wed Jul 2 11:02:17 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 2 Jul 2003 11:02:17 -0400 Subject: A possible bug in python threading/time module? In-Reply-To: Message-ID: [vm_usenet] > I've been running this segment of code (slightly simplified to > emphasize the main part): > > ----START of Script---- > > import time > import threading > > sem = threading.Semaphore(2048) > > class MyThread(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > sem.acquire() > > def run(self): > j = 0 > for i in range(1000): > j = j+1 > time.sleep(60) > sem.release() > > #main > for i in range(4096): > MyThread().start() > > ----END of Script---- > > I ran it on python 2.2.2 and python 2.3b1, and on both all of the > threads started successfully, acquiring the semaphore until 0 > resources were left. However, about 10-20 threads remain active after > a while (and the semaphore is lacking resources, respectively). I > waited for about two hours, and nothing changed - it appears to be > hanging. Did anyone encounter this behaviour before? > Am I the only one who ran into this situation? Is this a bug? If you run "enough" threads, chances are high you'll eventually run into a platform thread bug on any platform -- but into different platform bugs on different platforms. You didn't say which OS or platform thread library you were using, and those are probably the only things that matter. Here's a simplified and generalized minor rewrite of the above, with a comment about what happens under Win2K and 2.3b2. I've got no interest in chasing it down, since it's hung in the bowels of a Windows DLL and there's no evidence of a Python bug: """ import time import threading # One thread hung at the end on Win2K at N == 2011. # No problem if N < 2011. N = 2011 sem = threading.Semaphore(N) class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) sem.acquire() def run(self): time.sleep(5) sem.release() for i in range(2*N): MyThread().start() """ From mwilson at the-wire.com Wed Jul 23 13:45:16 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 23 Jul 2003 13:45:16 -0400 Subject: The global statement References: Message-ID: In article , "David Hitillambeau" wrote: >On Wed, 23 Jul 2003 16:56:08 +0200, Thomas G?ttler wrote: > >> If foo and bar are in the same file, >> you don't need the "global". > >Then when is "global" required? What is it's role? More to the point, maybe (although it doesn't do much): global_var = 27 def f1(): global global_var if global_var % 2 == 1: global_var = 3 * global_var + 1 def f2(): global global_var while global_var % 2 == 0: global_var /= 2 def f3(): return (global_var != 1) while f3(): print global_var, f1() print global_var, f2() print global_var where f1 and f2 will behave very differently if the `global` statements are removed. Normally, any time code inside a function assigns to a symbol, it does it in the functions local namespace. In these cases, there'll be a compiler error. Because f3 doesn't assign to global_var, it doesn't need the `global` statement. That is, the *only* global_var that f3 could possibly access is the "global" one. You could include a global statement for documentation's sake if that were your taste. And of course global_var is local as far as the `print` statements are concerned. Regards. Mel. From jdhunter at ace.bsd.uchicago.edu Mon Jul 14 22:31:58 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 14 Jul 2003 21:31:58 -0500 Subject: Open MS Excel Spreadsheet with Python In-Reply-To: (Sybren Stuvel's message of "15 Jul 2003 01:44:06 GMT") References: Message-ID: >>>>> "Sybren" == Sybren Stuvel writes: >> I think I'm missing something fairly fundamental, but I've >> googled all over the place and can't seem to find anything very >> introductory about opening and using data from MS Excel using >> Python. Probably are. Do you use http://groups.google.com to search the archives of this mailing list? If you go there, and search for excel group:*python* you'll likely find everything you need to know. In a nutshell, using the win32 extensions you can access excel directly. On other platforms, you'll probably need to go with an xl->csv converter, and then either parse the csv yourself or use the excellent csv module (http://object-craft.com.au/projects/csv); note that a csv module will be standard with the python library as of python 2.3. If you decide to go this route, let me know: I do a lot of XL->CSV work in python and have a few utility functions that may come in handy. JDH From richardc at hmgcc.gov.uk Wed Jul 16 10:53:55 2003 From: richardc at hmgcc.gov.uk (richardc) Date: Wed, 16 Jul 2003 15:53:55 +0100 Subject: Python Quiz References: Message-ID: <3f156704$1@mail.hmgcc.gov.uk> Sorry, I didnt mean to suggest for a second that Python's use of indentation (ws), is a problem or in any way a labour of love like FORTRAN's. "Michael Chermside" wrote in message news:mailman.1058359706.27031.python-list at python.org... SNIP > Definitely NOT. Without addressing the question of HOW Python came by the > idea of using indentation to indicate block structure, it clearly couldn't > have been from Fortran, because what Python does and what Fortran does > are COMPLETELY different. Very true, but to say that FORTRAN and Python have nothing in common would also be untrue. They both use ws to delimit syntatic elements, not the same elements but use it in a very different way to most other languages. I admit that Python probley gained no insiration from FORTRAN and any 'similarities' are coincidental. > There's also the fact that "lines" (statements) are defined by line breaks > in Python -- but I rarely hear complaints about this, since most programmers > mentally chunk up code into "lines" anyway. No complaints there > Of course, I'm not suggesting that whitespace is *meaningless* in Python > outside of indentation... should hope not Please dont misinterprit my post as an attack on Python, whilst Im a old-hat C++ programmer and first time I looked at Pythno I thought... urggh, no brackets thats horrid. After a bit better look, I love it. Like everything it has its place. Sorry if I upset anyone... I know FORTRAN's bad, but its not that bad... erm, actually mabe it is ? As for OCCAM, I havent programmed in that for years, that was fun *lost in fond memories* Rich From max at alcyone.com Thu Jul 3 20:22:39 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 03 Jul 2003 17:22:39 -0700 Subject: Why so many references to global variables? References: <0S2Na.6305$bD1.721957@news20.bellglobal.com> Message-ID: <3F04C8CF.DE38E6D0@alcyone.com> J-P wrote: > Well, sys.getrefcount() does tell me there are 3 millions references > to it and other globals. Even though this doesn't eat up all my memory > (how large is a reference object in Python?), ... Reference counts are just maintained internally with a single number that's incremented or decremented. > I definitely think > there's > something fishy with keeping that many references to global variables > that appear here and there in the script. Yes, it does. It strongly suggests that the fishiness is in your C extension. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Now I must follow them! \__/ Beowulf, King of the Geats From yaipa at yahoo.com Sat Jul 26 22:26:24 2003 From: yaipa at yahoo.com (yaipa h.) Date: 26 Jul 2003 19:26:24 -0700 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> Message-ID: <6e07b825.0307261826.5c83c47a@posting.google.com> Vincent, You don't list Webware oddly enough. I have been using it with the Cheetah templating engine. Works fine, with good support. Python 9 White Paper on Webware -------------------------------- http://www.python9.org/p9-cdrom/index.htm Cheetah dev page ---------------- http://www.cheetahtemplate.org/ Cheers, --Alan vincent_delft wrote in message news:<3f23003f$0$266$ba620e4c at reader0.news.skynet.be>... > I'm looking for a Web Tool kit to build web pages with the following > criteria (in priority order) : > - easy to use, develop (reuseability of code, ...) > - flexible (ideally should run with Python CGIHTTPServer and/or with Apache > (with or wihout mod_python) > - possibility to have load balancing and/or caching (for very high loaded > web pages) > > I've founded lot of tools ... > > I've read the doc of most of them, I've tested some of them. > But, is there anyone "experienced user" who can give the pro-cons for each > of those solutions ? (or propose an another) > > Is there a site who list the main charateristics of each of those Web tool > kit ? > > Thanks > > > Zope (www.zope.org), > SkunkWeb (http://skunkweb.sourceforge.net/), > Quixote (http://www.mems-exchange.org/software/quixote/), > Twisted (http://www.twistedmatrix.com/) > Albatross (http://www.object-craft.com.au/projects/albatross/) > Cherrypy (...) > pwo (...) > ... From glenfant at NOSPAM.bigfoot.com Tue Jul 1 08:00:38 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Tue, 1 Jul 2003 14:00:38 +0200 Subject: PyQT and Mandrake 9.1 Message-ID: Hi, I've been very excited by PyQT evangelists. But I'm stuck installing this (SIP + PyQT) on my new Mandrake 9.1. (Python 2.2.2) I downloaded SIP + PyQT from their latest address... http://www.riverbankcomputing.co.uk/ Then the SIP builder (build.py) asks for the path to QT header files. I didn't find them in the classical /usr/include, nor "locate" did find anything like "qt*.h" and there is no qt-develxx.rpm "like" in the 3 Mandrake CDs. Did I miss something ? Thanks in advance. --Gilles From Andreas.Ames at tenovis.com Tue Jul 22 07:10:21 2003 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Tue, 22 Jul 2003 13:10:21 +0200 Subject: weakref and thread safety (in python 2.1) Message-ID: <788E231C269961418F38D3E360D1652526C9CB@tndefr-ws00021.tenovis.corp.lan> Hi all, I'm using python 2.1 and can't easily upgrade (Zope). I'm using the Queue module to synchronize/communicate between two threads and weakref.proxy objects to avoid cycles. Scenario: thread1: - is the sole consumer (non-blocking get) - holds the reference to the queue thread2: - is the sole producer (blocking put) - holds a weak reference to the queue I've noted that, when thread2 incidentally blocks on the queue (because it's full), while thread1 deletes the queue, the weak reference isn't deleted and thread2 keeps blocking forever. I came up with the following destruction scheme for the queue (within thread1; q is the 'strong' ref to the queue), which *seems* to solve my problem (as of some preliminary tests): qw = weakref.proxy(q) # a second weak reference (this time within # thread1) del q try: qw.get_nowait() # if thread2 blocks on the (weakrefed) queue, # qw still exists here; the get_nowait() call # wakes thread2 up. I *hope* that its # weakreference will be destroyed when it can # block again in its next call to put() # (leading to a weakref.ReferenceError) except: pass Is this thread-safe? I don't know enough about the implementation of the weakref module to decide if it is guaranteed that thread2's weak reference to the queue will be destroied *before* thread2 can call 'put()' (or rather before thread2 can block) for the next time. Can someone more knowledgeable help me out please? TIA, andreas From gh at ghaering.de Wed Jul 9 09:00:33 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Jul 2003 15:00:33 +0200 Subject: format discs. In-Reply-To: References: Message-ID: <3F0C11F1.4000405@ghaering.de> Taka wrote: > On Wed, 09 Jul 2003 06:26:38 +0000, Flanagan wrote: >>hello to all >> >>somebody can say to me whereupon I modulate of python I can format >>discs. >> >> >>thanks flanagan > > Let's presume you want to format a unix partition and that it is > /dev/hda1. > The do this: > > #!/bin/python > > import os > partition = open ('/dev/hda1', 'w') > > for x in range(os.path.getsize('/dev/hda1'): > partition.write ('0') > > partition.close() > > > :) Didn't you mean ;-) instead of :) ? Your approach is hard to beat in inefficiency. -- Gerhard From max at alcyone.com Mon Jul 21 20:08:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 21 Jul 2003 17:08:16 -0700 Subject: Automatically filling in answers to interactive shell command questions References: Message-ID: <3F1C8070.787A7293@alcyone.com> Ted Weatherly wrote: > Is it possible to use python to automatically fill in the answers to > interactive shell command questions? For example, I am using a shell > command addperson that behaves as follows: > > > addperson > First Name: Ted > Birthday: 12/08/1977 > Height: 6'0" > Location: San Francisco, CA > > > > I am prompted for "First Name: " and I enter "Ted". I am prompted for > "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 > people or more...it gets tiresome. > > Assuming I can't change the addperson command to read data from a > file, is there any way to use python to fill in the data for the > expected questions? Perhaps a different language would be better? expect was designed for this. If the addperson program doesn't require an interactive shell, you can get away with it with something as simple as: addperson < <221d8dbe.0307272345.63503afd@posting.google.com> <221d8dbe.0307290635.fea912d@posting.google.com> Message-ID: srijit at yahoo.com wrote: [snip] > I was just wondering that if Python has to be compatible to MS.NET > does it mean > that > > 1) Python should be re-written C# like Jython has been written in > Java ? > > But my bigger concern is about the term "Portability". More than > OS, it looks like frameworks/VMs (.NET and Java ) are getting more > dominant today. > > So for middleware like Python (though Python script runs on its > own VM) should be compatible with both the frameworks in order to > remain practically portable. > Of the two frameworks mentioned (MS .Net and Java) we already have Python in Java. So, before doing Python in/on MS .Net it would be worthwhile to ask whether Python in Java (Jython) has succeeded. In order to answer that, we need to specify what we mean by success. My belief is that Jython has succeeded in producing usable code. But, is it used? And, does it result in Python being more popular? Are there projects and project groups out there that had a requirement to work with Java but chose to do their work in Jython rather than Java. And, of those that did so, were these projects successful. Was using Jython a net gain over using Java itself? Or, eventually, did they re-write all the Python code in Java? Or, did they wish they had? Or, did they leave behind code that was a burden to Java developers that came after them? Or, ... I'd choose Python. But, I'm a Python zealot. Ask yourself this question: Would a consultant or contractor who had no ideological commitment to Python (which I do) choose to work in Jython over Java, and why? And, if you cannot come up with positive answers to the above questions (positive for Python/Jython), then why should anyone do Python in MS .Net? One additional consideration is that a consultant/contractor can bill more hours if Java is used than they can if Python/Jython is used, because development in Java is slower than development in Python. So, why would the consultant/contractor choose Python over Java? I'd like to hear that Jython has been enormously successful at making in-roads into the Java world, but I'm skeptical. Oh, and on comp.lang.perl, do you think they worry that Perl will die if it does not play well in the Java and in the MS .Net worlds? - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From alanmk at hotmail.com Thu Jul 17 10:48:37 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 15:48:37 +0100 Subject: list() coercion References: Message-ID: <3F16B745.9CF3EF54@hotmail.com> Ian Bicking wrote: >>> However, list() seems to call the object's >>> __len__, >>> >>> Is there a way I can keep this from happening? Greg Ewing: >> Give your object an __iter__ method that returns >> itself. Ian Bicking wrote: > I'm not clear on how that will help...? > > It already does have an __iter__ method, but it returns a separate > iterator. Just to be explicitly clear 1. You're retrieving record sets from a database. 2. You want to build a list from the database results, one list entry for each result row. 3. You don't want to have the list preallocated (thus requiring invocation of __len__()), because the time saving is not worth it (compared to the cost of the SQL count() operation), since you're going to be iterating over the record set anyway. Therefore, use an iterator to build up the list. This will not call __len__(). Instead, the list will continually be appended to, until the iterator raise StopIteration. The list may be re-allocated multiple times, as the number of records retrieved exceeds the allocation unit size of lists. But this will likely still be lower cost than your SQL count(). The object returned from the __iter__() method should have a .next() method which returns the next row in your result set. So if you have implemented a .next() on your result set object, define your __.iter__() method as follows class ResultSet: def next(self): "Pseudocode" result = databasecursor.fetchone() if result: return result else: raise StopIteration def __iter__(self): return self Have I understood the problem correctly? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ted at REMOVE_THIS.sendmail.com Tue Jul 22 14:16:24 2003 From: ted at REMOVE_THIS.sendmail.com (Ted Weatherly) Date: Tue, 22 Jul 2003 11:16:24 -0700 Subject: Automatically filling in answers to interactive shell command questions References: <3F1C8070.787A7293@alcyone.com> Message-ID: Thanks for all the useful suggestions! I tried both approaches, piping to STDIN using 'addperson < person.data' and using a pexpect script (below), and both work well. Using pexpect hides all the STDOUT text, and piping to STDIN displays the STDOUT text (but doesn't show the answers provided). Some of the questions for my 'addperson' command are conditional...ie. sometimes 'Birthday: ' is asked and sometimes it isn't. Therefore, pexpect is a better fit for me. Thanks again! -Ted PS> The actual command I was using is different. Regardless, this python script should do the trick (it might have some minor flaws): #!/usr/bin/env python # addperson.py """This automatically answers questions when running addperson """ import pexpect import re # Store list of answers about each person answers = [ ['Ted', '12/08/1977', '6\'0"', 'San Francisco, CA'], ['Jesus', '12/25/0000', '6\'2"', 'Bethleham'], ['Satan', 'n/a', 'n/a"', 'Hell'], ] # Iterate over all the people for a in answers: done = 0 child = pexpect.spawn ('/usr/sbin/addperson') # Iterate over all the questions for the command while not done: i = child.expect (['First Name: ', 'Birthday: ', 'Height: ', 'Location: ']) if i>=0 or i<=3: # Send answer for this question child.sendline (a[i]) #print 'Answered question #'+str(i+1) if i==3: done = 1 print 'Done with'+str(a[0]) "Erik Max Francis" wrote in message news:3F1C8070.787A7293 at alcyone.com... > Ted Weatherly wrote: > > > Is it possible to use python to automatically fill in the answers to > > interactive shell command questions? For example, I am using a shell > > command addperson that behaves as follows: > > > > > addperson > > First Name: Ted > > Birthday: 12/08/1977 > > Height: 6'0" > > Location: San Francisco, CA > > > > > > > I am prompted for "First Name: " and I enter "Ted". I am prompted for > > "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 > > people or more...it gets tiresome. > > > > Assuming I can't change the addperson command to read data from a > > file, is there any way to use python to fill in the data for the > > expected questions? Perhaps a different language would be better? > > expect was designed for this. If the addperson program doesn't require > an interactive shell, you can get away with it with something as simple > as: > > addperson < Ted > 12/08/1977 > 6'0" > San Francisco, CA > EOF > > Or by putting these one per line in a file, > > addperson < people.data > > One certainly _could_ use Python for this, but in this case there are > probably better (and much simpler) tools for the job. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > / \ Behind an able man there are always other able men. > \__/ (a Chinese proverb) From mwh at python.net Mon Jul 21 12:31:32 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 21 Jul 2003 16:31:32 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) References: Message-ID: <7h3ispvzw4f.fsf@pc150.maths.bris.ac.uk> Scott Schlesier writes: > On Mon, 21 Jul 2003 09:58:19 -0000, Irmen de Jong > wrote: > > Am I experiencing a "technical difficulty", or are all of the links > below broken? I think there's been some quoted-printable nagery happening. Cheers, mwh -- LINTILLA: You could take some evening classes. ARTHUR: What, here? LINTILLA: Yes, I've got a bottle of them. Little pink ones. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From tim.one at comcast.net Fri Jul 18 18:29:47 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 18 Jul 2003 18:29:47 -0400 Subject: Threading Pool Event() In-Reply-To: Message-ID: [Graeme Matthew, to Aahz] > Thanks, ive actually been using your OSCON slides which have helped a > lot. So it technically correct that all worker threads in a thread > pool are either doing some work or polling the queue to find out if > there is a job to process ? They don't poll in the sense most people use that word: > eg: (pseudocodish :-)) > > def run(self): > > while 1: > > self.lock.acquire() > > if QueueManager.HasJob: > job = QueueManager.GetFreeJob() > __processJob(job) > > self.lock.release() I agree that's what most people mean by polling: running a "spin loop", checking over and over again, possibly with a time.sleep() call per iteration to avoid saturating the CPU. That's not what Queue.get() does, though! You can find the source code in Lib/Queue.py. When .get() is called without a timeout argument, it simply tries to acquire a particular internal lock. If you dig into that deeply enough, you'll eventually find that if the thread can't acquire the lock immediately, in the bowels of your C library and/or operating system it goes to sleep, and passively waits for a platform-specific gimmick to wake it up again when the lock it's waiting for gets released. No looping is involved (well, none at the Python level -- your C library and/or OS may have an internal loop, although in no case should a thread waiting on a Queue.get() consume appreciable CPU time). From jeremy at alum.mit.edu Tue Jul 15 12:46:48 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 15 Jul 2003 12:46:48 -0400 Subject: Mix lambda and list comprehension? In-Reply-To: <6f5b3f88.0307150732.1b0a2526@posting.google.com> References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> <6f5b3f88.0307150732.1b0a2526@posting.google.com> Message-ID: <1058287608.18967.102.camel@slothrop.zope.com> On Tue, 2003-07-15 at 11:32, Peter Barth wrote: > Thanks a lot, works fine. > However, the solution does not really feel "pythonesque". > Is it considered a usability bug or fine as is? If there's something that's not Pythonesque, I'd say its creating function objects inside a list comprehension, not the standard scoping rules that apply everywhere. Jeremy From Juha.Autero at iki.fi Thu Jul 31 07:00:54 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Thu, 31 Jul 2003 14:00:54 +0300 Subject: Python speed vs csharp References: Message-ID: <87n0ev7yft.fsf@jautero.no-ip.org> Mike writes: > Since the test case code was fairly small, I > translated it to C and ran it. The C code runs in approximately 7.5 > seconds. That's compelling, but C isn't: part of my simulation includes a > parser to read an input file. I put that together in a few minutes in > Python, but there are no corresponding string or regex libraries with my C > compiler, so converting my Python code would take far more time than I'd > save during the resulting simulations. So, write only most executed parts with C as C extension to Python. This is the reason I like Python. If your program is not fast enough, you can implement critical functions with C. For example the error function would be very simple to turn into an C extension module using "Extending and Embedding the Python Interpreter" document from . There are several tools that make writing C extensions easier. I've used SWIG and Pyrex. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From frank at chagford.com Thu Jul 10 10:13:52 2003 From: frank at chagford.com (Frank Millman) Date: 10 Jul 2003 07:13:52 -0700 Subject: Business model for Open Source - advice wanted Message-ID: <246a4e07.0307100613.fc2fc50@posting.google.com> Hi all I would like some advice, and I hope that the good people on c.l.p will give me the benefit of their experience. I am busy developing an accounting package, using Python and wxPython, together with PostgreSQL on a Unix platform or SQL Server on a Windows platform. I am a qualified accountant and have been developing accounting software, mostly customised, for over 20 years. I have now got myself into a position financially where I can take a few months off and write "the perfect system". No, not really, but I have built up a lot of experience over the years, I have a lot of ideas about what I would like to see in a system, and I have decided to give myself the opportunity to see how good a system I can actually write. At some point quite soon I will have to start generating some revenue from my efforts. I have a number of people interested in what I am doing, and I was planning to start selling it as YAAS (yet another accounting system) and see how many customers I could get. As an alternative, I have been toying with the idea of releasing it under an Open Source license. Part of my thinking is to put something back into the Open Source community - I love working with Python, wxPython, PostgreSQL, etc, and it would be nice to contribute something. The other part of my thinking is that it should be possible, with a sound business model, to make a viable income out of supporting an Open Source product. However, as I have no experience of this, I was wondering how other people survive financially in the Open Source world. I have no "big daddy" that will pay me to pursue my dreams, so whatever I do has to bring in a reasonable income. Here are some of my ideas - any comments will by much appreciated. The essence of a business model must be that the source code may be free, but you have to pay for support. I believe that accounting systems more than most systems need support, and that a sensible company looking for accounting software would not consider anything that was not supported. Therefore it is important to decide what kind of support should be offered, and how to persuade customers to sign up for it. The software must be downloadable and runnable by anyone, and it must be fully functional, at no charge. I realise that there is an option to restrict functionality in the free version and make it available only to licensed users, but then you are into security codes, source code protection, etc, which would at least partially defeat the object, so I am not thinking along those lines. There will be full online help (it will probably start off sketchy, but I will improve it over time), and maybe there should be an FAQ available. That, I think, is all that should be free. I would like to open a free discussion forum (probably a mailing list) to discuss the software from a technical perspective. I am an experienced programmer, but I am nowhere near being a Pythonista, so I am sure there will be many areas ripe for improvement. I would like to remain open to as much of this kind of feedback as possible. However, any support of the software from a business or accounting perspective will be available to registered users only. For a monthly support fee (I am thinking of a range of $50-100 per month - let me know if it is too high or too low) users will be able to request support via email, which will be responded to promptly. I have a small staff at present, and if this idea is successful I will plough money back into expanding the support infrastructure. To retain registered users once their software has settled down, I have in mind a website restricted to registered users which will provide sufficiently interesting content to persuade them to keep up their registration. The main content I can think of is enhancement requests - it is the nature of accounting software that there is a continuous demand for enhancements, and I intend to keep on enhancing and improving the product. I envisage a forum where users can forward ideas, and others can respond/comment/criticise until there is some consensus. A roadmap of agreed enhancements can be posted on the free website, which will hopefully attract more users into signing up so that they can participate. Here are a couple of pitfalls that I can see, and my possible solutions to them. Firstly, a user will be able to terminate his support contract at any time, and the software will continue to function. Therefore some may be tempted to stop paying until they have a problem, then pay for a month, get an answer, and stop again. My thinking is that 3 months must be paid up front to activate a support contract. Secondly, a consultant may use my software to build up a client base, pay a single support fee, and use that to support all his clients. I don't think I can (or even want to) prevent that, but I can restrict it by limiting each contract to a single email address for replies to support queries. These are my thoughts so far. Any comments - suggestions, warnings, personal experiences - will be much appreciated. Many thanks Frank Millman From max at alcyone.com Sun Jul 27 19:31:19 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 27 Jul 2003 16:31:19 -0700 Subject: file.close() References: <2inav-q64.ln1@beastie.ix.netcom.com> Message-ID: <3F2460C7.44B8B046@alcyone.com> Dennis Lee Bieber wrote: > Hallvard B Furuseth fed this fish to the penguins on Friday 25 July > 2003 12:51 pm: > > > Um. Explicit close does raise an exception if it fails, right? > ... > Looks like it doesn't care... As long as the file /had/ been > opened > first (doesn't look like the interactive interpreter collected f until > the del either). I don't think you've demonstrated that; all you've shown is that builtin Python file objects make file closing idempotent. You haven't demonstrated a case where there actually is an I/O error that occurs when .close gets called. In particular, I _really_ don't know what you meant to show with this snippet, as it really has nothing to do with files at all: > >>> f > > >>> del f > >>> f.close() > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'f' is not defined -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ He who knows how to be poor knows everything. \__/ Jules Michelet From eichin at metacarta.com Mon Jul 21 20:22:53 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 21 Jul 2003 20:22:53 -0400 Subject: pythonic malloc References: Message-ID: <7g1xwjqujm.fsf@pikespeak.metacarta.com> I was going to suggest struct.pack: >>> import struct >>> struct.pack(" Hello, Forgive my python newbieness. Assume I have a list named heck_of_a_list. how would I extract the number of elements out of it ? (I'm looking for something like perl's $#heck_of_a_list operand) thanks B -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Wed Jul 16 10:36:19 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2003 14:36:19 GMT Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED_Fue?= References: <3F130ED4.2030804@skynet.be> <3F13C137.6090705@igpm.rwth-aachen.de> Message-ID: On Tue, 15 Jul 2003 10:54:15 +0200, "Helmut Jarausch" wrote: >Fredrik Lundh wrote: >> Helmut Jarausch wrote: >> >> >>>OK, I believe to know why the last line >>>print '3' three times, since only a reference >>>to 'f' is stored within the lambda expression >>>and this has the value 'thrice' when 'print' >>>is executed. >>> >>>But how can I achieve something like an >>>evaluation of one indirection so that >>>a reference to the function referenced by 'f' >>>is stored instead. >> >> >> assuming you meant "the function reference by 'f' when the lambda >> is created", the easiest solution is to use default argument binding: >> >> flam = [lambda x,f=f: f(x) for f in funcs] >> >> the "f=f" construct will bind the inner name "f" to the current value of >> the outer "f" for each lambda. >> >> the nested scopes mechanism is often introduced as the "right way" to >> do what was done with argument binding in earlier versions of Python. >> however, nested scopes bind *names*, while argument binding binds >> *values*. > >Many thanks for that hint, >still a part of the question remains (unclear to me) > >Obviously Python allows references to references, since >e.g. 'once' (the 'name' of a function) is a reference to >the code and 'f' is a reference to that reference. (you call it >name binding) >A similar situation arises in Maple and there one has the choice >to either derefence all references down to the real object >or to just derefence a single time. > >Example > >def once(x): return x >def twice(x): return 2*x >ref= once >def caller(): > callee=ref # (*) > print callee(1) > >caller() # prints 1 >ref= twice >caller() # prints 2 so that demonstrates name binding > >how can I get the current value (like 'xdef' in TeX) >of 'ref' in the assignment (*) above, so that >'callee' becomes an (immutable) reference to 'once' ? > IWT the straight-forward way would be to capture ref in a callable class instance: >>> def once(x): return x ... >>> def twice(x): return 2*x ... >>> class Caller(object): ... def __init__(self): self.callee = ref # global ref at time of init ... def __call__(self): print self.callee(1) ... >>> ref = once >>> caller = Caller() >>> caller() 1 >>> ref = twice >>> caller() 1 >>> caller2 = Caller() >>> caller2() 2 >>> caller() 1 You could also make a factory function that captures ref using a closure: >>> def ffun(): ... callee = ref ... def caller(): print callee(1) ... return caller ... >>> ref = once >>> caller = ffun() >>> caller() 1 >>> ref = twice >>> caller_twice = ffun() >>> caller_twice() 2 If you just wanted the first-used ref to be "sticky," you could do something kludgy: (note that this pospones capturing ref until the first call vs class instance creation or ffun call) >>> def caller(): ... if not hasattr(caller,'callee'): setattr(caller,'callee',ref) ... print caller.callee(1) ... >>> ref = once >>> caller() 1 >>> ref = twice >>> caller() 1 You can "unstick" it and have it stick again: >>> del caller.callee >>> caller() 2 >>> ref = once >>> caller() 2 Regards, Bengt Richter From bignose-hates-spam at and-zip-does-too.com.au Tue Jul 22 01:27:35 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 22 Jul 2003 15:17:35 +0950 Subject: Python bug with dictionary References: <3F1C84F4.3B1E4F9A@n.com> Message-ID: On Mon, 21 Jul 2003 20:27:32 -0400, none wrote: > class Dict: > items = {} > name = "" These attributes belong to the class, and are not distinct between instances. (For the same reason, all the functions you define in the class become methods, shared between all instances.) If you want each instance to have attributes distinct from other instances, set them during the instance's initialisation: ===== >>> class Foo( object ): ... def __init__( self, name = None ): ... self.items = {} ... self.name = name ... def addItem( self, item ): ... self.items[ item.name ] = item ... >>> class Bar( object ): ... def __init__( self, name = None ): ... self.name = name ... >>> bar1 = Bar( "bar1" ) >>> bar2 = Bar( "bar2" ) >>> bar3 = Bar( "bar3" ) >>> bar4 = Bar( "bar4" ) >>> >>> foo1 = Foo( "foo1" ) >>> foo2 = Foo( "foo2" ) >>> >>> foo1.addItem( bar1 ) >>> foo1.addItem( bar2 ) >>> >>> foo2.addItem( bar3 ) >>> foo2.addItem( bar4 ) >>> >>> foo1.name 'foo1' >>> foo1.items.keys() ['bar1', 'bar2'] >>> >>> foo2.name 'foo2' >>> foo2.items.keys() ['bar3', 'bar4'] >>> ===== I've also changed two other things: don't name objects (of any kind) after reserved words like "dict", you'll just lead to confusion. Don't bother with redundant getBlah() and setBlah() methods; just access the attributes directly, using __getitem__() and __setitem__() in the few cases where you actually need to intervene. -- \ "[The RIAA] have the patience to keep stomping. They're playing | `\ whack-a-mole with an infinite supply of tokens." -- kennon, | _o__) http://kuro5hin.org/ | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From alex_eberts at videotron.ca Mon Jul 14 11:46:38 2003 From: alex_eberts at videotron.ca (Alexander Eberts) Date: Mon, 14 Jul 2003 11:46:38 -0400 Subject: Accessing an instance's __init__ args from outside the class Message-ID: I'm new to python so appologies to the group if this question is asked often. I'm wondering if it's possible to query an object instance to find out what arguments the instance's __init__ function was called with from *outside* the class's local namespace. For example, if I define a class Foo as follows: import sys class Foo: def __init__(self, *args): print args # no problem here ...and then create an instance of Foo: >>> someobj = Foo('bar', 'bleck') ('bar', 'bleck') Now, I'd like to be able to find out what arguments someobj was called with. So first I tried: >>> print someobj.args but I get: "AttributeError: args" so then I tried: >>> print some_obj.__init__.func_defaults which returns an empty tuple and then I tried: >>> some_obj.__dict__['args'] Traceback (most recent call last): File "", line 1, in ? KeyError: args No dice.. Is there any way to find out what arguments an object was called with? Are the args stored with the instance? I scoured the python faq but there are no answers (that I could see) to this question. Any help would be much appreciated. yours, Alex Eberts From adechert at earthlink.net Tue Jul 29 18:57:15 2003 From: adechert at earthlink.net (Alan Dechert) Date: Tue, 29 Jul 2003 22:57:15 GMT Subject: Voting Project Needs Python People References: <5ab0af73.0307211623.6e12f807@posting.google.com> <84fc4588.0307290514.54d68563@posting.google.com> Message-ID: Thank you Anand, I am forwarding your message to our list. Alan "Anand Pillai" wrote in message news:84fc4588.0307290514.54d68563 at posting.google.com... > I am ready to join this project. As for knowing python I guess > I do. > > Before you take my word for it take a look at my homepage > at http://members.lycos.co.uk/anandpillai. > > I dont need money, just free beer and pizza ;-) (joking) > > ~Anand > > > "Alan Dechert" wrote in message news:... > > "Matt Shomphe" wrote in message > > news:5ab0af73.0307211623.6e12f807 at posting.google.com... > > > "Alan Dechert" wrote in message > > news:... > > > > > > > We have an excellent team together. We're looking for a few good Python > > > > coders willing to volunteer for this free open source project. It will > > be > > > > on sourceforge.net later today. > > > > > > Are there any prerequisites for joining the team? > > > > > It would be nice if you know some Python. Do you? > > > > BTW, I'm told it will take a day or two to get the project going on > > sourceforge.net. > > > > Alan Dechert > From bokr at oz.net Mon Jul 28 16:00:39 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 20:00:39 GMT Subject: Readling all input from stdin References: Message-ID: On Mon, 28 Jul 2003 13:25:33 +0200, Svenne Krap wrote: >Hi. > >I am writing a small script, that is called from an external program >(the qmail mailserver), I need to capture all input from stdin before >continueing the script .. > >I looked for sys.stdin.readlines() but that is not present. I found >sys.stdin.readline(), but how do I loop through it (or rather how do I >know, when I am finished with looping ?) > >Thanks in advance > ====< stdinlines.py >======================================================= import sys data = sys.stdin.read() for line in data.splitlines(True): # keeps \n ends. (False) or () would not print repr(line) # to see all chars represented ============================================================================ (I have a cat on my NT that copies stdin to stdout in text mode until it sees ^Z as EOF): [13:00] C:\pywk\clp>cat | python stdinlines.py trimmed three spaces to left three spaces to right three spaces both sides next line is empty last line with no EOL^Z 'trimmed\n' ' three spaces to left\n' 'three spaces to right \n' ' three spaces both sides \n' 'next line is empty\n' '\n' 'last line with no EOL' Regards, Bengt Richter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 29 18:25:59 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 00:25:59 +0200 Subject: Bottleneck: easy obscurity "encryption" via xor In-Reply-To: References: Message-ID: <3f26f477$0$49098$e4fe514c@news.xs4all.nl> Tino Lange wrote: > It turns out not to be quick at all. I really didn't expect this to be > a bottleneck, but it takes quite some time. >> return reduce(lambda x,y: operator.add(x, chr(y)), map(lambda char, _salt = salt: operator.xor(ord(char), _salt), str), "") Running this on a large string builds up a huge list of ints, that you are converting to chars and then concatenating them together using +... this creates a HUGE number of temporary string objects. The usual pattern of fast string joining is: ''.join(list-of-fragments) So first try: return ''.join(map(lambda char, _salt = salt: chr(operator.xor(ord(char), _salt)), string)) This runs MUCH faster already. But the version I'd recommend is: def xorcrypt(string, salt = 255): if salt <0 or salt> 255: raise "Invalid salt! Must be 0<=salt<=255!" return ''.join( [ chr(ord(c) ^ salt) for c in string ] ) because 1) salt must be 0..255 not only <=255 2) forget about map & lambda, use a list comprehension. That implementation runs about 20 times faster than your original one; 0.11 seconds for 100 Kb source data. (python 2.3) HTH, --Irmen de Jong From rastm2 at aol.commorespam Mon Jul 21 21:03:13 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 22 Jul 2003 01:03:13 GMT Subject: To ESR PLease fix links Message-ID: <20030721210313.03007.00000302@mb-m01.aol.com> Hi Eric, I've been quietly going around the web asking people to please fix the broken Tuxedo links to your pages as I find them. Hint.-- Hint-- http://www.catb.org/~esr/writings/cathedral-bazaar/ Your aware that many of the links in the books are still pointing to Tuxedo I'm sure. I also know how very busy you are. I really wanted to make an excuse for THANKing YOU for steering me to Python and programming in general with your "Hackers" page in 1997. I've been following that formula for 6-7 years now and hope that some day my H(obby)(abit) will pay off. So, I quietly remain in the shadows, reading everything you and other HEROs write. Coding my future. Thank you sincerely Ray St. Marie Rastm2 at aol.com From mwh at python.net Tue Jul 22 09:56:07 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Jul 2003 13:56:07 GMT Subject: [OT] On the TimBot References: <62slgvsljos7v5snie6toc4qucv5nt1n15@4ax.com> Message-ID: <7h3znj6y8nl.fsf@pc150.maths.bris.ac.uk> oren at REMOVETHIS1.hishome.net (Oren Tirosh) writes: > Christos "TZOTZIOY" Georgiou wrote in message news:<62slgvsljos7v5snie6toc4qucv5nt1n15 at 4ax.com>... > ... > > 3. To "Tron" fans: yes, you could assign the name TimBit to it, but it's > > a broken Bit; what's the use of a Bit that's always true? > > Henry Spencer is well known around the sci.space.* newsgroups for > being very rarely wrong. About as rarely as the TimBot. People that > manage to correct Henry get the coveted "I Corrected Henry" virtual > T-shirt. > > May I propose the "I Corrected Timbot" award? But Tim is never wrong: it's just that reality fucks up now and again. Cheers, mwh -- > Why are we talking about bricks and concrete in a lisp newsgroup? After long experiment it was found preferable to talking about why Lisp is slower than C++... -- Duane Rettig & Tim Bradshaw, comp.lang.lisp From printers at sendme.cz Thu Jul 3 05:10:15 2003 From: printers at sendme.cz (A) Date: Thu, 03 Jul 2003 11:10:15 +0200 Subject: How to setup webserver for Python Message-ID: <3F040F17.25697.E24EF9@localhost> Hello, I have a webhosting account with one company. I can use python from command line through Telnet(SSH) but can not run successfully Python program from a browser.(They use Apache web server.) What must I do? What permission must I set on directory and the python file? Here is a simple program I would like to run ######## #!/usr/bin/python print "Content-Type: text/html" print print"AAA" ######## Thanks for help Ladislav I look forward to hearing from you soon. Best regards, Ladislav Blazek( Mr.) BMA TRADING Ltd. email1: export at sendme.cz email2: export at bmatrading.com email3: exportimport at quick.cz Fax:/Tel +420 516 447921 Tel:+420 516 447920, Mobile:+420 602 849309 From grante at visi.com Thu Jul 17 12:24:56 2003 From: grante at visi.com (Grant Edwards) Date: 17 Jul 2003 16:24:56 GMT Subject: Reading from serial port & writing to X console References: Message-ID: <3f16cdd8$0$150$a1866201@newsreader.visi.com> In article , lec wrote: > I'm trying to write a program to read from the serial port & > write whatever that is read to the X console (/dev/tty7). For X > to recognize the characters sent, I believe you have to send > "scancodes". No. You can simply read /dev/ttyS0 and write to /dev/tty7: In shell: $ (stty 9600 -paren -ixon -ixoff; cat) /dev/tty7 Change the stty parameters as desired. In Python, just open /dev/ttyS0, /dev/tty7. Read from one and write to the other. There are a couple different serial port modules that wrap up serial ports into objects to hide the nasty termios stuff. Google the group for terms like PosixSeral PySerial. -- Grant Edwards grante Yow! Why was I BORN? at visi.com From ianb at colorstudy.com Wed Jul 2 01:49:36 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 02 Jul 2003 00:49:36 -0500 Subject: Circular Inheritance In-Reply-To: References: Message-ID: <1057124976.726.135.camel@lothlorien> On Tue, 2003-07-01 at 19:00, Ben Finney wrote: > Re-design the modules so that inheritance is a hierarchy. A band-aid > solution may be to create a new class that mediates between two others, > breaking the circle. Much better is to figure out why the classes need > to know so much about each other, and redesign them with smaller, > simpler interfaces. It seems quite reasonable to have circular dependencies between two or more classes. The most common case being that one class references the other, and the other class has back references. Very common, and it doesn't imply that the classes know too much about each other. You might encounter less problems if those classes go together in a single module, but module boundaries are just there to help the programmer organize code, they have little formal meaning. > Even if there were a way to do circular inheritance, it would be a > nightmare to understand, so needs to be redesigned anyway. He probably just meant circular dependency, since obviously inheritance doesn't make sense. Ian From fredrik at pythonware.com Thu Jul 31 12:02:57 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 31 Jul 2003 18:02:57 +0200 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: <67fdivk9iu0q1p7nc8smfj1miip3cbvobf@4ax.com> Message-ID: Aahz wrote: > (Despite my regular comments on python-dev, I don't contribute > code because SF refuses to make changes to allow Lynx to work > correctly.) maybe someone with an SF account could help you out? could it be worth setting up an aahz-helpers mailing list somewhere, manned by volunteers with SF access and modern browsers? From jjl at pobox.com Fri Jul 4 21:26:52 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Jul 2003 02:26:52 +0100 Subject: loading objects from ZODB References: Message-ID: <87brw93grn.fsf@pobox.com> "Gilles Lenfant" writes: > "Achim Domma" a ?crit dans le message de news: > be47oo$621$05$1 at news.t-online.com... > > I'm playing around with ZODB but I don't understand when objects are loaded > > from the DB. Assume I have an object containing a list of other objects. If > > this object is loaded from ZODB, when is the list filled? Only on demand? I > > think yes, because otherwise reading the top node would result in loading > > the whole database. But I wanted to be sure! BTrees (OOBTree, IOBTree, OITree, IITree) load contained objects on demand, most other data structures (including PersistentList and PersistentMapping) don't. > It seems you don't need to care about this. The persistence of objects is > (almost) transparent. > You get/set the objects through a transparent cache to the database. > The only rule : all objects must be picklable, and watch the doc about > _v_xxx and p_xxx attributes. That's not the only rule. Documentation is thin, of course. Andrew Kuchling's intro is required reading, as is Jim Fulton's (though the latter is particularly out of date, IIRC). There is some useful info on BTrees and associated data structures on the Zope wiki. John From ianb at colorstudy.com Sat Jul 5 00:57:42 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 04 Jul 2003 23:57:42 -0500 Subject: ANN: SQLObject 0.4 Message-ID: <1057381061.516.46.camel@lothlorien> SQLObject 0.4: http://sqlobject.org Changes ======= * New (cleaner) column definition style, including for foreign keys * Alternate naming conventions supported * Subclassing supported What Is SQLObject? ================== SQLObject is an object-relational mapper, translating RDBMS tables into classes, rows into instances of those classes, allowing you to manipulate those objects to transparently manipulate the database. SQLObject currently supports Postgres, MySQL, and SQLite. Links ===== Download: http://prdownloads.sourceforge.net/sqlobject/SQLObject-0.4.tar.gz?download Documentation: http://sqlobject.org/docs/SQLObject.html News: http://sqlobject.org/docs/News.html -- Ian Bicking ianb at colorstudy.com http://colorstudy.com PGP: gpg --keyserver pgp.mit.edu --recv-keys 0x9B9E28B7 From g2h5dqi002 at sneakemail.com Mon Jul 21 00:11:05 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 21 Jul 2003 16:11:05 +1200 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: References: Message-ID: Tony Meyer wrote: > What about non-English names? Names with umlauts, accents, Asian > characters, and so on? A chart of the Unicode characters on the wall, and a hex touchpad. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dtolton at yahoo.com Wed Jul 16 14:13:51 2003 From: dtolton at yahoo.com (Doug Tolton) Date: Wed, 16 Jul 2003 18:13:51 GMT Subject: Augmented Assignment question Message-ID: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> I have a function that returns a tuple: def checkdoc(self, document): blen = document['length'] bates = document['obates'] normal, truncated, semicolon = 0,0,0 for bat in bates: if len(bat) == 2 * blen: semicolon += 1 if len(bat) == blen - 1: truncated += 1 if len(bat) == blen: normal += 1 return normal, truncated, semicolon on the other side I have 3 variables: normal, truncated and semicolon I would like to be able to do an augmented assignment such as: normal, truncated, semicol += self.checkdoc(mydoc) however this returns the following error: SyntaxError: augmented assign to tuple not possible I did some reading and it seems that an augmented assignment is specifically verboten on tuples and lists. Is there a clean way to accomplish this? I dislike in the extreme what I've resorted to: fnormal, ftruncated, fsemicolon = 0,0,0 // loop through a file and process all documents: normal, truncated, semicolon = self.checkdoc(curdoc) fnormal += normal ftruncated += truncated fsemicolon += semicolon This solution strikes me as inelegant and ugly. Is there a cleaner way of accomplishing this? Thanks in advance, Doug Tolton dougt atcasedata dot com From bdesth.nospam at removeme.free.fr Fri Jul 25 16:19:19 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 25 Jul 2003 22:19:19 +0200 Subject: Static typing In-Reply-To: References: Message-ID: <3f218ef1$0$27926$626a54ce@news.free.fr> Michael Muller wrote: > Is there currently any plan to introduce static typing in any future > version of Python? Seriously, why would you do that ? Bruno From deets_noospaam at web.de Sun Jul 27 16:29:52 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2003 22:29:52 +0200 Subject: multithreading-problem References: Message-ID: Manish Jethani wrote: >> >> Placing a time.sleep(3) after the thread.start() fixed things. So it >> appears that the curried lambda passed as target is somehow a reference >> equal for all four invocations. > > No, I don't believe it to be true. It's probably just that the > other threads aren't getting a chance to run. Consider > time.sleep(0) in the while loop in work() No, they all run - just a few of them have the same parameters. In my real app, all of them do some work, which takes an individual amount of time. In the main-thread I wait for all of them to be terminated, and while doing that print how much are still running. All this works as expected. The only thing not working is the parameter passing. Diez From pedro.werneck at bol.com.br Sun Jul 20 10:30:55 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 20 Jul 2003 07:30:55 -0700 Subject: Tk mainloop() References: Message-ID: "Petr Evstratov" wrote in message > I need to change the contents of a label every second, but I think I will also use some other functions as well... Well... there are some docs here that you should read... http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm Note that if you want it to be continuousy called, you will need to re-register it on each call... From jjl at pobox.com Mon Jul 7 08:48:10 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Jul 2003 13:48:10 +0100 Subject: A story about Python... sort of References: Message-ID: <87wueu7bat.fsf@pobox.com> "Tony Meyer" writes: > > A chess program > > is different from a 3D game in that with a 3D game, you can > > stop at some point and say, "ok, this is fast enough." There [...] > This isn't really true. Sure you can say that the framerate is fast enough, > but when do you stop and say "the graphics look real enough"? (I'm sure > there is a point, but it's a distant point, like 'solving' chess). No matter how distant, it's nowhere near as far off as 'solving' chess (which is no doubt physically impossible, at least with classical (Turing machine) computation). John From hst at empolis.co.uk Thu Jul 31 11:53:44 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Thu, 31 Jul 2003 16:53:44 +0100 Subject: regular expression Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4E1@hendrix.empolisuk.com> Wiebke P?tzold wrote: > > Hi all, > > I wrote a little program. Here it is: > > import sys > import Mk4py > > db = Mk4py.storage("c:\\datafile.mk",1) > vw = db.view("people") > > def func(row): > try: > if row.Nachname[0:1]=='G': > return 1 > else: > return 0 > except AttributeError: > return 0 > > > vf = vw.filter(func) > > for r in vf: > print vw[r.index].Nachname,vw[r.index].Kongressbereich > > > I create a database that contains a table. 'Nachname' and > 'Kongressbereich' are special fieldnames. This program can search for > a special letter. In my example it is 'G'. and the search takes place > in 'Nachname'. > Mow I want to use regular expression. So that I can limit my search. > For example: I can search for Ge and it is not relevant wich letters > follow > Could somebody help me with this task? > > Wiebke > -- import re at the top of the program and replace your func function with (untested): compiled_pattern = re.compile('Ge') #match pattern is anything starting with 'Ge' def func(row): try: if compiled_pattern.match(row.Nachname): return 1 else: return 0 except AttributeError: return 0 _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From R.Brodie at rl.ac.uk Wed Jul 30 06:11:30 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 30 Jul 2003 11:11:30 +0100 Subject: mime types and vector graphics References: Message-ID: "Terry Hancock" wrote in message news:eomcnf5kxctp3LqiU-KYvg at august.net... > Well, that looks a lot like MIME content-types, but not quite. In > particular, MIME seems to have nothing to say about vector graphics (I > guess they must be in the "application" type?). But I'm not very > well-informed about MIME, so I wonder if my information is up-to-date. image/cgm is a registered MIME type, so I guess not. The RFC says something like - if you need a graphical output device to display it - it's an image. > How is SVG specified in MIME, for example? I've seen "image/svg" and > "image/svg+xml" and so on in a Google search, but one thing the web does > poorly is tell you what the date was on the page you're reading! :-O The trouble is that the W3C doesn't do MIME types, IANA does. IANA expect the format to be in wide use prior to assigning the type, which isn't a great fit for how the web works. So the answer is probably as image/svg+xml eventually. > When I want to add a vector type, such as DXF, for example, should I go > with: image/vnd.dxf (it's already registered) if it weren't I'd go with image/x-dxf > (or maybe something weird along the lines of the svg+xml stuff I saw above, > that looks frighteningly like adding a third layer in the MIME hierarchy). The +xml bit is a bit scary. The rationale is that you can do useful processing on a XML document (e.g browse the document tree) without any specific knowledge. From peter at engcorp.com Tue Jul 8 12:22:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 12:22:32 -0400 Subject: anything new on the ternary operator? References: Message-ID: <3F0AEFC8.B5B04C11@engcorp.com> Tor wrote: > > (if C: x else: z) > > Was this the winning syntax? http://tinyurl.com/763f > Why are the parentheses neccessary (and are they really)? Please don't reopen the discussion here, without at first reading the entire archive of the previous discussion. ;-) http://groups.google.ca/groups?th=45e47b6ed1fad306&seekm=mailman.1047355305.32469.python-list%40python.org#link1 -Peter From exarkun at twistedmatrix.com Tue Jul 15 20:01:46 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Tue, 15 Jul 2003 20:01:46 -0400 Subject: Curses module. In-Reply-To: References: Message-ID: <20030715235847.GA15654@intarweb.us> On Tue, Jul 15, 2003 at 07:03:33PM -0400, Alex wrote: > Hello all, > > I'm trying to learn Python, in particular the curses module. My system > is running Slackware 9.0 and the verion of Python that comes installed > with Slackware 9.0 is Python 2.2.2. > > I've been trying to access the curses.wrapper module without any > success. I know that the wrapper exists in /usr/lib/python2.2/curses yet > any reference that I make to it is rebuffed by the interpreter. > > Here's the python script I'm trying to run: > > [snip apparently correct code] > > This is the error message that I get when I try to run the script from > the CLI: > > Traceback (most recent call last): > File "./curses3.py", line 15, in ? > curses.wrapper(newWindow()) > AttributeError: 'module' object has no attribute 'wrapper' > > Any ideas as to what I could be doing wrong? > Do you, perhaps, have a file named "curses.py" in your current directory? If so, "import curses" will load this, and not the stdlib module. You could also try printing "curses.__file__" to make sure the module is really coming from where you believe it is. Jp From kbass1 at nc.rr.com Sun Jul 6 20:10:41 2003 From: kbass1 at nc.rr.com (Kevin Bass) Date: Mon, 07 Jul 2003 00:10:41 GMT Subject: Newbie Question: Abstract Class in Python Message-ID: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Hello: I am new to Python and want to know how to implement an abstract class? I have read through different books and I have no found this information. Thanks! Kevin From warlock at eskimo.com Thu Jul 3 13:01:19 2003 From: warlock at eskimo.com (Jim Richardson) Date: Thu, 3 Jul 2003 10:01:19 -0700 Subject: PyQT and Mandrake 9.1 References: Message-ID: On Tue, 1 Jul 2003 14:23:36 +0200, MK wrote: > "Gilles Lenfant" wrote > >> I've been very excited by PyQT evangelists. > > Be careful. QT is controlled by one company, > and it costs money. YMMV, however. > > Not on Linux, the Linux QT version, is GPL'd, so you can get it free, and Free. If you want to write closed source programmes with it, then you will need to buy a licence from TT, but if you want to write open source programmes, at least with Linux (I don't know about the MSWindows version) then you don't need to pay one red cent. -- Jim Richardson http://www.eskimo.com/~warlock Linux, because eventually, you grow up enough to be trusted with a fork() From cben at techunix.technion.ac.il Thu Jul 31 09:12:59 2003 From: cben at techunix.technion.ac.il (Beni Cherniavsky) Date: Thu, 31 Jul 2003 16:12:59 +0300 (IDT) Subject: streams (was: Re: Itertools) In-Reply-To: References: Message-ID: Mike Rovner wrote on 2003-07-30: > Beni Cherniavsky wrote: > > Any feedback welcome. I'd like to make it as Pythonic as possible. > > > An perhaps make it standard. Particular open questions: > > > - The linked lists are called "streams" by me because they are lazy > > and that's what such beasts are called in functional languages. > > Stream is used differently in Tcl and Unix. Minded separation > Python from functional approach (deprecation of filter, map; > doubtfulness of implementing tail recursion optimization) probably > it is not so inspiring for regular python programmer. > Point taken. But what do you call it then? Lazy linked lists has only one single-word name that I'm aware of and that is "streams"; there is no name for it in Tcl and Unix becauit is almost never used in them, as far as I know. > Lazy "streams" are a good thing provided they can be easily used for > organizing data pathes and connections. > Python already provides the minimal construct for connecting producers and consumers of data: the iterator protocol. It is minimalistic and becomes inconvenient when you want to use the same value more than one time, for lookahead, backtracking or simply connecting the same source to many consumers. All this is quite easy with the head/tail access to streams; it's a very powerfull abstraction. Since streams are implemented as linked lists, they don't leak memory for infinite iterators, unless you keep a reference to a fixed position in the stream. Over streams I've built an iterator which also provides the same powers but more in line with Python's iterator protocol. > > - `Cons` still requires lisp background but I don't know any name > > that would be recognizable to non-lispers anyway. And it's not > > a bad name. > > Construct, Glue, Merge? > Taken readability any whole word is better. > `Construct` is too long. Compare with `str`, `int`, `dict` rather than `string`, `integer` and `dictionary`. How would `Glue` and `Merge` be meaningful here? The only associasions of "glue" are what TeX puts between boxes and "glue layers" between different languages or libraries. "Merge" sounds like the process of taking several sequences of values and interlevaing them in some way (like in merge sort; BTW, it needs a lookahead of 1 for each stream, so it should be convenient to implement with streams). But this has nothing to do with what `Cons` does: creating a new stream by prepending given head to given tail. `Cons` is the only term I know of that unabigously refers to this operation, again coming from functional languages . There is another possibility: rename `Cons` to `Stream` and `Stream` to `LazyStream`; `Stream` would then be a factory function creating either depending on whether it got 1 or two arguments. Would this be better? > > - I called the operation for creating new iterator from same place > > "forking". Alternative names: `split`, `copy`, `clone`, `dup`, > > "lookahead", etc. What's best? > > copy is already using construct in python. Why not use it? > Copy was adviced against by Erik Max Francis, see: http://groups.google.com/groups?selm=3EEF7CA0.623C201C%40alcyone.com However, it really copies the iterator, it's just very fast. So I think I will indeed name this `.copy()` (aliased as `.__copy__`). > > - Anything else anybody needs? > > If I got the intend of Stream correctly, I wish use them as Tcl streams, > so I'd need combining and filtering and i/o. > You can use a `Stream` or `StreamIter` over a file object to get lookahead and mulitple passes over it, without requiring the file to be seekable! That's one of the main uses. It also gives you ability to "unread" any amount of data. Note that if you simply apply it to a file the stream operates on a line at a time; you will need to wrap the file with a custom generator if you wish to operate at character level; working at token level might be the best compromise. I'm not familiar with Tcl streams, so I don't understand the "combining and filtering" reference - can you elaborate? -- Beni Cherniavsky Put a backslash at the evening to continue hacking onto the next day. From peter at engcorp.com Thu Jul 10 21:31:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 21:31:22 -0400 Subject: Securing PyDoc and CGIHTTPserver References: <2621b014.0307100535.449ad06f@posting.google.com> <3F0D7887.9D069ED0@engcorp.com> Message-ID: <3F0E136A.6222F201@engcorp.com> Harry George wrote: > > Peter Hansen writes: > > > Jon Schull wrote: > > > > > > However, even with the patch, IP addresses can be spoofed. Here is an > > > additional security tactic that might be adopted. > > > > > > [...] However, if the port > > > were chosen at random and printed out, then only pydoc and the user > > > would know how to access the pydoc server. > > > > > My suggestion: don't attempt to mix security into each individual > > application in a piecemeal manner. Use the proper tools for the > > job, such as firewalls. Setting up a firewall on Linux or WinXP > > is nearly trivial at this point, and the learning experience is > > worth the effort for those who are new to this, so there's not > > much excuse for doing it properly, IMHO. > > Here, we have lots of COTS *NIX behind the corporate firewalls, and > want to provide internal security. We do this with SSL'd > communications. I can see how a firewall denies/allows specific IP > addresses (or at least claimed IP addresses), but not how it solves > sniffing, spoofing, man-in-the-middle, etc., where encryption > protocols are needed. Uh, yeah.... but the OP wasn't asking about sniffing, spoofing, or main-in-the-middle attacks, near as I can tell, nor about using encryption. He was suggesting an unusual modification to one or more applications which would otherwise be decoupled from security, by adding into them features which are better handled by firewalls. I'm not saying firewalls handle all security. At least I don't think I did. I vaguely remember saying "proper tools for the job, *such as* firewalls" [emphasis added], thus implying there are other approaches that might be appropriate. -Peter From vze4rx4y at verizon.net Mon Jul 14 22:30:07 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 15 Jul 2003 02:30:07 GMT Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <8f35dab2.0307141258.3da9b9d4@posting.google.com> Message-ID: [Jason Trowbridge] > Act I > I didn't know that python formatting could do that! I've always > treated it like C's printf-style of statements, as that seems to be > what it's primarily based off. That's why this one was included. Hope everyone learned something new. > The radix parameter gives the base for the conversion and may be any > integer in the range [2, 36], or zero. If radix is zero, the proper > radix is guessed based on the contents of string; the interpretation > is the same as for integer literals. > > That explains the 0 radix and the exception caused by the -1000 radix. > So why does it work with a radix of -909? I presume a bug (which > probably got fixed in later versions of Python). I'll have to see if > this behavior is present under Python 2.3b at home. The learning points are: * the 0 prefix indicator for octal is ignored when an explicit base is specified * specifying zero as a base allows the prefix to have the desired effect * -909 is an undocumented implementation detail (hackish but not a bug). > Apparently, os.putenv() doesn't work like I thought. > > Ah! os.putenv() updates the environment, but not the os.environ > dictionary. It looks like os.getenv() retrieves the environmental > variables from os.environ, and just assumes that it is up to date. > Since it defaults to None if the environmental variable doesn't exist > in os.environ[], that's what I get. Those are exactly the learning points. Congrats. BTW, the docs do say to update os.environ directly if you want it changed. > Aha! So the lambda is looking up f in the current scope when it is > executed! Instead of binding to the actual function object being > iterated over in the list comprehension, the lambda is binding to the > variable 'f' itself? Yes, but Fred's explanation is much more to the point. BTW, the example has nothing to do with lambdas, it is all about nested scopes and binding. You would experience the same issues with defs inside a regular for-loop. A secondary learning point is that list comprehensions overwrite and expose the loop variable just like an equivalent for-loop. > (Hey, these are fun!) I enjoyed reading your response. This is exactly the way I wanted the mysteries to be solved. IMO, the newsgroup has been needing to regain some its humor, curiousity, fun, and sense of playful exploration. Raymond Hettinger From fperez528 at yahoo.com Wed Jul 9 16:45:38 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 09 Jul 2003 14:45:38 -0600 Subject: LOADING DATA INTO ARRAYS References: Message-ID: satish k.chimakurthi wrote: > > Hi, > > I am trying to collect the following data in X,Y,Z arrays as following: > > 1.00000000000000 0.00000000000000D+000 0.00000000000000D+000 > 0.932113519778473 0.362166241174114 0.00000000000000D+000 > 0.737671227507627 0.675160099611485 0.00000000000000D+000 > 0.443073128844408 0.896485472551578 0.00000000000000D+000 > 8.83176797852179D-002 0.996092358889152 0.00000000000000D+000 > -0.145819420809848 0.989311223283493 0.00000000000000D+000 > -0.391263558087552 0.920278668726310 0.00000000000000D+000 > -0.625821331717327 0.779966448488364 0.00000000000000D+000 > -0.822296905793933 0.569058695322129 0.00000000000000D+000 > -0.953713306870443 0.300717356163965 0.00000000000000D+000 Hi, you might want to spare yourself some wheel re-inventing: In [1]: cat data.dat 1.00000000000000 0.00000000000000D+000 0.00000000000000D+000 0.932113519778473 0.362166241174114 0.00000000000000D+000 0.737671227507627 0.675160099611485 0.00000000000000D+000 0.443073128844408 0.896485472551578 0.00000000000000D+000 8.83176797852179D-002 0.996092358889152 0.00000000000000D+000 -0.145819420809848 0.989311223283493 0.00000000000000D+000 -0.391263558087552 0.920278668726310 0.00000000000000D+000 -0.625821331717327 0.779966448488364 0.00000000000000D+000 -0.822296905793933 0.569058695322129 0.00000000000000D+000 -0.953713306870443 0.300717356163965 0.00000000000000D+000 In [2]: import scipy In [3]: ,scipy.io.read_array data.dat ------> scipy.io.read_array ("data.dat") Out[3]: array([[ 1. , 0. , 0. ], [ 0.93211352, 0.36216624, 0. ], [ 0.73767123, 0.6751601 , 0. ], [ 0.44307313, 0.89648547, 0. ], [ 8.83176798, 0.99609236, 0. ], [-0.14581942, 0.98931122, 0. ], [-0.39126356, 0.92027867, 0. ], [-0.62582133, 0.77996645, 0. ], [-0.82229691, 0.5690587 , 0. ], [-0.95371331, 0.30071736, 0. ]]) In [4]: data = _ In [5]: data[1,0] Out[5]: 0.93211351977847301 In [6]: data[4,:] Out[6]: array([ 8.83176798, 0.99609236, 0. ]) In [7]: from Numeric import * In [8]: sin(2*pi*data) Out[8]: array([[ -2.44921271e-16, 0.00000000e+00, 0.00000000e+00], [ -4.13726328e-01, 7.61766230e-01, 0.00000000e+00], [ -9.97001167e-01, -8.91462758e-01, 0.00000000e+00], [ 3.50103955e-01, -6.05505553e-01, 0.00000000e+00], [ -8.70901144e-01, -2.45499665e-02, 0.00000000e+00], [ -7.93300122e-01, -6.71090900e-02, 0.00000000e+00], [ -6.31286730e-01, -4.80218587e-01, 0.00000000e+00], [ 7.10746430e-01, -9.82326731e-01, 0.00000000e+00], [ 8.98588241e-01, -4.20420374e-01, 0.00000000e+00], [ 2.86745429e-01, 9.49654034e-01, 0.00000000e+00]]) You just need to install scipy from http://scipy.org. And you'll get a ton of real numerical libraries to boot, which from the format of your data (fortran) I suspect you'll need soon. Best, f. From ianb at colorstudy.com Sun Jul 20 18:29:52 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 17:29:52 -0500 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: References: Message-ID: <1058740192.28091.2169.camel@lothlorien> On Sun, 2003-07-20 at 15:43, Alan Dechert wrote: > In the world of voting technology experts, I'm known as the guy that has > proposed to use commodity PCs as voting machines running open source > software with a printer to generate the paper ballot. While I have been > pushing the idea since Dec of '00, I haven't gotten any project funded yet. > Back then, I was just a crank with an idea. Now people are starting to take > it more seriously. I have some computer scientists and some students > interested in producing a demo of the system I have described. Primarily, > this demo is intended to introduce the idea to the public. Lots of ideas > for which language to use for the demo have been tossed around. I would > like to get some feedback on whether or not you think Python would be good > for this and why. > > This will be throw-away code. It will be pure coincidence if we end up > using any of it when the real [funded!] project gets underway. We will be > demonstrating to some reporters the look and feel of our voting machine -- > and by extension to the public, especially since we plan to have a demo on > the web that anyone with an Internet connection can try out. Some have > suggested HTML or XML but I'm not sure this will give us fine enough control > over the page layout. > > Here are some requirements for the demo: > > 1) The display will be for 1280 x 1024 resolution. While other resolutions > may be supported in the final product, the demo will only support this > resolution (the large screen is a critical usability advantage). Here is a > mock up of the on-screen ballot image: > > http://home.earthlink.net/~adechert/ballot-mockup3.gif > > Pretty much, I want pixel-for-pixel control over what goes on the display. If you really want pixel-for-pixel control, then SDL will provide this for you. Pygame (pygame.org) provides an interface to SDL, though it's somewhat low-level, pyui (pyui.sf.net) is slightly higher-level, but poorly documented and maybe not that helpful. In particular, I'd be concerned about text rendering, and then the consistent translation of that to print. PDF would be easier to generate, though I'm not sure how you would make that interactive. Reportlab generates PDFs nicely. Perhaps it would be possible to lay out the boxes accurately so you know where they are, then let the PDF renderer fill in the text. How exactly you would render the PDF I'm not sure... though heck, it doesn't have to be that interactive. You could simply render it to images, and compose those images to come up with the screen. That's probably easier and a better experience than allowing any change in flow or layout based on something the user does (i.e., you wouldn't want a selection to take up more space once selected, even if the text itself becomes larger). Maybe there's other rendering techniques you could use that I'm not aware of. The interface looks really dense to me, though, while not being large enough for common ballots anyway. Once you add in judges, you're getting a lot of options. And the county commissioner input is way too dense. Also, I suspect that the entire ballot is way to dense to be used with a touchscreen, where the accuracy of input isn't very good. You're going to have to plan on all votes being multi-page, and you might as well just program for that. The printout could still be single page, but then it won't look like the ballot they filled out, though that's probably fine. I really don't know why everyone wants to use touchscreens in voting machines. I hate touch screens, they are a horrible input method. ATM-style input is much better -- real buttons lined up along the side of the screen. Very reliable, not just the hardware, but the accuracy of input. The only problem is when the buttons are misaligned, so it's not clear how the screen selection maps to the buttons. The only advantage of touchscreens is they are somewhat more flexible, but that's also their greatest flaw. You could even fit those buttons only normal monitors. The buttons will be further away from the screen, but you can paint in strips on the enclosure right up to the screen so that it is very clear how the buttons correspond to the screen. Even if the buttons were an inch from the screen and raised up off the screen, the stripes would make it very clear. Anyway, I wish you luck -- we certainly need open voting systems. The current closed systems scare me. From peter at engcorp.com Mon Jul 14 22:50:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 22:50:18 -0400 Subject: Stop Python from exiting upon error in Windows References: Message-ID: <3F136BEA.5B56562@engcorp.com> Tom Plunket wrote: > > Or- catch the error in your mainline, and do a sys.raw_input() > call on exception. Tom meant just "raw_input()", which is a builtin, rather than sys.raw_input which does not exist, of course. To answer your question in the other reply, yes, you can nest exceptions. If you have a try/except and the raw_input in the except, however, you won't see any exception traceback printed at the console so you'll need something like the traceback module and one of the functions from it, like traceback.print_exc(). -Peter From clifford.wells at comcast.net Fri Jul 18 22:31:07 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 18 Jul 2003 19:31:07 -0700 Subject: Threading Pool Event() In-Reply-To: References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Message-ID: <1058581867.24384.2928.camel@devilbox.homelinux.net> On Fri, 2003-07-18 at 18:29, Graeme Matthew wrote: > ok still a bit confused sorry .... first attempt at a thread pool > > Am I correct in saying that each thread runs in a continious loop Yes. > each thread calls queue.get. The get method will block and not return > anything until an item is placed into it. When an item is placed into > it, one of the threads will get assinged a job i.e the first one that > happens to be in use during the cycle ? I think you have the idea, but I'm not sure (your terminology escapes me a bit toward the end). What happens is each thread blocks waiting for something to be placed on the queue. When something is put on the queue, one of the available threads (i.e. one that is blocking on queue.get() rather than processing a job). Only a single thread will be woken for each item that is put on the queue. It isn't knowable which thread that will be. > The job is returned to the thread, it runs with the job and does all > the processing then returns and calls queue.get again and waits for a > job to become available ? Yes. > When placing a job via Queue.put() one must acquire a lock place it > and then release it No. The locking semantics are internal to the Queue object. Do not concern yourself with it. It simply works. Do not attempt to put locks around it. > Am i aslo correct in saying that queue is actually doing the blocking > and controls which thread gets the job ? In a sense (that is, for practical purposes). How it is done internally by the interpreter isn't important. > Lastly, sorry for all the questions, surely the CPU usage is the same > when the queue is waiting for jobs and when the threads are polling as > theyre all in one process anyway The threads are asleep while waiting. They don't consume any CPU. The queue doesn't "wait" for jobs (that is, it doesn't loop, poll or otherwise consume any CPU time), when you call queue.put() it is a method call on an object, not a thread. > Am i getting this or am i way off :-) Just a little way off ;) Regards, Cliff -- My only regret is that I ever was born -Swans From skip at pobox.com Tue Jul 15 15:52:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 15 Jul 2003 14:52:10 -0500 Subject: Can't install csv parser In-Reply-To: References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: <16148.23402.184248.383806@montanaro.dyndns.org> bogal> I tried this first; went to the suggested alternative second. bogal> Here's what happens when I run setup.py: bogal> C:\Python22\Lib\site-packages\csv> bogal> python.exe C:\PYTHON22\LIB\SITE-P~1\CSV\SETUP.PY bogal> usage: SETUP.PY [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] bogal> or: SETUP.PY --help [cmd1 cmd2 ...] bogal> or: SETUP.PY --help-commands bogal> or: SETUP.PY cmd --help bogal> error: no commands supplied Setup.py needs to know what of several things you want to do (just build the package, build and install the package, build a distribution, etc). Try this command: python.exe C:\PYTHON22\LIB\SITE-P~1\CSV\SETUP.PY install That should do any necessary building and install all the files. Skip From tzot at sil-tec.gr Tue Jul 8 12:47:18 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 08 Jul 2003 19:47:18 +0300 Subject: Shared vs static link performance hit --and Windows? References: Message-ID: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> [I: statically-linked python is 25% faster than dynamically-linked on my machine] [Skip: explains that python possibly uses excessive function calls to and fro shared libraries so that explains the difference] Thanks, Skip; now if only someone more Windows-knowledgeable than me could also comment on whether we could see a similar speed increase by building a static Windows EXE... I do have a computer with Visual Studio 6 available at work, but I don't know much about VS[1] to answer this myself; I gave it a try, but I got lost in the Project Settings and how to merge the pythoncore (the dll I believe) and the python (the exe) projects. [1] Although lately I did give a shot to compile a custom module for haar image transforms following the directions in the docs; it was trivial in Linux --kudos to all of you guys who worked on distutils-- and fairly easy on Windows, so I have both an .so and a .pyd with the same functionality for my program... -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From zathras at thwackety.com Wed Jul 16 09:00:06 2003 From: zathras at thwackety.com (Michael Sparks) Date: Wed, 16 Jul 2003 14:00:06 +0100 (BST) Subject: Python Quiz In-Reply-To: <1058359673.3f154979ded2a@mcherm.com> Message-ID: richardc writes: > Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's > fixed format syntax. On Wed, 16 Jul 2003, Michael Chermside wrote: > Definitely NOT. Without addressing the question of HOW Python came by the > idea of using indentation to indicate block structure, it clearly couldn't > have been from Fortran, because what Python does and what Fortran does > are COMPLETELY different. Python is however pretty much peas in a pod with the way Occam uses whitespace/indentation for structure & folding. Neither is in any way close to the way Fortran uses it IMHO. Michael. From moo at sneakmail.zzn.com Wed Jul 2 03:35:37 2003 From: moo at sneakmail.zzn.com (Mikko Ohtamaa) Date: 2 Jul 2003 00:35:37 -0700 Subject: Assing a COM Interface to a Python object for callbacks Message-ID: <26caea2b.0307012335.1d717429@posting.google.com> Hi, I am quite new to Python, PythonCom and COM generally. As a former Java programmer, I have found Python's flexible ability to access native Win32, especially COM, very comfortable. However, there is quite little on-line documentation and examples available about PythonCOM. The only good sources I have found were the sample chapter from Mark Hammond's book and some decades old PowerPoint show. I have a following problem: I am trying to do XML Schema validation using MSXML SAX parser through PythonCOM API. MSXML offers two different interfaces for SAX: One for VB and one for C++. C++ one is named ISAXXMLReader and VB one is named IVBSAXXMLReader. I haven't found what is the basic difference between these interfaces though I have carefully read MSXML SDK documentation. I assume IVBSAXXMLReader might have some IDispatch functionality which is requirement for PythonCom(?). The problem is that SAX Parser requires COM interface for callback. You must assign a COM interface as a handler to the parser. When the parsing begins, the handler calls this interface. saxReader.errorHandler = myErrorHandler <-- COM Interface I do not know how to turn Python class into COM interface on the fly. I have managed to open the C++ version ISAXXMLReader of the interface. I have NOT succeed to do this for VB versioon IVBSAXXMLReader, because I do not know how it happens. I assume you have to use CoCreateInstance, but it returns "Class not registered", see the sample below. After opening ISAXXMLReader I have not been able to pass COM error handler for it. I have reasons not to go through full process registering my own error handler as a COM server into Windows registry and create it using win32com.client.Dispatch("Python.MyErrorHandler"). Is there a way to create COM server on the fly and get the COM handle for it? I have been trying to read win32.client and win32.server Python sources and even PythonCOM C sources, but unfortunately my skillz are not 1337 enough to see the big picture. How to assign a COM Interface for a Python object? It goes somehow through policies and wrapping, right? Unfortunately every approach I have tried end to an error saying my wrapper IPyDispatch cannot be used as ISAXErrorHandler. Mikko Ohtamaa Student of Industrial Engineering & Management Oulu, Finland Sample code: class MySaxErrorHandler: # Some random stuff in stucked into this class # hoping it would help policies & wrapping _reg_progid_ = "Art2ComponentValidator.SaxErrorHandler" _reg_clsid_ = "{a60511c4-ccf5-479e-98a3-dc8dc545b7d0}" _reg_clsctx_ = "INPROC_SERVER" _com_interfaces = [ "{a60511c4-ccf5-479e-98a3-dc8dc545b7d0}" ] _query_interface_ = "{a60511c4-ccf5-479e-98a3-dc8dc545b7d0}" _public_methods_ = [ "error", "fatalError", "ignorableWarning" ] # A piece of VB sample: #Private Sub IVBSAXErrorHandler_error(ByVal oLocator As SXML2.IVBSAXLocator, strErrorMessage As String, ByVal nErrorCode As Long) # WriteErrorToResults "Error", strErrorMessage, _ # nErrorCode, oLocator.lineNumber, oLocator.columnNumber #End Sub def error(oLocator, strErrorMessage, nErrorCode): print strErrorMessage def fatalError(oLocator, strErrorMessage, nErrorCode): print strErrorMessage def ignorableWarning(oLocator, strErrorMessage, nErrorCode): print strErrorMessage def saxtest(): # SAXXmlReader MIDL: a4f96ed0-f829-476e-81c0-cdc7bd2a0802 # sax error handler: a60511c4-ccf5-479e-98a3-dc8dc545b7d0 # ivbsaxerrorhandler: d963d3fe-173c-4862-9095-b92f66995f52 # ivbsaxxmlreader: 8c033caa-6cd6-4f73-b728-4531af74945f # test path switcher useISAX = 0 if useISAX: # Use c++ version ISAXXMLReader saxReader = win32com.client.Dispatch("Msxml2.SAXXMLReader.4.0") errorHandler = MySaxErrorHandler() # ISAXErrorHandler: a60511c4-ccf5-479e-98a3-dc8dc545b7d0 iid = pywintypes.IID("{a60511c4-ccf5-479e-98a3-dc8dc545b7d0}") # What I should do instead of this? saxReader.errorHandler = win32com.server.util.wrap(errorHandler, iid) # Following error: # File "C:\Python22\Lib\site-packages\win32com\server\util.py", line 28, in wrap # ob = ob.QueryInterface(iid) # Ask the PyIDispatch if it supports it? # pywintypes.com_error: (-2147467262, 'No such interface supported', None, None) else: # Use VB version, IVBSAXXMLreader clsid = pywintypes.IID("{8c033caa-6cd6-4f73-b728-4531af74945f}") iid = clsid create_as = win32com.client.pythoncom.CLSCTX_INPROC_SERVER iface = win32com.client.pythoncom.CoCreateInstance(clsid, None, create_as, iid) # pywintypes.com_error: (-2147221164, 'Class not registered', None, None) From nospam at mega-nerd.com Sun Jul 13 22:50:23 2003 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Mon, 14 Jul 2003 02:50:23 GMT Subject: AIFC (Python and audio files.) References: <3F1219D7.829F2F43@mega-nerd.com> Message-ID: <3F121A64.4127BA22@mega-nerd.com> Erik de Castro Lopo wrote: > > AIFC files contain digitally sampled sound, much like the data > stored on a CDROM. Sorry, I meant like the audio data stored on an AUDIO CD, not a CDROM. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "Don't be fooled by NT/Exchange propaganda. M$ Exchange is just plain broken and NT cannot handle the sustained load of a high-volume remote mail server" -- Eric S. Raymond in the Fetchmail FAQ From shane at zope.com Fri Jul 25 18:39:25 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 25 Jul 2003 18:39:25 -0400 Subject: Static typing In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4738@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4738@admin56.narex.com> Message-ID: <3F21B19D.4040502@zope.com> Bjorn Pettersen wrote: >>From: Shane Hathaway [mailto:shane at zope.com] >>def foo(bar, baz): >> assert isinstance(bar, int) >> assert isinstance(baz, str) > > [...] > > ...which means you can't use foo with unicode strings or UserStrings, That's right, and that's intentional. The function is designed to work only with byte arrays. This invites someone who wants to pass a unicode object to first verify that the function will actually work properly with unicode. > etc., etc. This is C programming in Python, ugly, inefficient, > inflexible, and un-Pythonic. It is highly useful documentation. There is nothing inefficient about it. It is as flexible as the programmer makes it. It is quite Pythonic, although you should only declare the types of arguments when the type matters. I should say that in actual practice, I haven't used isinstance() checks. Instead, I've been checking against Zope interfaces. def foo(conn): assert IDatabaseConnection.isImplementedBy(conn) Shane From gherron at islandtraining.com Fri Jul 25 09:55:59 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 25 Jul 2003 06:55:59 -0700 Subject: decimal to binary In-Reply-To: <200307250653.18754.gherron@islandtraining.com> References: <200307250653.18754.gherron@islandtraining.com> Message-ID: <200307250655.59854.gherron@islandtraining.com> On Friday 25 July 2003 05:21 am, manuel wrote: > How to convert a decimal to binary ? > > thx, > > Manuel We probably need more information than that to answer your question. For instance statement x = 123 converts the decimal number represented by the decimal digits 123 into binary form and stores it in variable x. Of course you have no access to the binary digits as print x converts back to decimal to print "123" So what is it you really want? Gary Herron From warlock at eskimo.com Wed Jul 23 13:00:49 2003 From: warlock at eskimo.com (Jim Richardson) Date: Wed, 23 Jul 2003 10:00:49 -0700 Subject: Shallow vs Deep copies [was Re: python assignment] References: Message-ID: <1jr2v-vd.ln1@grendel.myth> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tue, 22 Jul 2003 22:46:56 -0400, Tim Peters wrote: > The rule that the object in question is never copied. There are no > exceptions to this. Copying an object requires invoking some method > of the object, or applying some function to the object. For example, > d.copy() returns a (shallow) copy of a dict d, and L[:] returns a > (shallow) copy of a list L. To clarify for me please. A shallow copy of an object, returns an object that contains references to objects within the copied object, yes? so a list consisting of [1,2,a,"a"] when copied shallowly, will return exactly that, but when copied deeply, will reture [1,2,"whatever a points to","a"] yes? If I understand the above correctly.... how deep does a deep copy go? can you vary the depth? Or is it binary, shallow or deep? Thanks. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE/Hr9Bd90bcYOAWPYRAnaYAKDDRFGR6FG3ytgN2dwf7w1shDND3QCgs33B 8jNxKhsF1Ti7bkbPzbCxEx4= =6a1K -----END PGP SIGNATURE----- -- Jim Richardson http://www.eskimo.com/~warlock Linux, because eventually, you grow up enough to be trusted with a fork() From exarkun at intarweb.us Sat Jul 5 13:21:40 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 5 Jul 2003 13:21:40 -0400 Subject: tp_base, tp_basesize, and __slots__ instance __class__ reassignment Message-ID: <20030705172121.GA24165@intarweb.us> In trying to update some code built on top of reload(), I've hit a point of confusion in how it is determined whether or not __class__ is allowed to be rebound. Consider, for example: >>> class Foo(object): ... __slots__ = 'a', 'b' ... >>> class Bar(object): ... __slots__ = 'a', 'b' ... >>> f = Foo() >>> f.__class__ = Bar Traceback (most recent call last): File "", line 1, in ? TypeError: __class__ assignment: 'Bar' object layout differs from 'Foo' The cause of this particular error does not actually seem to be that the object layouts of Bar and Foo are incompatible, but rather that the object layouts of _object_ and Foo are incompatible. I've tracked down the point of rejection to same_slots_added (Objects/typeobject.c:2347 or thereabouts): static int same_slots_added(PyTypeObject *a, PyTypeObject *b) { PyTypeObject *base = a->tp_base; int size; if (base != b->tp_base) return 0; if (equiv_structs(a, base) && equiv_structs(b, base)) return 1; size = base->tp_basicsize; if (a->tp_dictoffset == size && b->tp_dictoffset == size) size += sizeof(PyObject *); if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) size += sizeof(PyObject *); return size == a->tp_basicsize && size == b->tp_basicsize; } I do not understand why the final line is comparing size against each of a and b's tp_basicsize, rather than perfoming some comparison between a and b directly. Can anyone enlighten me? Jp -- Where a calculator on the ENIAC is equipped with 18,000 vacuum tubes and weighs 30 tons, computers in the future may have only 1,000 vacuum tubes and weigh only 1.5 tons. -- Popular Mechanics, March 1949 From max at alcyone.com Mon Jul 14 03:10:18 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 00:10:18 -0700 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Message-ID: <3F12575A.9218496E@alcyone.com> Stephen Horne wrote: > All variables are implemented as references, but that is not the same > as saying that all values are references. Right. And this is an extremely important point in Python. Variables are bindings of names to objects. Objects are entities in and of themselves. The object is what is mutable or immutable, not the name. Names are transitory. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The little I know, I owe to my ignorance. \__/ Sacha Guitry From davecook at nowhere.net Sat Jul 5 17:03:05 2003 From: davecook at nowhere.net (David M. Cook) Date: Sat, 05 Jul 2003 21:03:05 GMT Subject: Red Hat 9, Python and Glade - a mixure not working? References: Message-ID: In article , Hans Deragon wrote: > def on_button4_clicked(source=None, event=None): You should exit the mainloop here: gtk.main_quit() > sys.exit(); > > gtk.glade.XML('project3.glade') Should be xml = gtk.glade.XML('project3.glade') > xml.autoconnect({ > 'on_button4_clicked': on_button4_clicked > }) Or you can just use xml.signal_autoconnect(locals()) See glade_demo.py in the /usr/share/doc/pygtk2-1.99.14/examples/glade/. For more info on pygtk see http://www.async.com.br/faq/pygtk/index.py?req=index http://www.moeraki.com/pygtkreference/pygtk2reference/ Dave Cook From hokiegal99 at hotmail.com Sun Jul 6 20:31:15 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sun, 06 Jul 2003 20:31:15 -0400 Subject: Using Loops to track user input In-Reply-To: References: Message-ID: Perl's motto is "there's more than one way to do it," right? Well, after reading all of these responses, I think Python could make the same claim. Thanks again guys! Bob Gailer wrote: > Not to neglect the 1-liner: > > import operator; reduce(operator.add,[int(raw_input("Number>")) for i in > range(10)]) > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 From pythonguy at Hotpop.com Mon Jul 21 10:05:01 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 21 Jul 2003 07:05:01 -0700 Subject: How to save web pages for offline reading? References: Message-ID: <84fc4588.0307210605.14f00cc0@posting.google.com> Hi I am the developer and maintainer of 'HarvestMan', a program which does exactly what you want ( and more ). It is an offline webcrawler written completely in Python. It is currently in 1.1 beta version. Dont bother to write code yourselves. HarvestMan supports HTTP/FTP/HTTPS protocols and works across proxies and can crawl intranets. There is documentation available for its use and I give free support, as much as my time permits me :-> The freshmeat project page is here: http://www.freshmeat.net/projects/harvestman Give it a try and let me know your experience. Thanks ~Anand hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > I am trying to download pages from Python, for offline reading. This > to save telephone costs :-) > > If a page contains something like > > and I use fp=urllib.urlopen(...) and then fp.read(), I get the HTML > but not the CSS. As a result the page looks bad when reading offline. > How to solve this? Also the .GIF's in a page would be nice, but this > is less important and also would take more time to download. From sross at connectmail.carleton.ca Thu Jul 10 13:50:41 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 10 Jul 2003 13:50:41 -0400 Subject: for in sequence problem... possible new operator to add to python References: <3a8fc6c5.0307100816.634c83a3@posting.google.com> <5_gPa.8878$ru2.867718@news20.bellglobal.com> Message-ID: > Ick. At the very least, return self.itervalues() Sure. I was either unaware of itervalues() or my awareness of it had yet to register (now it has, so, thanks). From cybersamurai at mac.com Sun Jul 13 16:53:29 2003 From: cybersamurai at mac.com (cybersamurai at mac.com) Date: Sun, 13 Jul 2003 17:53:29 -0300 Subject: py2exe Message-ID: <0E95BB27-B574-11D7-A515-000393B10A78@mac.com> I am develop a application with wxpython, pycrypto, and Python 2.2, I need know if py2exe get all modules needed for my application work without install any application stead one exec file of my application and without I select manually this modules? From jjl at pobox.com Thu Jul 31 13:34:09 2003 From: jjl at pobox.com (John J. Lee) Date: 31 Jul 2003 18:34:09 +0100 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: <87el06d2i6.fsf@pobox.com> "John Roth" writes: [...] > That said, I've come to the conclusion that the editor should take > care of these things for you. If you prefer a brace free notation, > you should be able to tell your editor to present the program to you > that way. If you prefer braces, then it should be able do that for > you as well. That kind of stylistic thing doesn't belong in the > language. 100% agreed: once-and-only-once dictates this. Manually maintaining both braces and indentation (as in C, with some editors) is Just Plain Bad for this reason. > In fact, if I didn't have to deal with the braces, I think I'd come > around to the view that the text should have them. Explicit is > better than implicit, At least in the absence of proper research results, I think this part of it *is* religious. To some people, it's obvious that whitespace is better on the eyes. To others, it's obvious that whitespace + braces is better on the eyes. One group may well be wrong <0.5 wink>. This argument (that braces are another visual cue which make code easier to read -- provided that they're automatically maintained in sync with the indentation), is the only argument against pure-whitespace that has ever made any sense to me. Irrespective of whether you pick whitespace or braces as the thing the compiler takes notice of, though, the optimal solution probably still involves an editor that supports showing/hiding braces, so the syntax is (theoretically!) a non-issue. In practice, editors don't seem to currently support showing and hiding braces automatically. At least editors do get you out of most mistakes caused by brace-y languages. Of course, whitespace *is* still superior because the storage format doesn't duplicate state -- so people with poor editors can't produce ambiguous code :-) (remember code can be ambiguous to *people* even if it isn't to a compiler). OTOH, *Python's* scheme is inferior to a pure-space-character indentation scheme because off the tab-vs.-space issue :-( > and there are a few things that the > automatic indentation makes rather difficult in the design area. [...] What are those things?? John From kmj9907 at cs.rit.edu Tue Jul 29 20:27:16 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Wed, 30 Jul 2003 00:27:16 GMT Subject: PyQt Help and Advice References: Message-ID: On Wed, 30 Jul 2003 00:18:32 +0100, Phil Thompson wrote: > > To correct one misconception... > > PyQt was first released on November 1st 1998. There have been 34 releases in > all. The next release, including support for Qt v3.2.0, will be around August > 12th. It isn't new. > > Phil Phil, Any idea when Qt3.2 will have noncommercial support in windows? From staschuk at telusplanet.net Thu Jul 24 23:59:12 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 24 Jul 2003 21:59:12 -0600 Subject: python assignment In-Reply-To: ; from danbmil99@yahoo.com on Thu, Jul 24, 2003 at 07:25:36PM -0700 References: Message-ID: <20030724215912.A1193@tibia.amotlpaa.bogus> Quoth dan: [...] > but again the +[] looks funky in the morning light. Can I always > assume that an operation of this sort will return a new object, even > if it has no effect on one of the operands? Afaik it's not documented, but I think you may safely assume that arithmetic on lists will always produce a new list, even in such cases as a_list + [] 1*a_list Having such expressions possibly return the existing object is a harmless optimization for immutable types, but would be madness for mutable objects such as lists. Guido is not mad. (A little eccentric sometimes, occasionally silly, and noticeably Dutch, but not mad.) > I suppose a clearer fix would be v[x] = copy.copy(temp), eh? Yes, that, or v[x] = list(temp) or v[x] = temp[:] according to taste. The latter is most common, I think. -- Steven Taschuk staschuk at telusplanet.net "[T]rue greatness is when your name is like ampere, watt, and fourier -- when it's spelled with a lower case letter." -- R.W. Hamming From piet at cs.uu.nl Sat Jul 5 10:46:16 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 05 Jul 2003 16:46:16 +0200 Subject: Newbie: Tkinter and macPython References: Message-ID: >>>>> gtewalt at earthlink.net (gt) (GT) wrote: GT> I'm waffling between Ruby, and Python as a programming GT> language. GT> I borrowed a friends book on Ruby, and have played with GT> it a bit. GT> I went by the library to check out 'Learning Python' GT> but i was too late, the library had closed already... GT> Anyway, to the point. GT> I downloaded macPython for OSX, and was trying to get GT> a simpe Tkinter example to work form Lundh's tutorial, GT> I think it was. GT> Bu I get an error... I guess you have downloaded a Python installation with proper Tkinter support. I had that also a few weeks ago. I installed the new 2.3b2 from source and it works. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From Aaron.Hawley at uvm.edu Mon Jul 28 18:26:22 2003 From: Aaron.Hawley at uvm.edu (Aaron S. Hawley) Date: Mon, 28 Jul 2003 18:26:22 -0400 Subject: Inheriting (subclass) of dict data attribute (copying) In-Reply-To: References: Message-ID: On Sun, 27 Jul 2003, Aaron S. Hawley wrote: > [What] Would be the most obvious (best in idiom) to overwrite the > dictionary of my derived dict class? The old school way is obvious to > me. > > TIA, /a > > #!/usr/bin/env python > > from UserDict import UserDict > > class Old_Chickens(UserDict): ## old school > def __init__(self, chickens): > self.set_chickens(chickens) > def set_chickens(self, chickens): > self.data = chickens > > class New_Chickens(dict): ## new school > def __init__(self, chickens): > self.set_chickens(chickens) > def set_chickens(self, chickens): > self = dict.__init__(self, chickens) > > > new_chickens = New_Chickens({'white': 12, 'brown': 8}) > print new_chickens['white'] > > old_chickens = Old_Chickens({'white': 12, 'brown': 8}) > print old_chickens['white'] this would probably be fine: #!/usr/bin/env python from UserDict import UserDict class Old_Chickens(UserDict): ## old school def __init__(self, chickens): UserDict.__init__(self) #FIX: be sure to call the base __init__ self.set_chickens(chickens) def set_chickens(self, chickens): self.data = chickens class New_Chickens(dict): ## new school def __init__(self, chickens): dict.__init__(self) #FIX: again, be sure to call the base __init__ self.set_chickens(chickens) def set_chickens(self, chickens): dict.__init__(self, chickens) #FIX: you need only recall __init__ ... try reading the "Unifying types and class in Python 2.2" before posting a question about subclassing types: http://www.python.org/2.2/descrintro.html From max at nowhere.com Tue Jul 22 15:32:00 2003 From: max at nowhere.com (max4) Date: Tue, 22 Jul 2003 19:32:00 +0000 (UTC) Subject: wxpython display jpg in a frame Message-ID: hello i would like to know if there is a good tutorial about how to do this or if someone could explain thank you [ i want to add a jpg to an existing about dialog] From mis6 at pitt.edu Fri Jul 18 09:02:59 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Jul 2003 06:02:59 -0700 Subject: [development doc updates] References: <20030715221007.07C7A18F01B@grendel.zope.com> Message-ID: <2259b0e2.0307180502.4951656b@posting.google.com> Andy Jewell wrote in message news:... > do the new resolution rules only apply to "New Style Classes" ? Yes. See http://www.python.org/2.3/mro.html Michele From ianb at colorstudy.com Sat Jul 12 14:56:21 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2003 13:56:21 -0500 Subject: new in town In-Reply-To: References: Message-ID: <1058036181.28466.102.camel@lothlorien> On Sat, 2003-07-12 at 13:39, Elaine Jackson wrote: > As comforting as it is to know that there are "several ways of doing this", I'd > be even happier if I knew the name of just one of those ways. The FAQ searcher > doesn't seem to understand lengthy explanations and hand-waving. Then maybe the better answer would be: Python can be compiled into a Windows executable for distribution, but it cannot be compiled to improve speed. If you have performance issues there are a multitude of solutions (as in any language), but don't expect to have problems until you actually see a problem. Usually Python performance is entirely adequate. Ian From rjhiii2002 at yahoo.com Mon Jul 28 21:02:50 2003 From: rjhiii2002 at yahoo.com (Robert Hathaway) Date: Tue, 29 Jul 2003 01:02:50 GMT Subject: Comp.Object FAQ - Version II Beta - Latest Object Oriented Resource - Please Participate! Message-ID: <_IjVa.60532$852.17419@twister.nyc.rr.com> COMP.OBJECT FAQ Version II Beta now Available http://www.objectfaq.com/oofaq2 ================================================== - Latest Important Information on Object Technology - What's New Page - What professionals *must keep up on* in rapidly changing environment - Available on Homepage, email notification on updates now available - Good Resource Site - Latest in Object Technology - Complete Coverage of Object Orientation - Up to date on Java, C++, .net (more C# soon) - Runs on J2EE/EJB site, very cool running examples - Participate in new OO Survey (J2EE/EJB impl) - Real-Time Results - Survey soon canonical example of J2EE/OO Arch/Design patterns What's New: 0.9 What is Open Source Software? (And where to get best OO) 0.10 What are the Major new Object Oriented Technologies? 0.11 What are Web Services? 0.12 What is available on Software Architectures? The comp.object FAQ, at one time the most up to date resource on object technology anywhere, is back in business. A new beta site has gone up hosted on the open source JBOSS J2EE/EJB platform and all are invited to join in and take a look. A new survey on object technology is available for those who logon, results are presented in real-time. New surveys, information of greatest interest to those in OO, and new examples and patterns are available and much more new material is forthcoming. New summaries on J2EE, .net, Web Services, and open source, all rapidly changing and critical to keep up on by professionals, are available and examples of all, complete with design documentation will be available shortly, including those now running on the site. A new summary 'cheat sheet' of the GOF patterns, which can help to learn all of them and when to use them in a glance - will be available within a week, and a summary and comparison matrix of new architectural styles, approaches, and patterns (yes, even including RUP and XP) will follow and provide an opportunity to see all of the new software architecture methods at a glance. Please take a look at the new Object FAQ and participate in the latest survey, by doing so you and the entire OO community will benefit by seeing the results. The first survey is a beta test, more interesting surveys will be available shortly, 1 per month on topics we all need to keep up to date on. Feedback is most welcome. I'd like to think the comp.object FAQ, one of the first documents up on the Web, is the best FAQ around and with your participation will stay that way. Best Regards! Bob Hathaway Object FAQ Maintainer rjh at objectfaq.com From tadin_antispam at cirus.dhz.hr Thu Jul 17 04:15:28 2003 From: tadin_antispam at cirus.dhz.hr (Marijan) Date: Thu, 17 Jul 2003 09:15:28 +0100 Subject: Jython classpath question References: Message-ID: No it is not true. If you can access your class from java, in jar file or not, (it has to be in the classpath), you can access it from jython. I've been playing with jython and java a while ago, but I can remember I had to do a little trying out, before I figured out how to access some java class. As far as I can remember you can have more java classes in one *.class file, so it is possible that you have to write: import classfilename.classname or similar, but do not blame me if I am wrong here, as far as I can remember I had to to some trying out in this direction. There is also a jython mailing list, and two books about jython. "Tennessee James Leeuwenburg" wrote in message news:pan.2003.07.17.02.29.12.502474 at removme.bom.gov.au... > Hi all, > > Sorry for the newb question, but Googling and FAQing didn't work. Is it > correct that Jython can only access Java classes which are inside JAR > archives in the JYTHON_HOME directory? IT doesn't seem to be documented. I > ask because I want to do groovy prototyping using Jython, and save myself > a lot of coding overhead to try something a little out-of-the-box. > > I have a working directory where all my code lives, and because my app is > under rapid development, I would prefer to avoid creating a JAR file every > time I want to do some Python scripting? > > What do people suggest I do? > > Thanks, > -Tennessee From max at alcyone.com Thu Jul 3 14:18:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 03 Jul 2003 11:18:48 -0700 Subject: python 2.3b[12] References: <3F037015.3D6D7034@alcyone.com> <200307031200.25633.drlinux@columbus.rr.com> Message-ID: <3F047388.6702AB8D@alcyone.com> Dave Reed wrote: > Still get 2.3b1. > > Here's the file size of the Python-2.3b2.tgz file: 8421285 > > Is that correct? You can look on the python.org Web site and check this for yourself. If you didn't uninstall the beta 1 and are installing the beta 2 into a _different prefix_, it's almost certainly the case that what you're seeing is simply contamination. Delete the old beta before installing the new one. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ To love without criticism is to be betrayed. \__/ Djuna Barnes From jjl at pobox.com Sat Jul 26 19:43:59 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 00:43:59 +0100 Subject: How to detect typos in Python programs References: <3F214977.AEB088C8@engcorp.com> Message-ID: <877k64c0qo.fsf@pobox.com> Manish Jethani writes: [...] > > The proposed typo catcher would probably catch a typo like > > > > sys.edit (5) # finger didn't get off home row > > > > but it probably would *NOT* catch > > > > sys.exit (56) # wide finger mashed two keys > > 1) That's in a different class of typos. Such things can't be > auto-detected in any language. It will probably require close > examination by the human who wrote it in the first place, or > someone who has been debugging it. That was, indeed, precisely the point that was being made. Tests can catch these, static type analysis can't. > 2) No on calls sys.exit() like that. 5, or 56, is probably a > constant defined somewhere (where such typos are easier to spot). Yes. Do you have a point? John From mcfletch at rogers.com Sat Jul 19 20:12:36 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 19 Jul 2003 20:12:36 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: Message-ID: <3F19DE74.6020009@rogers.com> Aahz wrote: >In article , >Mike C. Fletcher wrote: > > >>Nope, I'm trying to make meta-classes which have rich properties. The >>particular project is a plug-in system, where the classes (the >>metaclass-instances) want to have all sorts of rich metadata associated >>with them in a way which meshes with the rest of the system (i.e. using >>a descriptor-based introspection mechanism). >>... >> >> > >Keeping in mind that I'm really not following this discussion all that >closely (because metaclasses give me headaches), are you trying to make >a *metaclass* that has properties or a *metaclass instance* (i.e. a >class) that has properties? > > Just the meta-class instances (classes). Wasn't sufficiently precise in my description, the properties are normally declared in the meta-class, but they are actually properties of the meta-class instances. Sorry about that, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From paul_rudin at scientia.com Thu Jul 10 09:28:42 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 10 Jul 2003 14:28:42 +0100 Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: >>>>> "Paul" == Paul Rudin writes: > r= reduce(lambda x,y: x+'|'+y, c,'')[1:] It occurs to me that this isn't what you want if c contains special regexp chararacters so really it should be: r= reduce(lambda x,y: re.escape(x)+'|'+re.escape(y), c,'')[1:] > So putting it all together as an alternative version of your > fuction: > !!warning - untested code!! > import re > def stringReplace(s,c): > r= reduce(lambda x,y: x+'|'+y, c,'')[1:] r= reduce(lambda x,y: re.escape(x)+'|'+re.escape(y), c,'')[1:] > return re.compile(r).sub('',s) From jocsch at phreaker.net Sun Jul 6 16:00:59 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Sun, 06 Jul 2003 22:00:59 +0200 Subject: Search for mapping solution References: <3F087E85.9D8018E9@hotmail.com> Message-ID: > > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] >>>> d = dict([(x[0], x[2]) for x in lines]) >>>> d > {'sam': '1', 'fred': '0,50'} fred should be 0,60. The 3rd column should be summarized. > > OK, I'll write and maintain a 1000-line perl program as penance ... > > sometimes-concise-is-elegant-too-ly yrs. > From jjl at pobox.com Sat Jul 12 10:36:57 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Jul 2003 15:36:57 +0100 Subject: What's new with Gnosis References: Message-ID: <87d6gf6cc6.fsf@pobox.com> "Raymond Hettinger" writes: [...] > ACT I --------------------------------------- > >>> s = list('abc') > >>> try: > ... result = s['a'] > ... except IndexError, TypeError: > ... print 'Not found' > ... > > Traceback (most recent call last): > File "", line 2, in -toplevel- > result = s['a'] > TypeError: list indices must be integers The second 'argument' of except is the caught exception object, so that code works as if you did try: result = s['a'] except IndexError, e: TypeError = e print 'Not found' -- which doesn't catch the TypeError. > ACT II -------------------------------------------- > >>> class MyMistake(Exception): > ... pass > > >>> try: > ... raise MyMistake, 'try, try again' > ... except MyMistake, msg: > ... print type(msg) > ... > > Again, the second 'argument' of except gets the exception object, not the string you used in the raise. These two are equivalent [XXX er, I *think* they're always equivalent]: raise SomeError, 'my error message' raise SomeError('my error message') The second form is more explicit, hence better. Exception objects do have a __str__ method, though, so you can print them as if they were strings: try: result = s['a'] except IndexError, e: print e because print calls the e.__str__ method to do its work. > ACT III -------------------------------------------- > >>> class Prohibited(Exception): > ... def __init__(self): > ... print 'This class of should never get initialized' > ... > >>> raise Prohibited() > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited() > Prohibited: > >>> raise Prohibited > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited > Prohibited: These are equivalent: raise Exception raise Exception() The second is more explicit, hence better. Since exception classes always end up getting instantiated whichever way you write the raise statement, you need to write __init__ correctly if you override it. The Exception base class has an __init__ that it expects to be called, so you should call it: [At this point, I had to look up the arguments to Exception.__init__.] class Prohibited(Exception): def __init__(self, *args): Exception.__init__(self, *args) print 'This class will get initialized' In this case, the lack of that Exception.__init__ call is what's causing the "" message, but it could cause other problems too. [Actually, with your interactive example, I don't get the " ACT IV ----------------------------------------------- > >>> module = 'Root' > >>> try: > ... raise module + 'Error' > ... except 'LeafError': > ... print 'Need leaves' > ... except 'RootError': > ... print 'Need soil' > ... except: > ... print 'Not sure what is needed' > ... > > Not sure what is needed A raised string exception only matches the string in the except statment if both strings are the same object. It's not enough for them to have the same value. Two different string literals that have the same value aren't necessarily the same object: myerror = "myerror" anothererror = "myerror" # not *necessarily* the same object as myerror try: raise myerror except anothererror: # we only get here if it so happens that: assert myerror is anothererror except myerror: # we always get here, because: assert myerror is myerror > ACT V ----------------------------------------------- > >>> try: > ... raise KeyError('Cannot find key') > ... except LookupError, msg: > ... print 'Lookup:', msg > ... except OverflowError, msg: > ... print 'Overflow:', msg > ... except KeyError, msg: > ... print 'Key:', msg > > > Lookup: 'Cannot find key' except statements are checked in the order you write them. Class instance exceptions are matched as if by isinstance(raised_exception, caught_exception) so exceptions can be caught by their base classes. LookupError is a base class of KeyError, so the first except matches. John From postmaster at 127.0.0.1 Sun Jul 13 06:58:13 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Sun, 13 Jul 2003 22:58:13 +1200 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: On Sat, 12 Jul 2003 13:53:35 -0700, Tom Plunket paused, took a deep breath, then came out with: > I want to do something along the lines of the following C++ code: > > void change(int& i) > { > i++; > } > Is there any way to do references like this in Python? In Python, basic types like strings and numbers are a weird exception to the 'everything is an object' rule. When you pass any other object in a function, the function gets a ref to that object. But when you pass a string or numeric object, the whole thing (not a ref) gets passed. Your best bet would be to create a wrapper class for numbers, store the actual number in an attribute, and provide all the methods in Section 3.3.6 of the Python Reference Manual (__add__, __sub__ etc) to work on the value attribute. That way, you can use your numeric object in calculations, and when you pass it to functions (like your 'change()' above), things will work as expected. In fact, in most situations, it will look/feel/smell just like a number. But watch out for trying to assign to it, or using '+=' type operators - they will replace your object with a plain number. I attach below a sample class declaration for a numeric type which is passable by reference (no need to do this for string, since you can just use the UserString module). Cheers David class myint: def __init__(self, value): self.value = value def __getattr__(self, attr): if attr in ['__repr__', '__add__', '__repr__', '__add__', '__sub__', '__mul__', '__floordiv__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__', '__and__', '__xor__', '__or__', '__div__', '__truediv__', '__radd__', '__rsub__', '__rmul__', '__rdiv__', '__rtruediv__', '__rfloordiv__', '__rmod__', '__rdivmod__', '__rpow__', '__rlshift__', '__rrshift__', '__rand__', '__rxor__', '__ror__', '__neg__', '__pos__', '__abs__', '__invert__', '__complex__', '__int__', '__long__', '__float__', '__oct__', '__hex__', '__coerce__']: return getattr(self.value, attr) def __iadd__(self, other): self.value += other return self.value def __isub__(self, other): self.value -= other def __imul__(self, other): self.value *= other def __idiv__(self, other): self.value /= other def __itruediv__(self, other): self.value = self.value.__itruediv__(other) def __ifloordiv__(self, other): self.value = self.value.__itruediv__(other) def __imod__(self, other): self.value = self.value.__imod__(other) def __ipow__(self, other): self.value = self.value.__ipow__(other) def __ilshift__(self, other): self.value = self.value.__ilshift__(other) def __irshift__(self, other): self.value = self.value.__irshift__(other) def __iand__(self, other): self.value = self.value.__iand__(other) def __ixor__(self, other): self.value = self.value.__ixor__(other) def __ior__(self, other): self.value = self.value.__ior__(other) From staschuk at telusplanet.net Thu Jul 31 21:10:17 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 19:10:17 -0600 Subject: time, calendar, datetime, etc In-Reply-To: ; from bens@replytothegroupplease.com on Thu, Jul 31, 2003 at 11:09:18AM +0100 References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <20030731191017.D22513@tibia.amotlpaa.bogus> Quoth Ben S: [...] > Problem is, time.localtime() doesn't return a 9-element tuple any more, > it returns a struct_time. (Since 2.2, I think.) Ah, yes. I read Kylotan's question pretty sloppily, it seems. datetime.timetuple() does indeed return a struct_time, as do date.timetuple() and datetime.utctimetuple(), and this is clearly desirable and intended. I think I'll submit a doc patch. -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From kericks272 at earthlink.net Tue Jul 15 14:56:16 2003 From: kericks272 at earthlink.net (ken erickson) Date: Tue, 15 Jul 2003 18:56:16 GMT Subject: python 2.2.3 & mega widgets 1.1 Message-ID: Is Python Megawidgets 1.1 compatible with Python 2.2.3. I'm new to Python and I'm trying to work my way through some example is John Grayson's Python and Tkinter Programming book. He has some sample code that uses the PMW library. The reason I ask is due to a problem that I'm having in trying to run the demo code included with the widget library. I get an AttributeError message when ever the demo code attempts to use any of the Pwm methods. I've tried to find the meaning of the AttributeError message but I'm unable to locate this error message in any of the online documentation; including the FAQ. C:\Python22\Pmw\demos>python colors.py Traceback (most recent call last): File "colors.py", line 44, in ? Pmw.initialise(root, fontScheme = 'pmw1') AttributeError: 'module' object has no attribute 'initialise' -TIA From gregadelliot at hotmail.com Mon Jul 21 06:30:08 2003 From: gregadelliot at hotmail.com (jeff) Date: 21 Jul 2003 03:30:08 -0700 Subject: python tags on websites timeout problem References: <87d6g4u48y.fsf@pobox.com> Message-ID: Hiya, thanks everyone that replied, very informative. yep i looked into using the google api, although wasnt sure what it did at first so ill check that again, thanks for the sourceforge links thanks for everything else cheers greg From m at moshez.org Tue Jul 8 02:45:07 2003 From: m at moshez.org (Moshe Zadka) Date: 8 Jul 2003 06:45:07 -0000 Subject: looking for UDP package, network programming guidance In-Reply-To: References: Message-ID: <20030708064507.26358.qmail@green.zadka.com> On Mon, 07 Jul 2003, Tom Plunket wrote: > Searching the web turned up Twisted, although it seems like it > might be a bit bigger than I would have hoped (in terms of, > "there's a huge package here to figure out"), but as far as I can > tell it's the only UDP solution out there. Is this the case? It isn't the only one, but it makes it fairly easy to write UDP servers without worrying about the irrelevant low-level details. Here is a simple example, based on an example from the UDP howto: ''' from twisted.internet import protocol, reactor class UpperEcho(protocol.DatagramProtocol): def datagramReceived(self, data, (host, port)): self.transport.write(data.upper(), (host, port)) reactor.listenUDP(9999, UpperEcho()) reactor.run() ''' Run the above in the Python interpreter, and then in a different window: moshez at green:~$ echo hello | nc -u localhost 9999 HELLO Granted, perhaps not the most efficient way to uppercase strings, but hopefully I got the idea across. Despite Twisted's "largeness", you can usually limit yourself to the howto you're interested in, and read others only as they come in useful. [If you have further Twisted questions, the Twisted mailing list is the best forum to ask in.] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From edreamleo at charter.net Thu Jul 10 18:32:45 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 10 Jul 2003 17:32:45 -0500 Subject: A new view of gcmodule.c Message-ID: A few days ago I had the highly pleasurable experience of studying Python's garbage collecting code in gcmodule.c. Naturally, I studied the code using a Leo outline. I have just uploaded this outline to: http://sourceforge.net/project/showfiles.php?group_id=3458 The outline is in pythonGC.leo.zip in the Example Outlines section. This outline makes clear just how good the code really is. I shall not soon forget the dawning realization that this code is absolutely beautiful: incredibly short, simple and elegant. There are hardly any if statements in the core of the code! Those who want proof that Python is a brilliant piece of engineering need look no further than gcmodule.c. To find such a gem at the heart of Python is truly thrilling. I have studied a lot of programs in my life; it doesn't get any better than this. For the superb external documentation, see: http://www.arctrix.com/nas/python/gc/ Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From logiplex at qwest.net Fri Jul 18 12:44:21 2003 From: logiplex at qwest.net (Cliff Wells) Date: 18 Jul 2003 09:44:21 -0700 Subject: A challenge to the ASCII proponents. In-Reply-To: <3F172442.2040907@v.loewis.de> References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <1058546661.2717.16.camel@software1.logiplex.internal> On Thu, 2003-07-17 at 15:33, Martin v. Loewis wrote: > So what do you think about this message?: > > ???????? > > Look Ma, no markup. And not every character uses two bytes, either. > And I can use Umlauts (???) and Arabic (???.????) if I want to. > > I don't know for whom this renders well, but I guess MSIE5+, NS6+ > and Mozilla 1+ are good candidates - without the need for saving > things into files. Looks fine in Evolution 1.4.3. Well, that is, it looks like a bunch of gibberish, which is what I expected to see -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From just at xs4all.nl Tue Jul 8 11:02:29 2003 From: just at xs4all.nl (Just van Rossum) Date: Tue, 8 Jul 2003 17:02:29 +0200 Subject: path module In-Reply-To: <16138.55918.159252.387878@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Just> Also: this would not be portable on platforms not using / as > Just> os.sep, ... > > Not necessarily. True, but it takes guessing: "did the author really mean to specify several path components here, or is he/she intentionally using the unix path separater in file names on a platform that _does't_ use / as the path separator?". In the face of ambiguity etc. > My guess (again, without trying it) is that it does > the right thing. It doesn't... > Nonetheless, before anything like Jason's path module is incorporated > into the standard distribution, a PEP is almost certainly required. > I imagine there are some things which could be done better (or at > least differently) to make the overall module more acceptable. Absolutely. I really like Holger's observation that having path objects levels the road to virtual file systems (eg. use a zip file as a file system). Anyone intersted in volunteering to write that PEP? I'd like to contribute in some way, but I'm not going to write more than 1 PEP per year :-). Just From usenet_spam at janc.invalid Mon Jul 21 23:18:03 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 22 Jul 2003 03:18:03 GMT Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: Paul Foley schreef: > betacode Thanks, I didn't know about that. Have now searched Google for "greek betacode" and have bookmarked some of the results. :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From gminick at hacker.pl Tue Jul 29 02:55:12 2003 From: gminick at hacker.pl (Wojtek Walczak) Date: Tue, 29 Jul 2003 06:55:12 +0000 (UTC) Subject: Newbie on importing References: <68a42404.0306200929.6043eef0@posting.google.com> Message-ID: Dnia 20 Jun 2003 10:29:14 -0700, Michael J Whitmore napisa?(a): > Just read the Python tutorial looking for the answer to this question > What is the difference between (from sys import *) and (import sys). http://ASPN.ActiveState.com/ASPN/docs/ActivePython/howtos/doanddont/node4.html -- [ Wojtek Walczak - gminick (at) underground.org.pl ] [ ] [ "...rozmaite zwroty, matowe od patyny dawnosci." ] From scook at elp.rr.com Wed Jul 23 23:33:11 2003 From: scook at elp.rr.com (Stan Cook) Date: Thu, 24 Jul 2003 03:33:11 GMT Subject: Help writing to file Message-ID: I'm trying to have my program write to a log file. I have the idea, but I'm getting an error and don't understand why. File "D:\AetInstall\aet.py", line 201, in load_progs _log.write(string.ljust( _serv, 25)) AttributeError: 'str' object has no attribute 'write' I get the above message from this section of code: for s in _image: _serv = s print _serv _ErrorLevel=map_server(_serv) _log.write(string.ljust( _serv, 25)) _image is a list containing server names. Any help would be appreciated. Thanks, Stan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.501 / Virus Database: 299 - Release Date: 7/14/03 From aahz at pythoncraft.com Fri Jul 25 19:48:11 2003 From: aahz at pythoncraft.com (Aahz) Date: 25 Jul 2003 19:48:11 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: In article , Mike C. Fletcher wrote: >Aahz wrote: >>In article , >>Mike C. Fletcher wrote: >>> >>> * finally, stores the value >>> o tries to do what would have been done if there were no >>> descriptor (with the new, coerced value) >>> o does *not* create new names in the object's namespace (all >>> names are documented w/ descriptors, there's not a lot of >>> '_' prefixed names cluttering the namespace) >>> o does *not* require a new dictionary/storage-object attribute >>> for the object (the descriptor works like any other >>> descriptor, a *stand-alone* object that replaces a regular >>> attribute) >> >>But this is a recipe for name clashes. If you follow the first bullet, >>it's a normal attribute, but everything else says you want a property. >>Properties are themselves objects that are attached to names in an >>object. You can't have the same name bound to two different objects. > >It's true that: > > * your class has a namespace, and there are objects stored in that > namespace > o the objects stored in that namespace often are descriptors > o they are available to the instances which do not shadow them > (as I said, I can deal with this, and it's cleaner anyway). > + if they are descriptors, they modify instance access > to attributes That's technically inaccurate as phrased. First of all, not all descriptors get activated through attribute access, only data descriptors do. Data descriptors are descriptors that define a ``set`` attribute (which is essentially a method of the descriptor object). Secondly, it muddies understanding to say that the descriptor modifies access to attributes, as if the descriptor is a proxy for an attribute. Data descriptors *replace* attributes, and if you want to store a value, it's your responsibility to determine where that value is stored (and how to retrieve it). > * the metaclass instance's property *values* would be stored in the > metaclass instance's dictionary, just as is normally done (the > metaclass' property *descriptors* would be stored in the > metaclass' dictionary), there's no new conflicts created here, > everything just works like it does now, a lookup would look > something like this: > > >>> x.y >x doesn't have a __getattribute__, so see if it has a descriptor for 'y' Actually, x is the *last* object checked, and __getattribute__() is never called on instances. > get type(x).y > > type(x) doesn't have a __getattribute__, so see if it has a > descriptor for 'y' > > get type(type(x)).y -> this is just a simple descriptor, as > there's no higher-level descriptor, has a __get__ method, > calls it to retrieve type(x).y That should be type(type(x).y), I think. (I'm not testing this in code.) > returns the currently stored entry 'y' in type(x)'s dictionary, > which happens to be a descriptor > > has type(x).y, a descriptor with a __get__ method, calls it, gets > back value stored in instance's dictionary That's correct if type(x).y is a data descriptor; other types of descriptors do get overridden by the instance. >You wind up with some names that are not available for use *as >properties* on instances *iff* you set a simple value for the properties >of the meta-class instance, but you solve that the regular way, by >making the value stored by the meta-class instance's property a >descriptor, rather than a simple value. That's just the way classes >work. Yes, it's a "name clash", but everything in classes/instances is >name clashes . Instances don't have properties, only types do. A metaclass is "just" a class that creates classes (which are themselves types with new-style classes). Problems only show up when you want to access class behavior *through* a class instance. >Not a problem I can see in the problem I outlined just yet, there's >still no low-level value-setting mechanism exposed, The point is that there's no low-level value. You always have to explicitly specify the name and namespace when you use properties. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From belred1 at yahoo.com Sat Jul 12 15:09:44 2003 From: belred1 at yahoo.com (Bryan) Date: Sat, 12 Jul 2003 19:09:44 GMT Subject: Accessing and updating global variables among several modules References: Message-ID: "Fuming Wang" wrote in message news:a12f6af8.0307111938.4d7a9851 at posting.google.com... > Hi, > > I have several modules that need to access global variables among > them. I can do that by import modules: > > module A: > gA = 'old' > > module B: > import A > print A.gA > >>> 'old' > > change gA in module A after some initialization: > def init_fuct(): > gA = 'new' > > no change in module B: > print A.gA > >>> 'old' > > However, when I modify these global variables in one module, the other > modules would not see the changes. Any one has any suggestions? ( I > don't want to use from A import *) > > > Thanks, > Fuming i've used this technique before where different modules access a global variable in another module it works. i'm not understanding why you are having problems. i just did this test with strings... is this similar to what you are doing? it shouldn't matter how myvar gets set. --- test1.py myvar = 'abc' def set_myvar(x): global myvar myvar = x --- test2.py import test1 print test1.myvar test1.set_myvar('def') print test1.myvar --- from the interpreter >>> import test2 abc def >>> bryan From cwilbur at mithril.chromatico.net Tue Jul 1 08:44:30 2003 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Tue, 01 Jul 2003 12:44:30 GMT Subject: Fast CGI Vs Java Application Servers References: <20030630120924.209$qh@newsreader.com> <23891c90.0307010111.43fd3c43@posting.google.com> Message-ID: <87brwexw81.fsf@mithril.chromatico.net> paul at boddie.net (Paul Boddie) writes: > ctcgag at hotmail.com wrote in message > news:<20030630120924.209$qh at newsreader.com>... > > Switching a working application to a new language is about the > > greatest possible crime there is against code reuse. > > "We believe in code reuse. Apart from the system we just threw away, > of course." It's also possible that the old application just barely works, and that it will take more work to bolt new things onto the side of it than to rewrite it from scratch. If we're talking about a 15-year-old C application that had a web interface bolted onto it a few years back and which has been undergoing continual change and occasional expansion, I could certainly see a case for rewriting the whole mess. Charlton From pipen at beast_tu_kielce.pl Wed Jul 2 09:53:12 2003 From: pipen at beast_tu_kielce.pl (Artur M. Piwko) Date: Wed, 2 Jul 2003 13:53:12 +0000 (UTC) Subject: Partition names with Python References: <1056984252.3f004cbc6abd6@mail.uzem.itu.edu.tr> Message-ID: In the darkest hour on Wed, 2 Jul 2003 11:17:49 +0300, Erhan Ekici screamed: > But some machines /proc/partition file is empty.. > But /etc/fstab contain drives names..(sda1,sda2,cdrom,floopy etc) > > For Example My Server(Slackware 9)'s /proc/partition file contain nothing. > I must take partition names on all Linux(Redhat,Mandrake,Slackware etc).. > > Why do some machine's /proc/partition file contain nothing... > Yes, you have to compile it to kernel. The best choice is /etc/mtab, imho. Artur -- Before the Goat of Mendes... we all must take our turn | Artur M. Piwko Into the magic circle... where still the fire burns | mailto:s/_/./ We're spinning round and round... until one takes a fall | -- Mercyful Fate The fallen one will not return, the fallen one must burn | "Witches' Dance" From eger at cc.gatech.edu Mon Jul 14 21:10:59 2003 From: eger at cc.gatech.edu (David Eger) Date: 15 Jul 2003 01:10:59 GMT Subject: PyErr_SetString() != raise ? Message-ID: When I use PyErr_SetString() in an extension, python just keeps on chugging instead of acting as though a Python exception had been 'raise'd. Why is this, and do I really have to write the Python code to raise an exception manually after I've used PyErr_SetString()? Most recently, writing an iterator -- I write: if (nextEl == NULL) { PyErr_SetString(PyExc_StopIteration, "Array index out of bounds"); return NULL; } in my iterator extension, but when I use my extension, I get an infinite loop: eger at rosencrantz:/usr/src/CIM-stuff/wbemcli/bugs$ python2.2 Python 2.2.2 (#1, Mar 21 2003, 23:40:29) [GCC 3.2.3 20030316 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import StopIterTest >>> a = StopIterTest.dupstring("Amanda's") >>> b = StopIterTest.dupstring("got") >>> l = StopIterTest.stringArray() >>> l.add(a) >>> l.add(b) >>> for i in l: ... print i ... _10180840_p_string _10181b38_p_string None None None None None None None None None None (and so on, and so on...) The thing is, even though I *set* the exception with PyErr_SetString, to the interpreter, it doesn't get raised. Am I just misinterpretting how PyErr_SetString is supposed to work? -David From lorenb2 at bezeqint.net Thu Jul 31 05:11:28 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Thu, 31 Jul 2003 11:11:28 +0200 Subject: how to gunzip a string ? References: <025001c356a5$2d9aad10$6400a8c0@EVOD31> Message-ID: <001801c35743$b9f4cf40$6400a8c0@EVOD31> Thanks !!! it works fine. question: upon calling GzipConsumer's close methos, it in turn invokes a consumer close method, too. on the stupid_consumer you demonstrated there is no such method. the question is whether an extremely_stupid "def close(self): pass" method is just fine or is there something important to do with the data ? ~B ----- Original Message ----- From: "Fredrik Lundh" To: Sent: Wednesday, July 30, 2003 7:47 PM Subject: Re: how to gunzip a string ? > Bill Loren wrote: > > I guess I really need some sort of library that will do a gzip decoding to a > > compressed string. > > assume that I have a gzipped_string_reply I got from an HTTP server, > > It'd be superb to have a gunzip class that takes it and return its decoded > > equivalent. > > > > I managed to do it with the gzip library only after saving the string to a > > file and then opening and reading it > > with gzip.open, but it's extremely ugly. > > > > any suggestions ? > > trying again: > > http://effbot.org/zone/consumer-gzip.htm > (GzipConsumer module) > > interface code (based on john j. lee's posting): > > from GzipConsumer import GzipConsumer > > class stupid_gzip_consumer: > def __init__(self): self.data = [] > def feed(self, data): self.data.append(data) > > def gunzip(data): > c = stupid_gzip_consumer() > gzc = GzipConsumer(c) > gzc.feed(data) > gzc.close() > return "".join(c.data) > > unzipped_data = gunzip(gzipped_data) > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tim at zope.com Wed Jul 16 10:14:49 2003 From: tim at zope.com (Tim Peters) Date: Wed, 16 Jul 2003 10:14:49 -0400 Subject: __eq__ and __ne__ In-Reply-To: <3F0AF5D7.5030703@zope.com> Message-ID: [Tim] >>>> Since the richcmp operators aren't constrained to return scalars, >>>> an attempt to define one in terms of the others seemed futile. >>>> Instead they're 6 independent methods. [Shane Hathaway] >>> Ok. Thanks for finding the docs. I guess I'll stick to my >>> boilerplate code. I think some guidance should be added to the >>> Python docs, though, explaining that whenever you define __eq__, >>> you very likely ought to define __ne__ also. Doc patches are always welcome . [Jeremy Hylton] >> I believe C++ has the same behavior when you overload logical >> operators. So at least people familiar with the same behavior in >> other languages won't be surprised. [Shane] > Actually, C++ generates a compiler error if you try to do that. (See > the attached program.) Java doesn't run into this because it has a > simpler interface: the only operator you can override is equals(). So > in this case, C++ is fully explicit and Java is fully implicit, while > Python makes a guess. If we can't make it implicit like Java, then it > seems preferable for Python to raise an exception, similar to C++, > when you use the != operator with an instance that implements __eq__ > but not __ne__. With a clean slate, I'd agree. If Python 3 supports *only* richcmps, I expect that's what Guido will do there. The current comparison mish-mash is at least half backward-compatibility warts. This is something that needs to be simplified rather than complicated (it's already too complicated to understand in all cases!), but simplification probably can't be done anymore without breaking somebody's code. From bobsrefusebin at hotmail.com Thu Jul 31 12:57:28 2003 From: bobsrefusebin at hotmail.com (Bob Perlman) Date: Thu, 31 Jul 2003 16:57:28 GMT Subject: Plotting points with DISLIN Message-ID: Hi - I've been getting good results using the DISLIN data plotting package with Python. But I've been unable to plot points instead of curves. Can someone tell me how to turn off the between-points interpolation? And if there is a way to do it, is there a way to change the style of points plotted? Thanks, Bob Perlman From intentionally at blank.co.uk Mon Jul 14 23:46:55 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 04:46:55 +0100 Subject: anything like C++ references? References: Message-ID: On Mon, 14 Jul 2003 06:47:44 -0700, Michael Chermside wrote: >I have nothing whatsoever to add to this... it is just so clearly and >simply stated that I felt it was worth repeating. Of course, lots of >other people said the same thing in other ways, but I felt that Ian's >phrasing is particularly useful in explaining things to programmers >coming from a C-style background, even if it doesn't seem to reach >Stephen Horne. I know what is being said. And I don't *just* have a C background. However well you explain what Python does, that doesn't mean that it is doing the right thing. Mathematics says variables bind to values. Simple. But Python doesn't respect that. I don't care how the binding is implemented as long as the implementation respects the principle, but Pythons implementation has side effects - it is not transparent to the programmer. This causes confusion and errors. And saying that 'this is the way it is so get used to it' does not seem, to me, to be the Python way. When I was arguing against PEP238, a major argument for the change was simply that the division operator did the wrong thing, causing confusion and errors. The fact that PEP238 required a seriously incompatible change, and that experienced Pythonistas were used to the old way, was seen as a relatively minor concern. When I argued effectively that newbies should be told 'this is the way it is so get used to it', that really didn't go down too well. But right now, it seems that the majority are using precisely that argument against me. From bokr at oz.net Fri Jul 11 10:49:41 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jul 2003 14:49:41 GMT Subject: Deleting specific characters from a string References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: On Thu, 10 Jul 2003 08:56:14 +0200, Behrang Dadsetan wrote: >Bengt Richter wrote: >> On Wed, 09 Jul 2003 23:36:03 +0200, Behrang Dadsetan wrote: >> ====< removechars.py >======================================================== >> def removeChars(s, remove=''): >> return s.translate( >> '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' >> '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' >> ' !"#$%&\'()*+,-./' >> '0123456789:;<=>?' >> '@ABCDEFGHIJKLMNO' >> 'PQRSTUVWXYZ[\\]^_' >> '`abcdefghijklmno' >> 'pqrstuvwxyz{|}~\x7f' >> '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f' >> '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f' >> '\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf' >> '\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf' >> '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf' >> '\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf' >> '\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef' >> '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >> , remove) > >It looks to me like serious overkill. If I would put in a method like >that somewhere in my code, my colleagues would never talk to me again ;) > What looks like overkill? The 256-character string literal? It is easy to explain, and if you want utility functions like this, you can put them in a module and your colleagues may never see beyond the import statement and the calls, unless they are interested. It should have a doc-string though, which could advise using help(str.translate) for further info ;-) Note that the code for removeChars is not much to execute (29 bytecode bytes?), since the constant is pre-defined (and the 9 bytes for SET_LINENOs could be optimized out): >>> dis.dis(removeChars) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_FAST 0 (s) 9 LOAD_ATTR 1 (translate) 12 LOAD_CONST 1 ('\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\ x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:; <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85 \x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d \x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5 \xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd \xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5 \xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd \xfe\xff') 15 SET_LINENO 19 18 LOAD_FAST 1 (remove) 21 CALL_FUNCTION 2 24 RETURN_VALUE 25 LOAD_CONST 0 (None) 28 RETURN_VALUE (I believe the last two codes are never executed, just vestigial code-generation by-product for the case of non-explicit returns at the end). If you want to get rid of the extras, you can do python -OO and use lambda to get rid of the vestigial return code: >>> removeChars = lambda s, remove='': s.translate( ... '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' ... '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' ... , remove) >>> Gets you: >>> import dis >>> dis.dis(removeChars) 0 LOAD_FAST 0 (s) 3 LOAD_ATTR 1 (translate) 6 LOAD_CONST 1 ('\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\ x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:; \xfe\xff') 9 LOAD_FAST 1 (remove) 12 CALL_FUNCTION 2 15 RETURN_VALUE What do you mean by overkill? ;-) Regards, Bengt Richter From bokr at oz.net Fri Jul 18 20:00:15 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 00:00:15 GMT Subject: Python dictionary syntax, need help References: <56ba0aea.0307181142.7401aa02@posting.google.com> Message-ID: On 18 Jul 2003 12:42:06 -0700, crewr at daydots.com (Crew Reynolds) wrote: >I want to create a dictionary of note on/off timings and access it by >the name of the object. The following code works for one row. > >a = "Hammer1" >b = [5,45,45,45,45,50,55,57,59,61,60,59] > >notes = {a:b} >print notes["Hammer1"][3] >>>> 45 > >The problem is, I want to load the data from a file to populate >variables a and b and build a dictionary for "Hammer1" thru >"Hammer10". That way, I can stick the name of the object in the array >index and receive a list of note timings that I can index with an >ordinal as in the above example. > >This is straight Python syntax but I'm hoping someone has done this or >understands the syntax better than I. > >Thanks! Alternative solutions to this concept would be greatly >appreciated. If you want to get it from a file, I suggest making the file space-delimited and just use an (also space delimited unless see[Note 1]) '=' sign between dict key and associated values. I'll use the names you suggest, but note that plain integers will also work as "names" (keys) in a dict, and that might be handier in some cases, depending on how you want to access the dict. We'll simulate the file with an intialized StringIO instance: >>> import StringIO >>> infile = StringIO.StringIO(""" ... Hammer1 = 5 45 45 45 45 50 55 57 59 61 60 59 ... Hammer2 = 6 46 46 46 46 51 56 58 60 62 61 60 ... Hammer3 = 8 48 48 48 48 53 58 60 62 64 63 62 ... """) Starting out with an empty notes dict >>> notes = {} >>> for line in infile: ... if not '=' in line: continue # skip blanks etc ... lineitems = line.split() ... name = lineitems[0] ... numberlist = map(int, lineitems[2:]) ... notes[name] = numberlist ... That creates the dict: >>> notes {'Hammer1': [5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59], 'Hammer3': [8, 48, 48, 48, 48, 53, 58, 60, 62, 64, 63, 62], 'Hammer2': [6, 46, 46, 46, 46, 51, 56, 58, 60, 62, 61, 60]} Which you can access per your example: >>> notes["Hammer1"][3] 45 And we can show it in a bit more orderly way: >>> tosort = notes.items() >>> tosort.sort() >>> for name, value in tosort: print name, value ... Hammer1 [5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59] Hammer2 [6, 46, 46, 46, 46, 51, 56, 58, 60, 62, 61, 60] Hammer3 [8, 48, 48, 48, 48, 53, 58, 60, 62, 64, 63, 62] After the ... lineitems = line.split() statement, I probably should have added assert lineitems[1] == '=' or else been more forgiving and split in two stages, e.g., left, right = line.split('=') name = left.strip() numberlist = map(int, right.split()) HTH Regards, Bengt Richter From tim.one at comcast.net Sun Jul 27 11:33:01 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 27 Jul 2003 11:33:01 -0400 Subject: datetime1 - datetime0, same tzinfo, different dst In-Reply-To: <82a334e5.0307270635.3ce7e078@posting.google.com> Message-ID: [St?phane Bidoul] > I'm playing around with the new datetime module. > Looks nice, and a welcome addition to the core... > > I've a question about a behaviour of > substractions of "aware" datetimes around DST switch. > > The problem is that the difference gives wrong results > when the 2 datetimes have the same tzinfo instance, > but have different utc offsets due to DST. According to the docs, the results are correct . > The behaviour is consistent with what the documentation > says, but I find it quite unintuitive. > > Is that the designed behaviour? Yes. You can read Guido's thinking here: http://www.zope.org/Members/fdrake/DateTimeWiki/NaiveTime and here: http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo and at other less relevant pages in that Wiki. The first link explains that when you do datetime2 = datetime1 + timedelta there are 3 different answers people *might* expect. Guido picked the one that seemed best to him (if, say, timedelta is 24 hours, move to the same clock time on the next day, ignoring the deviations from that result accounting for DST boundaries would entail). The meaning of timedelta = datetime2 - datetime1 when datetime2 and datetime1 are in the same time zone follows from that decision. Throughout the implementation, combining (regardless of the specific operation involved) two datetimes with the same tzinfo members effectively treats them as naive datetimes. > ... > Well, it's actually consistent with the documentation > that says that no utc conversion is done when the 2 dates > have the same tzinfo, but I find it somewhat unintuitive > in this case. Yup, and other people (particularly Guido ) would find it unintuitive if it did what you expected instead. If it's any consolation, I originally implemented datetime to act the way you expect in this regard, but changed it at Guido's request. It seems odd to me too that whether time zone adjustments occur depend on whether the tzinfo members are or aren't the same. > ... > So in this case it works, but should we create > new tzinfo instances for each datetime we create. No, if you want DST-aware datetime differences, you can get them by converting to UTC first; or, effectively the same thing, instead of d1 - d2 do (d1 - d1.utcoffset()) - (d2 - (d2.utcoffset()) You already figured that out, of course -- that's what your d1.astimezone(utc) - d0.astimezone(utc) did, and that's the intended way to do it (provided you've written a utc class to model UTC). > The sample tzinfo module seems to imply they > are best used as singletons. Yes, for purposes of determining whether two datetimes are "in the same time zone", their tzinfo members are compared by object identity, so they pretty much have to be singletons to work as intended. From noah at noah.org Sat Jul 12 13:41:17 2003 From: noah at noah.org (Noah) Date: 12 Jul 2003 10:41:17 -0700 Subject: The ASPN compiler References: Message-ID: Gerhard H?ring wrote in message news:... > Fuzzyman wrote: > > What's the score on this (the ASPN python compiler) > Read the whitepaper, available on the ActiveState site. > ... > -- Gerhard The short answer is that it looks like a dead project. Actually, you are better off going to Mark Hammond's .NET page here: http://starship.python.net/crew/mhammond/dotnet/ This stuff is still pretty old, but not as crusty as the ActiveState info. Note that the ActiveState Python.NET page available here: http://www.activestate.com/Corporate/Initiatives/NET/Research.html?_x=1 It is not easy to find going through the ActiveState site. Luckily there is Google... Noah From hanzspam at yahoo.com.au Wed Jul 2 15:40:16 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 2 Jul 2003 12:40:16 -0700 Subject: Newbie advice for string fromatting References: Message-ID: <840592e1.0307021140.44563ece@posting.google.com> gtewalt at earthlink.net (gt) wrote in message news:... > O.k., four days into playing with python > and I have a little problem that I would like > to get some feedback on. > ( as far as the best way to go about it ) > > Basically, just a little Mad-Libs type script. > > Something like: > > libs = ["adverb", "noun", "verb", "tool"] > words = {a:j, n:j, v:j, t:j} > for x in libs: > print "Enter a ", x, ": ", > words[j] = raw_input() > print "The %s %s %s with a %s." % (a, n, v, t) > > What is the most efficient way to do something like this? This is pretty compact :) libs = ["adverb", "noun", "verb", "tool"] words = [raw_input("Enter a " + x + " : ") for x in libs] print "The %s %s %s with a %s." % tuple(words) Could be even written as a perverted one-liner. ...Maybe a real 'for' loop for getting the words would be better in this case though. So that the input could be verified too. From kericks272 at earthlink.net Mon Jul 28 04:10:03 2003 From: kericks272 at earthlink.net (ken) Date: Mon, 28 Jul 2003 08:10:03 GMT Subject: IDLE? Message-ID: I'm trying to find the correct method of launching IDLE (v 0.8) to debug a script. When I run without a script name and then enable the debugger option and then load and run the script I have no problems. However, I need to be able to add command line options (-h or --help). I can run the script with command line options (without the preceding IDLE) just fine but when I attempt to run "\Python22\Tools\IDLE\idle -d test.py -h" I get a syntax error on the call to Main() if __name__ == '__main__': main() File "test.py", line 367 main() ^ SyntaxError: invalid syntax What am I doing wrong? TIA From max at alcyone.com Thu Jul 10 21:52:53 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 10 Jul 2003 18:52:53 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> Message-ID: <3F0E1875.574DC6D7@alcyone.com> Paul Rubin wrote: > Because now you need a mechanism to store the session info on the > server, and you might want it to work across multiple load-balanced > servers that fail over to one another, etc. That's far superior to presenting the opportunity to exploits in the first place, in my opinion. Depending on the contents of the contents of that cookie, what you suggest may not be a problem at all (depending on how critical the data contained therein is). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I would rather understand one cause than be king of Persia. \__/ Democritus From bokr at oz.net Wed Jul 23 00:41:18 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Jul 2003 04:41:18 GMT Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> <2259b0e2.0307220744.156c95bf@posting.google.com> Message-ID: On Tue, 22 Jul 2003 16:41:29 -0600, Steven Taschuk wrote: >Quoth Michele Simionato: >> Steven Taschuk wrote in message news:... > [...] >> > I don't have anything substantial to add to others' posts, but I >> > wonder: under what circumstances do you want to do this? >> >> I wanted to check the output of ifilter or imap; [...] > >Ah. And then, if there were elements in the iterator, I assume >you would then process them somehow, right? Why not just do that >with a for loop, say, and check afterwards whether anything has >been done? A silly example: > > processed = 0 > for x in iterator: > process(x) > processed = processed + 1 > if processed: > # ... > You can avoid flag bumping in the loop: >>> x = object(); idx=id(x) >>> for x in iter(''): print x, ... >>> id(x)==idx 1 >>> for x in iter('abcd'): print x, ... a b c d >>> id(x)==idx 0 Regards, Bengt Richter From skip at pobox.com Tue Jul 8 10:59:41 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 09:59:41 -0500 Subject: anything new on the ternary operator? In-Reply-To: <40a939c9.0307080622.3118cfd7@posting.google.com> References: <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com> <40a939c9.0307080622.3118cfd7@posting.google.com> Message-ID: <16138.56413.684250.921762@montanaro.dyndns.org> >> [The consensus in EP was that Israel was in Europe] Alia> Sorry, I am confused: isn't Israel in the Middle East? Sure, but what continent is the the Middle East in, Europe, Asia or Africa? I had to make the same decision in Musi-Cal. I decided that Israel was part of Europe. The decision wasn't entirely arbitrary. Most concert dates we list for Asia are in Japan, Korea or Hong Kong. There are almost never any African concert dates listed. Israel was close enough to Europe that it made sense to group it there. Skip From alanmk at hotmail.com Tue Jul 29 12:29:57 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 29 Jul 2003 17:29:57 +0100 Subject: Casting stones (was Re: Debugging Python ?) References: <84fc4588.0307290453.52671e11@posting.google.com> <3F268802.BDB26B67@hotmail.com> Message-ID: <3F26A105.29AD2EC9@hotmail.com> [Aahz] >>> Top-posting is more annoying IMO. [Alan Kennedy] >>However, there is a down side: it makes it impossible to get >>meaningful summaries of a posters posting history on Google Groups. [Aahz] > To the extent that's an issue (and I don't necessarily agree that it is > an issue), I consider that Google's fault for not writing software that > accounts for quoting. If/when they fix their software, that solves the > issue from your perspective; in the meantime, we get easier-to-read > threads in realtime. I agree that Google could try harder, and also agree that we should not start top-posting, just to hack around Google. It is interesting to note that the Timbot's style of posting seems to address this problem, if not solve it. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=author:tim.one%40comcast.net+ It uses a style I have copied in this message, which is [Original poster] > What the original poster said With only a single line break between the two lines. The Timbots "summary view" at least shows that the text one one is seeing in the summary are the words of someone else. My own posting style, which is Original Poster: > What the original poster said fails to achieve that. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=author:alanmk%40hotmail.com+ Let's see how this message turns up on Google Groups. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From rimbalaya at yahoo.com Fri Jul 25 00:27:38 2003 From: rimbalaya at yahoo.com (Rim) Date: 24 Jul 2003 21:27:38 -0700 Subject: Why instancemethod when I can add functions to classes outside class body? Message-ID: <6f03c4a5.0307242027.85f195a@posting.google.com> Hi, It appears to me the simplest way to add a function to a class outside of the class declaration is as follows: >>> class a(object): ... pass ... >>> def f(self): ... print 'hi' ... >>> a.f = f >>> b=a() >>> b.f() hi It works even when the class and the function are in defined in different modules, and the call to the method in a third module. So what problem is the new.instancemethod() trying to solve? It is ok to point me to a PEP or the like. Thanks, - Rim From abelikov72 at hotmail.com Thu Jul 10 16:59:03 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 10 Jul 2003 20:59:03 GMT Subject: Embedding Python, threading and scalability References: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> <1057814773.188737@yasure> <7kergv8u1q5oib600e4ino24tf9fioo2gc@4ax.com> <3F0DC024.5A73B11B@engcorp.com> Message-ID: <1qkrgv0o2hcsvo8k95ljtsnhar5n5eljao@4ax.com> On Thu, 10 Jul 2003 15:36:04 -0400, Peter Hansen wrote: >Afanasiy wrote: >> >> On Thu, 10 Jul 2003 05:26:14 -0000, "Donn Cave" wrote: >> >> >Quoth Jeff Epler : >> >> >At any rate, it sure isn't because Guido can't scare up an SMP machine. >> >> Is this the absolute truth or just something people like to say? >> >> If it is true I am very surprised... I think getting Guido an SMP >> machine will not be very difficult, and could well be very cheap. > >Note the double negative in the phrase "isn't because Guido can't". > >That means in effect "Guido can". Nobody's disagreeing with that. Yes, I read a previous post which said "Give Guido a SMP machine." and read this one as the same, my mistake. From srijit at yahoo.com Thu Jul 10 05:02:52 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 10 Jul 2003 02:02:52 -0700 Subject: numpy and scipy for Python 2.3 Message-ID: <221d8dbe.0307100102.425cbba8@posting.google.com> Hello, I am interested to have numpy and scipy for Python 2.3 on Windows 98. Only binaries for 2.1 and 2.2 are available for download now. Can I easily create binaries for numpy and scipy from the sources? If so how? I am looking forward for some guidance. Regards, Srijit From tom.bradshaw at zytek.co.uk Tue Jul 8 06:20:52 2003 From: tom.bradshaw at zytek.co.uk (TB) Date: 8 Jul 2003 03:20:52 -0700 Subject: COM Programming Message-ID: <6308fa3f.0307080220.5889317b@posting.google.com> Hi, I am writing a COM object (in Delphi) to be accessed from an application using Python, this application is using 1.5.2, does this support the same COM functions as 2.2.3 that I have been testing with until now? are there any known issues? Also has anybody got any references to more info about Python using COM? Thanks Tom From jdhunter at ace.bsd.uchicago.edu Thu Jul 31 18:00:08 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 31 Jul 2003 17:00:08 -0500 Subject: Python speed vs csharp In-Reply-To: (Mike's message of "Wed, 30 Jul 2003 23:09:22 -0700") References: Message-ID: >>>>> "Mike" == Mike writes: Mike> My second question is, is there anything that can be done to Mike> get Python's speed close to the speed of C#? Can you use scipy? erfc is implemented in the scipy.stats module, which runs about 3 times faster than the pure python version in my simple tests. JDH From adalke at mindspring.com Mon Jul 14 12:44:59 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 14 Jul 2003 10:44:59 -0600 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: Alan Kennedy: > I'd love to hear of other similar phrases. And somehow I intuit > there's people in this ng who know lots of them :-) Related, for speech recognition: "It's hard to recognize speech" "It's hard to wreck a nice beach" (! Only 9 Google hits for "wreak a nice beach" and none for the full phrase?) And I tell the story about how in 9th grade we did sentence diagrams (a form of parse tree developed by english majors :) and the first one was "Have you ever seen a pilot fish?" Turns out this is ambiguous. I have two uncles who are (or were) pilots, so I was thinking - have I ever seen them fish? Not, "ahh, a 'pilot fish', like on sharks." The rest of the assignment was equally difficult if you didn't realize the difference. That was 20 years ago, and I'm still annoyed :) Andrew dalke at dalkescientific.com From kp at kyborg.dk Thu Jul 10 05:33:24 2003 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 10 Jul 2003 11:33:24 +0200 Subject: mx odbc In-Reply-To: References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> Message-ID: <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> David Bolen wrote: > Kim Petersen writes: > > >>I'm not arguing that thats not important - *but* paying 70$ >>pr. customer, is the equivalent of paying you for 1hr of support for >>each customer [not installation mind you], where our own >>licence/supportcost is already getting lower and lower... I find that >>_extremely_ steep - i could and would accept such a cost for the >>python platform (no trouble!) [except in the few (from our view) cases >>where the user just needs a small tool. > > > Except that if you're going to resell a product, presumably you'd go > for the per-developer fee ($1250). We work in teams - so that would be 1250*4 making the below calculation 18*4 (and we're not able to pull in freelancers on this kinda stuff then - other than paying another 1250). [Note: i'm being honest to the gist of the licence here - you could argue for one developer fee, rest of the developers run pr.CPU licence, and you build project on the developer machine for final wrapping] > It'll beat the per-CPU license at > about 18 customers (assuming one CPU per customer), and just continue > shrinking on a per-customer basis after that. In effect, the > per-developer license is a one time, royalty free, license, the > marginal unit cost of which disappears over time. As with anything, > the actual price is up to the owner to set, but on our part, we've > found the economics reasonable for the functionality supplied within > our commercial endeavors. > > Is it the only way to go for database access with Python - certainly > not. But for us (Windows platform with ODBC sources) its worth it for > the effort Marc-Andre has put in to best support ODBC in that > environment. Not arguing about Marc-Andre's fine contributions - they are excellent ;-) I have no idea about the support (obviously) - but then i hardly ever buy/use support for development tools [especially not open-source ones]. > > Just another data point for what it's worth. > > -- David -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From martin at v.loewis.de Sun Jul 13 16:22:31 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 13 Jul 2003 22:22:31 +0200 Subject: =?UTF-8?B?w7HDr8Olw7jDqMOgw6sgw6TDq8O/IMOww67DscOxw6jDqcOxw6o=?= =?UTF-8?B?w6jDtSDDr8Oow7LDrsOtw7nDqMOqw67DoikpKQ==?= References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F11D94A.7050208@removeme.free.fr> Message-ID: <3F11BF87.9000208@v.loewis.de> Bruno Desthuilliers wrote: >> On second thought, what's he saying? >> > > He said : > "?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? > exe-???? ?????????)." That's not what he said. Instead, he said "?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? exe-???? ?????????)." To see that, you have to read the message in windows-1251. I think this roughly translates into "Can you please tell me where to find the proggie freezer (which appears to be needed to create exes)?" The program is called freeze, and it is located in the Tools directory, atleast of the source distribution. See the FAQ for other options to create exes. Regards, Martin From max at alcyone.com Fri Jul 18 23:14:18 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 18 Jul 2003 20:14:18 -0700 Subject: scanf string in python References: <3F178783.41DCA40F@alcyone.com> Message-ID: <3F18B78A.346D65A8@alcyone.com> Bengt Richter wrote: > Did you use the regex parens for a reason I am unaware of? > > >>> import re > >>> re.findall(r'(\d+)', '(1, 2, 3)') > ['1', '2', '3'] > >>> re.findall(r'\d+', '(1, 2, 3)') > ['1', '2', '3'] Habit. In any other context, I'd want to isolate those buggers in a group, so that's what I wrote that here. I wasn't specifically aware that they were unnecessary with re.findall. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I'm sharing the joy / I'm glowing like sunshine \__/ Chante Moore From jjl at pobox.com Tue Jul 29 16:55:12 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 21:55:12 +0100 Subject: urllib2 http status References: Message-ID: <87y8yh59zj.fsf@pobox.com> rosendo at dbora.com (rosendo) writes: > I'm writing a http client to test some applications. > The code below it's the core of the client: [snip] You're using *both* urlopen *and* add_cookie_header / extract_cookies. Don't do that. urlopen calls those methods itself. Also, HTTPError is a subclass of URLError, so your second except: suite will never be reached. I'm not sure what the purpose of the empty except: there is, either -- why not just let the exception propogate to top level? The unreleased version of ClientCookie can do Referer automatically. Ask me if you want a copy (the release is waiting for somebody to look at an RFE for urllib2 that I've posted). Also, Python doesn't use semicolons , and the second 'argument' to except receives an exception, not a exception message (string). > Before this code we declare c = ClientCookie.Cookies(), etc...... > Then i don't know how to know the status of the response, because the > property: > response.info().status seems not to function like i wait, that it's > with an 200, 301, 400, etc..... > How can obtein this status? If you get a returned response, it's always 200. For non-200 responses, urllib2 always raises an exception. It's probably a wart, but too late to change now. Corrected code (untested, since incomplete): try: start_ts = time.time() request = urllib2.Request('http://%s%s' % (req.host, req.path), req.data, req.headers) request.add_header("Referer", 'http://%s%s' % (req.host, req.path)) c.clear() #request = urllib2.Request('http://www.google.com') try: response = urllib2.urlopen(request) data = response.read() headers = response.info().headers #status = response.info().status except urllib2.HTTPError, e: print "URLError: ", e # Note: e.msg, e.code are what you want. # IIRC, HTTPError works just like a response object, too. duration = time.time() - start_ts print ('The result had status: 200 duration: %5.2f http://%s%s' % (response.info().status, duration, req.host,req.path)) except: print sys.exc_type,sys.exc_value print 'cagadita....' + str(req) John From pyth at devel.trillke.net Fri Jul 25 10:37:57 2003 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 25 Jul 2003 16:37:57 +0200 Subject: path module In-Reply-To: <11234c14.0307211016.344d40bc@posting.google.com>; from jason.orendorff@lumigent.com on Mon, Jul 21, 2003 at 11:16:57AM -0700 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <20030725163757.N6906@prim.han.de> Jason Orendorff wrote: > I wrote the 'path' module at: > http://www.jorendorff.com/articles/python/path > > There was some discussion on it here: > http://groups.google.com/groups?th=42ab4db337b60ce3 > > Just a few comments: > > Ian and Holger wondered why 'path' should subclass 'str'. It's because > a path is a string. Benefit: you can pass 'path' objects to functions > that expect strings (like functions in 'win32file'). I find this > really useful in practice. IMO you'll almost never use the following string-methods on a 'Path' object: capitalize center count decode encode expandtabs find index isalnum isalpha isdigit islower isspace istitle isupper ljust lstrip rjust splitlines startswith swapcase title translate zfill and so these methods pollute a Path object's name-space quite a bit. Also 'join', '__contains__', startswith etc. produce some ambigouity. I think it's convenient enough to use "str(path)" if passing a 'path' instance as a string somewhere. cheers, holger From kmj9907 at cs.rit.edu Mon Jul 28 16:45:13 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Mon, 28 Jul 2003 20:45:13 GMT Subject: How to reverse lookup characters in list? References: Message-ID: > Or just list(string.lowercase]) > [snip] > Haha.. I KNEW there was a better way to do it! It was late, I was tired, I had list comprehensions on my mind, . :) Keith From hwlgw at hotmail.com Sat Jul 5 15:21:36 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 5 Jul 2003 12:21:36 -0700 Subject: Bewildered graphs References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: > [Mark Fenbers] > I am investigating Python for the sake of ultimately generating hydrographs > (such as this: http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) > on-the-fly from a web server cluster. You are thinking about generating a .PNG or .JPG or .GIF or something like that? I have an idea: if your app is running on a web server cluster already, how about generating dynamic web pages displaying the graph. You could for example display this whole picture with SVG (http://www.w3.org/TR/SVG/ ). Even a simple CGI script in Python generating HTML plus CSS using "position: absolute" can do much like this. Note the BIG advantage of such a web application: everybody can use it with their browser; no installations, compilations, configurations. And the best way to generate SVG or HTML with Python from CGI is just using the string library and writing your own functions for things you notice you do often. [ I *know* they plan to deprecate the string library. But most web hosting Pythons are still 1.5.2 :-! ] -- Do you feel lucky punk? Make my day. From robin at jessikat.fsnet.co.uk Thu Jul 31 04:01:40 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 31 Jul 2003 09:01:40 +0100 Subject: PIL & TIFF transparency? References: Message-ID: In article , Myles writes >Robin Becker wrote in message news:Y at jessikat.fsnet.co.uk>... >> Has anyone done transparency with PIL & TIFF? I'm using PIL to generate >> a preview TIFF for embedding into an eps file and am being asked for the >> TIFF to support transparency. > >Simple example that makes pure white areas of an RGB image transparent >(there's probably a better way to create the mask, and a better way to >add the mask to the image, but this gives you a starting point): > >import Image, ImageChops >im = Image.open('/junk/pickme.png') ># create mask (will become alpha band i.e. transparency) >mask = im.point(lambda i : i == 255 and 255) # create RGB mask >mask = mask.convert('L') # mask to grayscale >mask = mask.point(lambda i : i == 255 and 255) # mask to B&W grayscale >mask = ImageChops.invert(mask) ># merge mask with image >R, G, B = im.split() >nuimg = Image.merge('RGBA', (R, G, B, mask)) >nuimg.save('/junk/out.tif', 'tiff') > >Regards, Myles. thanks very much, I didn't know the TIFF format even supported transparency till yesterday and now you say the PIL tiff plugin will handle it ok. Great work pythoneers! -- Robin Becker From alanmk at hotmail.com Sun Jul 20 10:16:48 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 20 Jul 2003 15:16:48 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> Message-ID: <3F1AA450.765D07FD@hotmail.com> Alan Kennedy wrote: >> One person, Bengt, said that he couldn't see it Ben Finney wrote: > This is identical to the justification of "$BIGNUM percent of our > target users use browser $BROWSER, so we can ignore the rest and > use methods only viewable by browser $BROWSER." Hmm, I fail to see the connection here. Fair enough, I made a mistake in structuring my original xml snippet. I didn't attempt to address the fact there are still some browsers out there that don't do XML. Bengt corrected that mistake by providing an HTML snippet that works in non-XML browsers as well, i.e. a superset of the set I covered. Given the current market breakdown for browsers, I guesstimate that Bengt's snippet worked for > 99.9% of recipients. > Which quickly leads to "You must use $BROWSER to view this site". > No thanks. No, that's the precise opposite of the point I was making. My position is "You must use markup-capable software to perceive what I've written. Your choice of software is entirely up to you: the only requirement is the ability to process (x|ht)ml". I try to avoid platform/language/os/browser dependent anything: that was the whole point of the post. > Provide a method that degrades gracefully to ASCII, the current > standard; then I'll be interested. #------------------------------------------------------------ snippet = """ γίγνωσκω """ def is7bitclean(s): for c in s: if ord(c) > 127: return 0 return 1 if is7bitclean(snippet): print "Yep, it's clean." else: print "Thou hast broken the rules." #------------------------------------------------------------ Is that what you meant by "graceful degradation to ASCII"? The 7-bit cleanness of my original snippet was the reason why it arrived safely in everyone's "inbox". Bengt's even-further-travelling HTML snippet is also 7-bit clean. And if the message structures used in the protocol transporting the messages were encoded in XML, you wouldn't even have seen any encoding declarations or pointy brackets, or had to copy&paste. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From nholtz at docuweb.ca Mon Jul 28 10:29:38 2003 From: nholtz at docuweb.ca (Neal Holtz) Date: 28 Jul 2003 07:29:38 -0700 Subject: floating point range generator References: <7xwue3lbzy.fsf_-_@ruckus.brouhaha.com> <7O%Ua.8994$AO6.2045@nwrdny02.gnilink.net> Message-ID: <639f17f8.0307280629.503c5533@posting.google.com> Carl Banks wrote in message news:<7O%Ua.8994$AO6.2045 at nwrdny02.gnilink.net>... > ... > A more robust version would look something like this (but it still has > problem #3): > > def frange(start, stop, step=1.0): > sign = cmp(0,step) > for i in xrange(sys.maxint): > v = start+i*step > if cmp(v,stop) != sign: > break > yield v > > The most robust way to handle this is to iterpolate, i.e., instead of > passing start, stop, and step, pass start, stop, and n_intervals: > > def interiter(start, stop, n_intervals): > diff = stop - start > for i in xrange(n_intervals+1): > yield start + (i*diff)/n_intervals > > An IEEE 754 (whatever) geek can probably point out even more accurate > ways to do these. You can easily invent examples where the number of elements generated may (or may not) suprise you. Here is an implementation that attempts to account for some of the problems of floating point arithmetic: # (See http://www.python.org/doc/current/tut/node14.html) def epsilon(): """Compute machine epsilon: smallest number, e, s.t. 1 + e > 1""" one = 1.0 eps = 1.0 while (one + eps) > one: eps = eps / 2.0 return eps*2.0 _Epsilon = epsilon() def frange2( start, stop, step=1.0, fuzz=_Epsilon ): sign = cmp( step, 0.0 ) _fuzz = sign*fuzz*abs(stop) for i in xrange(sys.maxint): value = start + i*step if cmp( stop, value + _fuzz ) != sign: break yield value And we can generate a bunch of test cases to compare this implementation with the first one above: for step in frange( 0.0, 1.0, 0.01 ): for stop in frange( 0.01, 10.0, 0.01 ): l1 = [x for x in frange( 0.0, stop, step )] l2 = [x for x in frange2( 0.0, stop, step )] if l1 != l2: print stop, step, len(l1), len(l2) print repr(stop), repr(step) print l1 print l2 print The first of many the differences noted is this: 0.06 0.01 7 6 0.060000000000000005 0.01 [0.0, 0.01, 0.02, 0.029999999999999999, 0.040000000000000001, 0.050000000000000003, 0.059999999999999998] [0.0, 0.01, 0.02, 0.029999999999999999, 0.040000000000000001, 0.050000000000000003] Under most normal output conditions, you would think that the stop value was 0.06 and the step was 0.01, so you would expect to get 6 elements in the sequence. Yet the first implementation gives you 7. This might be surprising, as under most output conditions the last value would appear to be equal to the stop value. Of course, the actual stop value is just slightly greater than 0.06. The second implementation gives you 6 elements in the sequence; though it can be argued which is "correct", the second implementation is probably less surprising in most cases. This is just another example, of course, of the idea that if it really, really matters how many elements are in the sequence, don't use floating point arithmetic to control the # of iterations. From chema-news at chema.homelinux.org Sun Jul 20 06:23:24 2003 From: chema-news at chema.homelinux.org (=?iso-8859-1?Q?Jos=E9_Mar=EDa?= Mateos) Date: Sun, 20 Jul 2003 12:23:24 +0200 Subject: "Pure Python" MySQL module like Net::MySQL References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 In comp.lang.python, Ravi (rxs141 at cwru.edu) wrote: > I did some googling, and found that there doesn't seem to be a pure > python MySQL communication module. There is one for perl however, I think there's a MySQLdb package for Python that might fulfill your needs. Regards, chema. - -- Chema Mateos - RinzeWind | Take out the "-news" in my e-mail address #debian-es irc.freenode.net | if replying. Message will be eaten by Jabber ID - rinzewind AT jabber.org | /dev/null if you don't. GPG-key: http://chema.homelinux.org/~chema/key.asc -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE/Gm2c9P6GbSlI+hkRAg+dAJ9MQWl33yv7+nRkKCWZjLixguW8DACgjQ+D sxGBFj4nUORjCOq4pgIoEHI= =dU1C -----END PGP SIGNATURE----- From wim_wauters at skynet.be Wed Jul 9 14:27:29 2003 From: wim_wauters at skynet.be (WIWA) Date: 9 Jul 2003 11:27:29 -0700 Subject: SNMP support for Python under Windows Message-ID: <538fc8e.0307091027.1825b454@posting.google.com> I'm looking for SNMP support in Python. I have found pySNMP, but I'm not sure whether this works under Windows as well. A few questions: 1) Where do I need to install the pySNMP files? 2) What do I have to do in order to be able to write somethin like: "from pysnmp import session" Thakns in advance for all input From writeson at earthlink.net Mon Jul 7 17:26:23 2003 From: writeson at earthlink.net (Doug Farrell) Date: 7 Jul 2003 14:26:23 -0700 Subject: re module substitution confusion Message-ID: <88bc63c6.0307071326.3eb60848@posting.google.com> Hi all, I'm trying to do the following from within a code module: import re # text to match text = "Good morning x something /x, how are you today x something else /x" # pattern to match regex = re.compile("(x)(.*?)(/x)", re.DOTALL) # find first match m = re.search(regex, text) # keep looking while there are matches while m != None: # substitute in some other text for the exact match text = re.sub(m.group(), "Mr. Phelps", text) # find the next match m = re.search(regex, text) print text This works within the Python shell, but I can't seem to make it work from within a program. It would seem like the re.sub(m.group()...) would work fine as m.group() just returns the matched string completely. Any help would be greatly appreciated, Doug Farrell From aahz at pythoncraft.com Tue Jul 29 10:11:09 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2003 10:11:09 -0400 Subject: Casting stones (was Re: Debugging Python ?) References: <3c91a864.0307282013.2acb2d1f@posting.google.com> <84fc4588.0307290453.52671e11@posting.google.com> Message-ID: In article <84fc4588.0307290453.52671e11 at posting.google.com>, Anand Pillai wrote: > >It would be nice if you could give a name to your email address, i.e if >you are not that paranoid as it seems. Top-posting is more annoying IMO. I remember e-mail addresses better than names, anyway. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From amk at amk.ca Thu Jul 31 11:19:10 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 31 Jul 2003 10:19:10 -0500 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <1sScnW0Sv7DzrrSiRTvUpQ@speakeasy.net> On Thu, 31 Jul 2003 08:06:29 -0500, Skip Montanaro quoted: > Ben> doing... I'm just a newbie who's found date and time handling in > Ben> Python to be confusing, and thought I'd mention it. (And I am the > Ben> original poster, btw.) If nobody else agrees, maybe it's not > Ben> really a problem. It's also not very hard to write a PEP; start with an existing PEP for the headings, and skim PEP 1 for the PEP life cycle. Parsing of date/time formats is the big omission from 2.3's date support and the big advantage that mxDateTime still has. With 2.3 you still have to roll your own parser for ISO-8601 format or whatever. Fixing the rfc822 module is probably the largest problem; we can't just change getdate() to return a datetime instead of a 9-tuple, so it'll have to be supported as a new method. The standard library should probably use datetime as much as possible, but backwards-compatible 9-tuple-based interfaces will still need to be supported. --amk (www.amk.ca) Hello! I'm the Doctor. I believe you want to kill me. -- The Doctor, in "Silver Nemesis" From ta-meyer at ihug.co.nz Tue Jul 22 21:33:39 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 23 Jul 2003 13:33:39 +1200 Subject: [OT] RE: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F8E3D@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AB7C@its-xchg4.massey.ac.nz> > Spelling variations cause some challenge. For example, > B WRIGHT > BILL WRIGHT > WILLIAM WRIGHT > WILL WRIGHT > WILIAM WRIGHT > WILLIAM WRITE > might all refer to the same person. I don't understand you crazy Americans :) Names aren't unique identifiers - what happens when I write in "William Wright", meaning William Wright that lives next door to me, and you write in "William Wright", meaning William Wright who lives a few streets away from me? (Assuming that William Wright wins, is the the first guy by that name who stands up that becomes president?) =Tony Meyer From richardc at hmgcc.gov.uk Wed Jul 16 06:40:52 2003 From: richardc at hmgcc.gov.uk (richardc) Date: Wed, 16 Jul 2003 11:40:52 +0100 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: <3f152bb4$1@mail.hmgcc.gov.uk> 'Question 8' Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's fixed format syntax. I can only think of Python and FORTRAN off the top of my head which use whitespace as part of the syntax. As an aside, is there any reason that people like O'Reilly books use a picture of a snake on the front cover? Its not named after the snake. Should we have the 'Python programming red book' (blue cover), and the 'Python pocket reference' (a 3000 page tome of a reference book). Just my thoughts Rich "Anand Pillai" wrote in message news:84fc4588.0307152253.20858619 at posting.google.com... > Hi Pythonistas, > > I have placed a quiz on Python on the trivia site www.funtrivia.com. > Here is the link. > > http://www.funtrivia.com/quizdetails.cfm?id=139672 > > Looks like it is the first quiz on Python on this site. > > Please try it out if you like quizzing. > Let me know if there are any factual errors. > > Thanks > > ~Anand From ricardo.b at zmail.pt Thu Jul 17 22:43:31 2003 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Fri, 18 Jul 2003 03:43:31 +0100 Subject: Looking For A Wildcard File Name Parser References: Message-ID: import glob On Fri, 18 Jul 2003 01:40:07 +0000, YoTuco wrote: > I've been looking for a good wildcard file name parser. That is, some module > in Python or something someone has made that can take a file name with the > '*' or '?' wildcards in it, parse a list[] and give back the matches. It > seems like a common enough task that one would be around? Or do I just > have to roll up my sleeves, dig-in and learn RE? > > Thanx in advance for your input. > > --YoTuco -- Ricardo From bobx at linuxmail.org Tue Jul 8 20:06:59 2003 From: bobx at linuxmail.org (Bob X) Date: Wed, 09 Jul 2003 00:06:59 GMT Subject: ftp a file by date and name match References: <1001ff04.0307080629.7ef1e277@posting.google.com> Message-ID: "John Hunter" wrote in message news:mailman.1057683552.18026.python-list at python.org... > >>>>> "Bob" == Bob writes: > Perhaps you'll join the ranks of the converted? > > JDH Perhaps! I am looking forward to 2.3. From peter at engcorp.com Thu Jul 10 16:16:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 16:16:14 -0400 Subject: A very short story about Python in a Nutshell Message-ID: <3F0DC98E.BDC96606@engcorp.com> So there I was just sitting there, minding my own business, and in walks one of the programmers, holding "Python in a Nutshell". [1] "Peter," he says, "this has gotta be the best book you've bought so far. [2] Every thing I need to look up, it's got it." THE END (I told you it was a very short story.) -Peter [1] http://www.amazon.com/exec/obidos/ASIN/0596001886/qid%3D1057868151/sr%3D11-1/ref%3Dsr%5F11%5F1/102-0808187-6963307 [2] I've bought at least 50 computer books in the last couple of years. From danb_83 at yahoo.com Wed Jul 2 22:41:58 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 2 Jul 2003 19:41:58 -0700 Subject: whitespace and ?asc()? References: <3F02086D.9010300@ihug.co.nz> Message-ID: Steven Taschuk wrote in message news:... [snip] > Note also that at the interpreter prompt you can (some of) those > ASCII codes in hex just by looking at the value of the string: > > $ python > ... > >>> import string > >>> string.whitespace > '\t\n\x0b\x0c\r ' > > If your ASCII chart doesn't have hex, continue with > > >>> 0x0b, 0x0c > (11, 12) > > to obtain the decimal values. FYI, '\x0b' == '\v' (vertical tab) '\x0c' == '\f' (form feed) From peter at engcorp.com Sun Jul 6 22:50:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Jul 2003 22:50:55 -0400 Subject: Using Loops to track user input References: Message-ID: <3F08E00F.69360669@engcorp.com> Gerhard H?ring wrote: > > hokiegal99 wrote: > > I don't understand how to use a loop to keep track of user input. Could > > someone show me how to do what the program below does with a loop? > > Your text book or tutorial should show that quite well, but here we go: [snip] > If your prof is any good, (s)he reads this newsgroup as well ;-) You missed this one Gerhard. In another thread, hokiegal99 already told us "I am a funeral director trying to write a small program that calculates the number of years, months and days a person has lived by entering the year, month and day of their birth. ..." Not homework this time. :-) -Peter From tomg at em.ca Wed Jul 16 23:41:54 2003 From: tomg at em.ca (Tom Goulet) Date: Thu, 17 Jul 2003 03:41:54 -0000 Subject: hex to signed integer References: Message-ID: Steven Taschuk wrote: > return struct.unpack('!i', binascii.unhexlify(s))[0] Hmm, is not in in Python 1.5.2. > (This will not be the inverse of '%08x' % n in Python 2.4, when > '%x' % -1 will produce '-1', but I think it does what you want.) | >>> print "%08X" % -1294044542 | __main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a \ | signed string in Python 2.4 and up Argh. Thanks for warning me. I only want to store thirty-two bits as an integer and input and output that value of hexadecimal in Python versions 1.5.2 through 2.4, and it's causing me a lot of grief. It looks like I'm going to have to resort to for both input and output. > value = long(s, 16) A second argument to is not in Python 1.5.2, either. Using from instead works. Thanks! -- Tom Goulet, tomg at em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html From bogal2 at comcast.net Tue Jul 15 14:31:46 2003 From: bogal2 at comcast.net (BogAl) Date: Tue, 15 Jul 2003 13:31:46 -0500 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: > >> Try putting the .pyd in C:\Python22\Lib\site-packages > > BogAl> Unfortunately, I'm still getting the error message. > > Dave> Does it work if you put the csv.pyd file in the current directory? Yes, it does. What does that mean I should do now? From fightplatetectonics at yahoo.com Fri Jul 25 11:26:12 2003 From: fightplatetectonics at yahoo.com (Fightplatetectonics) Date: 25 Jul 2003 08:26:12 -0700 Subject: [ANN] PyHtmlTable: New Python CGI table generating utility Message-ID: <2e1f08c5.0307250726.14b82d50@posting.google.com> What: Html Table generation on the fly. Why: Couldn't find a python equivalent to Table.pm or Table.php If you're using python cgi's to generate tables, it might be worth a look. Ultra simple example: t = PyHtmlTable( 1, 2, {'width':'400','border':2,'bgcolor':'white'}) t.setc( 0, 0, "First cell", {'bgcolor':'red'} ) t.setc( 0, 1, "2nd cell" ) t.display() Voila, you've got a table, but wait there's more....(The bamboo wok is coming soon) More Features: Autogrows table if cells set outside initial range. Allows dynamic insertion of new rows and columns anywhere in the table Allows setting of individual row and cell attributes via arbitrary dictionaries Allows spanning of rows and columns Allows bulk population of table data via arrays to arbitrary locations in the table. Provides default cell attributes for tablewide uniformity and the ability to override these on a cell by cell basis. It's fun, it's free, it's on freshmeat: http://freshmeat.net/projects/pyhtmltable/ Cheers, fptt. From andy at wild-flower.co.uk Fri Jul 18 16:34:30 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 18 Jul 2003 21:34:30 +0100 Subject: Python dictionary syntax, need help In-Reply-To: <56ba0aea.0307181142.7401aa02@posting.google.com> References: <56ba0aea.0307181142.7401aa02@posting.google.com> Message-ID: <200307182134.30354.andy@wild-flower.co.uk> On Friday 18 Jul 2003 8:42 pm, Crew Reynolds wrote: > I want to create a dictionary of note on/off timings and access it by > the name of the object. The following code works for one row. > > a = "Hammer1" > b = [5,45,45,45,45,50,55,57,59,61,60,59] > > notes = {a:b} > print notes["Hammer1"][3] > > >>> 45 > > The problem is, I want to load the data from a file to populate > variables a and b and build a dictionary for "Hammer1" thru > "Hammer10". That way, I can stick the name of the object in the array > index and receive a list of note timings that I can index with an > ordinal as in the above example. > > This is straight Python syntax but I'm hoping someone has done this or > understands the syntax better than I. > > Thanks! Alternative solutions to this concept would be greatly > appreciated. So you want something like: Python 2.2.1 (#1, Dec 4 2002, 23:43:31) [GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux-i386 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> notes={"hammer1": [5,45,45,45,45,50,55,57,59,61,60,59], "hammer2": [25,245,245,245,245,250,255,257,259,261,260,259], "hammer3": [35,345,345,345,345,350,355,357,359,361,360,359], "hammer4": [45,445,445,445,445,450,455,457,459,461,460,459], } >>>#let's play at indexing... >>> notes["hammer1"] [5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59] >>> notes["hammer2"] [25, 245, 245, 245, 245, 250, 255, 257, 259, 261, 260, 259] >>> notes["hammer2"][5] 250 >>> notes["hammer2"][10] 260 >>> notes["hammer4"][11] 459 >>>#what keys did we have? >>> notes.keys() ['hammer1', 'hammer3', 'hammer2', 'hammer4'] >>>#lets 'process' the dict (enumerate the keys) >>> for hammer in notes.keys(): print "hammer:",hammer, for note in notes[hammer]: print note, print hammer: hammer1 5 45 45 45 45 50 55 57 59 61 60 59 hammer: hammer3 35 345 345 345 345 350 355 357 359 361 360 359 hammer: hammer2 25 245 245 245 245 250 255 257 259 261 260 259 hammer: hammer4 45 445 445 445 445 450 455 457 459 461 460 459 >>>#Ah! the hammers are in the wrong order because dictionaries don't >>>#preserve sequences. We just need to sort the keys... >>> hammers=notes.keys() #get the keys into a list >>> hammers.sort() >>> for hammer in hammers: print "hammer:",hammer, for note in notes[hammer]: print note, print hammer: hammer1 5 45 45 45 45 50 55 57 59 61 60 59 hammer: hammer2 25 245 245 245 245 250 255 257 259 261 260 259 hammer: hammer3 35 345 345 345 345 350 355 357 359 361 360 359 hammer: hammer4 45 445 445 445 445 450 455 457 459 461 460 459 >>> #that should do it! hope that helps -andyj From stacom at stacom-software.de Fri Jul 25 08:57:57 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Fri, 25 Jul 2003 14:57:57 +0200 Subject: data conversion question (binary string to 'real string') Message-ID: Hallo all there, maby I don't see the forest because of all that trees, but : from struct import * # how can I convert f = float(0.5) # with bin_str = pack('!f', 0.5) # now bin_str is '?\x00\x00\x00' # to "3F000000" ????? Thanks a lot for any help From newsgroups at jhrothjr.com Sat Jul 12 07:51:06 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 12 Jul 2003 07:51:06 -0400 Subject: Collective memory References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: "Abigail" wrote in message news:slrnbgt6ls.ab5.abigail at alexandra.abigail.nl... > Walter Bushell (proto at panix.com) wrote on MMMDC September MCMXCIII in > : > ++ Charles Richmond wrote: > ++ > ++ > int *p, x, y; > ++ > > ++ > then: > ++ > > ++ > y = x/*p; > ++ > > ++ > is quite different from: > ++ > > ++ > y = x / *p; > ++ > > ++ > The first way, "/*" will begin a comment...the second way, > ++ > you get the integer "x" divided by the integer pointed to by "p". > ++ > ++ Ouch!! That is one reason code coloring is *important*. > > Nope. That's a reason why code colouring is evil. If you write code, > and it isn't clear what you mean without the use of code colouring, > you did something wrong. Your code shouldn't rely on a specific code > colouring scheme to be understandable. This assumes that someone reading the code is going to be using a brain-dead editor. We need to get beyond that some day, and assume that people are going to be using decent tools. John Roth > > All in my opinion of course. > > > Abigail From klappnase at web.de Wed Jul 30 05:57:54 2003 From: klappnase at web.de (klappnase) Date: 30 Jul 2003 02:57:54 -0700 Subject: Boa-Constructor and linux-mouse Message-ID: Hello everyone, I have just downloaded and installed Boa-Constructor and I am really impressed. However I found that copy and paste with the middle mouse button does not work in the editor window. Does anyone know a way to fix this or won't this work at all? Thanks in advance Michael From MK at foo.com Tue Jul 1 10:58:19 2003 From: MK at foo.com (MK) Date: Tue, 1 Jul 2003 16:58:19 +0200 Subject: PyQT and Mandrake 9.1 References: Message-ID: "Paul Grimes" wrote > > Be careful. QT is controlled by one company, > > Sort of true I'd say it's true. What do you mean by "sort of"? No matter what anybody says, Qt is controlled by Trolltech, full stop. > > and it costs money. > > Not true, unless you want to distribute a closed source program So this is "sort of true", right? An A+ for your diplomacy, however. :-) From exarkun at intarweb.us Wed Jul 23 03:37:56 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 23 Jul 2003 03:37:56 -0400 Subject: Cluster Node Auto Discovery In-Reply-To: References: Message-ID: <20030723073756.GA31466@intarweb.us> On Tue, Jul 22, 2003 at 11:18:26PM -0700, Codepunk wrote: > Hi Everyone, > > I have written a specialized server in python and now I wish to look > at making it scalable. To do this I wish to include automatic > discovery of peer nodes operating on my network. Can anyone provide me > a pointer as to how I do such a thing? By how to do it I mean how does > something like that work at the network level? > > ping scan the ip range? > some sort of broadcast packet? > udp request to entire ip range? > > I am not asking for code just how is something like that typically > done? Take a look at Rendezvous (http://developer.apple.com/macosx/rendezvous/) and Zeroconf (http://www.zeroconf.org/) Jp From owski at hotmail.com Tue Jul 15 13:45:10 2003 From: owski at hotmail.com (Adam Ruth) Date: 15 Jul 2003 10:45:10 -0700 Subject: anything like C++ references? References: Message-ID: Stephen Horne wrote in message news:... > On Sun, 13 Jul 2003 22:42:21 GMT, "Bryan" wrote: > > > > >> 3. Why is there no way to reference an immutable object via a > >> pointer, other than stuffing it into a mutable object designed for > >> some purpose other than simple pointer behaviour? > >> > > >>>> a = (1, 2, 3) > >>>> b = a > >>>> id(a) > 15471760 > >>>> id(b) > 15471760 > >>>> print b[1] > 2 > >>>> > > > > > >i just referenced an immutable object via a "pointer" and i __did_not__ > >stuff it into a mutable object as you say. > >a and b "point" to the same object. > > Technically, but what is the point? You can't do pointer-style things > with it. You can't change the object in any way without changing the > id, and you can't use the mechanism to, for instance, allow 'var' > parameters. > > In short, you are showing evidence of the use of pointers internally > within Python, but that is not the same as providing pointer-like > semantics. I came to Python from Ada, and all I have to say is: Pointer-like semantics are evil. They're worse than goto's, they're deadly, damaging, and should be avoided at all costs. They're an unhappy necessity, akin to stop-lights. You need them because roads intersect, but if roads don't intersect, don't use them! From firehawk at yifan.net Sun Jul 27 00:00:40 2003 From: firehawk at yifan.net (Dave) Date: 26 Jul 2003 21:00:40 -0700 Subject: Floyd-Warshall Algorithem in Python Message-ID: Hello, I'm looking for a Floyd-Warshall Python implementation. The only implementation I have seen (searching this newsgroup) used a Python library called "Numeric". This implementation doesn't work anymore. I was wondering whether anyone knew of any FW implementations elsewhere, or knew how I could convert the old example to Python code that would run on Python 2.2? Thanks, Dave. From dave at pythonapocrypha.com Sun Jul 6 20:19:41 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 7 Jul 2003 00:19:41 +0000 Subject: A story about Python... sort of In-Reply-To: References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <200307070019.41132.dave@pythonapocrypha.com> On Thursday 03 July 2003 11:48 pm, Russell Reagan wrote: > "Dave Brueck" wrote > > > > I > > > mean, is Linux (or Windows) 'not a viable project'?? > > > > Well, again, neither of those are "applications level" projects. > > There is a rather large industry which I'll call "computer games" that is > rather CPU intensive, and AFAIK the vast majority of those games are > written in C/C++. It really depends on the definition of "application > level". If we're only including things like word processors and web > browsers in the "application level", then there isn't a great need for C++ > in the > "application level", Actually, games are a particularly good example to illustrate the point: 1) In the movement away from a lower-level language, games are probably one of the last hold-outs since performance often means so much. Still, even games do make the transition - the transition away from assembly being the main example. 2) Even the most performance-intensive games of today are already transitioning towards higher-level languages - is there any major first-person shooter or real-time strategy game coming out these days that doesn't boast a powerful scripting language? With each new generation of games the developers try to push more and more of the functionality into their scripting engine leaving as little as possible behind in C/C++ - the render loop, *some* of the AI, etc. Not only is the game customizable by the customers, the developers themselves prefer it because of fewer bugs and it makes it much easier to try new and cool stuff out. 3) More and more of the performance-intensive work is handled by hardware nowadays anyway - both video and audio. Furthermore, the game itself usually relies on a pretty rich and powerful supporting library like OpenGL or even DirectX, which depending on the route you take can supply a ton of the functionality that the game developer would normally write in C or C++. 4) All of the above mean that in many cases you already *can* do some pretty elaborate games in higher-level languages (the games listed on Pygame are a great example), and there's every indication that the trend will continue. There came a time when it was no longer economically viable to develop an entire game in assembly, and IMO we've *already* passed the point where it's no longer economically viable to develop most games entirely in C++ - the time to market is too long, it's too expensive to add new features, recovering from early incorrect decisions is too costly, etc. Games are moving to higher-level languages as much as they can because it's a competitive advantage to do so. > but there are certainly areas where speed and memory > efficiency is important. Oh, nobody disagrees with that. But due to increases in efficiency and decreases in prices, the number of cases is shrinking wherein speed and memory constraints require you to drop to a lower-level language. -Dave From iandjmsmith at aol.com Mon Jul 28 19:13:56 2003 From: iandjmsmith at aol.com (Ian Smith) Date: 28 Jul 2003 16:13:56 -0700 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> <2dc49b63.0307240824.4e1b2136@posting.google.com> Message-ID: <2dc49b63.0307281513.103344ae@posting.google.com> "Alan Dechert" wrote in message news:... > Thanks, Ian. I could not quite figure out if your binomial distribution > calculator would be applicable. > > Here's what Bill Buck ( billbuck at cox.net ) sent me. It turns out there is a > BINOMDIST function in Excel. I think it might be what I want. > > http://home.earthlink.net/~adechert/LOTAcceptanceCalculator.xls > > Let me try to clarify what I'm after. The paper record should always match > the electronic record. So the allowable defects is zero. If there is a > mismatch found in the sample, we don't publish the electronic tally: we take > all the paper ballots and check them. > > We are talking about an election conducted with computer-generated paper > ballots. The paper ballots represent the actual vote since these ballots > are what voters actually saw, verified, and cast. We will have an > electronic record obtained from the computers which should match each paper > ballot generated. We want to use the electronic record since it will give > us an instant result -- but we have to check it against the paper ballots to > be sure the election result is correct. So, in this scenario, the > electronic count is a prediction (or preliminary tally). > > So, if by the preliminary electronic tally a candidate won a race by 1 > percent, I want to know how many ballots we have to check (random sample) to > be certain that the result predicted is true. > > When I put one million into this Confidence Level Calculator, and Acceptable > Quality Level of .01, a sample of 10,000 shows a confidence level of "1." A > sample of 2000 give C.L of 0.999999998 Presumably, "1" is really > .9999999999+ more 9s. Can we get more decimal places? > > So I guess the Lot Fraction Defective is analgous to the predicted victory > margin. Is that right? > > I would still like a standalone calculator that doesn't require Excel. > > Alan Dechert The BINOMDIST function in Excel calculates either the cumulative probability function or the probability mass function for the binomial distribution. BINOMDIST is usually accurate when it works but is known to fail with large numbers of trials, small event probabilities etc. The functions used by the calculators in http://members.aol.com/iandjmsmith/EXAMPLES.HTM are somewhat more robust and more accurate than BINOMDIST. I gather what you want is to choose a sample size based on how may mismatches there would have to be to change the result. If any mismatches are found then you take all the ballot papers and check them. This would mean that the closer the result was, the bigger the sample size would have to be. In the case where the electronic count is a dead heat all ballot papers would have to be checked! If so then the spreadsheet at http://home.earthlink.net/~adechert/LOTAcceptanceCalculator.xls is doing roughly what you want. There appears to be a slight error in there where it uses $C$4 instead of $D$4 in cells C15 to V42, although it is irrelevant to you since the value in $C$4 is 0 anyway. If it used =BINOMDIST() instead of =1-BINOMDIST() in cells C15 to V42 then you would be able to see how small the probability of not seeing a mismatch is (i.e. you don't really need more decimal places). What I'm not sure of is whether "The Lot Fraction Defective" is analagous to the predicted victory margin or to twice the predicted victory margin. This would depend on whether mismatches were ignored or counted the other way round. The only real problem is that since the sample size could be large relative to the population size, the binomial distribution may not provide an adequate approximation to the Hypergeometric distribution (I assume you will be using sampling without replacement - the binomial is strictly only correct for sampling with replacement). Using the Hypergeometric calculator, if we have 1 million ballot papers and 100 mismatches could cause the result to be changed then the probability of observing 0 mismatches will depend on the sample size as follows sample size probability of failing to detect a mismatch when it might matter 100 0.99 1000 0.90 10000 0.37 1000000 2.65e-5 2000000 2.03e-10 If we have 1 million ballot papers and 10000 mismatches could cause the result to be changed then the probability of observing 0 mismatches will depend on the sample size as follows sample size probability of failing to detect a mismatch when it might matter 100 0.37 1000 4.30e-5 10000 1.35e-44 While the calculators at http://members.aol.com/iandjmsmith/EXAMPLES.HTM are useful in their own right, they are really supposed to be a demonstration of how to use the functions in myfunctions.js so people can then use the functions in their own software! In this case what we really want is to choose the sample size required given a total number of ballots, the critical number of mismatches and the probability that we do not detect a mismatch. The calculations are fairly simple and you can build your own calculator for this quickly and easily (see http://members.aol.com/iandjmsmith/reqss.htm). With this calculator, we can see that if we have a million ballot papers and the probability of failure to detect a mismatch is 1e-6, then the minimum sample size is related to the critical number of mismatches as follows:- Critical number of mismatches Sample size required 1 999999 10 748808 100 129031 1000 13714 10000 1374 100000 132 200000 62 300000 39 500000 20 900000 6 Ian Smith From elw at euc.cx Wed Jul 30 02:28:26 2003 From: elw at euc.cx (Jeffrey P Shell) Date: 29 Jul 2003 23:28:26 -0700 Subject: Web tool kit : pro - cons ? References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f24f3f7@shknews01> Message-ID: <240b1020.0307292228.35cc8d08@posting.google.com> "Remi Delon" wrote in message news:<3f24f3f7 at shknews01>... > The problem is that most people are "experienced users" with only a few of > the frameworks. > In order to find out all the little caveats of a perticular framework, one > has to use it for quite a big project (I'd say at least 6 months). > I don't think any of us have developed such big projects with more than, > say, 2 or 3 python frameworks. (in my case, I've only used Zope and CherryPy > for "real" applications. I've only "played" with the other frameworks). > This is why it is hard to have one person make a comparison of all the > frameworks ... That's very true. I've been using Zope, Principia, and Bobo almost back to their inception, and can't even grok other systems now. No offense to CherryPy or any of the other ones. But once you get proficient in a tool, it's hard to spend time with another when time is.. Well. What is time and who has it anyways? :) I've played with a couple of other Python web frameworks, I've even written my own (way back in the day when WebObjects was the only major app server on the market and *everything* else was home grown, and Java was still a cute way to add animation to web pages ;). But aside from the big jump to learning Zope 3 - I know I don't see any time in my future for doing a serious (ie - more than 'hello world' or 'guestbook') evaluation of anything else. :\. In response to the original question - things that I would use when evaluating kits today is community size, maturity, etc. There are a lot of "cool little idea" web kits that never reach completion, or anything close to it (again - having written one, I know). Some projects have been around for a while and have yet to reach a '1.0' milestone. Some of those may just be reaching for perfection. Others are left to languish while the core developers have to work for a living, or find other solutions. Others may be in a state of 'yeah, the current version is good enough', but a real 1.0 release never quite seems to get made. For the past few years, I've made the SCM decision for myself to never run on beta software, and seldom use pre-1.0 software, no matter how good it may be, because we've got dependability requirements from customers that we have to ensure are met. And software that looks immature generally gets ranked low on the list of evaluations. (of course, having a low quality 1.0 release is not a good idea either ;) Quixote and CherryPy both deserve attention for their templating systems. I like what I've seen of each more than the many variants of "Python Server Pages" out there that try to embed Python in HTML (Python's block structure just makes this already messy style messier). Database Abstraction is another key issue. Zope gets points here not only for the built in ZODB database, but for SQL Methods / Database Adapters. There is nothing in Zope that is tied to Postgres, MySQL, Oracle, Sybase, SQLite, etc. Yet it's always been able to use any of them since before it was Zope. There's just a nice simple abstraction layer that one seldom has to think about. Other tools try the O-R mapping route for abstraction with varying degrees of success. SkunkWeb has PyDO, WebWare has one (I can't remember its name right now). Zope's model is nice because it's not intrinsic to Zope that you use SQL - it's just a nice model to plug into if you need it, when you need it. I don't know how other toolkits stack up here. Some may just say "go find a Python adapter that works for you and do what you want with it", which seems to be as good of a way to go as any. Enterprise scalability could be another factor. SkunkWeb has aggressive caching and tight integration with Apache as one of its features for delivering dynamic chunks of content under high load. Zope has its built in transaction system, which makes database work nice. Database adapters and other objects can integrate themselves into this system to ensure that either everything succeeds and gets written, or everything fails and rolls back, and you're not stuck with some data in one database but none in another (it's only as infallible as the systems that support it. Thank gods for InnoDB in MySQL!). Transactions are automatic (but can be handled manually, if desired) - a web request begins a transaction, and a successful writing of the response commits it. Any exceptions raised abort it. This becomes one of those little subtle platform niceties that you forget about but are eternally grateful for. Usually ;). Other toolkits may vary - it depends on what itch they were initially trying to scratch when they started. The transaction stuff in Zope goes back to Bobo and the early BoboPOS (which became the ZODB) because of the work I assume Digital Creations was doing with databases. Having gone through the pain of half written text files generated by mediocre self-written CGI scripts, this became an early favorite feature :). In any case, this is just my evaluation list as it would stand today, given my experiences over the last couple of years. I don't know how rosy Zope would come up today if I were evaluating different frameworks under this criteria - I always think it would be nice to have time to really step back and evaluate some different options, if only to get a fresh perspective (kindof like taking some time to evaluate Ruby might give one a fresh perspective on programming Python). But - there's just no time in the schedule to justify such an undertaking, for better or for worse... From webmaster at dte.ua.pt Tue Jul 29 07:39:06 2003 From: webmaster at dte.ua.pt (=?ISO-8859-1?Q?M=E1rio_Gamito?=) Date: Tue, 29 Jul 2003 12:39:06 +0100 Subject: problems in a python script Message-ID: <3F265CDA.9090004@dte.ua.pt> Hi, I've downloaded the 30 days trial version of editize and followed the instructions in http://plone.org/Members/tlynch/HowToIntegrateEditize to install it. Everything runs smoothly until the creation of munge.py as explained in the above link. I get an error saying " Script line 4 inputvalue = inputvalue.replace("\r", "") ^ SyntaxError: invalid syntax" A curious thing is that when i save it, not only i get the above error, but also the lines begining with double cardinal (##) are gone!!! Also the text refers to "Note: you might need to edit the line calling munge in wysiwyg_support to reflect the name of your folder where all the Editize stuff is stored." Where is this is done ? Thank you in advance for your time and patience. Warm Regards, M?rio Gamito munge.py ----------------------------------------------------- ## Script (Python) "munge" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=inputvalue ##title= # to guard against files that might contain only # returns or linefeeds, we will delete each separately # rather than trying: replace("\r\n", "") inputvalue = inputvalue.replace("\r", "") inputvalue = inputvalue.replace("\n", "") inputvalue = inputvalue.replace("'", "'") return inputvalue ------------------------------------------------------------ From bokr at oz.net Mon Jul 14 16:24:57 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 20:24:57 GMT Subject: Accessing an instance's __init__ args from outside the class References: Message-ID: On Mon, 14 Jul 2003 11:46:38 -0400, "Alexander Eberts" wrote: >I'm new to python so appologies to the group if this question is asked >often. I'm wondering if it's possible to query an object instance to find >out what arguments the instance's __init__ function was called with from >*outside* the class's local namespace. For example, if I define a class Foo >as follows: > >import sys >class Foo: > def __init__(self, *args): self.args = args #[1] save args tuple as attribute of instance (self) > print args # no problem here > >...and then create an instance of Foo: > >>>> someobj = Foo('bar', 'bleck') >('bar', 'bleck') > >Now, I'd like to be able to find out what arguments someobj was called with. >So first I tried: > >>>> print someobj.args This would work if you saved the args in the __init__ method, like [1] > >but I get: "AttributeError: args" > >so then I tried: > >>>> print some_obj.__init__.func_defaults ^--?? this is out of a different test sequence, presumably > >which returns an empty tuple You would have gotten something if your __init__ had had some parameters with default values specified (BTW, notice that the 'bar' argument got used for x, and the rest went to *args). e.g., >>> class Foo: ... def __init__(self, x='x default', *args): ... self.args = args ... self.x = x ... print x, args ... >>> someobj = Foo('bar','bleck','fnord') bar ('bleck', 'fnord') >>> someobj.x 'bar' >>> someobj.args ('bleck', 'fnord') >>> print someobj.__init__.func_defaults ('x default',) >>> someobj.__dict__['args'] ('bleck', 'fnord') > >and then I tried: > >>>> some_obj.__dict__['args'] This is closely related to some_obj.args, but the latter form will look in the class __dict__ too and in base class __dict__'s, so e.g., the class could have a default value shared by all instances that don't shadow it by having instance attributes of the same name. >Traceback (most recent call last): > File "", line 1, in ? >KeyError: args > You get several attaboys for trying stuff interactively and posting by copy/paste from actual stuff ;-) >No dice.. Is there any way to find out what arguments an object was called >with? Are the args stored with the instance? I scoured the python faq but They aren't stored automatically (though you could inherit from a base class that did it for you, so it would appear automatic, but never mind that for now ;-) The ususal thing in __init__ is to save all the things you want the instance to carry as named attributes, e.g., self.args. You can also set up stuff that wasn't passed as args, e.g., self.flavors = ['strawberry', lemon', 'lime'], or self.count=0, etc. They show up later as some_obj.flavors, some_obj.count, etc. (using your instance name). >there are no answers (that I could see) to this question. Any help would be >much appreciated. > HTH, Regards, Bengt Richter From tjreedy at udel.edu Thu Jul 10 10:54:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2003 10:54:20 -0400 Subject: numpy and scipy for Python 2.3 References: <221d8dbe.0307100102.425cbba8@posting.google.com> Message-ID: wrote in message news:221d8dbe.0307100102.425cbba8 at posting.google.com... > Hello, > I am interested to have numpy and scipy for Python 2.3 on Windows 98. So am I and lots of other people. However, Py2.3 does not yet exist, only Py2.3b2. > Only binaries for 2.1 and 2.2 are available for download now. Betas are meant to be temporary and are not meant for production use. While exension writers might create binaries to help test the beta and compatibility therewith, they generally do not publically release such test versions. They may not work, will soon be obsolete even if they do, and would too likely generate unwanted support requests. When Python 2.3 is finished and released, Windows binaries for major add-ons should soon follow > Can I easily create binaries for numpy and scipy from the sources? If > so how? I am looking forward for some guidance. Be patient? Terry J. Reedy From jtuc at ev1.net Tue Jul 29 10:55:52 2003 From: jtuc at ev1.net (Jordan Tucker) Date: Tue, 29 Jul 2003 14:55:52 -0000 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> <467c9d67.0307290640.4f7d87b1@posting.google.com> Message-ID: A fix that seems to work (at least it lets DllRegisterServer succeed) is inserting the following before the aforementioned line: scriptDir = None if hasattr(sys, 'argv'): scriptDir = os.path.split(sys.argv[0])[0] This allows registration, but now when I try to instantiate one of the objects defined in my dll from the interpreter, I get the following error: Fatal Python error: PyThreadState_Get: no current thread This also happens with the server example included. Do I have to use something other than win32com.client.Dispatch to connect to an inproc server from a dll? I think I've used it before to do the same thing with non-py2exe dlls. Jordan From max at alcyone.com Sun Jul 13 03:55:22 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Jul 2003 00:55:22 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <3F11106A.65FDA8F2@alcyone.com> Tom Plunket wrote: > IMHO the variable binding discussion doesn't answer the question, > it just provokes more questions. :) But the answer to those questions is usually something ending with, "Look, Python just doesn't handle variables the same way C++ does." :-) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It seems like Karma's making his rounds \__/ Kina From pyth at devel.trillke.net Tue Jul 8 16:39:35 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 8 Jul 2003 22:39:35 +0200 Subject: Newbie - Directory/File Creation In-Reply-To: <3F0B2724.D87E5D9F@engcorp.com>; from peter@engcorp.com on Tue, Jul 08, 2003 at 04:18:44PM -0400 References: <68a42404.0307081209.4baafd5@posting.google.com> <3F0B2724.D87E5D9F@engcorp.com> Message-ID: <20030708223935.L6906@prim.han.de> Peter Hansen wrote: > Michael J Whitmore wrote: > > > > If I do the following, a file is created in the current working > > directory: > > TestFile = open("TestTest.out", 'w') > > > > My question is how to create a file that includes a pathname without > > having to mkdir beforehand. > > Example: > > TestFile = open("TestDir\TestTest.out", 'w') > > > > Shouldn't open be smart enough to create the TestDir directory before > > creating TestTest.out ? > > > > Is there another command that will do this? > > Use os.path.makedirs() first, although if you really want to do this, Peter means os.makedirs() of course. > I would separate the "ensure this directory exists" part from the > "create this file" part. Or combine the two, but call your own method > which internally checks whether the path exists (os.path.split() and > os.path.isdir() are good for part of this), then creates it if necessary > using makedirs(), then finally creates the file and returns the > file object. Michael might be interested in the following "makepath" recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117243 cheers, holger From export at hope.cz Fri Jul 4 01:39:27 2003 From: export at hope.cz (BMA TRADING) Date: Fri, 04 Jul 2003 07:39:27 +0200 Subject: CGI script is in plain text In-Reply-To: <1057280192.13137.24.camel@lothlorien> References: <3F04B0A4.32692.3596CD0@localhost> Message-ID: <3F052F2F.1426.547BB32@localhost> On 3 Jul 2003 at 19:56, Ian Bicking wrote: > On Thu, 2003-07-03 at 15:39, A wrote: > > I have a webhosting account with one company. > > They have Apache running. > > When I start CGI script from a web browser, the result is plain text( the copy of that script) > > I can not access > > httpd.conf > > file so I changed > > .htaccess > > file. I put into it > > > > Options +ExecCGI > > Sethandler /usr/bin/python.exe .py > > Try renaming the file to .cgi -- as long as the #! line is right, it > doesn't matter the extension. Also, you may have to put the script in > the cgi-bin directory. > > Ian > Dear Ian, Thank you for your reply. I tried to rename it but it does NOT work. In the same directory I can successfully run Perl script( .pl extension) but no Python scripts. Any idea? Thanks Ladislav From i.am at going.in.circles Tue Jul 22 08:57:51 2003 From: i.am at going.in.circles (Richard Lee) Date: Tue, 22 Jul 2003 12:57:51 GMT Subject: Where can one get Python 1.4 and Pythonwin 1.0? Message-ID: <41dqhv43pp8d8kb76r2u2sm3bnbbkic4cm@4ax.com> Hi. I need to test and document some really old software. For that, I have to install P 1.4 and Pwin 1.0 (the latter which is based on P1.4). Python.org has downloads going back to P1.5.2. And the link to version of the earliest Win32 extensions containing Pwin corresponds to P1.5.2. Thanks for any help. From peter at engcorp.com Tue Jul 15 23:17:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 23:17:55 -0400 Subject: Foreign characters References: Message-ID: <3F14C3E3.5FBF55B1@engcorp.com> Tetsuo wrote: > > How do I get Python to work with foreign characters? When I try to > print them, I get a unicode error (characters not ASCII). Wasn't > unicode invented for the express purpose of working with non-ASCII > characters? The FAQ might help: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp -Peter From maxm at mxm.dk Tue Jul 1 04:10:38 2003 From: maxm at mxm.dk (Max M) Date: Tue, 01 Jul 2003 10:10:38 +0200 Subject: Howto: extract a 'column' from a list of lists into a new list? In-Reply-To: References: Message-ID: <3F0141FE.4090007@mxm.dk> Greg Brunet wrote: > Even better yet... the reason I'm trying to do this is to make it easy > to refer to a field by the field name as well as the field number. I > expect to be reading all of the data into a list (1 per row/record) of > row objects. If someone wants to be able to refer to FldA in record 53, > then I'd like them to be able to use: "row[52].FldA" instead of having > to use "row[52][4]" (if it's the 5th field in the row). I was planning > on using the __getattr__ method in my row object like the following: If that is all you want to do, this might be the simlest approach: fields = [ ('STOCKNO', 'C', 8, 0), ('DACC', 'C', 5, 0), ('DEALERACCE', 'C', 30, 0), ('D-ACCRTL', 'C', 9, 0), ('D-ACCCST', 'C', 9, 0) ] def byName(field, name): fieldNames = { 'name':0, 'letter':1, 'val1':2, 'val2':3, } return field[fieldNames[name]] for field in fields: print byName(field, 'name') regards Max M From owski at hotmail.com Wed Jul 16 15:06:40 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 19:06:40 +0000 (UTC) Subject: anything like C++ references? References: Message-ID: <20030716130631003-0600@news.xmission.com> In Michael Chermside wrote: > Adam Ruth writes: >> I assume that you're referring to people 'faking' pointer in Python ( >> such as wrapping variables in lists, etc.) I'd ammend your statement >> to say: And the worst thing you can do is to obscure the issue >> even more by disguising them as something else, WHEN YOU DON'T >> REALLY HAVE TO. In Python, there is no situation where "you really >> can't avoid pointers". It's only when you program C or C++ in >> Python that you think you can't avoid pointers. There are much >> better idioms to achieve the desired results. > > Look, first of all, let me say that I disagree with Stephen Horne in > this discussion. Or, to be more precise, I think that the approach he > is using is not one which is useful in describing Python. HOWEVER, > that doesn't mean that there's NOTHING to what he is saying, and your > claim that there is no situation requiring "pointers" in Python seems > wrong to me. > > Actually (to be quite pedantic) it is technically true. For instance, > I could write a program in Python which simulated a turing machine, > and then write the entire program to be executed on THAT. But this > is a meaningless definition for "requiring" a feature -- by this > definition NO feature is ever needed if the language is turing > equivalent without it... for instance, Python doesn't ever need > classes, modules, dictionarys, or functions (I'm pretty sure a > turing machine could be written which didn't use any of these). > > What's more useful is to say that a feature is not "needed" if there's > a straightforward alternate way to handle the situations where it > would normally be used. For instance this (using C++ syntax for > "references"): > > def returnsMultipleValues(x, &minusFive, ×Five): > """Calculates x+5, x-5, and x*5.""" > *minusFive = x - 5 > *timesFive = x * 5 > return x + 5 > > Is unnecessary, since this: > > def returnsMultipleValues(x): > return x + 5, x - 5, x * 5 > > would work fine. However, there are some places where it IS useful to > be able to modify a value within a routine. I have written code like > this: > > i = [0] > stuff.append( makeNewComplexObject(i, 'name', 'fred') ) > stuff.append( makeNewComplexObject(i, 'age', 17) ) > stuff.append( makeNewComplexObject(i, 'item') ) > stuff.append( makeNewComplexObject(i, 'item') ) > > where the source for makeNewComplexObject() went like this: > > def makeNewComplexObject(iBox, objName, *objArgs): > # increment i > i = iBox[0] > iBox[0] += 1 > > if objName == 'name': > # some simple cases > return new NameObject(*objArgs) > elif objName == 'age': > # some complex cases > yrsOld = objArgs[0] > if yrsOld >= 18: > return new AdultAge(*objArgs) > else: > return new MinorAge(*objArgs) > elif objName == 'item': > # some cases that use i > return new IndexedItem(i) > > Now, clearly, this code was inspired by C code which used an > idiom like this: > > i = 0 > stuff[i] = newComplexObject(i++, "name", "fred") > stuff[i] = newComplexObject(i++, "age", 17) > stuff[i] = newComplexObject(i++, "item") > stuff[i] = newComplexObject(i++, "item") > > And certainly it *can* be rewritten in Python without "boxing" the > variable i. However, it would also be nice to be ABLE to "box" the > variable i. So it's not as if references would be USELESS in Python. > I just think it'd be better handled differently (one-item list, or > maybe a container class) rather than redefining assignment in Python > as Stephen seems to prefer.[1] > > -- Michael Chermside > > [1] - Stephen doesn't want to change Python now for historical > reasons. But my position is that if I were inventing a NEW > language I'd do it Python's way by choice, because I think > it's better. > You are correct in that there are times when pointer semantics would be somewhat useful, but they're never necessary. His statement was that there are time that "you really can't avoid pointers". That's not true. I definitely went a little overboard, and it sounds like I'm saying, "not only are pointers not necessary, they're never desirable". My tone was a bit more knee jerk than was prudent. Your code example isn't really about pointers, though, as the C++ version doesn't use pointers. There's also another difference, the caller is responsible for incrementing the counter, which is quite different than your Python version. There are a number of ways to write that without "pointers" that express the intent just as clearly, if not more. The real question is what does the i represent? If it represents the index of the object in the list, then this is more clear: > stuff.append( makeNewComplexObject(len(stuff), 'name', 'fred') ) > stuff.append( makeNewComplexObject(len(stuff), 'age', 17) ) > stuff.append( makeNewComplexObject(len(stuff), 'item') ) > stuff.append( makeNewComplexObject(len(stuff), 'item') ) In the worst case (needing the most new code to implement) it would need to be written with a very small "counter" class: > class Counter(object): > def __init__(self, initial=0): > self.value = initial > def inc(self): > self.value += 1 > return self.value > stuff.append( makeNewComplexObject(i.inc(), 'name', 'fred') ) > stuff.append( makeNewComplexObject(i.inc(), 'age', 17) ) > stuff.append( makeNewComplexObject(i.inc(), 'item') ) > stuff.append( makeNewComplexObject(i.inc(), 'item') ) This is just as clear as the C++ version, and more clear than the Python version that wraps with the list. This example, though, doesn't really show the difference, it's too trivial. All of the versions are clear enough, with the difference being academic. I would be interested in seeing a more complex example where something would be substantially cleaner with pointers. I have to acknowledge the possibility that they exist, I don't know everything... yet :) Adam Ruth From justinjohnson at fastmail.fm Sun Jul 6 21:22:50 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Sun, 06 Jul 2003 19:22:50 -0600 Subject: win32service problems In-Reply-To: References: Message-ID: <20030707012250.ABE12389DD@www.fastmail.fm> Windows 2000. Aftering searching google for similar problems I'm beginning to think I hit the dreaded shared section memory problem on win2k. Ugh... -Justin On Sun, 6 Jul 2003 00:18:39 +0200, "Tomas Christiansen" said: > Justin Johnson wrote: > > I created an NT service using win32service. This service runs as a > > particular user on the domain and accepts connections to run commands on > > the server. The service is working great on most of the servers I have, > > but on one server it fails to start > > What OS'es are on the servers? > > ------- > Tomas > -- > http://mail.python.org/mailman/listinfo/python-list > From owski at hotmail.com Mon Jul 14 14:35:57 2003 From: owski at hotmail.com (Adam Ruth) Date: 14 Jul 2003 11:35:57 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: Stephen Horne wrote in message news:<7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv at 4ax.com>... > On 13 Jul 2003 21:03:59 -0700, owski at hotmail.com (Adam Ruth) wrote: > > C++ has precisely one type of variable. That variable is a placeholder > for a value of a datatype which is specified in the declaration. The > datatype may be a pointer datatype, but so what? Pointer datatypes are > not treated any differently than other datatype except that they, like > all datatypes, they have their own set of functionality. Granted. Pointers are no different than other data types, but they are typically used for operations that are semantically very different than other datatypes are used for. In that sense, they are, at a high level, different data types. It's like how c programming is taught has having pass by reference and pass by value, when there is only pass by value at the implementation level. Pass by reference is a concept added on top of the language. > C++ references are tellingly also called self-dereferencing pointers. > They are not a distinct concept - they are syntactic sugar. I suspect > they mainly arise out of the modern desire to disguise pointers and > fantasize that they're not there, though they certainly work very well > in certain contexts. Syntactic sugar or no, they still behave differently than other datatypes and are therefore not consistent... IMHO. > Funny thing. When I use algebra, the variables I define don't end up > referring to different values, functions or whatever unless I > explicitly redefine them. When I write a definition on one piece of > paper, the things I wrote earlier on another sheet don't change. > > Seems to me that the math equivalent of assignment (defining named > things) works very much like the 'static language definitions' as you > put it. The devil is in the details. Math assignment is static assignment is dynamic assignment. They really are all the same thing at a high level, but it's the implementation and the subtleties that make them vary. Adam Ruth From mcherm at mcherm.com Tue Jul 8 07:54:46 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 8 Jul 2003 04:54:46 -0700 Subject: Search for mapping solution Message-ID: <1057665286.3f0ab1067a739@mcherm.com> Alan Kennedy writes: > Must ..... resist ..... temptation ..... to ..... write .... oneliners > > D'oh! I'm so weak willed.... > > >>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > >>> d = dict([(x[0], x[2]) for x in lines]) Speaking as the guy who just complained about the one-liners: "That's no one-liner, that's just concise!" Of course, it's the answer to a simpler question than what the OP posted. ;-) > No more posting for me for a while. Please continue... anyone willing to apologize when they're wrong is worth hearing from. Does-this-mean-I-have-to-apologize-for-picking-on-one-liners lly yours, -- Michael Chermside ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From pablo at no.spam.pl Fri Jul 25 04:18:15 2003 From: pablo at no.spam.pl (Pablo) Date: Fri, 25 Jul 2003 10:18:15 +0200 Subject: I am so impressed References: <3f207dcc$0$137$1b62eedf@news.wanadoo.nl> Message-ID: > I've been looking for a nice python editor for a while. I was using a great > general purpose editor called EditPlus. It did the job pretty good.... > > I've now downloaded Eclipse with the TruStudio plug-ins from www.xored.com > and it's great! > > i had to share that with you I haven't used TruStudio plugin for Eclipse but Eclipse itself is too slow to use it for me. Have you tried Eric3? It looks great, has a debugger. I you haven't tried it do it. I'm impressed. Cheers Pablo From mlh at furu.idi.ntnu.no Wed Jul 9 08:52:26 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Wed, 9 Jul 2003 12:52:26 +0000 (UTC) Subject: anygui newbie question References: <54omgv8rb7p08uct892h6q1qck489gvoph@4ax.com> Message-ID: In article <54omgv8rb7p08uct892h6q1qck489gvoph at 4ax.com>, Gerard C Blais wrote: > [snip] >Window comes up fine. When I click the button, I get a run-time error >and the traceback says my handler function has received an unexpected >argument, "source". As far as I can tell, "source" should be >expected. [snip] >Any ideas? Any place to look besides the on-line manual ahd Hetland's >Practical Python? The problem is actually addressed in Practical Python... You're using the planned 0.2 event handler syntax (used in the Practical Python examples), but should (for now) use the 0.1.1 syntax. In other words, rather than def handler(event): ... you should have def handler(**kwds): ... or the like. There is a note about this on page 339 of Practical Python. >Thanks, > >Gerry -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From mwh at python.net Tue Jul 8 06:42:14 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 8 Jul 2003 10:42:14 GMT Subject: anything new on the ternary operator? References: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> <3F09235B.6F7DE56@alcyone.com> Message-ID: <7h3brw5papl.fsf@pc150.maths.bris.ac.uk> Erik Max Francis writes: > There's not much doubt that the conditional operator will not be making > it into Python in the future, but just because the BDFL has made a > decree (although a significantly delayed one), it's a little naive to > think that discussion of it will not continue. This clause was in the > PEP ("the subject better not come up again"), but I'm not sure how this > clause will really have much effect. Slightly astonishingly, this does really seem to work. Consider PEP 666. Cheers, M. -- If I didn't have my part-time performance art income to help pay the bills, I could never afford to support my programming lifestyle. -- Jeff Bauer, 21 Apr 2000 From ggg at zzz.it Wed Jul 30 15:07:25 2003 From: ggg at zzz.it (deelan) Date: Wed, 30 Jul 2003 21:07:25 +0200 Subject: Webware application question In-Reply-To: <2LTVa.13085$Oz4.4738@rwcrnsc54> References: <2LTVa.13085$Oz4.4738@rwcrnsc54> Message-ID: Aaron Buhr wrote: > Hello all. I am looking to rebuild our corporate website from Cold > Fusion to Python/WebWare/Cheetah. I am new to all three, so I apologize in > advance if my questions are ignorant. I do not understand how one would > cache database connections using WebWare. At this point I do not want to > use Middlekit, but I would like to compartmentalize all my database > connection code and cache it for performance. there's a module in webware called dbpool that caches DB connection. you may want to check this thread on the webware mailing list archive: http://tinyurl.com/ijhc i strongly suggest you subscribe both to webware anc cheetah lists. being a newbie too i've found very supportive people on both ML :) bye -- email: goldicus1970 AT yahoo.it web: http://www.deelan.com From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 2 02:57:00 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 02 Jul 2003 06:57:00 GMT Subject: arbitrary long integer aritmetics References: Message-ID: On Wed, 2 Jul 2003 16:46:38 +1000, Leo wrote: > is there a python module around allow using arbitrary long integers? The 'mpz' module provides an interface to the GNU MultiPrecision maths library: but is currently deprecated. The above URL gives references to development on replacement multiprecision interfaces currently in development. -- \ "Judge: A law student who marks his own papers." -- Henry L. | `\ Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mhammond at skippinet.com.au Thu Jul 31 19:08:25 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 01 Aug 2003 09:08:25 +1000 Subject: Win32All InvokeTypes exception after upgrade In-Reply-To: References: Message-ID: At the top of the makepy generated files, there are a couple of "default" values. These were recently changed from 'pythoncom.Missing' to 'pythoncom.Empty'. This change was made so "named parameters" would work in most objects. The problem is that the semantics for COM defaults are not well defined - different objects use different techniques. I guess you have 2 choices: * Explicitly pass 'pythoncom.Missing' in these params. * Copy your makepy generated file to a local file, rename it, change the defaults, and import this module for your project. Or I guess the third option is to help me look into making this work for everyone. Unfortunately, this is the first problem report I have had, but there have beenp lenty of success reports that the new strategy works better. Mark barry g wrote: > When trying to upgrade my Win32All package from build 148, that came > in the ActiveState install, to any of v150 thru v156 I start receiving > an exception. It apparently is related to the "output arguments" in > the ActiveX control's methods. If I leave the output parameters off I > get the message at the bottom. If I fill the arguments the function > performs happily. > > Am I missing some step or setting that makes the output parameters > optional again? I could change all my code to supply dummy values, > but we have a large enough number of COM controls and function calls > that I'd prefer to maintain the old calling style if possible. > > obj.DeviceToLatLon(x,y,10,10) #works in either 148 or 156 > (35.453, -75.2214) > > obj.DeviceToLatLon(x,y) #used to return a tuple - now generates > exception > Traceback (most recent call last): > File "ChartNotebook.py", line 978, in OnMouseMove > lat, lon = obj.DeviceToLatLon(x, y) > File "C:\Python22\lib\site-packages\win32com\gen_py\8754AEB3-1466-11D4-A779-0050DA6B8675x0x1x2.py", > line 62, in DeviceToLatLon > return self._oleobj_.InvokeTypes(37, LCID, 1, (24, 0), ((3, 0), > (3, 0), (16389, 0), (16389, 0)),x, y, lat, lon) > com_error: (-2147352571, 'Type mismatch.', None, 3) > > > Thanks, > Barry From skip at pobox.com Thu Jul 3 17:39:34 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 3 Jul 2003 16:39:34 -0500 Subject: Python Code Snippets In-Reply-To: References: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> Message-ID: <16132.41622.577481.966194@montanaro.dyndns.org> Aur?lien> I wish it had a better ordering than just a list, but it's Aur?lien> full of good stuff. You can always buy the book. It has both an index and a table of contents. Skip From kamikaze at kuoi.asui.uidaho.edu Tue Jul 15 06:19:18 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 15 Jul 2003 10:19:18 GMT Subject: anything like C++ references? References: Message-ID: Tue, 15 Jul 2003 03:16:08 +0100, Stephen Horne : > On 14 Jul 2003 23:31:56 GMT, kamikaze at kuoi.asui.uidaho.edu (Mark > 'Kamikaze' Hughes) wrote: >> It looks like you've almost reached understanding, though you've been >>given a bad start with a very idiosyncratic and monolingual >>understanding of what "computer science" teaches--that was certainly not >>in the classes I took, but apparently yours were different. > Really. My computer science lessons were taught in a way that > respected the source of most of the theory in mathematics - > algorithms, Church's lambda calculus and that kind of stuff. > What did your lessons teach? How computer programming actually works, how to make interpreted and compiled languages, how to use them to solve problems, how to analyze algorithms, etc.... The usual. Among those were classes in languages other than C, which is very broadening, and I highly recommend that to you. History lessons and maths are fine for liberal arts and science credits, but they're not computer science. As for respect, I respect working code. Theory without working code isn't just useless, it's an actively harmful delusion. >> Since every operation in Python operates on pointers, there's no use >>in having a special syntax for it. You don't need all the * and & and >>-> line noise. > The point of the thread is not pointers - they are a side issue. Not so. They are the central, the *only* issue, you just don't realize it. Python just does not have what you think of as "assignment" or "variables". It only has pointers. If you understand and accept that, you'll be able to use Python successfully. If you persist in elevating inappropriately-applied theory above reality, you will fail. > When you use variables, you are using a concept from mathematics. In > mathematics, variables bind to values. All values are immutable. That's very nice. Python is not mathematics. It's a programming language. While there are some mathematical foundations to CS, it's primarily an engineering discipline with its own terms and entirely different considerations. > Python binds variables to objects, not values. For immutable objects > this is an unimportant implementation detail. For mutable objects, it > breaks the mathematical principle of variables being bound to values. Yes, it sure does. But would you look at that, my Python code still seems to work just fine. Guess it just doesn't know it's violating important mathematical principles. i=i+1 is just as much a mathematical heresy, but it doesn't matter, either. That's because PYTHON IS NOT MATHEMATICS. >> Stop trying to make Python into C/C++, and you'll be happier with it. >>Or stop using Python, if you really don't like the design philosophy. >>There are plenty of Algol-derived languages out there. PHP and >>especially Perl are more C-like in their internal logic, and you might >>find them more pleasant. > This is bogus. > I don't want Python to become C or C++. I want Python to respect > principles that come from mathematics and computer science. Not for > reasons of theory pedanticism, but because the current system can and > does regularly cause confusion and errors. On the contrary, implementing the design you suggest causes confusion and errors; we see that all the time with C newbies, confronted with variables that may be on the stack, on the heap, or pointers to variables that could be anywhere. Python is internally consistent, and this behavior only has to be explained once to be fully grasped with all of its implications. I have taught several previously-non-programmers to use Python, and how names and objects worked was never once an issue after the first lesson. The only people who have problems with it, IME, are those who are willfully ignorant, or who just skimmed a tutorial and some example code rather than learning the language properly. Since Python has the same behavior as most of the Lisp-philosophy languages, rather than the Algol-philosophy ones like C, yes, you do want Python to become something it's not. > The fact that Python claims to be a very high level language, and yet > you have to worry about the binding of variables to objects - > something that should be a low level implementation detail - has very > real everyday implications. This is a meaningless statement. What are those "very real everyday implications"? Python works just fine, and the "everything is an object, and names just point to objects" paradigm is vastly easier to explain to newbies than your soi-disant mathematical paradigm. > Respect the idea of variables binding to values and suddenly the need > for pointers becomes more obvious. You cannot abuse mutable objects to > fake pointer functionality (another everyday fact of Python > programming) if the binding of variables to values (rather than just > objects) is respected. If you're trying to say that the trick I showed you of modifying a list to reproduce the effect of reference arguments is not possible in, say, C, you're wrong. Trivially proven wrong, even, since Python is implemented in C. In fact, the only languages where that won't work are those which don't allow passing complex arguments at all; some pure-functional toy languages, perhaps. If you're seriously demanding that all languages adhere to a religious observance of object and variable purity that exists in no serious programming language, you might want to stop and consider *why* nobody "respects" that. Eh, enough. You've been shown how Python really works, and why. Anything else is quite futile. If you want Python to change to obey your ideals, well, you're unlikely to effect that change; pigs will fly and politicians will tell the truth first. You are the only change that can and must happen here, if only to a different and more suitable language. Perhaps you should write your own language, if no others are acceptable to you. Good day. -- Mark Hughes "The computer is incredibly fast, accurate, and stupid. Man is unbelievably slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation." -Leo Cherne From bokr at oz.net Fri Jul 25 21:54:19 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2003 01:54:19 GMT Subject: How to detect typos in Python programs References: Message-ID: On Fri, 25 Jul 2003 12:20:57 -0600, Bob Gailer wrote: >--=======6B79482F======= >Content-Type: text/plain; x-avg-checked=avg-ok-74704BF8; charset=us-ascii; format=flowed >Content-Transfer-Encoding: 8bit > >At 07:26 PM 7/25/2003 +0530, Manish Jethani wrote: > >>Hi all, >> >>Is there a way to detect typos in a Python program, before >>actually having to run it. Let's say I have a function like this: >> >> def server_closed_connection(): >> session.abost() >> >>Here, abort() is actually misspelt. The only time my program >>follows this path is when the server disconnects from its >>end--and that's like once in 100 sessions. So sometimes I >>release the program, people start using it, and then someone >>reports this typo after 4-5 days of the release (though it's >>trivial to fix manually at the user's end, or I can give a patch). >> >>How can we detect these kinds of errors at development time? >>It's not practical for me to have a test script that can make >>the program go through all (most) the possible code paths. > >consider: > use a regular expression to get a list of all the identifiers in the program > count occurrence of each by adding to/updating a dictionary > sort and display the result > >program_text = """ def server_closed_connection(): > session.abost()""" >import re >words = re.findall(r'([A-Za-z_]\w*)\W*', program_text) # list of all >identifiers >wordDict = {} >for word in words: wordDict[word] = wordDict.setdefault(word,0)+1 # dict of >identifiers w/ occurrence count >wordList = wordDict.items() >wordList.sort() >for wordCount in wordList: print '%-25s %3s' % wordCount > >output (approximate, as I used tabs): > >abost 1 >def 1 >server_closed_connection 1 >session 1 > >You can then examine this list for suspect names, especially those that >occur once. We could apply some filtering to remove keywords and builtin names. > >We could add a comment at the start of the program containing all the valid >names, and extend this process to report just the ones that are not in the >valid list. > That's cool. If you want to go further, and use symbols that the actual program is using (excluding comment stuff) try: ====< prtok.py >======================================================== #prtok.py import sys, tokenize, glob, token symdir={} def tokeneater(type, tokstr, start, end, line, symdir=symdir): if (type==token.NAME): TOKSTR = tokstr.upper() #should show up for this file if symdir.has_key(TOKSTR): d = symdir[TOKSTR] if d.has_key(tokstr): d[tokstr] += 1 else: d[tokstr] = 1 else: symdir[TOKSTR]={ tokstr:1 } for fileglob in sys.argv[1:]: for filename in glob.glob(fileglob): symdir.clear() tokenize.tokenize(open(filename).readline, tokeneater) header = '\n====< '+filename+' >====' singlecase = [] multicase = [key for key in symdir.keys() if len(symdir[key])>1 or singlecase.append(key)] for key in multicase: if header: print header print ' (Multicase symbols)' header = None for name, freq in symdir[key].items(): print '%15s:%-3s'% (name, freq), print if header: print header; header = None print ' (Singlecase symbols)' byfreq = [symdir[k].items()[0] for k in singlecase] byfreq = [(n,k) for k,n in byfreq] byfreq.sort() npr = 0 for freq, key in byfreq: if header: print header header = None print '%15s:%-3s'% (key, freq), npr +=1 if npr%4==3: print print ======================================================================== Operating on itself and another little file (you can specify file glob expressions too): [18:55] C:\pywk\tok>prtok.py prtok.py gt.py ====< prtok.py >==== (Multicase symbols) tokstr:6 TOKSTR:4 NAME:1 name:2 (Singlecase symbols) append:1 argv:1 clear:1 def:1 end:1 import:1 keys:1 len:1 line:1 open:1 or:1 readline:1 sort:1 start:1 upper:1 else:2 fileglob:2 has_key:2 items:2 multicase:2 n:2 sys:2 token:2 tokeneater:2 type:2 None:3 filename:3 glob:3 npr:3 singlecase:3 tokenize:3 d:4 freq:4 k:4 byfreq:5 for:8 if:8 in:8 key:8 header:10 print:10 symdir:11 ====< gt.py >==== (Singlecase symbols) __name__:1 argv:1 def:1 if:1 fn:2 for:2 import:2 in:2 main:2 print:2 sys:2 arg:3 glob:3 Regards, Bengt Richter From timr at probo.com Tue Jul 1 00:35:41 2003 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jun 2003 21:35:41 -0700 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> Message-ID: <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> "Louis M. Pecora" wrote: >Fredrik Lundh wrote: > >> > >>> -7 % 5 >> > 3 >> > >>> Numeric.array(-7) % 5 >> > -2 >> > >>> Numeric.remainder(-7, 5) >> > -2 >> >> looks like Numeric implements C semantics, which is different >> from how Python does it. > >Hmmm... "remainder" makes sense. But "%" is mod, right. IIRC from my >abstract algebra days (only 30 yrs ago :-) ) The "X mod n" function >maps onto the postive integers from 0 to n-1. So sounds like numeric >contradicts the math texts. Not good since it's a math module. That's a bit harsh. The problem is that there is no universal agreement in the world of computer science as to what the semantics of the modulo operator should be when presented with a negative operand. Contradicting Fredrik, something I do with great reluctance, the C standard specifies that the behavior is implementation-defined, so in fact BOTH answers "implement C semantics". Fortran, on the other hand, defines A mod P as A-INT(A/P)*P, which is exactly what Numeric produces. Since folks interested in numerical programming often have a strong Fortran background, it is not terribly surprising that Numeric should follow Fortran's lead. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From adechert at earthlink.net Mon Jul 21 04:04:10 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 08:04:10 GMT Subject: Electronic voting with free software References: <7x1xwknx1v.fsf@ruckus.brouhaha.com> Message-ID: <_7NSa.112455$Io.9624954@newsread2.prod.itd.earthlink.net> "Paul Rubin" wrote in message news:7x1xwknx1v.fsf at ruckus.brouhaha.com... > "Alan Dechert" writes: > > Our project incorporates a proposal for Remote Attended Internet Voting to > > replace the various existing absentee voting methods employed today. > > I wouldn't want to use the public internet that way. It sounds like > an invitation to launch DOS attacks against the parts of the network > where one's political opponents live. I don't see the need for any > network connection as long as the election info can be delivered to > all the polling places before the election starts. If every election > can be enrolled in an FEC database a few weeks before election day > (that means the database has all the info that would get printed on a > ballot), then the whole database can get dumped to CD-ROM or DVD-ROM > and shipped to all the polling places in time for the election, no > internet needed. > That's a thought. It might be feasible to aggregate all the databases from all the counties for all the contests (although these databases might be larger than you think -- especially when you have all the audio files in all the different languages). However, the main problem I see is the voter files. You'd also need all the voter files from all the states and some of these get updated too close to Election Day. In other words, with remote absentee voting -- with no pre-printed roster like you have at the precinct polling places -- we need to ID the voter and verify registration (including the precinct in which registered). HAVA calls for statewide databases and this should help a lot for cleaning up these files. Remote poll workers should be able to access the voter file online to verify registration. Several studies conducted so far regarding Internet voting have turned thumbs down on unattended voting but have concluded that attended Internet voting should be feasible. It's already pretty much a given that it will be available for overseas military (perhaps as soon as 2004). Alan Dechert From rastm2 at aol.commorespam Fri Jul 25 02:43:37 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 25 Jul 2003 06:43:37 GMT Subject: python assignment References: Message-ID: <20030725024337.01143.00000859@mb-m22.aol.com> Ray was tryin to follow the thread ... Dan was talking to Tim about something. (see below signature if your not following thread and want to know what it's about.) ... and Ray had a question. >[Dan to Tim paraphrased] > >My solution, which I'm worried about, was this: > > for x in range(n): > temp = [x+y for y in range(3)] #or whatever > v[x] = temp + [] #'assignment by copy'??? > Ray's question = That last line "v[x] = temp + []", that's equivelent to "v.append(temp)", is it not? TIA Ray St.Marie Rastm2 at aol.com Thread I got this from >"Tim Peters" wrote in message >news:... >> [Tim] >... >> Bjorn added more appropriate words -- it would be bad design for the >> __iadd__ method of a mutable type to return a pre-existing object other >than >> self. >> >> >>> a = [1, 2] >> >>> b = [1] >> >>> b += [2] >> >> While "a == b" must be true at this point, it would be a nightmare if "a is >> b" could be true at this point. For immutable types it doesn't matter: >> >> >>> a = (1, 2) >> >>> b = (1,) >> >>> b += (2,) >> >> It so happens that "a is b" is not true at this point under any Python >> released so far, but it could be true someday without causing harm. >> >> Sorry for the confusion! > >Ok, that makes sense to me. I still think it would be a good idea to >put a section in the Tutorial -- perhaps under "for computer >scientists and those who want to learn more" -- describing how Python >binds names to objects. > >In particular, the fact that a list is a list of pointers, not the >objects themselves, seems like an important point to make, even for >relative newcomers. > >Here's the thing that tripped me up, and the solution I came up with, >which I am now unsure of: > >#original code -- v[] is a list > > for x in range(n): > temp = [x+y for y in range(3)] #or whatever > v[x] = temp > >so I was quite surprised to find all members of v[] were in fact >pointers to one object, temp[]. > >My solution, which I'm worried about, was this: > > for x in range(n): > temp = [x+y for y in range(3)] #or whatever > v[x] = temp + [] #'assignment by copy'??? > >So I'm still unclear as to whether an expression like temp+[] is >defined as returning a new list or not. Seems like it might be >undefined, since either way is arguably 'correct'. > From duncan at NOSPAMrcp.co.uk Thu Jul 24 03:48:32 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 24 Jul 2003 07:48:32 +0000 (UTC) Subject: The global statement References: Message-ID: Andy Jewell wrote in news:mailman.1058999017.16056.python-list at python.org: > I found it easier to envisage the Python global statement as the > inverse of the Pascal/Modula/C concept: Indeed, Pascal/Modula/C say "here's a variable, use it anywhere! Program structure? Who needs it?". Python, OTOH, requires you to say near the point of use "I am going to break the rules of good program design, but just for this function." In some ways this is analagous to the COMEFROM statement (see http://www.fortran.com/fortran/come_from.html). Just not very. -- 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 jgoerzen at complete.org Thu Jul 24 17:28:09 2003 From: jgoerzen at complete.org (John Goerzen) Date: Thu, 24 Jul 2003 16:28:09 -0500 Subject: Towards thread groups? Message-ID: <87n0f33992.fsf@complete.org> Hello, I am the author of OfflineIMAP[1], a program that currently is a heavy user of threads. For various reasons (see below), thread groups are something that is highly desirable for me in Python. Is anyone aware of an implementation of thread groups for Python? Is anyone else working on this? Is anyone else experiencing this sort of pain? Here's why I need this: OfflimeIMAP is a bi-directional IMAP/Maildir synchronization system. It can synchronize multiple accounts at once. Within a given account, it can synchronize multiple folders at once. Within a given folder, it can synchronize multiple messages at once. All these simultaneous actions are handled by threads. (In case you're wondering, there are bounds in the system to prevent this all from running away.) Right now, error handling is not very good. Let's say that one of the 5 connections to an IMAP server for Account A dies on us and we get a network exception. Ideally, with this condition, I would shut down all the other threads processing Account A, terminate its open connections, and restart it. (An unexpected error can leave OfflineIMAP with an incorrect idea of what is on the server, so the safest thing to do is reset the algorithm and thus get updates from the server on what exactly it knows about.) However, I can't do that with the current system. The best thing I can do is catch the exception and transmit it to an exception handling thread. (By overriding methods of the Thread object.) That's close, but... The exception handling thread can do things like print out the error. But the recourses available to it are: 1) terminate the entire application, and 2) ignore the error. Option #2 is not satisfactory, to the only remaining option is #1. Here are some other things that won't work: * Putting all network code within a try block. Several problems with that: the exceptions thrown are different for different types of connections (plain socket, ssl, etc), and may not be known in advance. Moreover, actions such as "download message" are done in individual threads, and the parent thread -- which really needs to know about this -- has no way to get the message until it does a join, which it may or may not ever have cause to do. Even then, it would usually be better for it to get the message immediately. * Save some state on thread exit and retrieve it on join(). Possible, yes, and might be a usable workaround. However, there are a number of places in the code that don't do a join(), and this seems an error-prone way of doing things. It basically involves manually passing data back up the "thread chain", like passing error codes back up through the call chain in C. Essentially, many of the benefits of exceptions in the first place disappear. Thoughts anyone? [1] OfflineIMAP is at http://quux.org/devel/offlineimap -- John Goerzen From mwh at python.net Tue Jul 15 11:56:28 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jul 2003 15:56:28 GMT Subject: Multiple Class Inheritance Question References: <2259b0e2.0307140658.26192b82@posting.google.com> Message-ID: <7h3el0rn62g.fsf@pc150.maths.bris.ac.uk> mis6 at pitt.edu (Michele Simionato) writes: > Andy Jewell wrote in message news:... > > Read guildo's essay on new style classes - that explains it all. > > > > In the 'old days' i.e. before Python 2.2.x the rules were different. Now > > a > > new algorithm is used which copes better with this. As I said, read the > > essay (it's on www.python.org - just search for 'new style classes essay' > > ). > > > > hth > > -andyj > > ... and in Python 2.3 the rule has changed again ... > > http://www.python.org/2.3/mro.html Though not so much as to change the MRO in this situation. Cheers, M. -- FORD: Just pust the fish in your ear, come on, it's only a little one. ARTHUR: Uuuuuuuuggh! -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From guettler at thomas-guettler.de Mon Jul 21 06:07:59 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Mon, 21 Jul 2003 12:07:59 +0200 Subject: How to save web pages for offline reading? References: Message-ID: Will Stuyvesant wrote: > I am trying to download pages from Python, for offline reading. This > to save telephone costs :-) > > If a page contains something like > > and I use fp=urllib.urlopen(...) and then fp.read(), I get the HTML > but not the CSS. As a result the page looks bad when reading offline. > How to solve this? Also the .GIF's in a page would be nice, but this > is less important and also would take more time to download. Hi, Does it need to be done with pyhton? If not, I would use wget. It has very much features. thomas From sismex01 at hebmex.com Fri Jul 25 16:46:13 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 25 Jul 2003 15:46:13 -0500 Subject: looping through a file Message-ID: > From: Bruno Desthuilliers [mailto:bdesth.nospam at removeme.free.fr] > Sent: Viernes, 25 de Julio de 2003 03:25 p.m. > > [...snip...] > > No, but there are better ways to do it in Python : > > try: > thefile = file(filename) > except IOError: > doWhatEverWithException() > > for line in thefile.readlines(): > doWhatEverWithTheLine() > And even better ways: try: thefile = file(filename) except IOError: doWhatEverWithException() for line in thefile: doWhatEverWithTheLine(line) files have iterators now. :-) -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From newsgroups at jhrothjr.com Thu Jul 31 17:35:17 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 17:35:17 -0400 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: "Ian Bicking" wrote in message news:mailman.1059679007.20588.python-list at python.org... > On Thu, 2003-07-31 at 08:55, Anthony_Barker wrote: > > The three that come to my mind are significant whitespace, dynamic > > typing, and that it is interpreted - not compiled. These three put > > python under fire and cause some large projects to move off python or > > relegate it to prototyping. > > I think these are valid as "compromises", not to be confused with > flaws. These are all explicit choices, and ones for which the original > justifications remain valid. A lot of stuff in Basic is simply flaws, > or based on justifications that no longer apply to today's programming > world. I think I'd go with your first assessment. These are design choices. Compromises are things that you can't figure out how to get right within the structure of the major design choices. > Anyway, I might add mine: the nature of modules as executed code is a > compromise. That is, a module isn't a declaration, it's a program to be > executed in its own namespace. When you import a module, you are > executing the module then looking at the namespace. I wouldn't call it a compromise, but it does have its bad points when you're trying to construct a large, reliable system. > There are some advantages to this, particularly in the transparency of > the implementation -- things don't always work the way you might want > (e.g., circular imports), but it's usually not that hard to understand > why (and often the way you want things to work has nasty gotchas that > you wouldn't have thought of). It also opens up a lot of possibilities > for dynamicism in class and function declaration, like doing this in the > top level: > > if something: > def func(x): ... > else: > def func(x): ... > > But it's a compromise, because it makes things more difficult as well. > It's a *big* problem in any long-running process, where you may want to > modify code underlying the system without rebuilding the entire state. > Classes aren't declared, they are simply constructed, so by reloading a > module all the persistent instances still exist and refer to the defunct > class. You can modify classes at runtime, but this is different from > simply rerunning the class definition. (A clever metaclass *could* make > those equivalent, though... hmmm...) > A related problem is that Python objects generally can accept any > instance variable names, and names are not declared anywhere. Again, > this makes it difficult to deal with long-lived objects. If you change > the class so that all instances get a new attribute, old objects won't > be updated. I'm thinking about both of these things in terms of > Smalltalk, where they make tools possible that really add to the ease of > developing in its environment. Well, while that is true in detail, if you put the prototype in the class object, all instances will find it the next time they try to access it. References will get the class version, and assignments will update the instance. Of course, you had to change some of the methods to even get into this situation... John Roth > > Ian > > > From timr at probo.com Sun Jul 13 00:51:03 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jul 2003 21:51:03 -0700 Subject: Windows Python 2.3b2 bug? Edit with IDLE References: Message-ID: "Tim Peters" wrote: >[Bartolom? Sintes Marco] >> I am using Python 2.3b2 in a Windows 98 SE machine. If I right-click >> a .py file, the menu shows an "Edit with IDLE" option, but when I >> select it no IDLE window opens, as Python 2.2.2 did. Is it a known >> bug, or am I doing something wrong? Thanks > >It's a known bug, and will be fixed before the next release. There's a new >version of IDLE in a new location in 2.3, but the installer wasn't updated >accordingly (to point the "Edit with IDLE" action to IDLE's new home). This is easy to fix, if the original poster is not afraid of editing the registry. Go recursively search the Python directory for "idle.pyw". Remember the new path. Open regedit, and go to HKEY_CLASSES_ROOT Python.File shell Edit with IDLE command The default value will be something like: C:\Apps\Python22\pythonw.exe C:\Apps\Python22\Tools\idle\idle.pyw -e "%1" Change the path in the second parameter, and you should be good-to-go. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mis6 at pitt.edu Tue Jul 29 10:11:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 07:11:33 -0700 Subject: pretty printing graphs References: <2259b0e2.0307281530.218400ae@posting.google.com> Message-ID: <2259b0e2.0307290611.6e0e9abd@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > Well, here's the version with connectors: > Thanks Bengt, this give me some idea. I was writing something similar three or four days ago, but I was stuck with the connection lines. I had the very bad idea of drawing them as dots, but this is the unhappy result in a similar hierarchy: +------+ |object| +------+.. . . ... . . ... . . ... +------+ +------+ +------+ |ClassD| |ClassE| |ClassF| +------+.. .+------+ +------+ . ..... . . ... ... . . ... ... . +------+ +------+ |ClassB| |ClassC| +------+ .....+------+ . ..... . ..... . ..... +------+.. |ClassA| +------+ I think I will copy your connection lines idea, if not the code ;) Michele From news at yebu.de Mon Jul 21 05:29:39 2003 From: news at yebu.de (Karl Scalet) Date: Mon, 21 Jul 2003 11:29:39 +0200 Subject: pythonic malloc In-Reply-To: References: Message-ID: kjockey schrieb: > I have some simple UDP code that does: > s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr) > > This is OK, except that I'd like to change the text in the middle ("rachel", > which is the hostname FWIW), and the NUL padding needs to go out to make > the length 25 bytes (so the padding depends on the length of the name). > > So I could do something like: > retpacket = "\xf0\x00\x02\x00"+socket.gethostname() > while len(retpacket) < 26: shouldn't that be 25? > retpacket += "\x00" > s.sendto(retpacket, addr) > > But that feels "wrong". And Python in a Nutshell says its a bad idea - > "anti-idiom". > > Can anyone show me the true path? No idea, if it's the true path: hn = socket.gethostname() retpacket = '\xf0\x00\x02\x00%s%s' % (hn, (25-4-len(hn))*chr(0)) s.sendto(retpacket, addr) Karl > > Brad From gh at ghaering.de Tue Jul 1 17:34:39 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 01 Jul 2003 23:34:39 +0200 Subject: Haskell distutils-type system In-Reply-To: References: Message-ID: Isaac Jones wrote: > Hello Python Community. I bring greetings from the Haskell community > (http://www.haskell.org) ;) > > There has been a lot of discussion of late about creating a > grand-unified build & distribution system for "3rd party" Haskell > libraries (those not distributed with the compilers). Python's > Distutils has come up a few times. > [...] > The main issues facing us are: > > 1) there are a variety of Haskell "compiler" implementations, one of > which is an interpreter :) > [...] > 3) just about every Haskell "compiler" and release is > binary-incompatible, (except maybe for nhc98). That is, if we were > going to distribute binary libraries, we'd need different binaries for > ghc4, ghc5, and ghc6. Also we'd need different binaries for profiling > versions of the libraries, etc. > > For instance, if I were to create a binary package HUnit, which is a > simple case since its pure Haskell code, I would need: > hunit-{hugs,nhc98} hunit-ghc{4,5,6} hunit-ghc{4,5,6}-prof > > And whenever a new version of GHC6 is released (for instance), all of > the packages like hunit-ghc6 would need to be updated at the same > time. That doesn't even get into the issues of the wide variety of > preprocessors that are common in this rapidly advancing language[1]. > So all of this suggests to me that we want to keep a global list of > installed libraries and recompile them whenever a new Haskell > "compiler" gets installed. I'd recommend to stay away from automatic recompilation for release the first release. "Explicit is better than implicit." > This is why I want an abstraction layer > above make. > > So I want to ask you if you can think of any obvious things we should > watch out for if we try to do something similar to what Python is > doing. > > Also, there was some mention (in the related "summary of the > Developer's Day session") of Python's distutils creating a Makefile > and wrapping calls to make, is this what you're doing? No, distutils doesn't use make at all. It invokes the compiler and linker directly, if it compiles C extensions. It's actually quite messy: Normally, Python itself is built with an automake-based build process, that will create a Makefile from a Makefile.in and a pyconfig.h. Installing Pyhton installs the Makefile as well, and at distutils runtime, distutils parses this Makefile for extracting the compiler and linker flags, among others. The various compiler and > Do you / did you find yourself duplicating a lot of what make already > does, ie dependencies, etc, or do you utilize make? AFAIK Python's distutils doesn't know about dependencies. > What about configuration, do you typically interface with autoconf > somehow, or does distutils have its own way to figure out > configuration details? It parses the Makefile, which is usually generated by autoconf, as I described above. Obviously there are systems which don't use the autoconf-based build process and where this Makefile and the pyconfig.h are created manually. > Is a typical distutils setup.py program pretty much like what we see > in the example documentation? In my setup.py for C exntensions there are usually some platform-specific portions. if sys.platform.startswith("freebsd") and such. > The developer provides some meta-data > and gets a distribution tool? Yes. > Is there any support for more complex > stuff like interfacing with external systems? For writing C extensions? Of course. > Does distutils handle dependencies? [...] No. And because most C extensions are quite small, that's not really necessary IMO. -- Gerhard From bgailer at alum.rpi.edu Thu Jul 24 15:27:19 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 24 Jul 2003 13:27:19 -0600 Subject: Mystery Theater New Style Classes correction Message-ID: <5.2.1.1.0.20030724132648.028d8968@66.28.54.253> At 02:26 PM 7/24/2003 -0400, Terry Reedy wrote: >"Bob Gailer" wrote in message >news:mailman.1059062857.29503.python-list at python.org... > > Predict the output: > > > > class A(int): > > classval = 99 > > def __init__(self, val = 0): > > if val: > > self = val > > else: > > self = A.classval > >I am not sure what the point is. However, > >1. Rebinding the local variable 'self' (or any other local variable) >only affects further code within the function, which there is not any. >So the above conditional is equivalent to 'pass'. > >2. Because ints are immutable, the value of a new int is set within >int.__new__, which is not overwritten. Thus, the above __init__ is >irrelevant. In particular, the value of an A object has nothing to do >with the defaulted parameter 'val=0'. > > > a=A(3) > >3. This is equivalent to a=int(3). No surprises. > > > b=A() > >4. This is equivalent to b = int(). I thought this might raise an >exception. But after seeing the result (0). I remember Guido's >decision (and a recent PyDev discussion thereof) that callable builtin >types should, if possible, return a null value when getting a null >input. Hence > > >>> int(), long(), float(), tuple(), list(), dict() >(0, 0L, 0.0, (), [], {}) > > > print a,b >3,0 > >5. Result is same if 'val=0' is changed to 'val=9' or anything else. > > > [from OP's self followup] The question this leads to is: how does >one access the value of such a class within a class method? > >Since there is no class method presented, this make not much sense. >Bob: were you aware of 4.) above when you posted this? There's a lot I was not aware of. Your reply and <> have given me what I needed. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From bignose-hates-spam at and-zip-does-too.com.au Sun Jul 6 21:00:17 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Mon, 07 Jul 2003 01:00:17 GMT Subject: Newbie Question: Abstract Class in Python References: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Message-ID: On Mon, 07 Jul 2003 00:42:27 GMT, Kevin Bass wrote: > I am only looking for an answer about creating an abstract class in > Python and not a solution to a problem. I am looking for a way to > stop class instantiation of a class. This should be a generic > approach. Python, in general, doesn't try to stop the programmer doing things, the way many other languages do. This is known in the community as the "we're all consenting adults" philosophy. If you can tell us why you'd want to prevent class instantiation, we can discuss that. -- \ "It's a good thing we have gravity or else when birds died | `\ they'd just stay right up there. Hunters would be all | _o__) confused." -- Steven Wright | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mcfletch at rogers.com Sat Jul 19 07:47:03 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 19 Jul 2003 07:47:03 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: References: Message-ID: <3F192FB7.3060105@rogers.com> Bengt Richter wrote: >On Fri, 18 Jul 2003 08:48:44 -0400, "Mike C. Fletcher" wrote: > > ... >Not sure exactly what you are doing, but what does > > object.__setattr__(client, self.name, value) > >do in your context in place of > > client.__dict__[ self.name ] = value > >? > > __setattr__ invokes the entire tree of setattr machinery, *including* descriptor interception, so it just creates an infinite loop when used in descriptors. What I'm looking for is a (set of) method(s)/function(s) for use when constructing descriptors which allow for simply setting the value without going through the new setattr machinery. In effect, a function which knows how to do the equivalent of "client.__dict__[ name ] = value" for all built-in objects (objects, classes, __slot__ holding instance, etceteras). Hooks into which to hook is my goal, really. A lower-level API for doing what's normally done once you're done pre-processing the setting/getting/deleting "event". Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From pythonguy at Hotpop.com Sun Jul 20 16:55:18 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 20 Jul 2003 13:55:18 -0700 Subject: sys.setcheckinterval query Message-ID: <84fc4588.0307201255.254582df@posting.google.com> Quoting from documentation on sys module in python standard documentation. """ setcheckinterval(interval) Set the interpreter's ``check interval''. This integer value determines how often the interpreter checks for periodic things such as thread switches and signal handlers. The default is 10, meaning the check is performed every 10 Python virtual instructions. Setting it to a larger value may increase performance for programs using threads. Setting it to a value <= 0 checks every virtual instruction, maximizing responsiveness as well as overhead. """ I have a program that uses multiple threads. Is there any direct correlation between the number of threads my program might spawn and the value of ther 'interval' variable. I am interested in the last but one statement which says, "Setting it to a larger value may increase performance for programs using threads.". So my question is what would that value be? How can I find out the number of python 'virtual instructions' for every function I have? Thanks ~Anand From bdesth.nospam at removeme.free.fr Fri Jul 25 16:24:50 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 25 Jul 2003 22:24:50 +0200 Subject: looping through a file In-Reply-To: References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> Message-ID: <3f21903c$0$27898$626a54ce@news.free.fr> Adam wrote: > Psybar Phreak wrote: > >> hi all - ive just started with python (after having done java and c) >> and am >> having a little bit of trouble with the script. Im using as a login >> script. >> >> There's a users.dat file in the format >> user1 >> user1password >> user2 >> user2password >> ... etc >> >> at the moment - the code i work, only checks the first and second >> lines (ie. >> details of user1). but it appears that python doesn't have a do... >> while... >> until loop. >> No, but there are better ways to do it in Python : try: thefile = file(filename) except IOError: doWhatEverWithException() for line in thefile.readlines(): doWhatEverWithTheLine() From ebolonev at rol.ru Sun Jul 6 01:20:17 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Sun, 6 Jul 2003 16:20:17 +1100 Subject: redirect std out in TKinter window,WinXP Message-ID: Hello, All! I want to wrap a WGET in Tkinter application. How can I redirect(or catch) an output of WGET? Hum. May be I should read a log file. With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From gh at ghaering.de Sat Jul 26 21:11:56 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 27 Jul 2003 03:11:56 +0200 Subject: Web tool kit : pro - cons ? In-Reply-To: <3f230835$0$280$ba620e4c@reader0.news.skynet.be> References: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> <3f23034d$0$49103$e4fe514c@news.xs4all.nl> <3f230835$0$280$ba620e4c@reader0.news.skynet.be> Message-ID: <3F2326DC.3010900@ghaering.de> vincent_delft wrote: > My needs are : > - Build pages via templates (easy to split content and layout) ZPT seems to be a good option there. > - My pages will be defined with "boxes". I would like to have a tool that > can manage easely such "object". You mean a WYSIWYG web development IDE for Python? I don't think there's such a thing. > - I will use PostgreSQL as backend. I'd suggest you use pyPgSQL or psycopg for this. I'm a little biased towards pyPgSQL, being one of it's developers ;-) -- Gerhard From martin at v.loewis.de Sun Jul 6 07:45:36 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Jul 2003 13:45:36 +0200 Subject: redirect std out in TKinter window,WinXP References: Message-ID: "Egor Bolonev" writes: > I want to wrap a WGET in Tkinter application. I recommend that you don't. Use urllib instead. Regards, Martin From ian at emit.demon.co.ukx Thu Jul 17 06:53:30 2003 From: ian at emit.demon.co.ukx (Ian McConnell) Date: Thu, 17 Jul 2003 11:53:30 +0100 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> <3f152bb4$1@mail.hmgcc.gov.uk> Message-ID: <87wuehxw45.fsf@emit.demon.co.uk> "richardc" writes: > 'Question 8' > Im no expert but wouldnt you accept that Python has 'borrowed' FORTRAN's > fixed format syntax. I can only think of Python and FORTRAN off the top of > my head which use whitespace as part of the syntax. There was also Occam from the early eighties http://directory.google.com/Top/Computers/Programming/Languages/Occam/ where each construct was indented by two spaces to show structure: PROC write.string(CHAN output, VALUE string[])= SEQ character.number = [1 FOR string[BYTE 0]] output ! string[BYTE character.number] write.string(terminal.screen, "Hello World!") -- "Thinks: I can't think of a thinks. End of thinks routine": Blue Bottle ** Aunty Spam says: Remove the trailing x from the To: field to reply ** From usenet_spam at janc.invalid Sun Jul 6 18:31:26 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 06 Jul 2003 22:31:26 GMT Subject: Frustration with spurious posts. References: <3F06FD11.967D8D8A@hotmail.com> <3F081C10.8CF6B57@hotmail.com> Message-ID: Alan Kennedy schreef: > But if an email is sent from an individual to an individual, then such > "you sent me a virus!" emails can be very useful information. If you know what you're doing: okay. But that means you should always check a malware database to know how it works first. > Is there some sort of mail header that these virus checking gateways > could examine, to see if the email is from a list, rather than an > individual, before it sends these emails? Most mailing-list software adds some typical headers that can be used for that. At least Mailman & Majordomo do and they are the most-used ones. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From soyfree at ugcs.caltech.ed Thu Jul 31 04:51:03 2003 From: soyfree at ugcs.caltech.ed (Rob Sacamento) Date: Thu, 31 Jul 2003 01:51:03 -0700 Subject: keystroke check References: Message-ID: You may want to check out the pygame modules (http://www.pygame.org), specifically the event module. It's been a while since I've looked through the specifications for it, so I'm not positive it does exactly what you want, but it bears checking out. -Rob S. "Wes Fraser" wrote in message news:mailman.1059619004.15764.python-list at python.org... > Is there any way to check in a loop to see if at that > given moment in the program, a key on the key board is > being pressed without actually stopping like raw_ipnut > does? > > Thanks! > > Wes > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free, easy-to-use web site design software > http://sitebuilder.yahoo.com > From rmunn at pobox.com Tue Jul 15 13:21:19 2003 From: rmunn at pobox.com (Robin Munn) Date: Tue, 15 Jul 2003 17:21:19 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> Message-ID: richardc wrote: > Im guessing from the lack of responce that there arnt many python editors > which run on OSX. I didn't see your original post, so I missed that question. One editor I'd suggest you try out is Vim (http://www.vim.org/). Its name stands for "Vi IMproved"; it's basically the good old Unix editor vi with lots of extra features useful for programming, like syntax highlighting and folding. (For Python, use "set foldmethod=indent" -- it works like a charm!) Cons: It's vi. That means a pretty steep learning curve until you've gotten used to modal editing, where you go into "insert mode" to type text and go back into "command mode" (by hitting ESC) to move the cursor, copy and paste text, do searches, move text around, etc. Many people try vi and give up in disgust after five minutes. Pros: It's vi. That means a whole lot of power at your fingertips once you've gotten used to this editing style. I find that personally, I'm about twice as productive with vi as with another editor. YMMV, of course, but that's been my experience. And because vi has been a standard Unix editor for so long, *any* Unix system you use *will* have your favorite editor on it. Plus, Vim is available for all those non-Unix OS'es as well, so you'll never be forced to re-train your fingers on Yet Another Editor when you switch operating systems. If you don't like the vi style of modal editing, there's always the other grand old standard Unix editor, emacs. I'm sure there are several versions of Emacs that will run on OSX; but since I don't use Emacs myself, I can't tell you where to find them. One warning about Emacs, though this is mostly my personal preferences showing: its nickname is "Escape-Meta-Alt-Control-Shift". If you're used to, for example, hitting Command-Shift-S for "Save As..." then you might prefer Emacs' key style over vi's. Myself, I find that my touch-typing-trained fingers prefer hitting several keys in sequence (the way vi tends to do things) than several keys at once (the way Emacs tends to do things). But again, Your Mileage May Vary. Hope this helps. -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From jack at performancedrivers.com Mon Jul 14 03:50:03 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 14 Jul 2003 03:50:03 -0400 Subject: =?iso-8859-1?Q?Python_Mystery_Theatre_--_Episode_2:__As=ED_Fue?= In-Reply-To: ; from vze4rx4y@verizon.net on Mon, Jul 14, 2003 at 05:42:13AM +0000 References: Message-ID: <20030714035003.B1005@localhost.localdomain> On Mon, Jul 14, 2003 at 05:42:13AM +0000, Raymond Hettinger wrote: I didn't look at the code, excepting int() [which is a big exception] > ACT I ----------------------------------------------- > print '*%*r*' % (10, 'guido') > print '*%.*f*' % ((42,) * 2) I'll assume '%r' is __repr__ since '%s' is __str__ The star after a % means "placeholder for a number, get it from the arg list" so my guess is: * 'guido'* # padded to ten places, using spaces *42.000000000000000000000000* # 42 decimal points > ACT II ----------------------------------------------- > s = '0100' > print int(s) > for b in (16, 10, 8, 2, 0, -909, -1000, None): > print b, int(s, b) int(0100) == 64 # octal I looked up int_new() in intobject.c because I had never used the optional base parameter. the 'b' parameter is only legal for 1 >= base <= 36 but the magic constant[1] is -909, which is interpreted as base 10 > ACT III ---------------------------------------------------- > def once(x): return x > def twice(x): return 2*x > def thrice(x): return 3*x > funcs = [once, twice, thrice] > > flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)] > flam = [lambda x:f(x) for f in funcs] > > print flim[0](1), flim[1](1), flim[2](1) > print flam[0](1), flam[1](1), flam[2](1) funcs, flim, and flam all seem identical to me. all these should print 1 2 3 > ACT IV ---------------------------------------------------- > import os > os.environ['one'] = 'Now there are' > os.putenv('two', 'three') > print os.getenv('one'), os.getenv('two') no idea, so I'll punt Now there are three -jack [1] When optional arguments are omitted (in this case 'base') the C variable where they are recorded is left unchanged. In this case that variable starts at -909 so if it is passed in as -909 or omitted the code doesn't know. But why can't base just default to 10 in the first place? If the result is -909 (omitted or passed in as -909) we just do a base-10 conversion anyway. intobject.c PyObject *x = NULL; int base = -909; static char *kwlist[] = {"x", "base", 0}; if (type != &PyInt_Type) return int_subtype_new(type, args, kwds); /* Wimp out */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, &x, &base)) return NULL; if (base == -909) return PyNumber_Int(x); /* This will do a base-10 conversion anyway !!! */ if (PyString_Check(x)) return PyInt_FromString(PyString_AS_STRING(x), NULL, base); The only exception is that the first argument has to be a string if the optional base argument is used. I'm sure there was a reason for this ... ? int('99', 10) # legal int(99, 10) # silly, but should this really be illegal? From nsmith at ilangua.com Tue Jul 22 12:24:36 2003 From: nsmith at ilangua.com (Neil Smith) Date: Tue, 22 Jul 2003 17:24:36 +0100 Subject: profile output for kcachegrind ? In-Reply-To: <8dad5312.0307220731.5ff69a91@posting.google.com> References: <8dad5312.0307220731.5ff69a91@posting.google.com> Message-ID: <3F1D6544.6090607@ilangua.com> I've been using visualization of profile output as input to develop my first pyGTK application, but if the input format read by kcachegrind was well documented it would be a trivial task to get profile output in the correct format. Do you know whether it is well documented? Neil. Sebastien de Menten wrote: >Hi, > >I am using the profile module to watch hot spots in a python >application. > >The default output is already useful but has anyone tried to produce >output readable by kcachegrind (http://kcachegrind.sourceforge.net/) ? > >seb > > From tomas at fancy.org Mon Jul 14 22:06:14 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 19:06:14 -0700 Subject: Stop Python from exiting upon error in Windows References: Message-ID: Robert wrote: > How can I stop the Python interpreter from exiting when an error occurs? create a batchfile, tell Windows that the association of Python files is to that batch file, and put this in the file: python.exe %1 pause Or- catch the error in your mainline, and do a sys.raw_input() call on exception. -tom! From donn at u.washington.edu Wed Jul 16 18:45:04 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 16 Jul 2003 15:45:04 -0700 Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> Message-ID: In article <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed at 4ax.com>, Stephen Horne wrote: ... > I was told today that both Perl and ML have something equivalent to > pointers. I don't know either language, though. Given the current > audience, mentioning Perl may be a mistake - but we could look up the > rationale for including them in ML. In Objective CAML (if that's the ML they meant, or if this is general to other ML implementations, I don't know), there is a "ref" type that is essentially a mutable record with one member. Variables, if I may use the term loosely, are about the same as in Haskell - symbols, really, that are equated with some value and thereafter stand for that value. The value's internal state can change, if it supports that, but it can't be replaced with a different value. The only thing that ref adds to this is a notational convenience. You can say let a = ref 0 in begin ... a := !a + 1; ... end instead of the semantically equivalent type 'a myref = {mutable val: 'a} let a = {val = 0} in begin ... a.val <- a.val + 1; ... end Actually it's rather hard to see a great benefit there. But at any rate, this feature isn't fully equivalent to a hypothetical pointer in Python - it doesn't point to a location, it is just a mutable container. Donn Cave, donn at u.washington.edu From gh at ghaering.de Sun Jul 20 09:14:37 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 20 Jul 2003 15:14:37 +0200 Subject: Strings and Unicode In-Reply-To: References: Message-ID: <3F1A95BD.10006@ghaering.de> An AC wrote: > I have a function that takes a string as an input parameter. This > function then urlencodes the string and sends it to a server with > telnetlib.Telnet > > The problem is that the string gets converted into what seems to be > Unicode. How can I check to see if the input-string is Unicode and > convert it to a different character set (in this case ISO-Latin1). Either: if type(s) is unicode: s = s.encode("latin1") or: if isinstance(s, unicode): s = s.encode("latin1") if you want to be prepared for subclasses of unicode strings. I prefer the first version because of its efficiency. In the very rare case that any string or unicode subclasses appear I can switch to the second version later on. -- Gerhard From kjones9 at rochester.rr.com Sat Jul 26 22:58:13 2003 From: kjones9 at rochester.rr.com (Keith Jones) Date: Sun, 27 Jul 2003 02:58:13 GMT Subject: Seeing next character in an file References: Message-ID: On Sun, 27 Jul 2003 01:09:54 +0000, Grumfish wrote: > Is there a way to see the next character of an input file object without > advancing the position in the file? To do this, you can do the following: fin = file('myfile') ... char = fin.read(1) fin.seek(-1,1) # set the file's current position back a character You can then write your own subclass of file, if you want, with "peek" functionality: class flexfile(file): def __init__(self, fname, mode='r', bufsize=0): file.__init__(self, fname, mode, bufsize) def peek(self, cnt): data = self.read(cnt) self.seek(cnt * -1, 1) return data def peekline(self): pos = self.tell() data = self.readline() self.seek(pos, 0) return data From shane at zope.com Fri Jul 25 17:50:03 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 25 Jul 2003 17:50:03 -0400 Subject: Static typing In-Reply-To: <3f219c8d$1@nntp0.pdx.net> References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: <3F21A60B.9020709@zope.com> Scott David Daniels wrote: > You _might_ want some static typing information as program > documentation or to enable efficient program translation. The > types sig was interested in allowing type annotation where > possible. Remember, the type you might want may be more like > "what protocol must these objects (the ones passing through > this variable) follow" than "what are the construction details > of these objects". > > I would like to see interface descriptions describing what > kinds of parameters are required and results produced for > packages that I am considering using. If there were a single > central-python-endorsed form for those descriptions even better. > If the descriptions can be mechanically read, and at least > sometimes mechincally checked (possibly slowly, possibly only > for slow execution), I might use such a system to check a module > before announcing it to the world. Well, here's a pattern I've been trying out for this purpose: use assert statements at the top of the function. def foo(bar, baz): assert isinstance(bar, int) assert isinstance(baz, str) It has the following nice properties: - The type checks are useful for debugging and can be optimized away. - The intent is obvious. - No changes to Python are necessary. - You could easily parse the assert statements for type documentation (as long as the statements are kept simple.) - It avoids the need for some kind of docstring markup language. I'm quite happy with the pattern, although there are a couple of negative points that I can think of: - It's a bit verbose, although that verbosity enables you to perform bounds checking and operate with other type systems like Zope's interfaces. - You can't specify the type of the return values this way. What do you think? Should this become a common idiom? Shane From jtuc at ev1.net Mon Jul 28 11:42:01 2003 From: jtuc at ev1.net (Jordan Tucker) Date: 28 Jul 2003 08:42:01 -0700 Subject: Distutils output directory change? Message-ID: <467c9d67.0307280742.1d48b84d@posting.google.com> Hello, I've just upgraded a box to 2.3c2 from 2.2.1 and I am trying to compile an extension module with distutils. In my setup script I have a list of sources with relative pathnames, e.g. '../../common/helper.c' etc. Building with 2.2.1, the gcc command generated worked: it used '-o build/temp.linux-i686-2.2/helper.o'. But now building with 2.3c2 it generates the gcc command with '-o build/temp.linux-i686-2.3/../../common/helper.o', using the complete path that was specified in the setup script. This creates a problem because then gcc cannot create the output file. Is there a quick fix for this, a parameter I haven't seen in my cursory glance at the docs and distutils source? Thanks, Jordan From jjl at pobox.com Sat Jul 12 17:59:10 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Jul 2003 22:59:10 +0100 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: Message-ID: <873chb5rv5.fsf@pobox.com> Oops, still not used to Gnus. My followup to the 'What's new with Gnosis' thread was supposed to be to this thread. John From syver at inout.no Fri Jul 11 09:40:09 2003 From: syver at inout.no (Syver Enstad) Date: 11 Jul 2003 15:40:09 +0200 Subject: python mode problem in emacs References: <3097083.1057868749@dbforums.com> Message-ID: pygeek writes: > Hi everyone. > I've just installed emacs 21.3.1 on my WinXP machine. > I wanted to switch to Python mode then realized that > my emacs lacked the 'python-mode.el' file. After downloading > from python.org and byte-compiling the file, > I went on to look for the file '.emacs' or 'emacs.el' to include a > few lines of > command so that emacs would load python-mode. > I looked through and searched my hard drive, and there wasn't > such a file > by the name '.emacs' or 'emacs.el'. What's going on here? Where are > the files? > Can somebody help me? > Thanks in advance. I've think I've been through most of the problems you can encounter using Emacs, Python and win32 together. There are various tricks one has to do f.ex in order to get sourcelevel debugging to work (pdb gud mode). Mail me or post to this list if you have any further problems (I saw that your question was answered elsewhere). From davidcfox at post.harvard.edu Sat Jul 12 10:20:27 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Sat, 12 Jul 2003 14:20:27 GMT Subject: wxPython - question In-Reply-To: References: Message-ID: Artur M. Piwko wrote: > In the darkest hour on Thu, 10 Jul 2003 18:12:55 -0700, > Tom Plunket screamed: > >>By reading the docs and using the right flags. :) >> >>(I've been using wx for two weeks.) >> > > > Me - 2 days (-; > > >>wxFRAME_NO_TASKBAR - Creates an otherwise normal frame but it >> > > > Thanks. I was looking for function and this is a style... > I am fighting right now with setting/resetting this flag on live frame. > > Artur > I don't know about this one in particular, but there are very few styles which can be reset after the window is created. You might consider creating a new frame with the appropriate style when you want to switch to a different style. David From duncan at NOSPAMrcp.co.uk Wed Jul 16 05:04:17 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 09:04:17 +0000 (UTC) Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: owski at hotmail.com (Adam Ruth) wrote in news:f0f51c80.0307150921.7b6667e2 at posting.google.com: > 2) C++ makes a strong distinction between the initialization operator, >=, and the assignment operator, =. Both const and reference variables > use them differently. To me, that's a really big violation of proper > 'computer science', because conceptually they're the *same* thing. > But because of context, C++ makes a distinction. Python has no such > distinction, initialization and assigment are always the same. > > (This is true of all static languages with the concept of a constant, > and I don't really disagree with it as a valuable idiom, but it is > inconsistent internally, where Python is consistent. Do any languages > use a different operator for initialization?) Yes, Algol68. My Algol68 is more than rusty, but: Declare a name 'pi' to represent 3.1415926, i.e. declare a constant: REAL pi = 3.1415926; Declare a name 'x' to represent a local variable, and assign it a value: REF REAL x = LOC REAL; x := 3.1415926; Shorthand for the above: REAL x; x := 3.1415926; or even: REAL x := pi; Initialisation uses '=', assignment uses ':='. Note that the constant is defined as a real and initialised with one, but the variable is a reference to a real and initialised with a storage location. The last example is not initialising x with the value, it is implicitly initialising x with a location then assigning the value into that location. -- 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 tzot at sil-tec.gr Mon Jul 21 22:20:57 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 05:20:57 +0300 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: <1l7phvsthe07d5crnum699624msn4nqgue@4ax.com> On Thu, 17 Jul 2003 11:53:05 +0100, rumours say that Alan Kennedy might have written: >Here it is in a format where almost everybody will be able to see the >original greek verb on their screen. > >#--------- > >γίγνωσκω >#--------- if I may... that should be γιγνώσκω since a word ending in a long syllable could never have an accent in the third syllable from the end (that still applies in modern greek). -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From intentionally at blank.co.uk Mon Jul 14 22:48:20 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:48:20 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F135328.89C1F89C@alcyone.com> Message-ID: On Mon, 14 Jul 2003 18:04:40 -0700, Erik Max Francis wrote: >Roy Smith wrote: > >> The wierd thing is that I don't think either one really matches what a >> mathematician means when he writes "=". In math, "=" is neither an >> assignment or a test: it's an assertion. > >Right. In fact, when a mathematician really does mean rebinding, they >use an operator decidely unlike =, often :=, <-, <=, or some other >similar ASCIIzation. The equals sign in mathematics does not mean the >same thing it does in modern programming languages. It's just something >that one has to deal with early on or be forever annoyed. The fact that Python has, in this respect, followed the C etc tradition doesn't mean it is doing the right thing. >It's arguable that the Pascal family has the most mathematics-like >operations for equality and assignment here, but really it's just a >semantic issue of knowing which operator means what. One can even get >used to things like % means string formatting if one really tries :-). True enough. And if someone creates a language in which '+' does subtraction, I'm sure people could get used to that to. Doesn't mean it's the right thing, though. From claird at lairds.com Thu Jul 17 09:50:25 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 17 Jul 2003 13:50:25 -0000 Subject: Linux - python vs sh References: Message-ID: In article , Sybren Stuvel wrote: . . . >can be re-written as: > >( > echo '>>>>>>>>>>>>>>>>' > echo "$nr." > echo "Name: $rpmname" > echo > rpm -qi $rpmname > echo >) >> $file . . . ... or, for that matter, echo ">>>>>>>>>>>>>>>> $nr. Name: $rpmname `rpm -qi $rpmname " >> $file among other variants. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From andrew-pythonlist at puzzling.org Wed Jul 23 05:40:08 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 23 Jul 2003 19:40:08 +1000 Subject: Python 2.3c1: Raising a string doesn't trigger PendingDeprecationWarning. In-Reply-To: <7c58a0f1.0307230020.1336f4ea@posting.google.com> References: <7c58a0f1.0307230020.1336f4ea@posting.google.com> Message-ID: <20030723094008.GA3046@frobozz> On Wed, Jul 23, 2003 at 01:27:54AM -0700, Kerim wrote: > "What's New in Python 2.3" > (http://www.python.org/doc/2.3c1/whatsnew/node17.html) says that > "Raising a string will now trigger PendingDeprecationWarning.". But > with Python 2.3c1 it seems that it isn't the case: > > Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> raise 'error' > Traceback (most recent call last): > File "", line 1, in ? > error > >>> By default, the warnings module is configured to ignore PendingDeprecationWarnings (as opposed to DeprecationWarnings). If you instruct it otherwise, e.g. with -Wall, it does what you expect: bash-2.05b$ python2.3 -Wall Python 2.3b2+ (#2, Jul 5 2003, 11:28:28) [GCC 3.3.1 20030626 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> raise "foo" __main__:1: PendingDeprecationWarning: raising a string exception is deprecated Traceback (most recent call last): File "", line 1, in ? foo >>> -Andrew. From ghowland at lupineNO.SPAMgames.com Thu Jul 3 02:41:18 2003 From: ghowland at lupineNO.SPAMgames.com (Geoff Howland) Date: Thu, 03 Jul 2003 06:41:18 GMT Subject: Python executables? References: Message-ID: <82j7gv8b8sr7nejhunf32hb3oitc08s4pa@4ax.com> On 27 Jun 2003 09:24:22 +0950, Ben Finney wrote: >> This solves the problem of giving python programs to users who don't >> have python but doesn't solve the problem of the source "secrecy" >> (copyright). > >Wrong problem. If you want to hide your source code from your users, >don't expect help from free software programmers. I thought about this for a few days before responding (and Im sure I did a few other things too ;) ), but I wanted to comment on this. I think everyone that uses Python wants it to gain acceptance for the great language that it is. I believe that stating an attitude in this way is pretty counter productive in gaining any kind of wide-spread acceptance. Most of the replies to this request didn't mention the concept of NOT protecting the software, but 2 did to different degrees. As someone who uses and like open source software, and is slowly starting to release some things as open source, and ALSO someone who sells software and will continue in the future to sell software, I can say that nothing turns me off more to a community than being told what my goals should be. I can understand wanting everything to be open, but thats not reality and it never will be. Some people will always want things proprietary, and they will only work within systems that allow that. I think to be truly successful, systems will have to allow for this and make it easy to do. Currently Python does not make this REALLY easy to do, and in the privacy portion, I believe its not even possible. This was a big concern for me when I released my last for-sale software, but I just decided I didn't care that much, and I love working in Python. Some people will care enough, and will avoid Python because the ability to protect their end results aren't there. So far, the only semi-workable way to do this would be something like: - Build a C program that embeds Python. - Encrypt all the Python script/bytecode files. - On runtime, decrypt the files and then execute. Optional: - Change the bytecode values in the Python source, and include your new Python with different bytecode values. I tried this last thing just to see if it would work, and I got some problems compiling initially, so just gave up, but I think in theory it should work. Ignoring the Optional portion, this semi-solution is not actually very secure. It does however move the problem into having to decompile a C program, and then get it to decrypt the Python files. Then the normal Python bytecode -> source. It means any cracker will have to know something about both C and Python to do it, so a bit more barrier to entry. It also means that in the US, the (vile and despicable, but present) DMCA laws will make it a much more severe crime because "cryptography reverse engineering" needed to be applied, and may at least reduce corporations from doing this for fear of lawsuits/criminal charges if they are exposed. Anyway, this is a good bit of work and not a great solution, but is there anything else? If Python is to have avenues of support in all walks of the software industry, will something like this be required? >From what I understand, there are also very good Java decompilers, but no one seems to complain about Java's lack of security. Perhaps it is because it is seen as something that is really "compiled" while Python's loose compilation seems more whimsicle. I think Python faces a lot of different public relations problems, and just thought I'd pipe up about one that I have looked at myself, and that I think most people coming into the Python world are faced with and have to decide whether to ignore or not. -Geoff Howland http://ludumdare.com/ From ccosse at asymptopia.com Mon Jul 28 23:58:18 2003 From: ccosse at asymptopia.com (Charlie Cosse) Date: 28 Jul 2003 20:58:18 -0700 Subject: Tux Math Scrabble v2.2 Message-ID: <58329000.0307281958.6cf5bdd7@posting.google.com> Tux Math Scrabble is written in python and uses PyGame for multimedia. Tux Math Scrabble is a math version of the popular board game for ages 4-40, which is highly entertaining as well as great educational value. The game challenges young people to construct compound equations and consider multiple abstract possibilities. There are three skill-levels for practice from basic addition and subtraction through to multiplication and division. http://www.asymptopia.com From borcis at users.ch Tue Jul 15 15:33:47 2003 From: borcis at users.ch (Borcis) Date: Tue, 15 Jul 2003 21:33:47 +0200 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: <3F14571B.9030906@users.ch> Francois Pinard wrote: > > Automated translators which ignore punctuation are pretty fragile, too. > Here is a case where the exact same words are used, besides punctuation. > I read in one of Audouard's books ("De la connerie et des cons", if > I remember correctly), about Montcalm, a French Canadian military of > old times. The history reports that he said: > > "Messieurs les Anglais, tirez les premiers!" > > but Audouard wrote that he fears the correct writing should have been > something like: > > "Messieurs! Les Anglais... Tirez les premiers!" > > P.S. - I confess I would have more difficulty relating this one to Python. > The word categorisation disambiguation program that I intend to rewrite > in Python, one of these days, would (correctly) yield the same results > for both sentences, so Python-wise for me, this is a non-issue! :-) Reminds me of sitting, a dozen years ago, through the exposition, by an amator, of the theory of word stemming he had spent years, in his corner, to polish; applied to machine translation - that was the research activity of the institute I happened to work for at the time. Someone had invited a local University's professor of linguistics, specialized in morphology. That person apparently felt he needed to debunk the amator's proposal, and started pedantically expounding : "Your proposal to decompose prefix-stem-suffix to translate them separately and recompose the result won't work if the stems are not etymologically related (somehow the topic was translation between closely related languages). Take for instance the pair , ..." -- Of course it's possible : "faisable", "doable" ! Cheers, Boris Borcic -- python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT") From bokr at oz.net Fri Jul 11 16:33:19 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jul 2003 20:33:19 GMT Subject: Python - if/else statements References: Message-ID: On Sat, 12 Jul 2003 07:34:18 +1200, dmbkiwi wrote: >I am new to this group, and relatively new to python programming, however, >have encountered a problem I just cannot solve through reading the >documentation, and searching this group on google. > >I have written a theme in python for the superkaramba theme engine on kde >(see http://netdragon.sourceforge.net - if you are a kde/linux user, it is >a great visual applet engine). I have uploaded it to www.kdelook.org for >others to download and use, however, some users are having an issue, which >to me seems to be very strange. > >Basically the problem is that their version of python is ignoring an >if/else statement, and I can't understand why. Over 3000 people have >downloaded the theme, and only 3 people have identified this problem. The >relevant portion of code is: > >def meterClicked(widget, meter, button): > #print "meterclick" > global dayshow, daypicrem, ddon, ddcon, buttonpressed # these globals -- where do they come from? What module? # Note that each module has its own globals, so is are there different modules # that think they're sharing globals but really aren't? There are ways to solve that, # but first, is that relevant? # Second, are the globals accessible from multiple threads? Are you seeing hard-stuck errors or blue-moon errors? > if (meter == mainpic) and (button == 1): # always here? > if ddcon == 0: # and here ? > if ddon == 1: # and here? > deleteDayDetail(widget, dayshow) > karamba.redrawWidget(widget) > createCurrentDetail(widget) > karamba.redrawWidget(widget) > else: # never here, you're saying, right? # > else: # never here either, right? # # get here though? > buttonpressed = 1 > I used tabs above to line up (maybe ;-) with your text, but maybe you should run your code through tabnanny or something to check for consistent usage. I never use tabs (though I use the tab key and gvim puts in 4 space indentation for me ;-) so I haven't used the tab checkers, but you might benefit, perhaps. >What these users are experiencing is that this portion of code is being >processed, and evaluating all if statements as true, however, as you can >see, they cannot all be true each time this function is called. Their >versions of python also ignore the else construct. > >Can anyone shed any light on what might be going on with these users? > I'd check on the globals and threading issues first. Then see about building a mousetrap. Regards, Bengt Richter From jjl at pobox.com Tue Jul 8 19:27:00 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Jul 2003 00:27:00 +0100 Subject: Mock object creation by example? Message-ID: <878yr88urf.fsf@pobox.com> I had the bright idea a week or two ago to construct mock objects (for unit testing) "by example" by calling methods on a generic mock object. Say we have a class Bar, and we want to check that, when we use BarUser in a particular way, BarUser first calls method Bar.xyzzy with args "foo" and bar=2, then method Bar.do_nothing. # first, construct a mock object by example: m = Mock() m.xyzzy("foo", bar=2) m.do_nothing() # then run the test m.start_test() bu = BarUser(m) bu.method_a("foo", 1, bar=2) bu.method_b() That's it, essentially. It does needs a bit more complication than that to be useful. For example, a way specifying return values and exceptions to be expected, a way of asking it to pretend to be a class object, ways of making slightly fuzzy the expected number and order of calls and their arguments, and the ability to easily inherit from Mock and override methods etc. For example, you might say: m.return_something().returns(1) m.raise_something().raises(Exception) Of course, it turns out somebody else thought of it first. For example, in Java: http://www.abstrakt.de/mockcreator.html Anybody know if something like this already exists in Python? Actually, looking at the examples on mockcreator's web page does lead give you the suspicion that they've had some contact with a certain language : // setup of MockObjects MockFoo mockFoo = new MockFoo(); mockFoo.expectDoSomething( "nobody expects", "the spanish inquisition" ); // Testcode assertEquals( "the spanish inquisition", mockFoo.doSomething( "nobodyExpects" ) ); // Verify mockFoo.verify(); John From m at moshez.org Wed Jul 9 22:14:51 2003 From: m at moshez.org (Moshe Zadka) Date: 10 Jul 2003 02:14:51 -0000 Subject: Sample Web application (Re: Python vs PHP) In-Reply-To: <1057801996.3737.1223.camel@lothlorien> References: <1057801996.3737.1223.camel@lothlorien>, Message-ID: <20030710021451.24619.qmail@green.zadka.com> On 09 Jul 2003, Ian Bicking wrote: > I think installation is a major hindrance to Python's > adoption as a web programming language -- a combination off difficult > installation, and a lack of robustness and generality in installation > methods. Since PHP is widely adopted as a web programming language, I assume you think PHP's installation methods are robusts and general? Let me assure you, having done PHP configuration in Apache, it is far from it -- in fact, it is buggy and annoying beyond all measure. [I was *shocked* to discover, for example, I can't associate all .html files in a directory with PHP. I am sure it is a great visibility booster for PHP to have pages end with .php, but I didn't care much for it.] I actually think that in a world where people think PHP installation methods are sane, Python's barrier to entry (in that regard) is fairly low. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From wenning_qiu at csgsystems.com Tue Jul 8 17:54:22 2003 From: wenning_qiu at csgsystems.com (Wenning Qiu) Date: 8 Jul 2003 14:54:22 -0700 Subject: Embedding Python, threading and scalability Message-ID: I am researching issues related to emdedding Python in C++ for a project. My project will be running on an SMP box and requires scalability. However, my test shows that Python threading has very poor performance in terms of scaling. In fact it doesn't scale at all. I wrote a simple test program to complete given number of iterations of a simple loop. The total number of iterations can be divided evenly among a number of threads. My test shows that as the number of threads grows, the CPU usage grows and the response time gets longer. For example, to complete the same amount of work, one thread takes 10 seconds, 2 threads take 20 seconds and 3 threads take 30 seconds. The fundamental reason for lacking scalability is that Python uses a global interpreter lock for thread safety. That global lock must be held by a thread before it can safely access Python objects. I thought I might be able to make embedded Python scalable by embedding multiple interpreters and have them run independently in different threads. However "Python/C API Reference Manual" chapter 8 says that "The global interpreter lock is also shared by all threads, regardless of to which interpreter they belong". Therefore with current implementation, even multiple interpreters do not provide scalability. Has anyone on this list run into the same problem that I have, or does anyone know of any plan of totally insulating multiple embedded Python interpreters? Thanks, Wenning Qiu From wilkSPAM at OUTflibuste.net Wed Jul 30 11:57:04 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 30 Jul 2003 17:57:04 +0200 Subject: plug: pyBoards.com References: <191e20c8.0307300703.6e84b9ed@posting.google.com> Message-ID: <87y8ygnh2n.fsf@flibuste.net> usenet at kyle.sent.com (Kyle Babich) writes: > > pyBoards.com is a community for all of you Python programmers out > there. So, why not take a minute to stop by and register? > The shame is to use a php forum... ;-p -- William Dode - http://flibuste.net From ianb at colorstudy.com Sun Jul 13 15:48:09 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2003 14:48:09 -0500 Subject: anything like C++ references? In-Reply-To: References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <1058125689.28468.410.camel@lothlorien> On Sun, 2003-07-13 at 12:51, Stephen Horne wrote: > On 13 Jul 2003 12:19:08 -0400, aahz at pythoncraft.com (Aahz) wrote: > > >Whether one can mutate a specific object is simply an > >attribute of that object, rather than requiring a different syntax. > >Trying to focus on the mutable/immutable distinction is what causes the > >mental blowup -- keep your eye on the objects and bindings and you're > >fine. > > That's exactly it - you have to focus on whether an object is mutable > or immutable for that exact reason. No you don't! Mutable and immutable objects act the same with respect to assignment. However, because you cannot change a immutable object in place, to get a different value you must rebind. You must *use* mutable and immutable objects differently -- but that is not surprising, because they are obviously very different objects! You have to use integers and lists differently in part because one is mutable and the other isn't -- but mostly because one is a number and the other is a list. Different objects are different! Python is not novel in the way it deals with variables. Scheme and Smalltalk, for instance, act exactly the same, as do many other dynamically typed languages (though there are different opinions on whether strings should be mutable -- but it's agreed there has to be some immutable string-like type, e.g. symbol). The reason you are getting this reaction is that anyone that comes from those backgrounds thinks you are crazy, as does anyone who has embraced the Python model. This isn't a funny little feature, this is the way all strong, dynamically typed languages work. > While I admit I'm not sure, I believe that in early versions of Python > immutable values literally were copied. Mutable types were made > mutable because of efficiency concerns about copying overheads that > would occur otherwise. If an object is large enough that it is > worthwhile modifying items within it in-place then it tends to be > worthwhile trying to avoid copying overheads, even though these two > aspects of 'mutability' are actually quite distinct in principle. The problem you have is you are still thinking of variables as slots, which is not correct. Variables in Python are bindings. Assignment never copies anything, or creates anything except for changing the variable to point to a different address location. *Every* Python assignment (a=b) is like the C assignment (a=&b). > Tell me one case where it is sensible for a function to behave such > that whether the caller sees a change in a variable it passed as its > argument should depend on the type. Generally a function takes either immutable values (e.g., ints and floats) or mutable values for a certain argument. However, there is a class of operations which are generally operate in an immutable manner, that is, create copies of the objects instead of changing them in place. So even though lists are mutable, list concatenation does not mutate, and in general adding two things (with +) will not mutate either object. Immutable values, by design, do not have the same methods and operations as the mutable counterparts (or at least the mutating methods of those mutable objects). *That* would be a design bug. > Tell me one case where an object storing values should care about > callers mutating values it holds *only* for certain types. Objects don't *store* values, they *refer* to values. You are still thinking like you're in C (or C++). This is why you are having a problem. Ian From jorgencederberg at hotmail.com Thu Jul 24 02:58:53 2003 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Thu, 24 Jul 2003 08:58:53 +0200 Subject: Tkinter Listbox looses selection on Tab In-Reply-To: References: <117880a1.0307221040.60a27c0d@posting.google.com> Message-ID: Martin Franklin wrote: > On Tuesday 22 July 2003 19:40, J?rgen Hansen wrote: > >>Hi >> >>I have a problem with a Listbox in Tkinter. When I tab through several >>widgets with the tab-key, the listbox looses its selection, even >>though it has been selected with .selection_set. The example below >>demonstrates this. Can anyone provide me with some help on this? >> >>Regards >>Jorgen >> >>Ps. I'm on a W2K machine with Python 2.2.2 >> >>---- >>from Tkinter import * >> >>root = Tk() >>colors = ['Yellow', 'Black', 'White', 'Green'] >> >>lb = Listbox(root) > > > > Jorgen, > > Try setting exportselection=0 in the Listbox construction like so: > > lb = Listbox(root, exportselection=0) > > This seems to work on my linux box. > > > Martin > > Hi Martin, It worked on my W2K machine too! Thanks alot. I skimmed through some TCL/TK documentation, but I'm still somewhat puzzled over the default behavior. But I'm sure I'll figure it out someday. Have a nice day Jorgen From bokr at oz.net Thu Jul 17 17:15:00 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 21:15:00 GMT Subject: Regular expression help References: Message-ID: On Thu, 17 Jul 2003 08:44:50 +0200, "Fredrik Lundh" wrote: >David Lees wrote: > >> I forget how to find multiple instances of stuff between tags using >> regular expressions. Specifically I want to find all the text between a >> series of begin/end pairs in a multiline file. >> >> I tried: >> >>> p = 'begin(.*)end' >> >>> m = re.search(p,s,re.DOTALL) >> >> and got everything between the first begin and last end. I guess >> because of a greedy match. What I want to do is a list where each >> element is the text between another begin/end pair. > >people will tell you to use non-greedy matches, but that's often a >bad idea in cases like this: the RE engine has to store lots of back- would you say so for this case? Or how like this case? >tracking information, and your program will consume a lot more >memory than it has to (and may run out of stack and/or memory). For the above case, wouldn't the regex compile to a state machine that just has a few states to recognize e out of .* and then revert to .* if the next is not n, and if it is, then look for d similarly, and if not, revert to .*, etc or finish? For a short terminating match, it would seem relatively cheap? >at this point, it's also obvious that you don't really have to use >regular expressions: > > pos = 0 > > while 1: > start = text.find("begin", pos) > if start < 0: > break > start += 5 > end = text.find("end", start) > if end < 0: > break > process(text[start:end]) > pos = end # move forward > > Or breaking your loop with an exception instead of tests: >>> text = """begin s1 end ... sdfsdf ... begin s2 end ... """ >>> def process(s): print 'processing(%r)'%s ... >>> try: ... end = 0 # end of previous search ... while 1: ... start = text.index("begin", end) + 5 ... end = text.index("end", start) ... process(text[start:end]) ... except ValueError: ... pass ... processing(' s1 ') processing(' s2 ') Or if you're guaranteed that every begin has an end, you could also write >>> for begxxx in text.split('begin')[1:]: ... process(begxxx.split('end')[0]) ... processing(' s1 ') processing(' s2 ') Regards, Bengt Richter From kmj9907 at cs.rit.edu Mon Jul 28 02:11:30 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Mon, 28 Jul 2003 06:11:30 GMT Subject: How to reverse lookup characters in list? References: Message-ID: okay, isn't the number in the list the index of the new letter? So you'd just use alphabet[d].. though what you're doing can be done in a much simpler manner.. for starters... check out the string module. you can do import string string.lowercase that gives you a-z, lowercase.. I think you'll be fine with a string, rather than a list (infact, it's better since it's immutable). If you must ahve a list, you can do [a for a in string.lowercase] to get a list of characters from a to z. Now, all you're really doing with all those lists and loops is just mapping from one character to another. In fact, you're just doing a rotX, where x is the value of your variable v you could just do: rotation = int(raw_input('rotation value: ')) word = raw_input('word: ') .................... new_word = '' for char in word: position = string.lowercase.index(char) position += rotation # this makes it wrap around. i.e. 'z'+2 = 'b' position = position % 26 new_word += string.lowercase[position] print 'your new word is', new_word .................... Hope that helps some. On Mon, 28 Jul 2003 00:15:35 -0400, tjlan wrote: > ---------------------------------------------------------------------------- > from time import sleep > #Alphabet list used to move letters forward for simple encryption. > alphabet = > ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q.... > > word_list = [] > number_list = [] > number_list2 = [] > new_word = [] > #variable for how far you want to switch v = 2 > word = raw_input("Word: ") > a = len(word) > for x in range(0, len(word)): > print word[x], > word_list.append(word[x]) > b = alphabet.index(word[x]) > number_list.append(b) > > for x in range(0, len(number_list)): > c = number_list[x] > c = c + v > number_list2.append(c) > > for x in range(0, len(number_list2)): > d = number_list2[x] > new_word.append(d) > > for x in range(0, > #Stopped here because dont know of way to switch back. From staschuk at telusplanet.net Mon Jul 21 21:06:55 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 21 Jul 2003 19:06:55 -0600 Subject: recognizing empty iterators In-Reply-To: <2259b0e2.0307210626.11a1bbf1@posting.google.com>; from mis6@pitt.edu on Mon, Jul 21, 2003 at 07:26:15AM -0700 References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: <20030721190655.A1960@tibia.amotlpaa.bogus> Quoth Michele Simionato: > [...] In other words I am looking for an > "isempty" function to use in "if" statements such as > > if isempty(iterator): > do_something() > > without side effects. [...] I don't have anything substantial to add to others' posts, but I wonder: under what circumstances do you want to do this? -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From andychup at yahoo.com Thu Jul 31 20:36:41 2003 From: andychup at yahoo.com (Andy C) Date: 31 Jul 2003 17:36:41 -0700 Subject: How do I get a reference to a KEY value of a dictionary? Message-ID: <645db655.0307311636.71923378@posting.google.com> I am new to python, so please bear with me if I am making some conceptual error. Basically I want to create a graph with an adjacency list representation, but I don't want any of the adjacency lists to have duplicate strings when it is avoidable. I have a function createEdge that adds an edge to the graph. The arguments will be distinct since they are read from text files. But basically I want to use the dictionary as a string pool, and if the argument string equals something in the pool already, don't use the argument string, just a use a reference to something in the string pool already. Is this a waste of time? Because I know in python I cannot be certain that the argument strings that are read from files are even garbage collected anyway. I could certainly do the job with duplicate strings, but it would seem wasteful. I am a C programmer, and old habits die hard. The following code works -- I tested it and entries in the adjacency list that are equivalent are in fact identical. But it seems rather stupid to have a dictionary of the form {'alice': 'alice', 'bob': 'bob'}, etc. i.e. the keys and values are the same. It would be nice if I can get a reference to the key in the same time as a hash lookup. I know I can do dictionary.keys().index( 'string' ) or something but that would be pretty inefficient, I believe. class GraphAccumulator: def __init__( self, fileFunction ): self.fileFunction = fileFunction self.adjList = {} # adjacency list self.nodes = {} # list of nodes for preventing string dupes def createEdge( self, node1, node2 ): # another way of doing by using a dictionary nodes = self.nodes if nodes.has_key( node2 ): node2 = nodes[ node2 ] else: nodes[ node2 ] = node2 adjList = self.adjList if adjList.has_key( node1 ): adjList[ node1 ].append( node2 ); else: adjList[ node1 ] = [ node2 ]; # singleton edge list From alanmk at hotmail.com Thu Jul 10 06:59:52 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 10 Jul 2003 11:59:52 +0100 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> Message-ID: <3F0D4728.45284530@hotmail.com> Kim Petersen wrote: > I have no idea about the support (obviously) - but then i hardly ever > buy/use support for development tools [especially not open-source ones]. Well, that just about says it all for the theory that "open source developers should make their money from services". What many people seem to forget is that maintaining high quality software *is* a service: in the case of mxODBC, a very high quality service. If M-A-L didn't charge licensing fees, then he'd be providing a high quality service, i.e. well designed, maintained and up-to-date software, without any income at all, since, in general, developers don't buy support for development tools, unless they absolutely must. Kim Petersen wrote: > [snip] paying 70$ pr. > customer, is the equivalent of paying you for 1hr of support for each > customer [not installation mind you], where our own licence/supportcost > is already getting lower and lower It's a free market: pick another (cheaper) ODBC driver and use that instead. Just make sure that your customers understand that they will get a poorer quality product from you because they're paying you less money, so you have to use lower quality components in your software: I wonder how long they'll be your customers. Kim Petersen wrote: > We work in teams - so that would be 1250*4 making the below calculation > 18*4 (and we're not able to pull in freelancers on this kinda stuff then > - other than paying another 1250). And how much would you pay these freelancers? Probably quite a substantial amount over the weeks or months that you retain them, and probably *far* in excess of the developer license cost for mxODBC. How much improved productivity will you get from those developers because they're not spending a week chasing weird bugs in the database/ODBC code? I feel quite annoyed when people give out about having to pay money for software: someone, somewhere has to write that software: that someone has to pay the rent, the utility bills, etc, etc, etc, etc. Demanding that everyone work for nothing is completely unreasonable: just because you're too stingy to pay for what you get. Some OSS developers are fortunate enough that they don't have to charge money for their software, because the government, or the education system, or some charitable foundation, pays their wages. But that's not true for all OSS developers. To those who continue to complain about having to pay for software, I say: If you don't like paying, fork the software, maintain your own product and let it be free (both in the free-speech and the free-beer senses): see how you long *you* last. not-biting-the-hand-that-feeds-ly yrs. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From intentionally at blank.co.uk Thu Jul 17 13:17:38 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Thu, 17 Jul 2003 18:17:38 +0100 Subject: anything like C++ references? References: <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com> Message-ID: <66mdhvcm18bjm4f507q576evpau4hpmmq0@4ax.com> On 17 Jul 2003 03:54:58 +0200, Heiko Wundram wrote: >On Wed, 2003-07-16 at 22:02, Stephen Horne wrote: >> The pointer thing was raised in the context of a larger discussion. It >> *would* be necessary if another change was made (don't worry, it won't >> happen). > >I know the broader discussion context, but if changes like those (e.g. >copy on write) were to happen at some further point in time, that would >definitely be the moment for me to stop using Python, and switch to >Ruby. I already said a long time ago that these weren't serious suggestions for Python. I used words something like "python wouldn't be python any more" and "in an alternative universe, maybe". From LogiplexSoftware at earthlink.net Thu Jul 3 18:25:47 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 03 Jul 2003 15:25:47 -0700 Subject: wxPython mouse controls In-Reply-To: <9afd3f36.0307030127.2abc37a1@posting.google.com> References: <9afd3f36.0307030127.2abc37a1@posting.google.com> Message-ID: <1057271147.16862.37.camel@software1.logiplex.internal> On Thu, 2003-07-03 at 02:27, Jim Shady wrote: > Hi, > > I am looking at the feasibility in using wxPython on a project our > company needs. > > I intend to show a bar graph in a frame. I can either generate an > image and show it in a panel, or maybe draw it on a canvas (?). Either > case, the vital feature that we need is the ability to choose parts of > the bar by clicking and dragging on it. The selected portion will then > be zoomed into again by the software, generating a new bar graph. > > Is this possible using wxPython? Yes. If you plan on using wxPython you should subscribe to the wxPython mailing list: http://www.wxpython.org/maillist.php -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From max at alcyone.com Thu Jul 24 00:12:34 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 Jul 2003 21:12:34 -0700 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: <3F1F5CB2.7FB4C205@alcyone.com> Ben Finney wrote: > It seems that nesting the 'try' clauses doesn't scale well. What if > fifty files are opened? Must the nesting level of the 'try' clauses > be > fifty also, to close them promptly? If you're manipulating fifty files in one block, presumably you're doing so in a uniform way: allFiles = [...] try: ... finally: for eachFile in allFiles: eachFile.close() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Man is a hating rather than a loving animal. \__/ Rebecca West From daniel.dittmar at sap.com Wed Jul 9 11:26:01 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 9 Jul 2003 17:26:01 +0200 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: A.M. Kuchling wrote: > At PyCon, it was generally agreed at the Web programming BoF that the > authors of the various Python frameworks should all implement the same > example application so that potential users can compare the resulting > code. Nothing much has been done on this front since then; we should > get things moving again by figuring out what the example application > should be. The Java Pet Store was suggested, but it was pointed out > that it's a very large application, requiring too much effort for an > author to do in their spare time. Ian Bicking did something like this with http://colorstudy.com/docs/shootout.html with a Wiki as the example application. If there is interest, I would volunteer to copy this into the Wiki so that it can be more easily extended. I already got Ian's permissionto do so, but was so far too lazy for it. > Let's think about the requirements for an example application: > > * Should be implementable in a few evenings > * Should exercise a reasonable set of features. > * HTML generation (duh!) > * Accepting a form > * Returning non-HTML files (generating a GIF, say) > * Sessions * access control I suggest using http://www.python.org/cgi-bin/moinmoin/WebProgrammingShootOut as the entry point for the specification of the application. Daniel From gtewalt at earthlink.net Tue Jul 1 14:48:16 2003 From: gtewalt at earthlink.net (gt) Date: 1 Jul 2003 11:48:16 -0700 Subject: Newbie: Tkinter and macPython References: Message-ID: "Russell E. Owen" wrote in message news:... > In article , > gtewalt at earthlink.net (gt) wrote: > > >I'm waffling between Ruby, and Python as a programming > >language. > >I borrowed a friends book on Ruby, and have played with > >it a bit. > >I went by the library to check out 'Learning Python' > >but i was too late, the library had closed already... > > > >Anyway, to the point. > >I downloaded macPython for OSX, and was trying to get > >a simpe Tkinter example to work form Lundh's tutorial, > >I think it was. > >Bu I get an error... > > > ># File: hello1.py > > You have hit MacPython at a slightly awkward time. MacPython (through > version 2.2.x) runs as a carbon application on MacOS X and the Tk > interface was never "carbonized" (I think because the underlying Tk was > never carbonized, but whatever the reason, the fact is it will not > work). (MacPython can also be configured as a classic app, simply by > double clicking the suitable application in the installation, in which > case Tkinter runs just fine at least if you boot into MacOS 9, I'm not > sure if it runs in Classic emulation mode.) > > If you want to run Python 2.2.x/Tkinter on MacOS X you can do it as > follows: > > Download and install aqua tcl/tk. Version 8.4.1 is the latest that will > work with Python 2.2.x. A binary distribution is available from > ; there are three > flavors available; I recommend TclTkAqua (having "wish" around is nice. > I'm not sure the full "BI" version adds anything you'll find useful. > > Download and install Python. For Python 2.2.x I suggest using Bob > Ippolito's binary installer , since it includes > Tkinter and some other useful stuff already built. Note that it also > includes wxPython, an alternate GUI that you may wish to look at. > > If you prefer to install thiss stuff from source, my home page > has a suitable link. Installing > from source is not for the faint of heart (though it'll be easier for > Python 2.3). > > Warning: unix Python 2.2.2 requires \n line endings for files, which is > not the Mac norm. Any decent text editor (e.g. BBEdit or Pepper) *can* > save files with \n, but you have to configure it to do it. This problem > will go away with Python 2.3. > > > Python 2.3 will be the first version that unifies "MacPython" and unix > Python (thanks to hard work by Jack Jansen and others). Python 2.3b1 is > available now from Jack's MacPython site > . Install aqua Tk/tcl as > above, then install the 2.3b1 binary installer. You have to do a bit > more work to get Tkinter installed -- I think MacPython 2.3b1 comes with > a package manager that will do the job, but I've not yet tried it. > > I personally use both 2.3b1 and have had no problems with it. (I > actually have a dual installation; 2.3b1 with aqua Tk and 2.2.2 with > unix style x-windowing Tk; both work well.) > > In conclusion, life will be grand when Python 2.3 is released. Meanwhile > it's a bit of work, but not too bad. > > > I hope this helps. > > -- Russell Wow. I never expected anything this thourough for a response. Thanks Russell. I have actually installed MacPython 2.3b1. I tried the package manager, but at the time it wouldnt connect to the 'database' (if I remember correctly) At any rate, it looks like I need aqua Tk. It would seem that I should un-install 2.3b1, install aqua Tk, then reinstall 2.3b1 and implement the package manager. Thanks again. -- Greg From mwh at python.net Tue Jul 15 11:57:44 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jul 2003 15:57:44 GMT Subject: How to give a custom object instance a type name ? References: Message-ID: <7h3adbfn60d.fsf@pc150.maths.bris.ac.uk> "Graeme Matthew" writes: > works fine, ta > > x.__class__.__name__ > 'Dispatcher' > >>> You could also use new-style classes, btw. 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 janeaustine50 at hotmail.com Wed Jul 2 01:46:18 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 1 Jul 2003 22:46:18 -0700 Subject: __del__ not working with cyclic reference? (and memory-leaked?) References: Message-ID: "Aahz" wrote in message news:bdtlji$pmh$1 at panix2.panix.com... > In article , > Jane Austine wrote: > > > >I have some code using singleton pattern. The singleton instance > >is shared as a class variable. The problem is that the singleton > >instance is not cleared automatically. > > > >Following is a simplified version that shows the problem: > > > >-------- > >#foobar.py > >class FooBar: > > def __del__(self): > > print "FooBar removed" > > > >FooBar.foobar=FooBar() > >-------- > > > >Why is this so? Due to the cyclic reference? Isn't python's gc > >supposed to treat it? What singleton idiom is recommended > >otherwise? > > There are two issues that you'll run into with this: gc doesn't work on > classes that define __del__(), and prior to Python 2.3, gc doesn't run > on exit. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > I read the gc module reference thoroughly and thanks to your short comment, I could understand it. (I should not use __del__ for singleton patterns, but any other alternatives?) But does the fact that __del__ is not called for some objects mean they are not freed from memory and therefore memory-leaked? From duncan at NOSPAMrcp.co.uk Fri Jul 11 09:45:57 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 11 Jul 2003 13:45:57 +0000 (UTC) Subject: text file edit object References: Message-ID: Skip Montanaro wrote in news:mailman.1057928298.10364.python-list at python.org: > Should be, though you have the obvious overhead of gulping the entire > file. For very large files it would probably be more efficient to read > the file in smaller chunks and only avoid writing the last ten lines. > However, the code gets that much more baroque. ;-) It doesn't have to get terribly baroque: def skiplast(n, iterable): """skiplast(n, iterable) -> iterator Yields all but the last n entries from the iterable""" buffer = [] for value in iterable: buffer.append(value) if len(buffer) > n: yield buffer.pop(0) Then you can do: infile = file("foo.txt", "r") outfile = file("foo.txt.new", "w") for line in skiplast(10, infile): outfile.write(line) infile.close() outfile.close() Refactoring to avoid shuffling the data in the buffer is left as an exercise for anyone who feels it to be a problem. -- 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 Fri Jul 25 16:45:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Jul 2003 15:45:36 -0500 Subject: Beefing up socket.ssl(...) In-Reply-To: References: <84e0f331.0307251036.6504b16a@posting.google.com> <16161.36214.435946.860897@montanaro.dyndns.org> Message-ID: <16161.38640.870082.867246@montanaro.dyndns.org> >> http://www.python.org/patches/ Ed> I'm not sure whether this "functional change" would be considered a Ed> "bug fix" or "feature addition". The SSL support in socketmodule.c Ed> seems to be lacking almost to the point of being "unusable"... I Ed> can't imagine anyone actually using it for anything "real" in it's Ed> current state, and in that sense, it may be legitimate to call my Ed> changes a "bug fix". This is open source. If you don't submit the code, who will? ;-) Also, note that the SSL code has been factored out into Modules/_ssl.c. Ed> Or I could just hack on socketmodule.c with every new Python release Ed> and hope that someone eventually adds better SSL support. If nobody ever submits such code it will never get into Python. Essentially all functionality that's there today is because writing it scratched an itch for the author. Skip From stuart at gallpath.com Thu Jul 3 08:38:53 2003 From: stuart at gallpath.com (Stuart Galloway) Date: Thu, 03 Jul 2003 12:38:53 GMT Subject: module and file locations Message-ID: Hi, I am writing a debugging a Tkinter program. While debugging I want to run it by pressing F5. When in use I want to run it by double-clicking (win2000) The program reads and write to various files which I want to store in the same directory (or a sub directory) of the main script. My question is: How can my program where it lives so I can get the base directory? argv[0] - will this work debugging if I just import the file? There is some about finding where a module is. This seems to return readable text that would require parsing rather than just a file name Thanks, Stuart From owski at hotmail.com Tue Jul 15 13:21:39 2003 From: owski at hotmail.com (Adam Ruth) Date: 15 Jul 2003 10:21:39 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: Stephen Horne wrote in message news:<9mh6hv45v18apgn6lp7bo6mm63e5oba9rd at 4ax.com>... > >You say that there is one gold standard definition for what a variable > >is. Yet even though C++ deals with variables in three semantically > >distinct way, they are somehow all valid within that definition? > > C++ does not deal with variables in three semantically distinct ways. > It provides a wide range of data types (including pointer types and > reference types) and, in keeping with the mathematical concept of an > abstract data type, each has both its own set of values and its own > set of operations. The only way in which semantics vary from variable > to variable is in that some of those semantics are tied to the > abstract data type. I was going to stay out of this thread because we were just retreading the same ground with different wording, and it was pointless. But here you've brought up something that is completely false, and new to the discussion: > C++ does not deal with variables in three semantically distinct ways. You're correct, it deals with variables in more than three semantically distinct ways. Now, semantic may mean something different to you than it does to me, but if I have two variables and I cannot use the same syntax with each, they're semantically different. Let's look at some of the differences. int i = 1; *i = 5; Does this work? No, it doesn't, because pointers are semantically different than non pointers. register int x = 5; int *y = &x; This also cannot be done. Why? Different semantics for register variables. int y = 1; int x = 2; int &m = y; m = x; Now, here are two problemmatic things. 1) References are just pointers with syntactic sugar, right? Well, it's a pretty thick layer of sugar. Not only can't you use * to dereference, but you don't use & to get the reference, and you don't use -> to access members. References are in the netherworld between pointers and regular variables. In some cases they act like variables, in others they act like pointers. Now that's confusing. 2) C++ makes a strong distinction between the initialization operator, =, and the assignment operator, =. Both const and reference variables use them differently. To me, that's a really big violation of proper 'computer science', because conceptually they're the *same* thing. But because of context, C++ makes a distinction. Python has no such distinction, initialization and assigment are always the same. (This is true of all static languages with the concept of a constant, and I don't really disagree with it as a valuable idiom, but it is inconsistent internally, where Python is consistent. Do any languages use a different operator for initialization?) Now here's one that's very germain to the topic: void mod(char *value) { value[0] = 'a'; } char *str = "hello world"; mod(str); What about this one? str is immutable (or more accurately, its value is immutable). How does mod know this? It doesn't, it's a seg fault. Now, not only is str immutable, but its not inferrable at any point within the function (I guess you could look at it's region in memory, but then you're really down at the implementation layer). Does this violate 'computer science' principles? I'd say it violates the principles you've put forward. > Even when using pointers, the binding of variables to > values is preserved. It is merely that pointer values provide an > indirect way of referencing a store location, or placeholder, which > may be manipulated (ie bound to a different value) using some other > means of identifying that placeholder. The only real difference between this and Python is that in C you're looking at a region in memory that is most always mutable. Python doesn't need to follow this idiom to be correct. Why? Because Python doesn't have regions in memory, it's a non-existent concept. In C you have variable -> memory -> value. In Python you have variable -> value. You may not like this, but I don't think you can correctly say that the C way is 'better' or 'more in line with computer science'. And it certainly isn't more confusing, that's a crock. What you need to know to work with variables in Python is a much smaller base of knowledge than what you need to work with C++. To you it doesn't seem that way, because C++ is second nature to you. But if you took two novice programmers and tried to explain both ways, the persion learning Python would 'get it' much sooner, because there's much less to 'get'. All I have to do is think about the blank stares I get when I try to teach a new programmer about pointers. It's a difficult concept to get, and it's difficult mainly because you need to understand implementation to get it, something you constantly accuse Python of. In C++ you *need* to know implementation of pointers, references, etc to be effective. And you will be surprised quite often by confusing and unexpected semantics and behavior. That just doesn't exist in Python, when I make an assignment, I *know* what's going to happen. And even if C++ is more 'correct' from a computer science standpoint, Python is more simple, concise, and consistent. I'll take that any day. Getting back to the original topic of the discussion, pass by reference. There's a very, very good reason Python doesn't do it: It's not necessary. It only exists in C and C++ to overcome limitations in both languages. Those limitations *don't* exist in Python, so there's no need for pass by reference. There is no example of a situation where pass by reference is the only way to do things, in fact, the way that Python works allows for much *better* ways to achieve those goals. It's simply unnecessary. From alanmk at hotmail.com Wed Jul 9 12:20:09 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 09 Jul 2003 17:20:09 +0100 Subject: QUESTION References: Message-ID: <3F0C40B9.E607A784@hotmail.com> Matt5883 at aol.com wrote: > What is python 2.1.1? Skip Montanaro wrote: > I think you might want to be careful about deleting Python from your > COMPAQ. It appears that COMPAQ did actually deliver Python on some > of their systems: > > http://wingide.com/pipermail/marketing-python/2003-February/001050.html That's fascinating. And a great development for python if true. I just wanted to point out that the above email message from the "marketing-python" list refers to python 2.2 being installed on HP machines. But the OPs question was "What is python 2.1.1?" So maybe the python 2.1 installation is from a different source? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jjl at pobox.com Wed Jul 30 14:27:50 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 19:27:50 +0100 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> Message-ID: <87brvbx42h.fsf@pobox.com> max writes: [...] > The problem with spaces is that you need to do 5 times the work of a > tab to get decent-looking indentation :). Get an editor. :-) John From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Thu Jul 10 08:56:35 2003 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Koczian) Date: Thu, 10 Jul 2003 14:56:35 +0200 Subject: Calling Excel module functions from python [repost] In-Reply-To: References: Message-ID: Mark Carter schrieb: > In Excel, I have a module named modCSV which has a function named > SaveSheet(), which I want to be able to call from python. How do I do > it? > > I've opened the workbook containing the module, and executed the code: > > from win32com.client import Dispatch > xlApp = Dispatch("Excel.Application") > xlApp.Visible = 1 > wb = xlApp.ActiveWorkbook > wbc = wb.VBProject.VBComponents("modCSV") > wbc.SaveSheet() > > but I get the error message: > > Traceback (most recent call last): > File "C:\Documents and Settings\mcarter\My > Documents\cvs-tree\project\2195\code\temp.py", line 17, in ? > wbc.SaveSheet() > File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", > line 454, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .SaveSheet > > It apparently likes the line wbc = ... , but then hates > wbc.SaveSheet(). *Sigh* Try xlApp.Run('SaveSheet') That works with ordinary Excel macros, but I don't know about VBProject.VBComponents. Possibly this might work: wbc.Run('SaveSheet'). HTH, 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 ray at rays-web.com Sat Jul 19 21:20:20 2003 From: ray at rays-web.com (Ray Smith) Date: Sun, 20 Jul 2003 01:20:20 GMT Subject: Python vs ... In-Reply-To: References: <3f19dad1@news.syd.ip.net.au> Message-ID: <3f19ee33@news.syd.ip.net.au> Ben Finney wrote: > On Sat, 19 Jul 2003 23:57:40 GMT, Ray Smith wrote: > >>when I program a tricky well written piece of code > > > When I see a piece of code that can be described as "tricky", I think > "Gee I bet this is a source of bugs". > > Make your code obvious, please. Trickiness is what I want in a mystery > novel or a puzzle, not in code to be read by humans. "Tricky" was probably a bad word ... "difficult" might be a better word. So to say it again ... ''' when I program a difficult problem "well" in another language I say to myself ... "Gee I was clever" when I program a difficult problem "well" in Python I say to myself ... "Gee Python is Clever" ''' Regards, Ray Smith From adalke at mindspring.com Mon Jul 21 13:50:13 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 21 Jul 2003 11:50:13 -0600 Subject: Python voting demo discussion References: Message-ID: Alan Dechert: > Ian Bicking and Andrew Dalke did say they thought Python should be fine for > the demo but I didn't get much detail about why we should prefer it over > some of the other possibilities: HTML, XML, Perl, Java, PHP, C, C++, C#, C, > etc. Just posted a suggestion in that thread, but figured I would elaborate on it here. While Python can do what you want, you'll have to work through some sort of graphics toolkit to get the screen placement and interface code. The standard GUI toolkits (wxPython, Qt, SWING, etc.) are designed for a windowing system with a platform-appropriate look&feel. As such, they likely won't give you the sort of control you want over the system, and you'll end up writing your own. If you're going to do that, you should look at tools designed for that level of control. There are two categories I know of. One is designed for games, and the other for multimedia presentations. For Python, the best bet is pygame, which uses a lower-level toolkit. There are likely bindings for this toolkit for other languages. However, in general I've found Python to be a surperb language and think it would be the easiest development language for this task. The other option is to look for multimedia or prototyping systems. The best example is Flash, which is often used for animations in web pages. These can be very fancy with all sorts of novel controls, and the Flash company (Macromedia) has their software to make it easy to develop these applications, though I've never used them. You would also need to verify you can print from their tools... So if you want a demo, or you want to experiment with different interfaces, you might consider using Flash or related tools and only later, once you're ready for the next development stage, do you worry about the actual mplementation language used for deployment. Andrew dalke at dalkescientific.com From sjmachin at lexicon.net Mon Jul 14 19:54:40 2003 From: sjmachin at lexicon.net (John Machin) Date: 14 Jul 2003 16:54:40 -0700 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: BogAl wrote in message news:... > Thanks for the reply, Dave.... > > > Try putting the .pyd in C:\Python22\Lib\site-packages > > Unfortunately, I'm still getting the error message. > I would suggest that you (1) Remove all your copies of csv.pyd (2) Install the csv module properly by following the instructions on Dave's website (i.e. briefly, you unpack the distribution into a directory, and then run setup.py) (3) If you still have a problem, post a message that shows (a) what version of Windows you are running (b) what version of Python (c) your windows path (d) your Python path (import sys; print sys.path) (e) what you get when you run Python (at the DOS command line!!) with -v and try to import the csv module (f) what the MS depends utility says about C:\Python22\Lib\site-packages\csv.pyd Another thought: I found I had a python22.dll (dated Oct 2002, must be from Python 2.2.2) in my c:\WINNT\system32 directory and one dated May 2003 (must be from Python 2.2.3) in my c:\Python22 directory ... don't know how that happened; puzzling ... I've killed off the older one. You might like to search python22.dll *AND* msvcrt.dll and ensure that you are using the latest. HTH, John From bokr at oz.net Thu Jul 10 23:48:12 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jul 2003 03:48:12 GMT Subject: Python Global Constant References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: On Thu, 10 Jul 2003 02:01:47 -0400, Jp Calderone wrote: >On Thu, Jul 10, 2003 at 04:06:55PM +1200, Greg Ewing (using news.cis.dfn.de) wrote: >> Peter Hansen wrote: >> >Just do what you did above, without the "const" modifier, which >> >doesn't exist and is not really needed in Python. >> >> If you *really* insist on preventing anyone from changing >> them, it is possible, with some hackery. Here's one way >> that works: >> >> ####################################################### >> # >> # MyModule.py >> # >> >> _constants = ['PI', 'FortyTwo'] >> >> PI = 3.1415 >> FortyTwo = 42 >> >> import types >> >> class _ConstModule(types.ModuleType): >> >> __slots__ = [] >> >> def __setattr__(self, name, value): >> if name in self.__dict__['_constants']: >> raise ValueError("%s is read-only" % name) >> self.__dict__[name] = value >> >> del types >> import MyModule >> MyModule.__class__ = _ConstModule >> > > >>> import MyModule > >>> del MyModule._constants[:] > >>> MyModule.PI = 'Cherry, please' > >>> MyModule.PI > 'Cherry, please' > > Jp > Ok, this one is a little more resistant, I think (though I'm not sure how much more ;-): ====< makeconst.py >============================================================= import os, sys def makeconst(m): modulename = m.__name__ mpath = m.__file__ sfront = [ 'def forclosure(m):', ' dictinclosure = {' ] sback = [ ' }', ' class %s(object):'% modulename, ' def __getattribute__(self, name):', ' if name=="__dict__": return dictinclosure.copy()', # no mods ;-) ' return dictinclosure[name]', ' def __setattr__(self,name,val):', ' raise TypeError, "module %s is read-only"'%modulename, ' return vars()["%s"]()'%modulename, '' ] if mpath.endswith('.pyc'): mpath = mpath[:-1] if not mpath.endswith('.py'): raise ValueError, 'Not .py or .pyc based module: %s of %r'%(modulename, mpath) for line in file(mpath): line = line.strip() if not line or line[0]=='#' or not line[0].isupper(): continue lh,rh = map(str.strip, line.split('=',1)) sfront.append( ' %r:m.%s,'% (lh,lh) # get actual bindings from pre-constified module ) exec '\n'.join(sfront+sback) constmod = vars()['forclosure'](m) sys.modules[modulename] = constmod return constmod def importconst(name): return makeconst(__import__(name)) ================================================================================= and we'll import and "make constant" the module: ====< MyConsts.py >==================================== ####################################################### # # MyConsts.py # PI = 3.1415 FortyTwo = 42 ======================================================= >>> import makeconst >>> MyConsts = makeconst.importconst('MyConsts') >>> MyConsts.PI 3.1415000000000002 >>> dir(MyConsts) ['FortyTwo', 'PI'] >>> MyConsts.FortyTwo 42 >>> MyConsts.FortyTwo = 43 Traceback (most recent call last): File "", line 1, in ? File "", line 11, in __setattr__ TypeError: module MyConsts is read-only >>> setattr(MyConsts,'foo',123) Traceback (most recent call last): File "", line 1, in ? File "", line 11, in __setattr__ TypeError: module MyConsts is read-only >>> MyConsts.__dict__ {'PI': 3.1415000000000002, 'FortyTwo': 42} >>> MyConsts.__dict__['PI'] = 'Cherry?' >>> MyConsts.__dict__ {'PI': 3.1415000000000002, 'FortyTwo': 42} >>> vars(MyConsts) {'PI': 3.1415000000000002, 'FortyTwo': 42} >>> MyConsts.PI 3.1415000000000002 >>> object.__getattribute__(MyConsts,'__dict__') {} >>> object.__getattribute__(MyConsts,'__class__') >>> object.__getattribute__(MyConsts,'__class__').__dict__ >>> object.__getattribute__(MyConsts,'__class__').__dict__.keys() ['__module__', '__dict__', '__getattribute__', '__weakref__', '__setattr__', '__doc__'] >>> object.__getattribute__(MyConsts,'PI') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'MyConsts' object has no attribute 'PI' Well, we can force one that will come back that way >>> object.__setattr__(MyConsts,'PI','Cherry ;-)') Not this way: >>> MyConsts.PI 3.1415000000000002 But this way: >>> object.__getattribute__(MyConsts,'PI') 'Cherry ;-)' We can see it in the instance dict that was created: >>> object.__getattribute__(MyConsts,'__dict__') {'PI': 'Cherry ;-)'} But not via the object normally: >>> dir(MyConsts) ['FortyTwo', 'PI'] >>> MyConsts.__dict__ {'PI': 3.1415000000000002, 'FortyTwo': 42} >>> getattr(MyConsts,'__dict__') {'PI': 3.1415000000000002, 'FortyTwo': 42} So you can force the instance to get a __dict__ with whatever apparent attribute, but you can't make it apparent via normal attribute access, so it wouldn't affect modules importing and using MyConsts normally: >>> MyConsts.PI 3.1415000000000002 Well, some you can flesh out the special attributes/methods, but you get the drift. We could also use a metaclass to fake the name exactly (when __name__ is returned ;-) and in __repr__ and __str__. If you import MyConsts after makeconst does its thing, I'm not sure how to sabotage the result of the expression MyConsts.PI for other modules that have imported it, short of rebinding methods. Since the data is not in a class variable or class dict, I you'd have to go after the closure cell. I can find that (I think that's it below, though I'd have to print id(dictinclosure) to be sure), e.g., >>> object.__getattribute__(MyConsts,'__class__').__getattribute__.im_func.func_closure[0] but how do you get at the dict in the cell? I don't guess it should be allowed, even if it's possible. Otherwise you'll just have to mess with sys.modules similarly to get around it, I think, or accept that you just have constant bindings (maybe to mutable objects though ;-) Regards, Bengt Richter From srijit at yahoo.com Tue Jul 29 10:35:41 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 29 Jul 2003 07:35:41 -0700 Subject: Portability of Python (VS.Net, Java etc.) References: <221d8dbe.0307272345.63503afd@posting.google.com> Message-ID: <221d8dbe.0307290635.fea912d@posting.google.com> Hello, Thanks for your good response. This reply can be part of "Re: Python and VS.Net" thread but I would prefer to put it under a different subject. I was just wondering that if Python has to be compatible to MS.NET does it mean that 1) Python should be re-written C# like Jython has been written in Java ? But my bigger concern is about the term "Portability". More than OS, it looks like frameworks/VMs (.NET and Java ) are getting more dominant today. So for middleware like Python (though Python script runs on its own VM) should be compatible with both the frameworks in order to remain practically portable. This appears practically impossible unless we use lowerst common denominator of both the frameworks. So just compiling Python on GNU C for Windows instead of VC++ may not be enough. Moreover Google may also change in future (I have no idea now what may change!) I guess this topic would have been discussed before. If so, it will be nice member(s) can send me the links. Regards, Srijit anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:... > Me too, but this question should probably be asked in the Python > developers mailing list, which according to my analysis above should > be turned into a newsgroup as soon as possible. Also they'd better > answer that they're going to migrate to mingw-compiling soon :-) > From jdhunter at ace.bsd.uchicago.edu Wed Jul 9 15:08:45 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jul 2003 14:08:45 -0500 Subject: Deleting specific characters from a string In-Reply-To: <5ab0af73.0307091044.254f5aab@posting.google.com> (MatthewS@HeyAnita.com's message of "9 Jul 2003 11:44:02 -0700") References: <5ab0af73.0307091044.254f5aab@posting.google.com> Message-ID: >>>>> "Matt" == Matt Shomphe writes: Matt> Maybe a new method should be added to the str class, called Matt> "remove". It would take a list of characters and remove Matt> them from the string: you can use string translate for this, which is shorter and faster than using the loop. class rstr(str): _allchars = "".join([chr(x) for x in range(256)]) def remove(self, chars): return self.translate(self._allchars, chars) me = rstr('John Hunter') print me.remove('ohn') Also, you don't need to define a separate __init__, since you are nor overloading the str default. JDH From ianb at colorstudy.com Sat Jul 5 01:15:51 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 05 Jul 2003 00:15:51 -0500 Subject: Least used builtins? In-Reply-To: References: Message-ID: <1057382150.516.63.camel@lothlorien> On Fri, 2003-07-04 at 22:57, Lulu of the Lotus-Eaters wrote: > I don't think any of these are a big deal. But I see several > motivations for moving a number of the builtins that Bicking disagrees > on. The breakage could be made small to non-existent by including a > bunch of such things in a file like startup.py that gets loaded > automatically, but that can be changed in principle. > > One general point is that getting rid of builtins can make a minimal > Python footprint smaller (and load times slightly faster probably). For > embedded systems, handhelds, etc. reducing the required memory usage is > a good thing. It would be more correct to say that by having these in separate modules, it is easier to find code that uses them so it can be adapted to this minimal environment. Actually removing many of those builtins would create a version of Python that would not run most of the Python code out there -- moving things into different modules doesn't change that, it just means that "core Python" (i.e., the subset of Python's standard library used by 95% of significant code) is split among more modules. Of course, some stuff in builtins is obviously cruft, but not a huge amount of it. > A second issue is the PyPy project. I think it dovetails with that > project to move everything that is a likely candidate for > reimplementation *in* Python into non-core modules. Doing this is not > strictly a requirement for PyPy, but it fits the style of thinking. The premise of PyPy is that *everything* is a likely candidate for reimplementation in Python. It shouldn't matter if it's a builtin. > A third matter is my support for the function decorator/mutator idea. > classmethod, staticmethod, and property are nice method mutators, but as > a number of people pointed out in that thread, they are not the only > such modifiers one can imagine. Moreover, you can implement these in > Python (I incorrectly once doubted this), so spinning them out of core > makes sense from a #2 perspective. Certainly more operations are possible, useful, and to be encouraged. But it's also reasonable for a small set of those to become idiomatic and widely understood -- classmethod, staticmethod, and property are all general enough to apply. > Yet a fourth matter is that I think it would be slightly easier to teach > Python to beginners if __builtins__ did not include a number of > functions that were extremely difficult to explain to novices... and > that are really only of use to fairly expert Pythoneers. I find that > callable, classmethod, id, intern, and a number of others fall in this > category. My thinking is that anything meant for experts should need to > get imported by specific request. I disagree. There's nothing saying you have to describe everything in __builtins__ -- using that module as a teaching outline is surely a bad idea. You should feel entirely free to ignore many of those builtin functions as you like -- certainly some (like intern) *should* be ignored for as long as possible, ostracized even :) > |[super] Again, highly idiomatic, programmers should be discouraged from > |using this name for anything else > > Indeed. But non-advanced programmer won't be using it for its builtin > meaning either. Just look at all the threads by quite sophisticated > Pythonistas trying to clarify exactly what super() really does. You > cannot even understand this function without first getting C3 > linearization (and even then, figuring out what the different calling > forms all do is still tricky). That's a problem with super, not with its place in builtins. Super is kind of a sad retort to a perceived omission in the language... > |zip, like enumerate, is idiomatic -- importing it does not imply > |anything about your code, that it comes from itertools lends little > |insight into what zip does. > > Actually, I don't think a separate zip/izip does any good, nor > range/xrange. But those are more historical accidents. I wouldn't mind > seeing itertools have the same kind of status that sys does now. What's > the last script you wrote that didn't import sys? You don't technically > need it... until you want to do something with input, output or > arguments :-). That describes most of my modules! I seldom import sys -- I probably import os much more often, but certainly not half of the time. Sys is a good example of what would worry me about a module refactoring -- sys just feels like a dumping ground for everything that doesn't quite deserve to be in builtins, but doesn't really feel like it's anything else either. There's no cohesion, but it's considered hidden because it's in a module of its own. Ian From sismex01 at hebmex.com Fri Jul 4 10:04:15 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 4 Jul 2003 09:04:15 -0500 Subject: Python is a gem, you need to keep pushing it .... Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > Sent: Viernes, 04 de Julio de 2003 07:42 a.m. > > delphiro wrote: > > > [attribution removed... don't do that!] > > > Python *is* great but lets not pretend that its a good > > > fit for every problem. > > > > I doubt that (unless you develop hardware drivers). > > Are you saying that you think Python _is_ a good fit > for every problem, excluding only hardware drivers? > > -Peter > Seems like he is; in my experience Python has been flexible enough to fit any problem I've tossed at it. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From me at here.com Fri Jul 4 09:06:30 2003 From: me at here.com (Ton K.) Date: Fri, 04 Jul 2003 15:06:30 +0200 Subject: bug in Tkinter? invalid literal for int() line 1035 Message-ID: Folks, I get subject when binding to a listbox. The value for h is '??' which triggers the error. I'm running Python 2.2.2 from SuSE. Please help TK From pecora at anvil.nrl.navy.mil Tue Jul 1 11:19:59 2003 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 01 Jul 2003 11:19:59 -0400 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> Message-ID: <010720031119590501%pecora@anvil.nrl.navy.mil> In article <3g32gvcolis4485956egtc35akm6lh3uq5 at 4ax.com>, Tim Roberts wrote: > >Hmmm... "remainder" makes sense. But "%" is mod, right. IIRC from my > >abstract algebra days (only 30 yrs ago :-) ) The "X mod n" function > >maps onto the postive integers from 0 to n-1. So sounds like numeric > >contradicts the math texts. Not good since it's a math module. > > That's a bit harsh. You may be right. I got to work and checked my old Abstract Algebra book. The defintion is, We write a=b mod m if m divides (a-b) (i.e. no remeinder). The defintion does not say how to compute the mod, rather it is an expression of a relationship between a and b. Hence, writing -2=-7 mod 5 appears to be OK. The "uniqueness" comes in when we recogize that mod m defines an equivalence relation on the integers and so for a given m every integer falls into a unique class (or subset of integers). The set of m subsets is equivalent to the positive integers 0 to m-1. So it appears that the translation between math and computer science is not as clear as I thought. In math (well, number theory) mod is a relation, not an operation. In computer science it is an operation. Waddayathink? -- Lou Pecora - My views are my own. From alanmk at hotmail.com Mon Jul 14 11:36:55 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 14 Jul 2003 16:36:55 +0100 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: <3F12CE17.76A0A5@hotmail.com> Francois, >The "Time flies" is a classic. I heard it a few dozens of years ago. :-) >Another similar classic, for French, is "Le pilote ferme la porte.". I presume that is a play on "pilote ferme", as in "experimental farm", as well as the obvious meaning "the pilot/driver closes the door/gate". Is this meaning betrayed by the "le" matching "pilote", rather than the "la" it should have for "ferme". Or have I missed the point completely (I don't consider myself a strong french speaker)? Joyeux Le Quatorze! -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From gsmatthew at ozemail.com.au Fri Jul 18 08:10:31 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Fri, 18 Jul 2003 22:10:31 +1000 Subject: Threading Pool Event() Message-ID: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> Hi all I just cannot seem to find any documentation that shows an example of using the factory method Event() in threads. I have a thread pool and if there are no jobs in a Queue I want them to wait for something to be inserted. When a job is inserted I want to send an Event, the first thread that picks it up runs with the job the rest wait for another insert Event. I have been looking at some C, c++ implementations and some use a continious loop within a thread that polls the queue then if one is found pops it from the queue and runs with it. Problem when threads are dormant is it not better having the main thread (i.e process) sending a signal rather than 10 threads polling surely this is cpu intensive ?? any helps or references on Event() is much appreciated many thanks Graeme From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 24 18:34:47 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 25 Jul 2003 00:34:47 +0200 Subject: CGI "download" prompt? In-Reply-To: <77dd287a.0307240632.40c6c309@posting.google.com> References: <77dd287a.0307240632.40c6c309@posting.google.com> Message-ID: <3f205f06$0$49115$e4fe514c@news.xs4all.nl> Daniel Orner wrote: > Unfortunately, > the files that I'm trying to give the user are HTML files. How do I > make it so the browser prompts to save the file rather than just > display it in the browser? Try setting the Content-Type: header to something other than text/html, such as: application/octet-stream I think that any browser that respects the mime type will prompt to save a file with this mime-type. YMMV, especially with IE, because that thing tends to try to act 'smart' and looks at the file extension to determine what to do with the file. It will likely just display it.... --Irmen From rtw at freenet.REMOVE.co.uk Fri Jul 11 13:51:30 2003 From: rtw at freenet.REMOVE.co.uk (Rob Williscroft) Date: 11 Jul 2003 17:51:30 GMT Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> Message-ID: sebastien.hugues wrote in news:3f0e77fc at epflnews.epfl.ch: > Hi > > I would like to retrieve the application data directory path of the > logged user on > windows XP. To achieve this goal i use the environment variable > APPDATA. > > The logged user has this name: s?bastien. The second character is not > an ascii one and when i try to encode the path that contains this name > in utf-8, > i got this error: > > Ascii error: index not in range (128) > > I would like to first decode this string and then re-encode it in > utf-8, but i am not able to find out what encoding is used when i > make: > > appdata = os.environ ['APPDATA'] > > Any ideas ? > I don't know if it will help but: >>> import win32com.client >>> shell = win32com.client.Dispatch("WScript.Shell") >>> env = shell.GetEnvironment("VOLATILE") >>> j = [] >>> for i in env: ... j.append(i) ... >>> j [u'LOGONSERVER=\\\\COMPUTERNAME', u'APPDATA=C:\\Documents and Settings \\username\\Application Data'] >>> Note the leading u, which I don't get with: >>> import os >>> os.environ["APPDATA"] 'C:\\Documents and Settings\\username\\Application Data' Also note that APPDATA should also be in >>> env = shell.GetEnvironment("PROCESS") HTH Rob. -- http://www.victim-prime.dsl.pipex.com/ From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 24 01:26:15 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Jul 2003 15:16:15 +0950 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: On Thu, 24 Jul 2003 05:20:15 GMT, Bryan wrote: >> filelist = [] >> try: >> filelist.append(open(filename[0])) >> filelist.append(open(filename[1])) >> ... >> do_something(filelist) >> finally: >> for f in filelist: >> f.close() > > erik, carl... thanks... this is exactly what i was looking for The only substantial difference I see between this and what you originally posted, is that there is only one 'try...finally' block for all the file open/close operations. Is this what you were wanting clarified? -- \ "I spent all my money on a FAX machine. Now I can only FAX | `\ collect." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From johnroth at ameritech.net Thu Jul 3 10:21:53 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 3 Jul 2003 10:21:53 -0400 Subject: function overloading References: Message-ID: "Duncan Booth" wrote in message news:Xns93AC619ABDB55duncanrcpcouk at 127.0.0.1... > "Simon Burton" wrote in > news:pan.2003.07.01.19.42.06.202399 at webone.com.au: > > > class Im: > > def __init__(self,x,xx=None): > > if xx is not None: > > w,h = x,xx > > im = Image.new("I",(w,h)) > > elif type(x)==str: > > filename = x > > im = Image.open(filename) > > else: > > im = x > > self.im = im > > I would probably do it like this: > > class Im(object): > def __init__(self,im): > self.im = im > > def newFromFile(cls, fileName): > im = Image.open(filename) > return cls(im) > newFromFile = classmethod(newFromFile) > > def newBlank(cls, width=640, height=480): > im = Image.new("I",(width,height)) > return cls(im) > newBlank = classmethod(newBlank) > > Overloading is a bad idea, explicit is better than implicit. > > Using class methods as alternate constructors lets you have meaningful > parameter names, defaults for each variant (if you want them), and > docstrings (here left as an exercise for the reader). I keep forgetting about class methods, probably because they're new and I don't use Java enough. John Roth > > > -- > Duncan Booth duncan at rcp.co.uk > int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" > "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From vze4rx4y at verizon.net Sat Jul 12 02:56:52 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 12 Jul 2003 06:56:52 GMT Subject: Python Mystery Theatre -- Episode 1: Exceptions Message-ID: For your amusement and edification, I'm working on a series of Python puzzles designed to highlight areas of the language known only to those who have read the docs more than once. Each of the following sections contains a code snippet that someone, somewhere might find a little mysterious. Your goal is to sleuth through the code, identify what was expected versus what really happened, and to explain it briefly so that others will find it blindingly obvious. The mysteries are not difficult, but I would suprised if most readers didn't learn something new along the way. Of course, if you are a potential bot, then these mysteries will be very difficult because all you will see is the code operating as designed, implemented, documented and tested. When you post your results, I would be interested in knowing whether you already knew what was going on or whether you had to resort to: * reading other posts * googling * experimenting * or worse, re-reading the docs Raymond Hettinger ACT I --------------------------------------- >>> s = list('abc') >>> try: ... result = s['a'] ... except IndexError, TypeError: ... print 'Not found' ... Traceback (most recent call last): File "", line 2, in -toplevel- result = s['a'] TypeError: list indices must be integers ACT II -------------------------------------------- >>> class MyMistake(Exception): ... pass >>> try: ... raise MyMistake, 'try, try again' ... except MyMistake, msg: ... print type(msg) ... ACT III -------------------------------------------- >>> class Prohibited(Exception): ... def __init__(self): ... print 'This class of should never get initialized' ... >>> raise Prohibited() This class of should never get initialized Traceback (most recent call last): File "", line 1, in -toplevel- raise Prohibited() Prohibited: >>> raise Prohibited This class of should never get initialized Traceback (most recent call last): File "", line 1, in -toplevel- raise Prohibited Prohibited: ACT IV ----------------------------------------------- >>> module = 'Root' >>> try: ... raise module + 'Error' ... except 'LeafError': ... print 'Need leaves' ... except 'RootError': ... print 'Need soil' ... except: ... print 'Not sure what is needed' ... Not sure what is needed ACT V ----------------------------------------------- >>> try: ... raise KeyError('Cannot find key') ... except LookupError, msg: ... print 'Lookup:', msg ... except OverflowError, msg: ... print 'Overflow:', msg ... except KeyError, msg: ... print 'Key:', msg Lookup: 'Cannot find key' From max at alcyone.com Sun Jul 20 05:39:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2003 02:39:07 -0700 Subject: object as a reserved keyword References: Message-ID: <3F1A633B.98456C76@alcyone.com> Lawrence Oluyede wrote: > Does it worth to make "object" keyword a reserved one? > I'd like to avoid oddities like this: It's no different from overriding any of the builtins with a non-standard value: >>> int = float >>> float = str >>> str = lambda x: none >>> str = lambda x: None >>> file = 'elif' If someone wants to be abusive, he can. The idea behind Python is that everyone will behave like adults, so there's little need to worry about these kinds of things. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Do we really want to go to Mars / Do we really want to try \__/ Cassandra Wilson From a.schmolck at gmx.net Sat Jul 26 16:08:54 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 26 Jul 2003 21:08:54 +0100 Subject: Static typing References: Message-ID: "Michael Muller" writes: > Is there currently any plan to introduce static typing in any future > version of Python? (I'm not entirely sure that "static typing" is the right > term: what I'm talking about is the declaration of types for variables, > parameters and function return values). > > I know there was a "types SIG" which introduced several proposals, but it > expired quite a while ago, and I was wondering whether whether some > consensus has been reached on the subject or if it has just been shelved > indefinitely. I think the traits package hasn't been mentioned so far: http://www.scipy.org/site_content/traits/Traits_Users_Guide.htm 'as From duncan at NOSPAMrcp.co.uk Mon Jul 21 10:00:26 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 21 Jul 2003 14:00:26 +0000 (UTC) Subject: Python scripting with Paint Shop Pro 8.0 References: <87d6g4wzu7.fsf@pobox.com> Message-ID: Marc Wilson wrote in news:bpnmhvg7m3sf3rjphodfvgomtt3jg640hn at 4ax.com: > The documentation is, er, sketchy. The manual refers you to a > non-existant folder on the CD, and the Python content is referred to > as the "Python Scripting Engine", which suggests it may not be a full > implementation. If I have to install Python separately, so be it. > I'll look for the .pyd file and see if there a suspiciously-named > executable there as well. > The documentation is available as a separate download (for those people who didn't get their copy on CD, such as the evaluation copy). 4798 files, but having looked at them I wouldn't say they were the best documentation ever. -- 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 staschuk at telusplanet.net Tue Jul 1 11:22:03 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 09:22:03 -0600 Subject: Suggesting for overloading the assign operator In-Reply-To: <6f03c4a5.0306301931.3f15fbb7@posting.google.com>; from rimbalaya@yahoo.com on Mon, Jun 30, 2003 at 08:31:47PM -0700 References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> Message-ID: <20030701092203.A941@tibia.amotlpaa.bogus> Quoth Rim: [...] > The idea is to separate the value assignment from the type assignment, > by introducing a new operator, let's say the ':=' operator. > > '=' remains what it is, assigns type and value at the same time > ':=' assigns only the value That's a peculiar way of speaking. '=' does not assign type and value to a variable; it assigns an object to a name. [...] > In reality, := would just coerce the return type of the RHS of := to > the type of the variable on the LHS of the :=, preserving the value(s) > as best as it can. "The type of the variable" is not a meaningful phrase in Python: names do not have types; objects do. I assume you meant "the type of the object the name on the lhs is presently bound to". Coerce how? Do you want a new __magicmethod__ for this operation? Would ':=' mutate the object presently bound to the lhs name create a new object and rebind the lhs name? To be concrete: a = whatever b = a a := 7 assert a is b Should that assertion succeed or fail, in general? (Note that it fails in general if the ':=' is replaced with '=', even if whatever == 7.) Would ':=' support chaining? That is, would a := b := work? If so, would it be equivalent to _tmp = a := _tmp b := _tmp (except for the namespace pollution), to match the semantics of chained '='? (Note that the assignments happen left to right.) Would use of a name on the lhs of a ':=' cause that name to be considered local, as such use with '=' does? > If the type of the variable was still undefined, ':=' would behave > like '='. It might create confusion in future code, but does not break > old code. Yikes. Why not raise NameError if the name on the lhs of ':=' is not yet bound? > I think it would be a nice feature to have. Comments? Your example a = Currency(6) a := 7 is highly strange. (Even if we ignore the question of *which* currency is being represented; the example could easily be restated with, say, FixedPoint or Rational or some such.) How is it that your users are happy to write Currency(...) when first assigning to a name, but not happy doing so when assigning later? Do they not understand that '=' binds a name to an object? Are they C programmers who think of assignment as copying a value from one location in memory to another? Do they think of the first assignment as a type declaration for the name? (If any of these three are true, they need to be better educated -- they're all fundamental misconceptions about Python.) Do they need a language with syntactic support for Currency objects? -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From news at yebu.de Mon Jul 21 04:19:28 2003 From: news at yebu.de (Karl Scalet) Date: Mon, 21 Jul 2003 10:19:28 +0200 Subject: (mini-)ANN: Document for Python LaTeX setup In-Reply-To: <20030720122018.09823.00000328@mb-m11.aol.com> References: <20030720122018.09823.00000328@mb-m11.aol.com> Message-ID: Chatralias schrieb: > TYPOS > I only found one. > >>From: Dave Kuhlman dkuhlman at rexx.com >>I've written a document ... > > > > 2.1 Step 1 -- Install the Python Source > You will the source distribution for Python... > ^ > need <---? (using a monospace font:-) > > Thanks Dave, from your target audience (dare I speak for us all) > for the Great job. This is just what I needed. > > Ray St.Marie > RASTM2 at aol.com > > From mickey at tm.informatik.uni-frankfurt.de Thu Jul 10 16:06:54 2003 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 10 Jul 2003 20:06:54 GMT Subject: Problems Compiling PyQt3.7 References: Message-ID: mazu wrote: > I get errors about QAssistantClient while compiling PyQt 3.7, on my > debian woody with Qt 3.1.2. Here is compiler message: > > cd qt && /usr/bin/make -f Makefile > make[1]: Entering directory `/Downloads/KDE - libs/PyQt-x11-gpl-3.7/qt' > g++ -c -pipe -w -O2 -D_REENTRANT -fPIC -DSIP_MAKE_MODULE_DLL > -DQT_NO_DEBUG -DQT_THREAD_SUPPORT -I/usr/share/qt3/mkspecs/default -I. -I. > -I/usr/include/python2.1 -I/usr/share/qt3/include -o qtcmodule.o > qtcmodule.cpp > In file included from qtcmodule.cpp:37: > sip/qassistantclient.sip:37: qassistantclient.h: No such file or directory > In file included from qtcmodule.cpp:37: > sipqtQAssistantClient.h:42: parse error before `{' > sipqtQAssistantClient.h:45: destructors must be member functions > sipqtQAssistantClient.h:49: non-member function `property(const char *)' > cannot have `const' method qualifier > sipqtQAssistantClient.h:82: parse error before `private' > sipqtQAssistantClient.h:84: syntax error before `&' > sipqtQAssistantClient.h:87: parse error before `}' > sipqtQAssistantClient.h:89: syntax error before `*' > make[1]: *** [qtcmodule.o] Error 1 > make[1]: Leaving directory `/Downloads/KDE - libs/PyQt-x11-gpl-3.7/qt' > make: *** [sub-qt] Error 2 > > Anybody know any solution to this problem? I've got libqt3-mt, > libqt3-mt-dev, and Qt 3.1.2already installed. Seems your distribution is missing files. Download the Qt-3.1.2 source and copy the missing files into $QTDIR/include. :M: From sybrenUSE at YOURthirdtower.imagination.com Wed Jul 30 17:40:01 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 30 Jul 2003 21:40:01 GMT Subject: Python Jabber client for the Zaurus Message-ID: Hi there! I'm going on a holiday, and to leave something behind to remember me by, I've released Discuss Jabber 0.0.1. It's a jabber client written in Python/Qt for the Sharp Zaurus. It is still lacking a lot of features, but if you already have a jabber account somewhere, you can use this baby to chat on your Zaurus. Feel free to take a look at the code and improve it where you see fit. Send me an email with the diff, and I'll put your changes into the next version of Discuss Jabber! It's about time the Zaurus gets a good IM program! I'll continue developing in about three weeks, when I'm back from Slovenija. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From no at spam.invalid Wed Jul 2 14:47:45 2003 From: no at spam.invalid (Russell E. Owen) Date: Wed, 02 Jul 2003 11:47:45 -0700 Subject: Tkinter Image Button Bug References: Message-ID: In article , Erhan Ekici wrote: >There is a problem in my code.I think it is Tkinter bug.... >it works but doesn't display image. Instead of >image, only a square with color=#dddddd comes on screen. I think you are running into a common Tkinter pitfall (it is an intentional design decision, but I do not recall the argument for it): you need to explicitly maintain references to images; putting them in a Tkinter widget is not sufficient. In your code "icon" is garbage-collected when the function exits because using it to set the icon of the label b does not increment its reference count. I am almost certain it suffices to assign b._iconref = icon (_iconref being an attribute that the Label b is not likely to already have). I've appended your code suitably modified. I've not tested it. -- Russell >from Tkinter import * > >main=Tk() > >def toolbar(master): > toolbar= Frame(master) > pfile ="C:\\Python22\\samples\\ftp\\images\\help.gif" > icon = PhotoImage(file=pfile) > b=Label(toolbar, image=icon, width=10) b._iconref = icon > b.config(background="#dddddd", bd=1, relief=FLAT) > b.pack(side=LEFT, padx=2, pady=2) > #toolbar.config(background="#ffffff", bd=2, relief=GROOVE) > toolbar.pack(side=TOP, expand=YES, fill=X) > > >toolbar(main) >main.mainloop() From intentionally at blank.co.uk Sun Jul 13 22:35:18 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 03:35:18 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <1058126738.28456.424.camel@lothlorien> Message-ID: On Sun, 13 Jul 2003 21:36:14 -0400, Roy Smith wrote: >Jack Diederich wrote: >> I was a long time C++ guy and my a-ha moment was when I realized that the >> GoF's "Design Patterns" were not all universal -- some are C++ specific. >> Trying to force Python semantics into a C++ world view will leave you feeling >> empty every time. > >Thank you for writing this, it makes me feel better! > >I was having exactly this discussion just a couple of days ago with our >local hard-core C++ guy (who also poo-poo's Python, even though he's >never actually tried it). I made exactly the point Jack made -- that >the Design Pattern book is rather C++-centric, and some of it just >doesn't tranlate into Python very well. I thought that book uses Java (and UML)? I agree with the point, though. A pattern is supposed to be a standard way to implement an abstraction, but the best way to implement some abstraction varies from language to language. From mwh at python.net Mon Jul 14 12:58:05 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Jul 2003 16:58:05 GMT Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> <87y8z34d3d.fsf@pobox.com> <3F10959B.17327C19@alcyone.com> Message-ID: <7h3adbhnjb7.fsf@pc150.maths.bris.ac.uk> Erik Max Francis writes: > "John J. Lee" wrote: > > > Perhaps Erik was wondering, as I was, where that " > instance > > object>" came from. > > Indeed. I was quite aware of what was happening, just not clear on why > his particular Python session said something that mine didn't. It's probably a traceback.print_exc vs. the builtin traceback printing stuff thing? >>> class C(Exception): ... def __init__(self): ... pass ... >>> raise C Traceback (most recent call last): File "", line 1, in ? __main__.C>>> import traceback >>> traceback.print_last() Traceback (most recent call last): File "", line 1, in ? C: Seems so. Cheers, M. -- Any form of evilness that can be detected without *too* much effort is worth it... I have no idea what kind of evil we're looking for here or how to detect is, so I can't answer yes or no. -- Guido Van Rossum, python-dev From aahz at pythoncraft.com Tue Jul 29 19:02:37 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2003 19:02:37 -0400 Subject: Snake bath Message-ID: >From a thread on alt.poly: http://www.mindspring.com/~darkhawk/snakebath.jpg -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From aahz at pythoncraft.com Tue Jul 15 10:49:08 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2003 10:49:08 -0400 Subject: Regarding Thread pooling References: Message-ID: In article , sujata wrote: > > I have a query regarding threads. >Is it possible to create thread pools in python.i.e. create threads and = >then retrieve the memory allocated to it so that the same threads can be = >used over and over again rather than creating new threads each time i = >wish to execute functions many times. If its possible plz do let me know = >how to do so. >Can one have control over memory this way? Certainly. What you need to do is set up a while loop in each thread that picks up work from a Queue. One of the work types contains a flag that tells the loop to exit. (There are other ways, but that's the simplest and most straightforward.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From member32992 at dbforums.com Thu Jul 10 16:23:32 2003 From: member32992 at dbforums.com (pygeek) Date: Thu, 10 Jul 2003 20:23:32 +0000 Subject: no python mode for my gvim Message-ID: <3097082.1057868612@dbforums.com> Hello everyone. I have some problems regarding gvim and Python. I have gvim 6.2 running under WinXP, with Python mode feature included during compilation [+python/dyn]. Whenever I try to use gvim's python commands, the following error messages would appear: "E370: Could not load library python21.dll E263: Sorry, this command is disabled, the Python library could not be loaded." I have Python 2.2.2 running and what concerns me is that, I only have the file 'python22.dll' in C:\Windows\System32 and not 'python21.dll' as required by gvim. How do i go about loading the .dll file for gvim? Please advise. Thank you. --Daniel D.-- -- Posted via http://dbforums.com From jainpadam1 at rediffmail.com Wed Jul 2 06:55:37 2003 From: jainpadam1 at rediffmail.com (Padam Jain) Date: 2 Jul 2003 03:55:37 -0700 Subject: ASP Message-ID: Q1.How do u generated GUID's in Asp Pages Q2.How do u pass x-y coordinates to ASP Pages when u click on an Image. Q3.How do u call a VBScript function in an Anchor Tag. Q4.How do u access Object Instance or a variable in another Frame. Please kindly answer this question,its very urgent.I am stuck up here very badly. From jeske at chat.net Sat Jul 12 18:45:59 2003 From: jeske at chat.net (David Jeske) Date: Sat, 12 Jul 2003 15:45:59 -0700 Subject: Passing pointer to array from C to Python..and modifying same array in python? In-Reply-To: <3607e8e4.0307111306.16ab4c6a@posting.google.com> References: <3607e8e4.0307111306.16ab4c6a@posting.google.com> Message-ID: <20030712154559.A6639@mozart> On Fri, Jul 11, 2003 at 02:06:10PM -0700, JW wrote: > I have an array (presumably 'large') that is mallocced in a C > function and its values are initialized in that same function. I > would like to pass just the pointer to the beginning of the array > from this C function to a Pyton function. Then the python method > can individually access and MODIFY individual members of the array. > After the call to the python method, the C function will see any > changes to the array. > Can this be done? Of course this can be done, and there are a number of ways to do it. Based on your implication that there are many more values put in the array by the C code than will be accessed (or changed) by the Python code, this method might make sense: 1) have the C function construct a new python object (i.e. the "wrapper") 2) put the real pointer to the C array into the wrapper as instance data 3) register two methods for the object "get()" and "set()", impelemented in C as Python exported functions. The get method should take self and the array index as paramaters and return the values in that slot of the array The set method should take self, an index, and the values as paramaters and it should modify the real "C-version" of the array. 4) when you execute your python function, it will be given this "wrapper" object as a paramater. It can then call into the methods in the wrapper object to access and change the C-array "in-place" without converting it at all. Each new value which is set into the array is converted on the fly. 5) If you like, you can convert get() and set() to __get__() and __set__ so you can use array access syntax to access the array from python. -- David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske at chat.net From leej at citymutual.com Mon Jul 21 06:47:57 2003 From: leej at citymutual.com (L. A. Jackson) Date: Mon, 21 Jul 2003 11:47:57 +0100 Subject: Python voting demo discussion References: Message-ID: <5penhv47e8plbm07dd615s5e0kj8hsfu7o@4ax.com> When it comes to language selection I'm of the opinion that it should be based on the skillset and expertise available to you. If youre proposing python and have the human resources available with python as a skillset then go for it. If not then look closely at what skillset/s are available and tailor language selection around that. I will STRONGLY advise that you consider using XML (and if necessary get or train people with the necessary expertise ) since there are already several specifications out there ( e.g. vXML, eML) which have looked at the requirements for voting systems. These are open specifications and although they tend to be complex, they do massively increase the value and portability of any data which you capture. In addition XML has the strength of being easily transformable to other formats via XSLT. e.g. With some design and planning you should be able to use the same underlying data/format for output to web, screen or printer. My initial thoughts are that you should look at SVG for the control over onscreen output that you require and XSL for printed documentation. Python is a suitable "glue" language for this...see earlier comments however. Sounds like an interesting project btw. Hope it has good auditing features ;) Good Luck Lee On Mon, 21 Jul 2003 07:44:42 GMT, "Alan Dechert" wrote: >Thanks for the interesting discussion yesterday afternoon about the voting >software development project I am working on putting together. > >Almost all of the discussion had nothing to do with my question, but that's >okay. Actually, I knew it would probably go that was but I could not very >well say, "don't ask me all those other questions." It was reasonable for >you to ask. > >Ian Bicking and Andrew Dalke did say they thought Python should be fine for >the demo but I didn't get much detail about why we should prefer it over >some of the other possibilities: HTML, XML, Perl, Java, PHP, C, C++, C#, C, >etc. > >If you have anything to add regarding this specific issue, I would be >interested to hear it. > >Thanks again for your time. > >-- Alan Dechert > > From donn at u.washington.edu Mon Jul 7 12:53:22 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Jul 2003 09:53:22 -0700 Subject: print attitude References: <3F0669B5.679FB505@alcyone.com> Message-ID: In article <3F0669B5.679FB505 at alcyone.com>, Erik Max Francis wrote: ... > Printing an object prints its str, but simply specifying it as the value > of an expression in the interactive interpreter prints the repr. What > you're seeing is that both the str _and_ the repr of builtin container > types print the _repr_ of their elements. I consider this something of > a wart, but the rationalization is that it might be confusing if the str > were used when using (say) list.__str__ since it might contain spaces or > commas itself. > > >>> [' ', 'a, b', 'c', ' '] > [' ', 'a, b', 'c', ' '] > > If that were the str of the elements, it might be confusing: > > >>> '[%s]' % ', '.join(map(str, [' ', 'a, b', 'c', ' '])) > '[ , a, b, c, ]' > > I see the reasoning, but I'm not sure the benefit of the decision > outweighs the confusion it constantly calls. (This, along with standard > floating point equality questions, are probably the most frequently > asked questions about Python.) Speaking of floats, I believe lists containing floats are the main case where people really resist seeing the sense in this - but it's easier to call that a wart in float's repr, since they're as bugged wherever they see it and in my opinion rightly so. I think some time back, Steven Taschuk proposed to submit a rewrite of the str & repr documentation, and if that goes well it should be more or less explain the behavior of repr(list) without having to mention it specifically. Then that would make this kind of question an opportunity to clear up a whole area of confusion. Questions about a thing don't immediately indicate that it's ill conceived - I guess you have to consider how many questions there would be about the alternative. Donn Cave, donn at u.washington.edu From jepler at unpythonic.net Sun Jul 13 12:18:50 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 13 Jul 2003 11:18:50 -0500 Subject: removing spaces from front and end of filenames In-Reply-To: <93f5c5e9.0307130744.7e9d8377@posting.google.com> References: <3F10BABB.D548961B@alcyone.com> <93f5c5e9.0307130744.7e9d8377@posting.google.com> Message-ID: <20030713161850.GB32319@unpythonic.net> On Sun, Jul 13, 2003 at 08:44:05AM -0700, hokiegal99 wrote: > Erik Max Francis wrote in message news:<3F10BABB.D548961B at alcyone.com>... > > hokiegal99 wrote: > > > > > This script works as I expect, except for the last section. I want the > > > last section to actually remove all spaces from the front and/or end > > > of > > > filenames. For example, a file that was named " test " would be > > > renamed "test" (the 2 spaces before and after the filename removed). > > > Any > > > suggestions on how to do this? > > > > That's what the .strip method, which is what you're using, does. If > > it's not working for you you're doing something else wrong. > > for root, dirs, files in os.walk('/home/rbt/scripts'): > for file in files: > fname = (file) > fname = fname.strip( ) > print fname > > When I print fname, it prints the filenames w/o spaces (a file named " > test " looks like "test"), but when I ls the actual files in the > directory they still contain spaces at both ends. That's what I don't > understand. It seems that .strip is ready to remove the spaces, but > that it needs one more step to actually do so. Any ideas? Surely you need to actually rename the file: for root, dirs, files in os.walk('/home/rbt/scripts'): for name in files: newname = name.strip() if newname != name: os.rename(name, newname) Jeff From pinard at iro.umontreal.ca Wed Jul 2 06:05:54 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois_Pinard?=) Date: 02 Jul 2003 06:05:54 -0400 Subject: arbitrary long integer aritmetics In-Reply-To: References: Message-ID: [Leo] > is there a python module around allow using arbitrary long integers? Hi. No need for a module, this is all builtin in Python. On older version of Pythons, you needed an explicit `long(INTEGER)' to get into the realm of long integers, or else, an explicit `L' suffix to an integer constant. On recent Pythons, `a*b' should automatically produce a long result even if both `a' and `b' are simple (short) integers, without any kind of clue that the result will be long. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From sjmachin at lexicon.net Mon Jul 14 20:03:42 2003 From: sjmachin at lexicon.net (John Machin) Date: 14 Jul 2003 17:03:42 -0700 Subject: Can't install csv parser References: <3f11ba56$0$6532$afc38c87@sisyphus.news.be.easynet.net> Message-ID: BogAl wrote in message news:... > Thanks for the reply, Bernard.... > > > Running the MS "depends" utility on > > csv.pyd reveals that it only needs python22.dll, msvcrt.dll > > and kernel32.dll. Are these all on your PATH? > > > > I think they are now.... > "...C:\WINDOWS\SYSTEM\python22.dll;C:\WINDOWS\SYSTEM\KERNEL32.dll;\C: > \WINDOWS\SYSTEM\MSVCRT.dll;..." I think not; path should contain a list of *directories*, not *files* -- Windows is silently ignoring the non-existence of directories called "C:\WINDOWS\SYSTEM\python22.dll" etc. Rephrasing Bernard's question: do you have those 3 files in directories that are listed in your system path? After a normal Python installation, you would expect to have c:\Python22 in your path, and Python22.dll in that directory. From vze4rx4y at verizon.net Thu Jul 31 20:12:02 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 01 Aug 2003 00:12:02 GMT Subject: What does "*list" mean? References: Message-ID: "Diez B. Roggisch" wrote in message news:bgbkmf$gn9$05$1 at news.t-online.com... > Greg Smethells wrote: > > > What exactly does "*values" mean in the following code? Is this a > > pointer to a PyList? Why can I not find good documentation on this any > > where? I must be blind: > > Just two days ago I had the same qustion, and I got this as answer from > Raymond Hettinger: > > http://www.python.org/dev/doc/devel/ref/calls.html > > Regarding your C question: I didn't do such a thing, but *list only makes > the items of list be used as distinct arguments - so its more a matter of > the function signature you're calling. I'm sure you'll find something about > variable list arguments somewhere - that means that you function looks like > this: > > def foo(arg1, arg2, *args): Hmm, it sounds like the *args calling format needs to be added to the tutorial. Raymond Hettinger From andrew-pythonlist at puzzling.org Thu Jul 17 01:10:36 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 17 Jul 2003 15:10:36 +1000 Subject: Regular expression help In-Reply-To: References: Message-ID: <20030717051036.GB7618@frobozz> On Thu, Jul 17, 2003 at 04:27:23AM +0000, David Lees wrote: > I forget how to find multiple instances of stuff between tags using > regular expressions. Specifically I want to find all the text between a ^^^^^^^^ How about re.findall? E.g.: >>> re.findall('BEGIN(.*?)END', 'BEGIN foo END BEGIN bar END') [' foo ', ' bar '] -Andrew. From aahz at pythoncraft.com Tue Jul 29 10:21:39 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2003 10:21:39 -0400 Subject: variable assignment in "while" loop References: Message-ID: In article , Sybren Stuvel wrote: > >Is it possible to use an assignment in a while-loop? I'd like to do >something like "loop while there is still something to be read, and if >there is, put it in this variable". I've been a C programmer since I >was 14, so a construct like: > >while info = mydbcursor.fetchone(): > print "Information: "+str(info) > >comes to mind. Unfortunately, this doesn't work. Is there a similar >construct in python? Peter usually gives a good answer, but this time there's a better answer: def fetch_iter(cursor): info = True while info: info = cursor.fetchone() yield info for info in fetch_iter(mydbcursor): print "Information:" + str(info) Generally speaking, any time you want to do assignment as part of a while loop, you really want to convert it a for loop. BTW, DO NOT USE TABS in Python programs. You WILL regret it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From bokr at oz.net Thu Jul 17 11:31:29 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 15:31:29 GMT Subject: Recursion in compile() References: <781faf41.0307161629.6295618b@posting.google.com> Message-ID: On Wed, 16 Jul 2003 20:13:24 -0600, Steven Taschuk wrote: >Quoth Narendra C. Tulpule: >> is there any way to allow recusrion in compile()? Something like: >> >> src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \ >> '\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n' >> cobj = compile(src_code, 'myfile', 'exec') >> eval(cobj) > >This works fine for me -- it prints 479001600 as expected, on both >2.2.2 and 2.3b1. What is the problem you're seeing? > It works for me too. But the OP is saying "recursion *in* compile()" [my emphasis and spelling], and the recursion of fact doesn't involve recursion of compiler calls (at least not in the fact code). Maybe he is after something else? BTW, (to the OP), using triple quotes makes things more readable sometimes: >>> src_code = """\ ... def fact(n): ... if n <= 1: ... return 1 ... else: ... return n * fact(n-1) ... ... print fact(12) ... """ >>> cobj = compile(src_code, 'myfile', 'exec') >>> eval(cobj) 479001600 (For yet another readability improvement, leaving out the backslash would make a blank line that's not in the OP's string, but wouldn't hurt the compilation). Regards, Bengt Richter From intentionally at blank.co.uk Mon Jul 14 18:58:28 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 23:58:28 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: <39d6hv8s045s74mr1ortiah4h1b61ahubf@4ax.com> On 14 Jul 2003 07:56:40 +0200, martin at v.loewis.de (Martin v. L?wis) wrote: >Stephen Horne writes: > >> Funny thing. When I use algebra, the variables I define don't end up >> referring to different values, functions or whatever unless I >> explicitly redefine them. When I write a definition on one piece of >> paper, the things I wrote earlier on another sheet don't change. > >That, typically, is because you don't have any mutating operations in >your formulae. All functions you use are side-effect-free. If you >translated the sheets of paper literally into Python, the formulae >would work the way you expect them to work. Funny. Algorithms in mathematics have been around much longer than Python or even electronic computers. From fredrik at pythonware.com Thu Jul 10 01:58:34 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jul 2003 07:58:34 +0200 Subject: Odd scrollbar behavior in IDLE v1.0b2 (Bug?) References: <5ab0af73.0307091709.2baeca43@posting.google.com> Message-ID: Matt Shomphe wrote: > If I use IDLE and have a block of "wraparound" text (text that runs on > to the next line without having an explicit line break) then use the > scrollbar on the right-hand side to navigate (either by dragging on > the bar,using the scroll-wheel on the mouse, or clicking on the > directional arrows), the grey, moveable part of the scrollbar changes > size. that's how Tk's Text widget works; for performance reasons, the size of the scrollbar thumb is based on how many lines you see in the window, not the number of pixels they occupy. From exarkun at intarweb.us Mon Jul 21 19:27:32 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 21 Jul 2003 19:27:32 -0400 Subject: Automatically filling in answers to interactive shell command questions In-Reply-To: References: Message-ID: <20030721232732.GA14856@intarweb.us> On Mon, Jul 21, 2003 at 03:23:25PM -0700, Ted Weatherly wrote: > Is it possible to use python to automatically fill in the answers to > interactive shell command questions? For example, I am using a shell > command addperson that behaves as follows: > > > addperson > First Name: Ted > Birthday: 12/08/1977 > Height: 6'0" > Location: San Francisco, CA > > > > I am prompted for "First Name: " and I enter "Ted". I am prompted for > "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 > people or more...it gets tiresome. > > Assuming I can't change the addperson command to read data from a > file, is there any way to use python to fill in the data for the > expected questions? Perhaps a different language would be better? > Ahh, but addperson already reads data from a file! stdin! Have you tried: cat answer_file | addperson or even addperson < answer_file or, to keep it Python related, >>> import os >>> outf = os.popen('addperson', 'w') >>> inf = file('answer_file', 'r') >>> outf.write(inf.read()) >>> inf.close() >>> outf.close() Jp -- "If you find a neighbor in need, you're responsible for serving that neighbor in need, you're responsible for loving a neighbor just like you'd like to love yourself." -- George W. Bush, Sept. 16, 2002 From michael at foord.net Fri Jul 18 03:48:45 2003 From: michael at foord.net (Fuzzyman) Date: Fri, 18 Jul 2003 08:48:45 +0100 Subject: Python on the PocketPC Message-ID: I've just installed the version of Python 2.2 on my XDA..... and it works great :-) As I'm quite a newbie and have only written simple text-file parsing scripts its hardly a *rigorous* test of Python - but my scritps worked *without* modification - cool. *However* the XDA has only 32 mb of onboard storageand operating memory.......... and Python is currently occupying 8 meg of that onboard the device - this makes playing quake harder :-) Anyone know if python will cope with me shifting all its libraries etc onto a storage card ?? Fuzzyman --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera http://www.voidspace.org.uk Where Headspace Meets Cyberspace Cyberpunk and Science Resource Site Exploring the worlds of Psychology, Spirituality, Science and Computing -- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz http://www.learnlandrover.com From guido at python.org Fri Jul 11 15:13:43 2003 From: guido at python.org (Guido van Rossum) Date: Fri, 11 Jul 2003 15:13:43 -0400 Subject: Help Support Python Message-ID: <200307111913.h6BJDhi03789@pcp02138704pcs.reston01.va.comcast.net> I'm pleased to announce that the Python Software Foundation (PSF) is now accepting donations from individuals and companies interested in supporting our mission to improve the Python programming language. The PSF holds the intellectual property rights for Python and is working towards building a program to fund future Python development. Your donation will make a real difference in the quality of Python's future. For US individuals: The PSF is recognized as a 501(c)(3) charity, which means that you can deduct the full amount of your donation from your taxes. There is no minimum donation amount, so please help even if you can only afford a small contribution. For companies: The PSF is also seeking additional companies interested in becoming sponsors. For more information, please email psf at python.org. About the PSF: http://python.org/psf/ To donate: http://python.org/psf/donations.html You can donate using PayPal or by writing a check. Please pass this message along to anyone who may be able to help us. Thank You! Guido van Rossum, President of the Python Software Foundation --Guido van Rossum (home page: http://www.python.org/~guido/) From sfb at alysseum.com Wed Jul 9 11:23:04 2003 From: sfb at alysseum.com (Simon Bayling) Date: Wed, 9 Jul 2003 15:23:04 +0000 (UTC) Subject: QUESTION References: Message-ID: Python is a popular programming language. The program "c:\python2.1 \Python.exe" is required to run applications written in Python, so it most likely was installed by something else. Check c:\python21\INSTALL.LOG if there is one, it should tell you the date and time it was installed, if that's any help. Regarding whether you can safely delete it or not... That depends on where it came from. If it is required by another program, that program will break if Python suddenly disappears. In itself it is not going to be causing problems, and no-one here is going to classify it as 'unecessary junk'! ;) I suggest you go to a tutorial and start learning Python :) If that doesn't interest you, try renaming the folder and using your PC for a while... if nothing you want to keep suddenly breaks then you can most likely safely remove it. Cheers, Simon. Matt5883 at aol.com wrote in news:mailman.1057759874.18441.python-list at python.org: > > What is python 2.1.1? How did it get on my computer? Is it a > necessary program? Can I safely delete it/remove it? If so how? I > do not recall downloading it. Does it come bundled with some other > program? Maybe one of my kids did it. I do not see enough information > on your site to make these determinations. I have a Compaq 5184 with > OEM Win 98 installed...I do not ever recall seeing "python" in the > programs. I have been having alot of problems with my computer lately > and I am removing unecessary "junk" Thanks, > Matt From paul_rudin at scientia.com Wed Jul 2 04:32:58 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 02 Jul 2003 09:32:58 +0100 Subject: dcom client from non-windows python References: Message-ID: >>>>> "drs" == drs writes: > My guess is you would be more successful using pyro for the > distributed stuff. Ya, but that doesn't allow you to talk to, for example, excel running on a windows box directly. > my other guess is that python com simply wraps windows stuff, > and that reimplementing windows on linux would take a while. I'm not sure how much reimplementing windows is needed? There are other non-python tools that achieve this kind of thing - see e.g. - in theory you just need to know how to drive the dcom network protocol. From ianb at colorstudy.com Thu Jul 10 20:13:28 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Jul 2003 19:13:28 -0500 Subject: Sample Web application In-Reply-To: References: Message-ID: <1057882408.9504.1344.camel@lothlorien> On Thu, 2003-07-10 at 18:33, Jon Ribbens wrote: > In article , Ian Bicking wrote: > > Well, it wasn't Quixote I was talking about. It was more things like > > jonpy (with wt templates, specifically) > > Well, the way 'wt' works requires you to put 2 lines of mod_rewrite > rules in your .htaccess or httpd.conf, there's no getting around that. > I don't see it as a big hardship though. It's kind've fundamental to > they way 'wt' templates work and 2 lines of work in advance means a > lot of work saving later on. FWIW, I spent a lot of time trying to get those two lines to work, ultimately failing (it was a while ago, so I'm afraid I can't expand). It's entirely possible I was trying too hard and making it more complicated than it was... but configuring Apache in general is a pain, because diagnostics for that sort of configuration are largely nonexistent, you simply get incorrect behavior. Or maybe I got Apache right, but the file layout wrong. Whichever. My problems with FastCGI have been largely the same. It shouldn't be complicated, but somehow manages to be so anyway. The multitudes of FastCGI-reimplementors can't all be wrong, can they? ;) Always-reluctantly-a-sysadmin'ly y'rs, Ian From jjl at pobox.com Mon Jul 7 09:14:32 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Jul 2003 14:14:32 +0100 Subject: Collective memory References: <3f06af11$0$49113$e4fe514c@news.xs4all.nl> <3f071e0c.4620472@news.ocis.net> Message-ID: <87r8527a2v.fsf@pobox.com> Charles Shannon Hendrix writes: > In article > , Ben > Hutchings wrote: [...] > I debugged and maintained big Python programs, and it was a frequent > error and problem. [...] So, given that people here *have* maintained big Python programs, and haven't had these problems, what do you conclude about your team's development practices? John From peter at engcorp.com Sat Jul 19 23:59:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Jul 2003 23:59:11 -0400 Subject: Strange (?) list comprehension behavior References: Message-ID: <3F1A138F.549D1D@engcorp.com> George Henry wrote: > > class PSILex: > ops = ["~", "!", "@", ... "|", "||", ... ] What are those ...'s ? You may have left out critical data for us. > ... > def __findAtom(self): > result = "" > ops = [op for op in PSILex.ops if self.text.startswith(op)] > > ... results in a traceback and "TypeError: expected a character buffer > object." In trying to figure out what was going on, in the Python Shell I > subsequently tried Please post the precise traceback, cut and pasted. If it really said that, and your subsequent analysis is valid, I think one of your "ops" is not a string... From rreagan at attbi.com Sun Jul 6 22:02:06 2003 From: rreagan at attbi.com (Russell Reagan) Date: Mon, 07 Jul 2003 02:02:06 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: "Dave Brueck" wrote > Actually, games are a particularly good example to illustrate the point: > 1)... > 2)... > 3)... > 4)... Good points. > There came a time when it was no longer economically viable to develop an > entire game in assembly, and IMO we've *already* passed the point where it's > no longer economically viable to develop most games entirely in C++ - the > time to market is too long, it's too expensive to add new features, > recovering from early incorrect decisions is too costly, etc. Games are > moving to higher-level languages as much as they can because it's a > competitive advantage to do so. After thinking about it I tend to agree. I'm a little partial to C/C++ because I develop (as a hobby) a chess playing program, and I like tinkering with it to see how fast it can go, and finding clever ways of doing things. A chess program is different from a 3D game in that with a 3D game, you can stop at some point and say, "ok, this is fast enough." There is little point in making the game run at 1000 frames per second if no human eye can see more than 60 (or whatever the number is). With a chess program, you can never really say, "ok, this is fast enough." Deep Blue peaked out at around one billion positions per second with a very sophisticated evaluation of each position, and it was still only on par with the best humans in the world. At some point a machine will be able to look ahead from the opening to the end of the game and "solve" chess, and then we can say, "ok, that's fast enough." But until that happens in a few thousand years (maybe), there is no such thing as "fast enough". The same could be said for cryptography software, finding larger prime numbers, probably medical research, and other similar domains where "fast enough" doesn't exist. Granted, these are few, but some, like medical research and cryptography, are very important. Anyway, I know of one chess program written in python, and it is dreadfully slow compared to *any* program written in C/C++ (that I've seen anyway). I have just recently started learning python, and I'm interested in learning about the python/c options that are available, and seeing if I can write a chess engine in python/c that can compare to those written in C/C++. I really like python so far, but I'm not sure how well it is suited for a chess program. The things that make a chess program fast aren't really python's strengths, but hopefully I'm being pessimistic due to my lack of python/c knowledge. I just need to learn the language more so I can start playing with python/c. Hopefully I won't end up writing the entire thing in C and creating a python module like this: import chess chess.run_program_in_c print "Thanks for playing! Bye!" ;-) From sismex01 at hebmex.com Tue Jul 1 10:06:38 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 1 Jul 2003 09:06:38 -0500 Subject: Suggesting for overloading the assign operator Message-ID: > From: rimbalaya at yahoo.com [mailto:rimbalaya at yahoo.com] > Sent: Lunes, 30 de Junio de 2003 10:32 p.m. > > Hi, > > [..same rehash of overloading '=' a'la C++...] > > If the type of the variable was still undefined, ':=' would behave > like '='. It might create confusion in future code, but does not break > old code. > > I think it would be a nice feature to have. Comments? > It's *not* a nice feature to have. If this kind of functionality, strictly applicable to mutable types, is needed, then a self.set(x) method, or a self.value = x property, can be created. An overloadable assignment _statement_ is not going to happen. > > Thanks, > - Rim > You're welcome. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From soconnor at ibbotson.com Thu Jul 24 16:28:09 2003 From: soconnor at ibbotson.com (Sean O'Connor) Date: Thu, 24 Jul 2003 15:28:09 -0500 Subject: Newbie question about Python & W2K Admin Message-ID: This doesn't do what you want, but it's an example of some win2k admin. """Perform user and group administration""" import pythoncom import win32com.client import win32api import winerror UF_DONT_EXPIRE_PASSWD = 0x10000 def createGroup(computerName, groupName, groupDesc): try: obj = win32com.client.GetObject("WinNT://" + computerName) group = obj.Create("group", groupName) group.Put("Description", groupDesc) group.SetInfo() return group except pythoncom.com_error, (hr, msg, exc, arg): scode = exc[5] print win32api.FormatMessage(scode)[:-2] def createUser(computerName, userName, password, fullname, description): try: obj = win32com.client.GetObject("WinNT://" + computerName) user = obj.Create("user", userName) user.SetInfo() user.SetPassword(password) user.Put("FullName", fullname) user.Put("Description", description) flags = user.Get("UserFlags") flags |= UF_DONT_EXPIRE_PASSWD user.Put("UserFlags", flags) user.SetInfo() return user except pythoncom.com_error, (hr, msg, exc, arg): scode = exc[5] print win32api.FormatMessage(scode)[:-2] -----Original Message----- From: stuartc [mailto:stuart_clemons at us.ibm.com] Sent: Wednesday, July 23, 2003 2:25 PM To: python-list at python.org Subject: Newbie question about Python & W2K Admin Hi all: I need to change a few Local Security Settings on a number of W2K machines. An example of a Security Setting I need to change is the "Minimum password length" setting, which is under Account Policies, Password Policy. Instead of doing this manually on each machine, I would like to have an automated way to do this. Can Python be used for this ? Any direction on how to automate this using Python or some other tool will be greatly appreciated. - Stuart -- http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Thu Jul 3 11:52:10 2003 From: aahz at pythoncraft.com (Aahz) Date: 3 Jul 2003 11:52:10 -0400 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <6f03c4a5.0307022119.2b0a4bc1@posting.google.com> Message-ID: In article <6f03c4a5.0307022119.2b0a4bc1 at posting.google.com>, Rim wrote: > >I think the suggestion to solve the problem by using the __setattr__ >special method will not work because it intercepts attribute >assignment of the form "self.attr = somthing", and not what I want, >which is "name = something". Why don't you follow my suggestion about creating your own language? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From owski at hotmail.com Tue Jul 15 09:06:30 2003 From: owski at hotmail.com (Adam Ruth) Date: 15 Jul 2003 06:06:30 -0700 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> <20030714172215452-0600@news.xmission.com> Message-ID: Stephen Horne wrote in message news:... > On Mon, 14 Jul 2003 23:22:18 +0000 (UTC), Adam Ruth > wrote: > Whatever. I've admitted the mistakes that I recognise I've made. If > you think there are other mistakes that I haven't recognised, its up > to you whether you explain them or not. > > Just 'cause I can't sleep the last few nights, doesn't mean anyone has > to read my rantings, much less reply. Even if they *are* accurate > rantings ;-) I just think we've got different viewpoints, and that's okay. Usenet is different than the rest of the world in that opinions think they are facts (okay, maybe it's not so much different than the rest of the world). I'm always up for a lively debate, but at some point I do grow weary of hearing my own typing, and I'm certain that the bandwidth in this forum is better used for other purposes.... perhaps I'll go spew some opinions in comp.lang.java.advocacy... You've made some valid points, and I appreaciated hearing them, it's helped me to understand Python (and programming) that much better. Adam Ruth From news at exultants.org Tue Jul 1 05:05:38 2003 From: news at exultants.org (Van Gale) Date: Tue, 01 Jul 2003 09:05:38 GMT Subject: new to python - looking for a good book In-Reply-To: <9d5509fa.0306301704.3234d552@posting.google.com> References: <9d5509fa.0306301704.3234d552@posting.google.com> Message-ID: Peter Ballard wrote: > Why should I buy any of these books when I've got the (free) official > Python documentation downloaded, and always just a click or two away? Well speaking for myself, I like to read different viewpoints and learn insights that different authors are able to express. The official docs are great, but are purely reference. The Nutshell book goes beyond simple reference and provides some great insights and covers some areas outside of stock python (like DBAPI 2.0). Lundh's "Python Standard Library" goes beyond the official library docs by providing useful example code for most library modules. Van From martin at v.loewis.de Mon Jul 14 16:21:12 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 22:21:12 +0200 Subject: Reloading nested modules References: Message-ID: Greg Fortune writes: > I've wondered about the same problem and considered that as a solution, but > never tested it. I assume that *wouldn't* rebind all of the imports that > have already happened.. ie, I think the references to the old copies of > the modules would hang around even though new ones have been imported. Depends on the import. For import foo the reload would take effect, as, on reload, the module object stays, its dictionary stays, and it is just the dictionary contents that is recreated. For from foo import bar you still have the old value of bar after reloading. > Regardless, the scoping doesn't work so an attempt to reload the embedded > module assumes it is available in local scope and fails. Again, that would > lead me to believe my first statement is true, but when I tested just now, > I got no further than the scoping problem... What scoping problem? > I've been intended to write something that will take a module name and > rebind it in all namespaces that have it currently, but haven't got around > to it. If I ever do, I'll post it here :) Just ask Guido to borrow you the time machine - this has already been done. Regards, Martin From skip at pobox.com Sun Jul 27 21:17:06 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 27 Jul 2003 20:17:06 -0500 Subject: code coverage tool with emacs integration? In-Reply-To: <87ptjva3vx.fsf@pobox.com> References: <87u198ree4.fsf@pobox.com> <87ptjva3vx.fsf@pobox.com> Message-ID: <16164.31122.924239.543610@montanaro.dyndns.org> >> How would you get any context showing you what lines in the region >> had been executed at least once? John> Why would I want to? For me, analyzing code coverage consists of studying the code in the region around the uncovered line(s). Knowing which lines in the area have and haven't been covered helps me analyze what's missing in my test coverage. Skip From gradha at titanium.sabren.com Sun Jul 13 06:07:53 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sun, 13 Jul 2003 12:07:53 +0200 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. In-Reply-To: References: Message-ID: <20030713100753.GB19185@pedos.es> On 2003-07-12, Andrew Dalke wrote: > Grzegorz Adam Hankiewicz: > > The module provides two classes: Mailbox, a file-like > > object which allows you to iterate through the contents of > > a mailbox, and Email, an object which holds the individual > > emails returned by Mailbox. > > What does this do that the standard Python library doesn't support? > mailbox - http://python.org/doc/current/lib/module-mailbox.html > This module defines a number of classes that allow easy and uniform > access to mail messages in a (Unix) mailbox. > email - http://python.org/doc/current/lib/module-email.html > The email package is a library for managing email messages, * python 1.5.2 support. * last time I checked I was unable to use the mailbox module to read a mailbox, write it, and have them byte to byte identical. Didn't bother to check if this has changed, though: http://groups.google.com/groups?threadm=f4c749a5.0201291538.2cd15616%40posting.google.com * MUCH easier to use, open and read, you can't do much more. * MUCH smaller. Easier to read the source and understand it. * IHateUselessMixedCaseStyleThankYou. IHateEvenMore the_fact_that the standardpythonlibrary mixes so_many DifferentStylesTogether. * personal fulfillment, I enjoy rewritting wheels. -- Please don't send me private copies of your public answers. Thanks. From vze4rx4y at verizon.net Thu Jul 17 15:29:33 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 17 Jul 2003 19:29:33 GMT Subject: list() coercion References: Message-ID: [Bob Gailer] > I have just read the docs 2.2.5 Iterator Types. Unfortunately this page > seems to be written for someone who already understands the page. Is there > any other explanation or examples? The Py2.3 release candidate goes out tonight. In it, I've included sections on iterators and generators in the tutorial. I'm interested to know whether you find it helpful: http://www.python.org/dev/doc/devel/tut/node11.html#SECTION001190000000000000000 0 Raymond Hettinger From g2h5dqi002 at sneakemail.com Wed Jul 16 23:04:02 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 17 Jul 2003 15:04:02 +1200 Subject: list() coercion In-Reply-To: References: Message-ID: Ian Bicking wrote: > However, list() seems to call the object's > __len__, > > Is there a way I can keep this from happening? Give your object an __iter__ method that returns itself. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From alanmk at hotmail.com Sun Jul 20 14:35:27 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 20 Jul 2003 19:35:27 +0100 Subject: Threading Pool Event() References: <0tRRa.212$vD1.8077@nnrp1.ozemail.com.au> <9j3Sa.319$vD1.15038@nnrp1.ozemail.com.au> <3F195170.E60FB1A6@engcorp.com> <9uhSa.578$vD1.23592@nnrp1.ozemail.com.au> Message-ID: <3F1AE0EF.5C62A293@hotmail.com> Graeme Matthew wrote: > here is my code, please criticise it to death i wont take offence [snip] > #ON A MULTIPLE CPU MACHINE 2 SEPERATE SERVERS SHOULD BE RUN > #THE INCOMING REQUEST WILL NEED TO BE SWITCHED BETWEEN SERVERS > #THIS IS DUE TO THE GLOBAL INTERPRETER LOCK (GIL) IN PYTHON If my understanding of your intentions is correct, then I think you're expecting that multiple python threads within the same interpreter will migrate to multiple processors, and thus execute in parallel, i.e. simultaneously on multiple processors. However, the GIL prevents precisely that: if you have one python thread running on one processor, it will lock the GIL, thus causing all other python threads on other processors to be suspended until the GIL is free again. One way to achieve true concurrency across multiple processors is to release the GIL when you are processing, which you cannot do from within python code. You have to write a C language extension to do the work, that releases the GIL before doing its job, and reacquires it again when finished. If you really want true concurrency, and still want to write in pure python, then one way to do it is run multiple python interpreters in separate OS processes, which are bound to different processors. Which means that 1. You can no longer use Queue.Queue objects to communicate between servers, since your servers no longer share an address space. 2. You have to use some alternate comms mechanism between the two servers, such as shared memory, named pipes or something like Pyro. 3. You can no longer pass the socket object across wrapped in a "job" object, since the file descriptor tables of the two server processes will be different. Lastly, I have a question of my own: I've read statements along the lines of "having the GIL in python provides certain guarantees that make certain things possible". I can't remember specifics. I'd be most grateful if someone could point me to reading material (apart from the source, Luke :-) which describes what these guarantees are, and what they make possible. TIA, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mwilson at the-wire.com Thu Jul 10 16:57:02 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 10 Jul 2003 16:57:02 -0400 Subject: replace value of a specific position References: <3F0DA6FB.90603@soraia.com> Message-ID: In article , "Sean Ross" wrote: ># or, without importing the string module: >>>> t = '010010101001001110100101010111' >>>> t = ''.join((t[:5],'2',t[6:])) >>>> t >'010012101001001110100101010111' '2'.join ((t[:5], t[6:])) Sorry. Mel. From jtuc at ev1.net Tue Jul 29 10:40:10 2003 From: jtuc at ev1.net (Jordan Tucker) Date: 29 Jul 2003 07:40:10 -0700 Subject: Cannot register dll created using "py2exe --com-dll" References: <57de9986.0307290052.688e54c5@posting.google.com> Message-ID: <467c9d67.0307290640.4f7d87b1@posting.google.com> Err, I meant argv just isn't getting set :) It's early. From andy at wild-flower.co.uk Fri Jul 18 08:28:15 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Fri, 18 Jul 2003 13:28:15 +0100 Subject: using functions and file renaming problem In-Reply-To: <3F174E76.4000302@hotmail.com> References: <3F174E76.4000302@hotmail.com> Message-ID: <200307181327.49804.andy@wild-flower.co.uk> On Friday 18 Jul 2003 2:33 am, hokiegal99 wrote: > A few questions about the following code. How would I "wrap" this in a > function, and do I need to? > > Also, how can I make the code smart enough to realize that when a file > has 2 or more bad charcters in it, that the code needs to run until all > bad characters are gone? It almost is ;-) > For example, if a file has the name > " chars out of the file name. > > The passes look like this: > > 1. 2. -bad*mac\file becomes -bad-mac\file > 3. -bad-mac\file becomes -bad-mac-file > > I think the problem is that once the program finds a bad char in a > filename it replaces it with a dash, which creates a new filename that > wasn't present when the program first ran, thus it has to run again to > see the new filename. No, the problem is that you're throwing away all but the last correction. Read my comments below: import os, re, string bad = re.compile(r'%2f|%25|[*?<>/\|\\]') #search for these. print " " setpath = raw_input("Path to the dir that you would like to clean: ") print " " print "--- Remove Bad Charaters From Filenames ---" print " " for root, dirs, files in os.walk(setpath): for file in files: badchars = bad.findall(file) # find any bad characters newfile = file for badchar in badchars: # loop through each character in badchars # note that if badchars is empty, this loop is not entered # show whats happening print "replacing",badchar,"in",newfile,":", # replace all occurrences of this badchar with '-' and remember # it for next iteration of loop: newfile = newfile.replace(badchar,'-') #replace bad chars. print newfile if badchars: # were there any bad characters in the name? newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) print oldpath print newpath print " " print "--- Done ---" print " " wrt wrapping it up in a function, here's a starter for you... "fill in the blanks": -------8<----------- def cleanup(setpath): # compile regex for finding bad characters # walk directory tree... # find any bad characters # loop through each character in badchars # replace all occurrences of this badchar with '-' and remember # were there any bad characters in the name? -------8<----------- To call this you could do (on linux - mac paths are different): -------8<----------- cleanup("/home/andy/Python") -------8<----------- hope that helps -andyj From creedy at mitretek.org Wed Jul 23 10:49:20 2003 From: creedy at mitretek.org (Chris Reedy) Date: Wed, 23 Jul 2003 10:49:20 -0400 Subject: Python Mystery Theatre -- Episode 3: Extend this In-Reply-To: References: Message-ID: <3f1ea08e_2@corp-news.newsgroups.com> I tried these out myself after making my guesses. Here's what I found: Raymond Hettinger wrote: > [snip] > > This time, the extra credit is for picking-out the three > that surfaced as errors in my own, real code over > the past few years (the example context below may be > different, but the type of error occurred in real code). > > [snip] > > ACT I --------------------- > def real(z): > return hasattr(z, 'real') and z.real or z > def imag(z): > return hasattr(z, 'imag') and z.imag or 0 > for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L: > print real(z), imag(z) I spotted the error in this one (I've been bitten by this more than once) if z.real or z.imag is false, I get z or 0. That results is two problems: For 0+6j, the answer is 6j and 6.0, definitely not what was expected. For 8+0j, the answer is 8.0 and 0, not 8.0 and 0.0. This is close to what was expected and, if a bug at all, would be a rather subtle one. I would certainly expect that Raymond's been bitten by this one. I would guess that every experienced Python programmers been bitten by some form of this one. > ACT II --------------------- > uniq = {} > for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0): > uniq(k) = 1 > print len(uniq) I had to experiment with this one. I guessed 3, which turned out to be right. I was a little surprised that 'ten' and u'ten' hash the same. However, after thinking about that, I decided I was happy with that result. I was more surprised that 10 and 10.0 came out the same. One of these days I'll take the time to look up the hash algorithm for floats to see how this was achieved. > ACT III --------------------- > s = 'abracadabra' > for i in [3, 2, 1, 0]: > print s[i:], s[-i:] Got this one the first time. -0 == 0, so s[-0:] == s[0:] == s. I'll bet that this is one that burned Raymond. > ACT IV --------------------- > pets = list('cat ') > pets += 'dog ' > pets.extend('fish ') > print pets + 'python' I guessed ['c', 'a', 't', ' ', 'd', 'o', 'g', ' ', 'f', 'i', 's', 'h', ' ', 'p', 'y', 't', 'h', 'o', 'n']. I tried it to discover that the print statement at the end throws. I decided that not concatenating strings to lists doesn't bother me since I would believe that this is an error more often than not and pets + list('python') would hopefully make the intent clear. On the other hand, if I saw pets = list('cat') in code I was reviewing I suspect that I would want to assure myself that ['c', 'a', 't'] was what was intended and not ['cat']. I also much bothered by pets += 'dog ' working but pets + 'python' not. What's the justification for the checking in one place and not the other? > INTERMISSION (with output included, oh yeah! ------------ > >>>>import operator >>>>1 - reduce(operator.add, [1e-7]* 10**7) > > 2.4983004554002264e-010 Round off error. Welcome to the world of floating point arithmetic! > ACT V --------------------- > class Bin: > numitems = 0 > contents = [] > > def add(self, item): > self.numitems += 1 > self.contents += [item] > > laundry = Bin() > groceries = Bin() > > laundry.add('shirt') > groceries.add('bananas') > groceries.add('nuts') > laundry.add('socks') > groceries.add('pretzels') > > print laundry.numitems, laundry.contents > print groceries.numitems, groceries.contents Learned something on this one. I caught that, as defined, numitems and contents are attributes of the class Bin, rather than instances of Bin. (The fix is to add the missing __init__ method.) I predicted that the result of both print statements would be: 5 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] When I tried it I got: 2 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] 3 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] After thinking about it (and reviewing the Reference Manual), I realized that self.contents += items does an in place update of Bin.contents, but the augmented assignment self.numitems += 1, is the same as self.numitems = self.numitems+1 (since there is no in place update for integers or immutable objects in general), which has the result of creating the attribute numitems on the laundry and groceries instances. > ACT VI ----------------------------------------- > print "What is the technical name for this algorithm or transformation?" > a = range(0, 100, 10) > import random > random.shuffle(a) > print "Input:", a > swaps = 0 > for i in range(len(a)): > for j in range(i+1, len(a)): > if a[i] > a[j]: > i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1 > print "Output:", a > print "Workload;", swaps I went through a number of different answers on this one. First, there was the indentation error at if a[i] > a[j]. I decided that was probably a typo on Raymond's part. The assignment i,j, ... = j,i, ... . Kept me guessing. Why do that? At first I though it had no effect. (Note: that the corresponding assignment in a C program which read: for(i = 0; i < len(a); i++) for(j = i+1; j < len(a); j++) ... would require a lot more thought as to the likely result. At this point I convinced myself that this was an interchange sort gone wrong and would just produce garbage. When I tried it, I discovered that the correct technical name for this program is the identity transformation. That is, nothing happened. Reexamining the code, I realized that flipping the two indices has the effect of assigning the two array elements back to themselves, resulting in no effect. About this point in time, I also realized that the sort should work if you take away the spurious assignments to i and j. That is, a[i], a[j], swaps = a[j], a[i], swaps will actually sort the list correctly. The correct technical name for this is "sort by successive minima". This is a slightly different sort from an interchange sort or a bubble sort, even though all three of these sorts are O(n**2). What's the real lesson here? I have two suggestions: 1. Watch out for side effects when doing compound assignments. 2. Never try to write your own sort when a.sort() is available. ---------------- OK, which three did Raymond personnally stumble over. I'll guess I, III, and VI. Why VI? Well, because V, while subtle in some ways, doesn't look to me like one you'd run into until you knew what you were doing, at which point: why this missing __init__ method. VI looks like something you might do by accident while trying to write a sort routine. Chris From mis6 at pitt.edu Thu Jul 31 12:00:10 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 31 Jul 2003 09:00:10 -0700 Subject: keystroke check References: Message-ID: <2259b0e2.0307310800.3310ec83@posting.google.com> Wes Fraser wrote in message news:... > Is there any way to check in a loop to see if at that > given moment in the program, a key on the key board is > being pressed without actually stopping like raw_ipnut > does? > > Thanks! > > Wes > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free, easy-to-use web site design software > http://sitebuilder.yahoo.com On Unix/Linux you could use curses: import curses def wait4q(stdscr): stdscr.addstr("Press 'q' to exit\n") while True: if stdscr.getch()==ord('q'): break if __name__=='__main__': curses.wrapper(wait4q) However, curses could be overkill and it is not portable to Windows, AFAIK. The curses how-to suggest the console module, http://effbot.org/zone/console-index.htm which runs on Windows only. HTH, Michele From martin at v.loewis.de Sun Jul 6 10:27:02 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Jul 2003 16:27:02 +0200 Subject: PEP idea. ( removing __slots__ ) References: <3f073594$1_2@news1.vip.uk.com> <3f083043$1_3@news1.vip.uk.com> Message-ID: simon place writes: > The point is to combine __dict__ and __slots__ into a new __attribs__, > the distinction being the type of __attribs__. If you don't specify > __attribs__ in the class you get the default __dict__ behavior, if you > do, and use a tuple, then you get the __slots__ behavior, and you can > easily tell which by checking the type, you could also iterate over > the attributes without caring which it was. So how is this different from the current situation? If you don't specify __slots__, you get the default __dict__ behaviour, if you do, and use a tuple, you get the __slots__ behaviour, and you can easily tell which by checking the type. You also have the case of both __slots__ and __dict__ being in a type, and this is a useful case also. Regards, Martin From ngps at netmemetic.com Sun Jul 6 22:11:47 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 7 Jul 2003 02:11:47 GMT Subject: M2Crypto: How to check server certificate? References: Message-ID: According to Hallvard B Furuseth : > Does anyone know how I check the server certificate with M2Crypto? > Currently a program I have inherited does this: > > #!/local/bin/python2.2 > import xmlrpclib > from M2Crypto.m2xmlrpclib import Server, SSL_Transport > svr = Server('http://my.machine.no:8000', > SSL_Transport(), encoding='iso8859-1') > # TODO: check server certificate > secret = svr.login('myuser', 'mypassword') Specify an SSL context: from M2Crypto import SSL from M2Crypto.m2xmlrpclib import Server, SSL_Transport # Server is Zope-2.6.1 on ZServerSSL/0.12. ctx = SSL.Context('sslv3') ctx.load_cert_chain('client.pem') ctx.load_verify_locations('ca.pem') ctx.set_verify(SSL.verify_peer, 10) zs = Server('https://127.0.0.1:9443/', SSL_Transport(ctx)) print zs.propertyMap() My to-be-released ZServerSSL 0.12 does client certs, too, including mapping from a subject DN to a Zope username. The above snippet was written to test that. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 24 17:53:50 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 24 Jul 2003 23:53:50 +0200 Subject: Needing help with sockets In-Reply-To: References: <3f1c4378$0$49110$e4fe514c@news.xs4all.nl> Message-ID: <3f20556d$0$49101$e4fe514c@news.xs4all.nl> Martin Dion wrote: > Thank you for your reply, but I have not been able to find good information > about the select module for a client. Do you know a good place to find > tutorials about select module for clients ? I'm not sure what you mean with 'select module for a client'... What do you need to know that is not in the module documentation or the Python socket howto? Anyway have a look at the following mini example that I whipped up: ------------- from select import select from socket import * import sys sock=socket(AF_INET, SOCK_STREAM) sock.connect( ('ftp.xs4all.nl', 21) ) # ftp port print '>', # prompt while 1: ins, outs, exs = select([sys.stdin, sock], [], []) if sys.stdin in ins: userline=sys.stdin.readline() sock.send(userline) print '>', if sock in ins: socketdata=sock.recv(1000) # buffer = 1000 if socketdata: print socketdata, else: break # no more data ------------- Does this help? If not, please describe in more detail what you want to achive, what you've already tried and why that didn't work. Good luck! --Irmen de Jong From martin at v.loewis.de Sat Jul 12 17:12:16 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 Jul 2003 23:12:16 +0200 Subject: anything like C++ references? In-Reply-To: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <3F1079B0.3010600@v.loewis.de> Tom Plunket wrote: > Is there any way to do references like this in Python? No. Martin From srijit at yahoo.com Mon Jul 28 03:45:04 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 28 Jul 2003 00:45:04 -0700 Subject: Python and VS.Net References: Message-ID: <221d8dbe.0307272345.63503afd@posting.google.com> Hello, After going through various threads and messages, blogs and some local discussions, I would like to share my impression. However, I do not have any hands on experience on VS.NET. 1) Both Java and .NET are going to stay and keep competing with each other for developers' mindshare. 2) At present Python 2.3 for Windows is based on VC6. This cannot continue for ever. I consider absence of compatability of Python with VC7/VS.NET as a major threat for Python's future. 3) Python and Java are already compatible with each other through Jython. Python is also extremely compatible with Windows (without .NET) thorough Mark Hammond's excellent library win32all. 4) Unfortunately, Microsoft's .NET does not appear to be friendly for dynamic languages like Python. .NET framework seems to favour statically typed languages. But I look forward to a solution. 5) Even now, it is not easy to convince management about Python's adavantages in corporate world. It will be come more difficult, in future, if Python.NET is not available. 6) Ruby users are also taking initiative to make Ruby work with .NET framework. Refer http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&frame=right&th=9fa784e70c5dc0cf&seekm=20030716140638.M85561%40deltadata.dk#link1 I am interested to learn what core python team is thinking about compatability of Python 2.x, 3.x with Windows/VC7/VS.NET. Regards, Srijit "Matt Gerrans" wrote in message news:... > "Trent Mick" wrote: > > > If your Python code could thereby access the .NET libraries, that would > be > > > another story. That would be like Jython for .NET. I was hoping that > was > > > what Active State's Python-in-VS.NET-thingy was, but alas it was too > good to > > > be true: it is only (so far) a color-syntaxing Python editor that takes > two > > > or three minutes to load up. > > > > You are mixing up two difference ideas. ActiveState's VisualPython is a > > plugin for VS.NET to provide all the IDE stuff (like editting, > > debugging, interactive shell, help, intellisense, etc) for Python > > programmers. > > Uh, isn't that pretty much what I said? I don't think I mixed up the > ideas. I only said that what ActiveState's Visual Python was and what I > was originally hoping it would be were not the same. > > > The idea of integrating the Python language somehow into the .NET > > framework is independent of VS.NET-the-IDE, though I suppose one might > > like some level of connection between the two. Mark Hammond, before and > > while at ActiveState did do some exploratory work in this direction. But > > that is all it has come to so far: exploration. So your "too good to be > > true" does (currently) apply to a so called Python.NET. This code is > > currently in PyWin32's CVS tree one SourceForge: > > http://sf.net/projects/pywin32 > > There is also the independent Kobra project that I have not looked at. > > Yes, I was aware of these, too. Despite Microsoft's claims about the .NET > platform being language-independent, it doesn't seem to be a simple task to > get Python going on it. So far, I think there are only VB.NET, C++, C# > and J#. No Python#, Perl# or Ruby#, as of yet... From theller at python.net Fri Jul 4 11:15:07 2003 From: theller at python.net (Thomas Heller) Date: Fri, 04 Jul 2003 17:15:07 +0200 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: Message-ID: "Simon Burton" writes: > On Fri, 04 Jul 2003 10:59:39 +0000, Francesco Bochicchio wrote: > > >> Did anybody ever attempted to do something like this? >> >> Ciao >> ----- >> FB > > yeah, > > http://arrowtheory.com/software/python/index.html > > it's hard :) > I have tried cdecl.py to parse windows header files, and it does a pretty good job. I say this after also having tried PLY http://systems.cs.uchicago.edu/ply/ with a partial C grammer, and finally gave up because I'm not sure it is possible to parse ANSI C with a parser like this (at least its not possible for me). I found one problem in cdecl.py (it doesn't parse hex constants correctly), and I had to extend it somewhat for MS specific keywords like __stdcall or so. I also ran the header files through the MSVC preprocessor, and hand-edit them somewhat before throwing them at it. I'm not really sure if it's a good idea to automatically create ctypes wrappers from windows.h... But I finally gave up when I encountered some really strange errors... Thomas From pyth at devel.trillke.net Wed Jul 2 09:43:33 2003 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 2 Jul 2003 15:43:33 +0200 Subject: Good code patterns in Python In-Reply-To: <6qllvh9oi3.fsf@salmakis.intevation.de>; from bh@intevation.de on Wed, Jul 02, 2003 at 01:06:28PM +0200 References: <3F0285F0.EDF697E3@alcyone.com> <6qllvh9oi3.fsf@salmakis.intevation.de> Message-ID: <20030702154333.D6906@prim.han.de> Bernhard Herzog wrote: > Erik Max Francis writes: > > > The > > complete solution to this would probably be a conditional expression, > > e.g.: > > > > variable = (if condition: someValue else: otherValue) > > > > eliminating the duplication which can lead to errors. (Python, of > > course, doesn't have such a construct, and the silence after the > > conditional expression PEP vote and the long silence thereafter suggests > > that it never will.) > > Guido broke his silence at EuroPython: The ternary operator will not be > added to Python. and there was great joy especially among the people who didn't find an easy way to vote "no" :-) Actually Guido made it pretty clear that he will be very careful about adding language features especially at the syntax level. Moreover, for Python-3 he plans to throw out some stuff like the string-module ... cheers, holger From jjl at pobox.com Sat Jul 26 19:34:07 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 00:34:07 +0100 Subject: path module References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <11234c14.0307251219.70e77a85@posting.google.com> Message-ID: <87brvgc174.fsf@pobox.com> holger krekel writes: > Jason Orendorff wrote: [...about passing path objects to library methods that expect a string...] > > This is a type rule. Such a thing has no place in Python. > > Oh, the stdlib has lots of places where it expects certain types in > certain places. Look for e.g. 'isinstance'. It's not even a strict type rule. It's just that a path object wouldn't implement the string interface. I don't know why that would have 'no place in Python', or be 'counterlogical'. John From ianb at colorstudy.com Fri Jul 25 18:55:32 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 17:55:32 -0500 Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: <1059173731.28095.11177.camel@lothlorien> On Fri, 2003-07-25 at 12:28, Paul Paterson wrote: > Thanks Terry! I adjusted my tests and now see this behaviour exactly. > The function itself works but the changes do not propogate out to the > calling scope. So this approach of using locals() appears to be dead. > > Are there any other approaches? Think about what you are trying to do, and try to identify a (mutable) object that can encapsulate that. Then pass the object, and modify its instance variables, like: class Point: def __init__(self, x, y): self.x = x self.y = y def change(p): p.y = 10 obj = Point(0, 0) change(obj) assert obj.y == 10 Maybe this mutable object will simply be the main application object, and instead of functions you will use methods of that application object. Ian From graham__fawcett at hotmail.com Thu Jul 10 14:10:55 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 10 Jul 2003 11:10:55 -0700 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: Without regard to the specifics of your question: if you haven't done so already, I'd recommend reading Eric Raymond's essay "The Magic Cauldron." Summary: "This paper analyzes the economics of open-source software. It includes some explosion of common myths about software production economics, a game-theoretical account of why open-source cooperation is stable, and a taxonomy of open-source business models." http://www.catb.org/~esr/writings/magic-cauldron/ -- Graham From jjl at pobox.com Sat Jul 19 09:53:30 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Jul 2003 14:53:30 +0100 Subject: feature request: a better str.endswith References: Message-ID: <87k7aer5b9.fsf@pobox.com> Bob Gailer writes: [...] > In APL one can specify indexes for the various dimensions of an > array. If B is a rank 2 array, B[1 2;3 4] retrieves columns 3 and 4 of > rows 1 and 2. WIBNI one could in a similar way drill into a nested > list. I know the various importable array modules do some of these > tings, but they are limited to homogeneous data. Numeric isn't, and I presume numarray isn't, either. typecode 'O' in Numeric, IIRC. John From hst at empolis.co.uk Thu Jul 17 03:43:20 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Thu, 17 Jul 2003 08:43:20 +0100 Subject: Confusing automated translators. Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB53BDFC@hendrix.empolisuk.com> Tim Roberts wrote > Jack Diederich wrote: > > > >My favorite example is comifying a list. > >"1, 2, and 3" vs "1, 2 and 3" (journalist seem to prefer the later) > > > >"I dedicate this book to my parents, Jane, and God." > >"I dedicate this book to my parents, Jane and God." > > This is actually something that is changing over time. It > used to be that > "no final comma" was a hard and fast rule, but many of the more recent > style guides now suggest the comma. > > My 7th grader's English textbook advocates the final comma, > and it led me > to get her into trouble in one assignment. > -- Ah, the "Oxford comma". See http://www.askoxford.com/asktheexperts/faq/aboutother/oxfordcomma for a bit more about it. _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From ebolonev at rol.ru Sun Jul 6 18:17:57 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Mon, 7 Jul 2003 09:17:57 +1100 Subject: Using Loops to track user input References: Message-ID: Hello, hokiegal99! You wrote on Sun, 06 Jul 2003 16:32:37 -0400: h> I don't understand how to use a loop to keep track of user input. Could h> someone show me how to do what the program below does with a loop? h> Thnaks! h> ---------------------------- h> #Write a program that reads 10 numbers from the user and prints out the h> sum of those numbers. h> num0 = input("Enter a number: ") h> num1 = input("Enter a number: ") h> num2 = input("Enter a number: ") h> num3 = input("Enter a number: ") h> num4 = input("Enter a number: ") h> num5 = input("Enter a number: ") h> num6 = input("Enter a number: ") h> num7 = input("Enter a number: ") h> num8 = input("Enter a number: ") h> num9 = input("Enter a number: ") h> num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9 h> print num h> ---------------------------------- =========Beginning of the citation============== num = 0 for i in xrange(10): num=num+input("Enter a number: ") print num =========The end of the citation================ With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From mcherm at mcherm.com Wed Jul 16 13:39:48 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 16 Jul 2003 10:39:48 -0700 Subject: anything like C++ references? Message-ID: <1058377188.3f158de4a3a51@mcherm.com> Adam Ruth writes: > I assume that you're referring to people 'faking' pointer in Python ( > such as wrapping variables in lists, etc.) I'd ammend your statement to > say: > > And the worst thing you can do is to obscure the issue even more by > disguising them as something else, WHEN YOU DON'T REALLY HAVE TO. > > In Python, there is no situation where "you really can't avoid pointers". > It's only when you program C or C++ in Python that you think you can't > avoid pointers. There are much better idioms to achieve the desired > results. Look, first of all, let me say that I disagree with Stephen Horne in this discussion. Or, to be more precise, I think that the approach he is using is not one which is useful in describing Python. HOWEVER, that doesn't mean that there's NOTHING to what he is saying, and your claim that there is no situation requiring "pointers" in Python seems wrong to me. Actually (to be quite pedantic) it is technically true. For instance, I could write a program in Python which simulated a turing machine, and then write the entire program to be executed on THAT. But this is a meaningless definition for "requiring" a feature -- by this definition NO feature is ever needed if the language is turing equivalent without it... for instance, Python doesn't ever need classes, modules, dictionarys, or functions (I'm pretty sure a turing machine could be written which didn't use any of these). What's more useful is to say that a feature is not "needed" if there's a straightforward alternate way to handle the situations where it would normally be used. For instance this (using C++ syntax for "references"): def returnsMultipleValues(x, &minusFive, ×Five): """Calculates x+5, x-5, and x*5.""" *minusFive = x - 5 *timesFive = x * 5 return x + 5 Is unnecessary, since this: def returnsMultipleValues(x): return x + 5, x - 5, x * 5 would work fine. However, there are some places where it IS useful to be able to modify a value within a routine. I have written code like this: i = [0] stuff.append( makeNewComplexObject(i, 'name', 'fred') ) stuff.append( makeNewComplexObject(i, 'age', 17) ) stuff.append( makeNewComplexObject(i, 'item') ) stuff.append( makeNewComplexObject(i, 'item') ) where the source for makeNewComplexObject() went like this: def makeNewComplexObject(iBox, objName, *objArgs): # increment i i = iBox[0] iBox[0] += 1 if objName == 'name': # some simple cases return new NameObject(*objArgs) elif objName == 'age': # some complex cases yrsOld = objArgs[0] if yrsOld >= 18: return new AdultAge(*objArgs) else: return new MinorAge(*objArgs) elif objName == 'item': # some cases that use i return new IndexedItem(i) Now, clearly, this code was inspired by C code which used an idiom like this: i = 0 stuff[i] = newComplexObject(i++, "name", "fred") stuff[i] = newComplexObject(i++, "age", 17) stuff[i] = newComplexObject(i++, "item") stuff[i] = newComplexObject(i++, "item") And certainly it *can* be rewritten in Python without "boxing" the variable i. However, it would also be nice to be ABLE to "box" the variable i. So it's not as if references would be USELESS in Python. I just think it'd be better handled differently (one-item list, or maybe a container class) rather than redefining assignment in Python as Stephen seems to prefer.[1] -- Michael Chermside [1] - Stephen doesn't want to change Python now for historical reasons. But my position is that if I were inventing a NEW language I'd do it Python's way by choice, because I think it's better. From newsgroups at jhrothjr.com Thu Jul 31 08:03:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 08:03:10 -0400 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: "Ben S" wrote in message news:bgaphh$lua$1 at news7.svr.pol.co.uk... > Steven Taschuk wrote: > > Quoth Kylotan: > > [...] > >> And does datetime.timetuple() actually return something equivalent to > >> a struct_time as used by the time module? At first glance this looks > >> to be true, but it isn't clearly documented as such. > > > > Isn't it? > > > > timetuple() > > Return a 9-element tuple of the form returned by > > time.localtime(). > > > > > > Problem is, time.localtime() doesn't return a 9-element tuple any more, > it returns a struct_time. (Since 2.2, I think.) Strictly speaking, that's true, but the object that's returned *acts* like a sequence of 9 integers if you reference it properly. It seems like 2.2 did this in a number of places, so that you could reference values by name. I like the thinking behind it. It's a lot better documentation if you want to get one value at a time. John Roth > > -- > Ben Sizer > http://pages.eidosnet.co.uk/kylotan > > From staschuk at telusplanet.net Fri Jul 25 17:32:48 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 25 Jul 2003 15:32:48 -0600 Subject: How safe is modifying locals()? In-Reply-To: ; from paulpaterson@users.sourceforge.net on Fri, Jul 25, 2003 at 04:10:09PM +0000 References: Message-ID: <20030725153248.B205@tibia.amotlpaa.bogus> Quoth Paul Paterson: [...] > Does anyone have any alternative strategies for trying to achieve the > objective? A "Pythonic" approach such as, > > def change(x, y): > x = x + 1 > y = y + 1 > return y > > x = 0; y = 0 > y = change(x, y) > > Works in a single threaded environment but, because the value of 'y' > changes at the wrong time, with multiple threads there is a possibility > that two users of 'y' could dissagree on its value. Even if the simple y = y + 1 could change the caller's binding, there would be a race condition -- you'll need a lock anyway. (I'd be a bit surprised if this were not so in VB as well. Are statements atomic in VB?) -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From ben at dadsetan.com Thu Jul 31 18:21:34 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Fri, 01 Aug 2003 00:21:34 +0200 Subject: Secure FTP in Python? In-Reply-To: References: Message-ID: d z e k y l wrote: > Hello, > > I'd like to write a small backup utility in Python, which would take > advantage of Secure FTP to upload backup archives. Is there a library > implementing SFTP in Python (something like ftplib)? Or is there some other > (noncomplicated) way how secure uploading can be implemented in Python? > > Thank you for advice, > Michal > > I just read a posting about a new library building a secure tunnel for whatever protocol you want. Or at least that is how I understood it without looking into it at all :) So try looking if you can not use stunnel at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213238 + ftplib Regards, Ben. From g2h5dqi002 at sneakemail.com Wed Jul 16 21:58:13 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 17 Jul 2003 13:58:13 +1200 Subject: Confusing automated translators. In-Reply-To: References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <3F12CE17.76A0A5@hotmail.com> <16146.53798.759651.430032@montanaro.dyndns.org> Message-ID: JanC wrote: > Francois Pinard schreef: > > >> "The firm driver is carrying her." > > > Which is a nice example of something that could be misunderstood in > English. ;-) > > (Is the driver strong or does he work for a firm?) Or should we be directing followups to soc.sexuality.general?-) From sdementen at hotmail.com Tue Jul 22 11:31:55 2003 From: sdementen at hotmail.com (Sebastien de Menten) Date: 22 Jul 2003 08:31:55 -0700 Subject: profile output for kcachegrind ? Message-ID: <8dad5312.0307220731.5ff69a91@posting.google.com> Hi, I am using the profile module to watch hot spots in a python application. The default output is already useful but has anyone tried to produce output readable by kcachegrind (http://kcachegrind.sourceforge.net/) ? seb From tim.one at comcast.net Tue Jul 15 11:18:49 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 15 Jul 2003 11:18:49 -0400 Subject: md5 consistent across platforms/Python versions? In-Reply-To: Message-ID: [Gary Robinson] > I know that hash functions are often platform-dependent for efficiency > reasons. From what I understand, this includes Python's hash(), which > I have read is not guaranteed to return the same result across > platforms or even across Python versions. Indeed, a Python hash is a (short) Python int, so is a 32-bit value on most current boxes, but a 64-bit value on most 64-bit boxes. > Can someone tell me whether an MD5 hash using Python's MD5 library IS > guaranteed to return the same results for the same input string, > across platforms and Python versions? Yes, it's the same, and the same as what you'll get from any other correct program for computing an MD5 digest from that string. The same is true of the longer SHA digests (also available from Python, via the sha module). > My limited understanding of how MD5 is normally used would seem to > indicate that this must be the case, but it would be helpful for me > to have confirmation, since my knowledge in this area is very limited. It's confirmed, and your knowledge is now closer to unlimited . From sandskyfly at hotmail.com Fri Jul 4 10:34:49 2003 From: sandskyfly at hotmail.com (Sandy Norton) Date: 4 Jul 2003 07:34:49 -0700 Subject: Some guidance please: A Python multitrack recorder? References: Message-ID: "Dfenestr8" wrote in message: > I'm no coder. I'm just a working guy who likes to tinker with computers in > my spare time. > > That's my hobby. My passion is: playing instruments. Combining the two, > I've made a couple of event driven, GUI controlled progs in Python and > tKinter before. I made an abc/midi player, using the timidity, and > abc2midi packages. I also did a metronome, using the Snack sound toolkit. If you like python and music you may be interested in these links: - http://csounds.com/ - http://www.csounds.com/stevenyi/blue/ - http://cnmat.cnmat.berkeley.edu/OSC/ - http://galatea.stetson.edu/cgi-bin/viewcvs.cgi/ProctoLogic/ - www.stetson.edu/departments/mathcs/students/research/ cs/cs498/2001/danny_clinton/final.pdf - http://seqdublin.sourceforge.net/ - http://lennart.regebro.nu/music/python-midi/ Have fun, Sandy From dale at riverhall.NOSPAM.co.uk Fri Jul 4 10:31:09 2003 From: dale at riverhall.NOSPAM.co.uk (Dale Strickland-Clak) Date: 04 Jul 2003 14:31:09 GMT Subject: Apache mod_python and Sessions References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> Message-ID: Markus Schaber pushed the bounds of literature with: > Hi, > > Does anybody know a module that works with Apache 1.3 mod_python and > provides session tracking? > > > Thanks, > Markus > This is pretty easy to do by hand using MD5 and a cookie. -- Dale Strickland-Clark Riverhall Systems Ltd, www.riverhall.co.uk From mis6 at pitt.edu Mon Jul 21 14:04:25 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 21 Jul 2003 11:04:25 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> Message-ID: <2259b0e2.0307211004.56aa9d0a@posting.google.com> chrisperkins37 at hotmail.com (Chris Perkins) wrote in message news:<45228044.0307210522.1ef95144 at posting.google.com>... > def the(pred,seq): return True in itertools.imap(pred,seq) BTW, this suggest to me two short idiomas for multiple "or" and multiple "and", with shortcut behavior: def imultior(pred,iterable): return True in itertools.imap(pred,iterable) def imultiand(pred,iterable): return not(False in itertools.imap(pred,iterable)) Nevertheless, they seem to be slower than the non-iterator-based implementation :-( (at least in some preliminary profiling I did using a list and a custom defined predicate function) def multiand(pred,iterable): istrue=True for item in iterable: istrue=istrue and pred(item) if not istrue: return False return True def multior(pred,iterable): istrue=False for item in iterable: istrue=istrue or pred(item) if istrue: return True return False M. From skip at pobox.com Tue Jul 22 09:00:17 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 22 Jul 2003 08:00:17 -0500 Subject: PEP 304, and alternative In-Reply-To: <2c60a528.0307220408.73c6e740@posting.google.com> References: <2c60a528.0307220408.73c6e740@posting.google.com> Message-ID: <16157.13665.457639.544695@montanaro.dyndns.org> Andrew> haven't seen much discussion on PEP 304 recently, what's its Andrew> current status? Same as before. Andrew> It's so broad-brush; PYTHONBYTECODEBASE can only really be set Andrew> per-user, and is likely to cause the same problems PYTHONPATH Andrew> did (before site-packages and .pth files made all that easier). Why is this a problem? It gives the user control over where .pyc files will be written. My initial intent was that if users set it at all, it would be set something like PYTHONBYTECODEBASE=$HOME/tmp/python or PYTHONBYTECODEBASE=/tmp/skip/python Andrew> The problems with user rights also look really horrid. Say Andrew> bytecodebase is /tmp/python/. All users must have write access Andrew> to /tmp/python/home, so they can store PYCs for PYs in their Andrew> home directory; however if user A hasn't yet run a PY from his Andrew> home directory, user B can create /tmp/python/home/A and put a Andrew> booby-trapped PYC in, that could be run when user A executes a Andrew> script of the same name from /home/A. This is (minimally) addressed in the Issues section: What if PYTHONBYTECODEBASE refers to a general directory (say, /tmp)? In this case, perhaps loading of a preexisting bytecode file should occur only if the file is owned by the current user or root. By "general directory" I mean writable by more than just root. Andrew> I'd instead like to do it by having a writable mapping in sys Andrew> somewhere which can hold a number of directory remappings. This Andrew> could then be written to on a site-level basis by Andrew> sitecustomize.py and/or a user or module-level basis by user Andrew> code. eg. Andrew> sys.bytecodebases= { Andrew> '/home/and/pylib/': '/home/and/pybin/', Andrew> '/www/htdocs/cgi-bin/': '/www/cgi-cache/' Andrew> } Andrew> and so on. How is this better? How does it address the security problem you raised above? Andrew> Also it avoids the problem of what to do on multi-root Andrew> filesystems like that of Windows, as only string matching is Andrew> required. Windows' multi-root filesystem is a known problem. I've not yet been able to solve it, though I must admit I haven't worked on it in awhile either. Skip From jsd at cluttered.com Thu Jul 3 18:12:46 2003 From: jsd at cluttered.com (Jon Drukman) Date: Thu, 03 Jul 2003 15:12:46 -0700 Subject: Please confirm your message In-Reply-To: <200307032202.h63M2fTx029756@c10-mail1.cnet.com> References: <200307032202.h63M2fTx029756@c10-mail1.cnet.com> Message-ID: <1057270366.14553.TMDA@w024.z064002058.sjc-ca.dsl.cnc.net> This message was created automatically by mail delivery software (TMDA). Your message attached below is being held because the address has not been verified. To release your message for delivery, please send an empty message to the following address, or use your mailer's "Reply" feature. jsd+confirm+1057270366.14553.83c6d0 at cluttered.com This confirmation verifies that your message is legitimate and not junk-mail. -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Movie Date: Thu, 3 Jul 2003 17:02:27 --0500 Size: 2636 URL: From cidolfas at rpgclassics.com Thu Jul 24 18:14:50 2003 From: cidolfas at rpgclassics.com (Daniel Orner) Date: 24 Jul 2003 15:14:50 -0700 Subject: CGI "download" prompt? Message-ID: <77dd287a.0307240632.40c6c309@posting.google.com> Hello, I'm trying to figure out something... I'm writing a Python CGI system that (in one aspect) acts as a file system interface by allowing the user to upload/download files. The uploading is fine, but I'm having problems with the downloading. I want to have a button that the user can click and which would then open a "Save File" dialog in the browser - effectively "serving up" a file for download. Unfortunately, the files that I'm trying to give the user are HTML files. How do I make it so the browser prompts to save the file rather than just display it in the browser? I specifically want the filename to remain the same, so renaming the file won't work. Can anybody give me an idea as to how to do this? Thanks very much! --Daniel Orner From jjl at pobox.com Wed Jul 30 14:31:54 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Jul 2003 19:31:54 +0100 Subject: Syntax: pointers versus value References: <3F27F673.3000801@mathstat.concordia.ca> Message-ID: <8765ljx3vp.fsf@pobox.com> Danny Castonguay writes: > Simple question but I can't find the answer. Using an example: [...] > object. How then, do I duplicate the two objects; ie make a copy of > the object that listA is pointing to and have listB point to that > object. [...] http://www.python.org/doc/FAQ.html#4.38 John From aahz at pythoncraft.com Fri Jul 11 21:37:14 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 21:37:14 -0400 Subject: The "intellectual property" misnomer References: Message-ID: In article , Ben Finney wrote: >On Fri, 11 Jul 2003 15:13:43 -0400, Guido van Rossum wrote: >> >> The PSF holds the intellectual property rights for Python > >Ugh. Please don't propagate this ridiculous, meaningless term. It's >used to refer to a wide range of greatly disparate legal concepts; to >use it as a single term implies that there's some unifying "intellectual >property" principle joining them together, which is a falsehood. What Guido probably should have said was something more like, "The PSF is the holding organization for intellectual property rights for Python." The point being that -- eventually, if not now (due to some current muddles) -- the PSF will hold any and all intellectual property rights relevant to Python. While you've got a valid point, it's unnecessarily clumsy to iterate over all the different forms of intellectual property every time you mention them. The idea is that the PSF functions in a manner similar to the FSF in protecting all the bits of Python from encroachment. We don't know -- and can't know -- all the aspects that will be comprised under that umbrella, as various corporate interests try to stretch the idea of intellectual property. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From nhodgson at bigpond.net.au Wed Jul 23 04:38:48 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 23 Jul 2003 08:38:48 GMT Subject: Python and VS.Net References: Message-ID: Matt Gerrans: > By the way, just because you compile something with the compiler that comes > with .NET doesn't mean it is managed code. You can produce managed code rather than x86 code by adding the /clr command line option. You may also have to fiddle some other options which are incompatible with /clr. Neil From alia_khouri at yahoo.com Tue Jul 8 10:22:56 2003 From: alia_khouri at yahoo.com (Alia Khouri) Date: 8 Jul 2003 07:22:56 -0700 Subject: anything new on the ternary operator? References: <3F09E4B4.FED89C06@alcyone.com>, <3F09252F.9B0F52BD@alcyone.com>, Message-ID: <40a939c9.0307080622.3118cfd7@posting.google.com> Moshe Zadka wrote in message > On Mon, 07 Jul 2003, Erik Max Francis wrote: > > > (And, to trump your next response, yes, I know you do not > > hail from Europe.) > > Ah? Of course I'm from Europe. > [The consensus in EP was that Israel was in Europe] Sorry, I am confused: isn't Israel in the Middle East? Alia From jjl at pobox.com Tue Jul 29 17:54:07 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 22:54:07 +0100 Subject: How to properly package/distribute a pure python module? References: <5ab0af73.0307281045.6cb13cfe@posting.google.com> Message-ID: <87ispl579c.fsf@pobox.com> MatthewS at HeyAnita.com (Matt Shomphe) writes: > Are there any guidelines for packaging a pure python module? > Specifically, say I have a set of 10 functions, all of varying > behaviors (no unifying theme to bind them together into clear > subsets), that I would like to make available to others. What is the > best structure for the distributed module? A single file called > "functions.py" that people can put in "site-packages"[1]? A If it's "the simplest thing that could possibly work" (TM), I'd say yes, do that. John From nicodemus at globalite.com.br Fri Jul 18 19:19:55 2003 From: nicodemus at globalite.com.br (Nicodemus) Date: Fri, 18 Jul 2003 20:19:55 -0300 Subject: Bug overriding operators in new-style classes? In-Reply-To: <20030717183133.D931@tibia.amotlpaa.bogus> References: <00cb01c34c96$736685d0$2700000a@esss.com.br> <20030717183133.D931@tibia.amotlpaa.bogus> Message-ID: <3F18809B.70706@globalite.com.br> Hi Steven, Steven Taschuk wrote: >Quoth Nicodemus: > > >>I found a surprising behavior regarding new-style classes operator lookup. >>It seems that for operators, the instance methods are ignored. Observe: >> >> > [...] > > >>Is this a bug, or am I missing something? Any help would be appreciated. >> >> > >Working as designed, I think [1], though I've never actually seen >it documented. As you have observed, invocation of a magic method >(such as __add__ or __len__) by way of a special notation (such as >+ or len()) ignores the instance dict. That is, > len(x) >is not equivalent to > x.__len__() >(which would find __len__ in the instance dict by normal attribute >access) but to > type(x).__len__(x) >(which obviously ignores the instance dict). > >[...] > >[1] One reason I think it's intended is that these protocols >specify a self argument; for new-style classes, this is provided >by the descriptor machinery, which by design works only when the >function is found in the class dict. > > Thanks for the clarification! Regards, Nicodemus. From jerf at jerf.org Wed Jul 30 23:42:50 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 31 Jul 2003 03:42:50 GMT Subject: mixin class References: <3F24F8D2.E1ADFB08@web.de> Message-ID: On Mon, 28 Jul 2003 12:20:02 +0200, Udo Gleich wrote: > My question: How do I implement mixin classes > with new style classes? Um, if I understand what you're trying to do correctly, it's easy: -------------- import random class A(object): pass class B(object): pass class C(object): pass class D(object): pass mixin = random.choice([C, D]) class A_B_and_C_or_D(A, B, mixin): pass newName = A_B_and_C_or_D newInstance = newName() ---------------- (Warning: Didn't actually type this in) The classes being derived from can be variable; in fact I do this rather too frequently for my own good, perhaps. (I tend to use it for class I want to be intimately involved with each other, but also usable separately, having one of them dynamically derive from either object or the other class, depending on whether the other class is available.) So in this example, on any given run, class A_B_and_C_or_D will always derive from A and B, and may derive from either of C or D. You can dynamically do this in a loop or something if you're feeling creative, if you assign the class to new names, as I did here for "newName". AFAIK there's no way to programmatically create new classes with generated names without resorting to eval (bad idea), but you can bind them to new names after creation and that works OK. ---------------- classesILike = {} for i in range(10): class tmp(object): pass classesILIke[i] = tmp ---------------- and of course "tmp" may derive from what it will. The inheritance list is as dynamic as anything else in Python; feel free to use it that way. Personally I find this is a "killer feature"... you'd find it hard to describe in advance when you'd want it, but when you want it, you want it ***badly***, because the kludge will be a killer... and there are very, very few languages that can do this cleanly (and still share Python's other benefits). From martin at v.loewis.de Mon Jul 21 18:38:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Jul 2003 00:38:25 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> Message-ID: Alan Kennedy writes: > I personally don't have the slightest problem with reformulating NNTP > and POP to use XML instead: In a way, I think it's almost inevitable, > given how poor our existing "ascii" technologies are at dealing with > i18n and l10n issues. Emails and usenet posts are all just documents > after all. > > Would something like this really be so offensive (the Gaelic isn't, I > promise :-)? Or inefficient? It would be pointless doing so. All the infrastructure needed to communicate different encodings in NNTP is already there - no need to change any protocol at all. The specification part has already been done. It is called MIME. What is lacking is the implementations. Just saying "Use XML then" won't magically make implementations appear. Regards, Martin From intentionally at blank.co.uk Wed Jul 16 16:07:30 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 21:07:30 +0100 Subject: anything like C++ references? References: <3F149C69.7B990210@alcyone.com> Message-ID: <32cbhvkife283kggrn8btlql91eaitmka2@4ax.com> On Tue, 15 Jul 2003 17:29:29 -0700, Erik Max Francis wrote: >Python does _not_ have copy semantics, it has binding semantics. As you know, that's precisely what I see as a wart. From cavada at irst.itc.it Wed Jul 23 07:46:24 2003 From: cavada at irst.itc.it (Roberto Cavada) Date: 23 Jul 2003 13:46:24 +0200 Subject: ANN: mvc 0.2.1 released Message-ID: <1058960784.4097.506.camel@stadio> A simple Model-View-Controller framework for pygtk2. Also, implements the Observer pattern. With respect to the previous version, this version provides: 1. Observable properties are simple python class' properties (via metaclasses) 2. Every class can be an Observer for a model 3. Up-to-date docs and a simple example The latest version can be found here: http://sra.itc.it/people/cavada/dload/mvc-0.2.1.tar.gz rob -- _/_/_/ _/_/_/ Roberto Cavada _/ _/ _/ ITC-irst http://www.irst.itc.it _/ _/ _/ Automated Reasoning Systems - Formal Methods Group /_/_/ _/ Via Sommarive, 18 - 38050 Povo (TN) - Italy _/ _/ Tel: +39 0461 314 328 Fax: +39 0461 302 040 _/ _/_/ cavada#irst.itc.it http://sra.itc.it/people/cavada From mlh at furu.idi.ntnu.no Fri Jul 11 06:19:38 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 11 Jul 2003 10:19:38 +0000 (UTC) Subject: mx.DateTime.Parser.DateFromString('crap') References: Message-ID: In article , Koczian wrote: [snip] >Working on Windows I haven't got strptime. But you can still get it... http://py.vaults.ca/apyllo.py?find=strptime -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From buzzard at urubu.freeserve.co.uk Tue Jul 15 15:57:12 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 15 Jul 2003 20:57:12 +0100 Subject: bug in my code? References: Message-ID: "Terry Reedy" wrote in message news:ua-dnfQZuo4_946iXTWJkw at comcast.com... > > "Duncan Smith" wrote in message > news:bevl84$880$1 at news7.svr.pol.co.uk... > > Greetings. I am struggling to track down what I presume is a bug in > my > > code. The trouble is that it only raises its head occasionally. I > have > > managed to prune the code to the following: > > > > shutTest.py > > -------------------------------------------------------- > > import cPickle > > > > def test2(iterations): > > for i in range(iterations): > > try: > > f = file('C:\\Python22\\(2, 2, 2, 3, 4).shu', 'r') > > try: > > dependencies, nodes = cPickle.load(f) > > finally: > > f.close() > > except IOError: > > pass > > ---------------------------------------------------------------- > > > > Calling the function with a suitable argument (say, 100) doesn't > usually > > pose a problem. The file is opened OK and the data unpickled. But > > occasionally (or usually if I call the function with 1000 as > argument) I get > > the all too common, on Windows, > > > > 'The instruction at {some memory address} referenced memory at {some > other > > (and on one occasion the same) memory address}. The memory could > not be > > "read".' > ... > This sounds like maybe a hardware problem. > Yes. I can't see any problems with the code (although it wouldn't be the first time ...). I can't reproduce the problem on my work machine. > Is the unpickling necessary to get the error? -- or some discrepancy? > It seems so. > If you simply reread the file over and over, do you always get > *exactly* the same byte string? Test this by reading once before the > loop and comparing subsequent reads to first. Yes I do. I haven't been able to reproduce the problem (ie. the crashes, I fixed the file) by just opening / reading / closing the file. What I asking is > whether you might have flacky or overheated disk drive giving > intermittant errors more often than once a terabyte. > Possibly. Thanks Terry. Duncan From theller at python.net Fri Jul 4 08:58:58 2003 From: theller at python.net (Thomas Heller) Date: Fri, 04 Jul 2003 14:58:58 +0200 Subject: exit endless python loop in emacs References: Message-ID: <1xx6h2i5.fsf@python.net> "Leo" writes: > hi all > > how can i terminate/stop an endless python loop which i have started inside > emacs with C-c C-c. > > ta, leo C-g Thomas From intentionally at blank.co.uk Wed Jul 16 17:40:23 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Wed, 16 Jul 2003 22:40:23 +0100 Subject: anything like C++ references? References: <1058377188.3f158de4a3a51@mcherm.com> <3F15A96C.D557570C@alcyone.com> Message-ID: On Wed, 16 Jul 2003 12:37:16 -0700, Erik Max Francis wrote: >Assignments are definitely not sequence points. But function calls are. >So the code is well-defined, and is equivalent to > > = newComplexObject(i++, "name", "fred"); > stuff[i] = ; Ah - interesting. From alanmk at hotmail.com Mon Jul 21 05:51:32 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 21 Jul 2003 10:51:32 +0100 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> Message-ID: <3F1BB7A3.D4223855@hotmail.com> I don't want to go on and on about this, and I'm happy to concede that some of my points are far from proven, and others are disproven. However, there are one or two small points I'd like to make. Ben Finney wrote: >>> Which quickly leads to "You must use $BROWSER to view this site". >>> No thanks. Alan Kennedy wrote: >> No, that's the precise opposite of the point I was making. Ben Finney wrote: > You also stipulated "... from a Usenet post". Most Usenet readers > do not handle markup, nor should they. There are many benefits from > the fact that posts are plain text, readable by any software that can > handle character streams; 1. While there may be benefits from posts being plain text, there are also costs. The cost is a "semantic disconnect", where related concepts are not searchable, linkable or matchable, because their character representations are not comparable. 2. I chose the "from a usenet post" restriction precisely because of the 7-bit issue, because I knew that 8-bit character sets would break in some places. It was an obstacle course. > parsing a markup tree for an article is a whole order > of complexity that I'd rather not have in my newsreader. > > Expecting people to use a news reader that attempts to parse markup > and render the result, is like expecting people to use an email reader > that attempts to parse markup and render ther result. Don't. I don't expect people's newsreaders or email clients to start parsing embedded XML (I nearly barfed when I saw Microsoft's "XML Data Islands" for the first time). What I'm really concerned about is the cultural impact. I voluntarily maintain a web site for an organisation that has members in 26 countries, who not surprisingly have lots of non-ASCII characters in their names. Here's one: http://www.paratuberculosis.org/members/pavlik.htm Because of the ASCII restriction in URLs, I was only able to offer Dr. Pavl?k the above uri, or this: http://www.paratuberculosis.org/members/pavl%EDk.htm which sucks. Little wonder then that the next generation are choosing to explicitly remove the accents from their names, i.e. his colleague Dr. Machackova explicitly asked to have the accents in her name removed. Although I assured her that her name would be correctly spelled, on web sites that I maintain, the fact that her name breaks continually with various ASCII centric technologies makes her think it's not worth the hassle, or worth the risk of searches for her name failing. http://www.paratuberculosis.org/members/machackova.htm And what about Dr. Sigur?ard?ttir, Dr. Dj?nne, and Dr. de la Cruz Dom?nguez Punaro? Are they destined to be passed over more often than ASCII-named people? [BTW, I've written the above in "windows-1252", apologies if it gets mangled] Solely because of technical inertia, and unwillingness to address the (perhaps excessive) complexity of our various communications layers, i.e. our own "Tower of 7-bit Babel", we're suppressing cultural diversity, for no technically valid reason. I personally don't have the slightest problem with reformulating NNTP and POP to use XML instead: In a way, I think it's almost inevitable, given how poor our existing "ascii" technologies are at dealing with i18n and l10n issues. Emails and usenet posts are all just documents after all. Would something like this really be so offensive (the Gaelic isn't, I promise :-)? Or inefficient? #begin--------- An mhaith l'?inne dul go dt? an nGaillimh D? Domhnaigh? al?in ? cinn?ide na cail?n? agus na buachaill? #end----------- -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From duncan at NOSPAMrcp.co.uk Thu Jul 3 11:07:22 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 3 Jul 2003 15:07:22 +0000 (UTC) Subject: Python - get key pressing ? References: <3F043A1F.81E6CA6@engcorp.com> Message-ID: Peter Hansen wrote in news:3F043A1F.81E6CA6 at engcorp.com: > Krisztian Kepes wrote: >> >> I want to create an py program what process datas for long time. >> But: I want to abort it if I need. >> Not with Ctrl+Break ! > > Why not? Ctrl+Break, or more typically Ctrl-C, is the de facto > standard approach for terminating a console (non-GUI) application. > >> If I push a key (B, or other), the script must stop his work, and >> save the result created before. > > In this case, just wrap the code with a "try/except KeyboardInterrupt" > and put your "stop and save" code in the except block. (Note that > Ctrl-Break will bypass this, but Ctrl-C is caught as you would > expect.) Assuming we are talking about the Windows platform here. If you want to catch Ctrl-Break as well (and have a resonably recent version of Python), you just need to do this: import signal signal.signal(signal.SIGBREAK, signal.default_int_handler) and now pressing Ctrl-Break throws KeyboardInterrupt (in your application's main thread only). Of course the problem with handling the KeyboardInterrupt exception is that your data might not be in a suitable state for saving when the exception is thrown. Also (at least on Windows) it doesn't interrupt a socket call, so if you are using sockets you have to wait for a timeout. What I prefer to do is to start the main processing in a background, daemon thread. The main thread then just waits (by calling sleep for a short time) for the KeyboardInterrupt. When the interrupt is raised you can then try to communicate with the background thread in a more orderly fashion, either by sending it a message or by using a Lock() around access to the data you want to save. Here's an example of what I mean. The code below runs an XMLRPC server under windows but control break allows the system to shut down properly, closing files etc. This code didn't have locking around the XMLRPC requests, it should have because then the main thread could make sure it didn't shut down mid request, but it wasn't a big issue here. def RunXMLRPCServer(): """Run the XMLRPCServer, but do so in a different thread. The main thread simply sleeps so that it can respond to Ctrl+Break """ def XMLRPCThread(): server = SimpleXMLRPCServer.SimpleXMLRPCServer(('127.0.0.1', 8888)) server.register_instance(MyXMLServer()) server.serve_forever() import threading th = threading.Thread(target=XMLRPCThread) th.setDaemon(1) th.start() # Make ctrl+break raise a KeyboardInterrupt exception. signal.signal(signal.SIGBREAK, signal.default_int_handler) try: while 1: time.sleep(0.1) except KeyboardInterrupt: log.info("Break pressed.") -- 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 rimbalaya at yahoo.com Mon Jul 28 11:08:19 2003 From: rimbalaya at yahoo.com (Rim) Date: 28 Jul 2003 08:08:19 -0700 Subject: using extended built-in types References: <6f03c4a5.0306291248.325e5ecc@posting.google.com> Message-ID: <6f03c4a5.0307280708.28e5e8c8@posting.google.com> > If only ;) > > If your tolerance for evil is sufficiently high, you could use intrinisics, > a hack by Jp Calderone... > > PyCon lightning talk: > http://www.intarweb.us:8080/PyCon/intrinsics-lightning-0.xhtml > > Source: > http://www.intarweb.us:8080/evil/intrinsics.c The links do not work. Thanks, -Rim From gumuz at looze.net Wed Jul 9 04:14:24 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 9 Jul 2003 10:14:24 +0200 Subject: slightly off-topic Message-ID: <3f0bce25$0$13804$4d4ebb8e@news.nl.uu.net> as I recently found 'ctypes' I am looking for some cool dll's to wrap with ctypes. I am specifically keen on finding video/audio libraries, but a link to a website with a collection of all kinds of libraries would be even better. regards, guyon From mis6 at pitt.edu Tue Jul 29 10:00:36 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 07:00:36 -0700 Subject: pretty printing graphs References: Message-ID: <2259b0e2.0307290600.2c2a14e1@posting.google.com> Here is an enhanced version that also draws the metaclass instantiation relationship: import os def label(i,n): if n>1: return '[label="%s"]' % (i+1) return "" def dotMRO(cls): "Generate the dot code for the MRO directed graph" yield "digraph MRO_of_%s{\n" % cls.__name__ for c in cls.__mro__: n=len(c.__bases__) yield ' '.join([ ' edge [style=solid]; %s -> %s %s;' % (b.__name__,c.__name__,label(i,n)) for i,b in enumerate(c.__bases__)]) if type(c) is not type: yield \ ' edge [style=dashed]; %s -> %s;' % (type(c).__name__,c.__name__) yield '}' class M(type): pass O=object class F(O): pass class E(O): pass class D(O): pass class G(O): __metaclass__=M class C(F,D,G): pass class B(E,D): pass class A(B,C): pass dotcode='\n'.join(dotMRO(A)); print dotcode os.system('echo "%s" | dot -Tps > prova.ps' % dotcode) os.system('gv prova.ps&') See the graph at http://www.phyast.pitt.edu/~micheles/prova.ps Here I had a problem due to my lack of knowledge of "dot": class C inherits from F,D and G (in this order, see the labels 1,2,3). However, "dot" draws D before F and, without looking at the labels, one would think that D comes before F, which is not the case. IOW, the line FC should cross the line DC, and the F-arrow should be on the left of the D-arrow. Is there any way of fixing that? TIA, Michele From vze4rx4y at verizon.net Sat Jul 12 00:29:04 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 12 Jul 2003 04:29:04 GMT Subject: The "intellectual property" misnomer References: Message-ID: > >> If the PSF holds the copyright to Python, please say that. > >> If the PSF holds patents which cover Python, please say that. > >> If the PSF owns the trademark for Python, please say that. > >> If the PSF has trade secrets in Python, please say that. > > > > So you somehow managed to divine Guido's intent from that "ridiculous, > > meaningless term" > > No, I requested that the term be clarified, because *I don't* know what > is meant by "The PSF holds the intellectual property rights for Python". > It's a meaningless statement as it stands. PSF is the copyright holder and issuer of the python license to the code covered by that copyright. Type license() at the command prompt to see the elaboration using terms that *do* have meaning to the legal types who helped craft and vette the wording. In layman's terms, it means exactly what Guido said. Hope this helps, Raymond Hettinger From pyth at devel.trillke.net Tue Jul 8 05:32:19 2003 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 8 Jul 2003 11:32:19 +0200 Subject: path module In-Reply-To: <1057651068.5348.386.camel@lothlorien>; from ianb@colorstudy.com on Tue, Jul 08, 2003 at 02:57:49AM -0500 References: <1057651068.5348.386.camel@lothlorien> Message-ID: <20030708113219.H6906@prim.han.de> Ian Bicking wrote: > I think Jason Orendorff's path module is really nice: > http://www.jorendorff.com/articles/python/path/ Yes, looks nice. > Beats the hell out of os.path, which is an ugly thing indeed. The OO > interface means you could use the interface nicely to implement other > things, like URLs. The problem? It's just some module. The various os > functions (of which path replaces quite a few) have become idiomatic to > me, and I'm sure others as well. I find myself reluctant to use it in > code that's not essentially private, because it's changing something > small and seemingly trivial, and people won't be familiar with it. > > The solution? It should be a builtin! Or, if not a builtin, included > in the os module. But I actually like the idea of it being a builtin -- > if open is a builtin, path stands right up there too. It would get rid > of 90% of the use of the os module. > > Thoughts? Reactions? I agree that something like Jason Orendorff's path module should go into the standard library. I've coded a similar module and i think that a discussion about certain design decisions would probably improve our approaches. For example Jason lets the "path" object inherit from "str" (or unicode) but i think it's better to provide a "__str__" method so that you can say str(pathinstance).endswith('.py') and *not* base the path object on str/unicode. unicode(pathinstance) would just fail if your platform doesn't support this. First, i tried the inheritance approach, btw, but it is ambigous (e.g. for the join-method (str.join and os.path.join). Also, my module provides most of the os.path.* methods as "filters" so you can say dirs = filter(isdir, list_obj_pathobjects) fnames = filter(AND(nolink, isfile), list_obj_pathobjects) in addition to pathobject.isfile() etc. Recently, i also did some experimentation with "virtual-fs" features so that you can transparently access http/ftp/svn files/directories. I even got that to work with "-completion" but that was quite a hack :-) I am pretty sure that virtual-fs-like-extensibility would be a big "selling" point and would motivate the use of such a module and finally the inclusion into the stdlib. Of course, the local-fs should be the convenient case but it shouldn't be hard to use the same methods for accessing remote "repositories". Anyway, i am all for going in this direction and would probably like to participate in such a development and design effort. cheers, holger From alanmk at hotmail.com Tue Jul 22 06:25:58 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 22 Jul 2003 11:25:58 +0100 Subject: good python book References: <3f1cbbda_6@news.athenanews.com> Message-ID: <3F1D1136.AFB8CFA9@hotmail.com> anonymous at coolgroups.com wrote: > i'm looking to start learning python. could someone > recommend a good beginner's book for me? Plenty of useful and free introductory material here:- http://www.python.org/doc/Newbies.html And not a flattened dead tree in sight. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bokr at oz.net Tue Jul 29 15:22:50 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 19:22:50 GMT Subject: variable assignment in "while" loop References: Message-ID: On 29 Jul 2003 12:08:50 GMT, Sybren Stuvel wrote: >Hi there, > >Is it possible to use an assignment in a while-loop? I'd like to do >something like "loop while there is still something to be read, and if >there is, put it in this variable". I've been a C programmer since I >was 14, so a construct like: > >while info = mydbcursor.fetchone(): > print "Information: "+str(info) > >comes to mind. Unfortunately, this doesn't work. Is there a similar >construct in python? > I thought of a little variation on the list comprehension hack that is usually advised against: while [info for info in [mydbcursor.fetchone()] if info]: print "Information: %s" % info I sort of like the mnemonic of the if info that makes the while see [] at the end rather than e.g. [None][0] Regards, Bengt Richter From timr at probo.com Sun Jul 13 00:55:39 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 12 Jul 2003 21:55:39 -0700 Subject: wxPython - question References: Message-ID: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> "Artur M. Piwko" wrote: >How can I remove program entry from taskbar (not tray)? PLEASE resist the temptation to built Yet Another Tray Application. Win32 programmers seem to use the tray icons as a sign of their guruness, and every one of them seems to think that his application is so studly that it must occupy permanent real estate on my desktop. I've seen some trays that bloat to 20 or 30 icons. Don't do it. Your application just isn't that important. If you need to notify me of something, I find nothing wrong with a good old-fashioned dialog box. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From peter at engcorp.com Tue Jul 29 07:24:47 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 29 Jul 2003 07:24:47 -0400 Subject: How to detect typos in Python programs References: <3F214977.AEB088C8@engcorp.com> <877k64c0qo.fsf@pobox.com> Message-ID: <3F26597F.9B589160@engcorp.com> Manish Jethani wrote: > > There's a difference between my "abost()" example and the "56" > example. There's no function called abost anywhere in the > program text, so I should be able to detect the error with > static analysis. Even in C, the compiler warns about stray > function calls. You don't understand the dynamic nature of Python if you think this is something that is either easy or 100% reliable. Very contrived but instructive example: def func(x): pass import sys setattr(sys, 'ab' + 'ost', func) stick-that-in-your-static-analyzer-and-smoke-it-ly y'rs -Peter From ianb at colorstudy.com Thu Jul 17 23:18:30 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Jul 2003 22:18:30 -0500 Subject: list() coercion In-Reply-To: References: Message-ID: <1058498310.11511.1308.camel@lothlorien> On Thu, 2003-07-17 at 10:08, Raymond Hettinger wrote: > Instead of: > > list(yourobj) > > use: > > list(iter(yourobj)) Sigh... that's too bad. I'll probably just get rid of the __len__ method instead, as list(yourobj) (list(myobj)?) is a more appealing idiom than len(somebodysobj). Ian From ulope at gmx.de Fri Jul 18 21:31:24 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sat, 19 Jul 2003 03:31:24 +0200 Subject: Calling python from asp References: <3f17dc2c@cpns1.saic.com> Message-ID: "BDM" schrieb im Newsbeitrag news:3f17dc2c at cpns1.saic.com... > Greetings, > I'm having a difficult time calling a python module from within ASP. I have > narrowed the problem down the very beginning of my code, where I'm > attempting to import a method. Below is a snippet of the code > > import sys > print 'Imported Sys' > from pscape.xml.handler import pscape_xml_parser > print 'Imported XML Parser' > > The import sys statement works fine. The import of pscape_xml_parser is > failing. pscape.xml.handler is within my site-packages directory. I have > checked python's sys.path from within ASP, and > c:\python22\lib\site-packages is in the path. This code runs fine when > executed from within the python interpreter, but not when called from ASP. > > Any idea what I'm doing wrong here? I'm sure it must be something very > simple. I'm running this under Windows2000 Server, IIS5.0, Python 2.2.2, > and win32all-150. perhaps the webservers user (Normaly IUSR_......) has no rights to access the files within site-packages? Ciao Ulrich From aahz at pythoncraft.com Sun Jul 6 20:20:54 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2003 20:20:54 -0400 Subject: Newbie Question: Abstract Class in Python References: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Message-ID: In article <5U2Oa.239646$jp.6482027 at twister.southeast.rr.com>, Kevin Bass wrote: > >I am new to Python and want to know how to implement an abstract >class? I have read through different books and I have no found this >information. Thanks! Simple answer: you don't. Python doesn't really have that concept. If you tell us what you're trying to do, we can explain how to do that in Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From pyth at devel.trillke.net Sat Jul 26 03:49:09 2003 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 26 Jul 2003 09:49:09 +0200 Subject: path module In-Reply-To: ; from news@exultants.org on Sat, Jul 26, 2003 at 01:10:11AM +0000 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> Message-ID: <20030726094909.S6906@prim.han.de> Van Gale wrote: > holger krekel wrote: > > Yes, i think adding platform specific methods to a Path object makes sense. > > A friend and me started working on (local and subversion) Path > > implementations last week. > > ... > > Interesting, I started a project modifying Jason's Path module to work > on subversion trees as well. I didn't get too far before putting the > project on a back-burner so I'm glad to hear someone else is thinking > the same way :) It's even working although i am not sure we stay with the subversion-python bindings as they are fragile and incomplete at places. We might switch to using the commandline "svn" utility for the time beeing. > My extensions to Path included an additional argument to "open" that > included a version number, and a mechanism for retrieving some kind of > "metadata" associated with the file. We instantiate the Path like so path = SvnPath('http://codespeak.net/svn/vpath/trunk/dist', rev=X) where X is either -1 (default) meaning it should grab the latest revision or some positive revision number. When you 'visit' or 'listdir' or 'open' on that 'path' you stay in the same revision and thus get a consistent view. this is obviously a nice property. Btw, via the above URL you'll get our current implementation with lots of unittests. You currently need subversion-python-bindings which are not exactly easy to get going unless you already have a server-side install. > I also made another Path module that implements a "poor mans cms" if > subversion/rcs/cvs are not available. It uses hidden files with version > numbers in the filename to emulate a real version control system. I thought about this too. Right now we just want to make it easy and complete enough. cheers, holger From gumuz*NOSP at M*looze.net Wed Jul 16 18:18:46 2003 From: gumuz*NOSP at M*looze.net (Guyon Morée) Date: Thu, 17 Jul 2003 00:18:46 +0200 Subject: IMAP examples Message-ID: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> I can't seem to find any decent examples on how to use the IMPALIB module. the docs aren't that sophisticated unfortunately.... the cookbook entry comes close, but i'd like to know if someone knows some nice examples somewhere. thanx guyon From intentionally at blank.co.uk Sun Jul 13 22:24:28 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Mon, 14 Jul 2003 03:24:28 +0100 Subject: Qualified appology (was Re: anything like C++ references?) References: Message-ID: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Appols for changing the subject while still staying in the same topic - I just wanted to highlight this over my earlier boneheaded posts. This is a post of heavily qualified appologies. In summary, I've been thick-headed but I still believe that Python is doing the wrong thing. I hope I've actually achieved a degree of sanity on this attempt ;-) On 14 Jul 2003 00:17:19 +0200, martin at v.loewis.de (Martin v. L?wis) wrote: >Stephen Horne writes: > >> 1. Why are dictionarys called dictionaries (rather than references to >> dictionarys or whatever)? Similar for lists and class instances. > >Because they are the values themselves, instead of being references to >values. These values (like all other values) are objects, though, >which means they have identity, state, and behaviour. I've said my piece on meanings derived from computer science (and in turn from mathematics, as it happens - variables as placeholders for values predate electronic computers by quite some time. People have tried to point out that copy-on-write is redundant for immutable objects, but I've been too thick-headed. Sorry for that. Even so, you can think of immutable objects as achieving 'expected' assignment semantics simply because they are immutable. That does not apply to mutable objects. So you can claim that Python behaviour is consistent within itself, but only by claiming that it is consistently different from this 'expected' behaviour. Some people have already said that the word 'expected' is a fallacy - that computer science doesn't have fixed definitions for these things. Some have already named various languages which deviate in similar ways in either some or all cases. But these languages are actually deviating, either by convention or (in older cases) due to the limitations of past machines. That's not the same thing as saying they are doing 'the right thing' or that the computer science definitions don't exist - all it means is that a lot of programmers who are experienced in certain languages are familiar with this error-prone system and used to compensating for its problems. But a modern high-level language should do 'the right thing' - it should not be the programmers job to make allowances for an outdated workaround designed to give maximum performance by default on old machines irrespective of reliability. >> 2. Why are the values of mutable objects always forced to be accessed >> via a pointer (or reference or whatever)? > >Because all variables are references to objects. All variables are implemented as references, but that is not the same as saying that all values are references. As Guidos own words reveal (I already posted the link twice) the purpose of using immutables tuples is performance optimisation to save copying while still defending against against accidental mutation (ie it provides the computer theory standard assignment semantics efficiently). The same rationale should equally apply to all types, including the mutable types. In particular, it should apply to class instances. I shouldn't need to create separate mutable and immutable variants of classes to get this as the mutability of content should be the decision of the container rather than the content. I shouldn't need to force copying of class instances in the container for the exact same reason that Guido highlights for tuples. Guidos own example is actually quite bug prone in its own way. It behaves differently depending on whether you pass in the point values as tuples or lists. That is potentially a subtle, intermittent, hard-to-trace error waiting to happen. You can say 'validation' all you want. I did that back in the PEP238 days, and didn't get much support. What's good for the goose is good for the gander. >> This excuse is, as I already said, invalid. > >Which excuse? You have only listed questions in this message, not >excuses. Looking back, I was unfair to Tim Peters. The 'excuse' was percieved (mainly because I'm frustrated trying to get my point across, and because a circularity that arose (unless I was thick-headed about that too) in another post. I said 'if a then b', someone said 'no - a is wrong because c', I said 'ah, but if c then d' and the reply to that was 'no - c is wrong because a' - or at least I think that's what happened. Possibly I just need some sleep. I thought Tim was also guilty of this, but looking back I was wrong. Sorry, Tim. However, revisiting his post I still disagree with it... """ It's deliberate and thoroughly consistent. Any assignment semantics are error-prone in some contexts, though (Python's included -- side effects are like that). The simplicity and absolute consistency of Python-style assignment semantics are probably easiest for first-time programmers to pick up, and certainly dead easy for people coming from Lisp (etc) to pick up -- people coming from C (etc) often struggle with inappropriate expectations at first. """ At first glance it looked like Tim was saying 'its all assignment semantics rather than type semantics', hence my misjudging him. But one way or the other, there is an inconsistency between the behaviour of mutable objects and the computer science definitions of 'variable', 'value' and 'assignment' which does not arise for immutable objects (note careful wording - see earlier apology). Having copy-on-write for all objects (obviously the actual copying never happening for immutables) would be both fully self-consistent and consistent with the computer science definitions. The lack of this definitely does cause both confusion and errors. I also disagree with Tims statement that "Any assignment semantics are error-prone in some contexts". OK, mistakes can be made with any syntax for anything, but in the context of this discussion it is perfectly possible to get the best of both worlds. Make pointers/references explicit and make all assignments 'copy-on-write', and as I said earlier you get both mutability protection by default for all types and the ability to reference any type indirectly. Avoid the problems that make pointers in C, C++, Pascal etc so unreliable and, while perceptions of pointers as being inherently bug prone may persist they would be irrational - having pointers explicitly for all types would at worst be as bug prone as the existing situation where implicit references exist, and in particular where mutable types get abused to fake pointer/reference capabilities. It needs extra notation, but when mutables are used to fake pointers there is extra notation anyway - misleading notation. I'm not an anti-side-effect fanatic. I just don't want them to happen by default, and I don't have to worry about this every time I use a mutable type. And there really is no need for that to happen. From m at moshez.org Mon Jul 7 13:53:15 2003 From: m at moshez.org (Moshe Zadka) Date: 7 Jul 2003 17:53:15 -0000 Subject: anything new on the ternary operator? In-Reply-To: References: , <3F09252F.9B0F52BD@alcyone.com>, Message-ID: <20030707175315.31444.qmail@green.zadka.com> [Moshe Zadka] |I'm sorry, I was going to let this slide by, but this comment made it |impossible. How the hell do you figure EuroPython, the biggest Python |conference in Europe and largely equivalent to the size of PyCon, is a |"local" conference? [Lulu of the Lotus-Eaters] > Yeah, but Donald Rumsfeld has let us 'merkins know that Old Europe is > now irrelevant. What could be more clear? Well, to be quite honest, there were some "New Europe" attendees. The most excellent Lithuanians, and yours truly. -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From alanmk at hotmail.com Tue Jul 15 12:22:48 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 15 Jul 2003 17:22:48 +0100 Subject: [OT] sentances with two meanings References: Message-ID: <3F142A58.80426AA4@hotmail.com> Syver Enstad wrote: > > Given the biblical meaning of "known", this could have even more than > > two meanings :-) > > Does "to know" in english also mean to feel someone? In my own language > the direct translation of the english know also means to feel. I could > say (translated) "I know the cold", meaning I feel the cold > weather. To "know" someone, in the biblical sense, is to have "carnal knowledge" of them, i.e. "knowledge of the flesh", i.e. to have had sexual relations with them. Some of the English translations of the bible use terms such as "And Adam knew Eve, and Eve begat 2 children", etc, etc. These translations are probably from the middle ages, or earlier. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From http Mon Jul 28 04:04:30 2003 From: http (Paul Rubin) Date: 28 Jul 2003 01:04:30 -0700 Subject: Checking whether bool is a type References: <3F2442B2.E660E97@jandecaluwe.com> <2e5a8637.0307272216.5adba17d@posting.google.com> Message-ID: <7xfzkrcc1d.fsf@ruckus.brouhaha.com> jan at jandecaluwe.com (Jan Decaluwe) writes: > > If all you care about is differentiating between 2.2 and 2.3, yes. > > But this raises NameError, I believe, on earlier verisons without > > 'bool' builtin. What is wrong with using sys.version[:3] >= '2.3'? > > (Anyone - has sys.version always been around?) > > Nothing - I do a general version check like that on 2.2 > because I need generators. You could try "type(1==1) == type(1)" From staschuk at telusplanet.net Sat Jul 12 15:09:36 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sat, 12 Jul 2003 13:09:36 -0600 Subject: Python Mystery Theatre -- Episode 1: Exceptions In-Reply-To: <3F0FED18.E88DC91A@alcyone.com>; from max@alcyone.com on Sat, Jul 12, 2003 at 04:12:24AM -0700 References: <3F0FC088.3C56EDEA@alcyone.com> <3F0FD848.849E5D88@engcorp.com> <3F0FED18.E88DC91A@alcyone.com> Message-ID: <20030712130936.A385@tibia.amotlpaa.bogus> Quoth Erik Max Francis: [...] > But, as I recall, PEP 317 was outright rejected, so it looks like this > will be with us for a long time. It was indeed rejected, primarily on the grounds that its putative benefit did not justify the cost of migration. In the end, even I (the PEP author) agree with that assessment. I still believe, however, that the implicit instantiation which Raymond's Acts II and III illustrate is a wart, fully deserves inclusion in Python Mystery Theatre, and, as a matter of style, should usually be avoided. Of course, ... > I personally have never had a problem with the distinction, raise C, x > always seemed fairly clean to me even though really what you mean is > raise C(x). ... opinions vary. Guido, for example, was not convinced by the PEP's arguments that implicit instantiation is a Bad Thing. (Note that even if he had been, the migration cost would still have sunk the PEP.) After being rejected, the PEP grew the section which briefly discusses these points and others. -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From someone at somewhere.com Sun Jul 27 10:21:35 2003 From: someone at somewhere.com (reh) Date: Sun, 27 Jul 2003 14:21:35 GMT Subject: eric3, pyqt, qscintilla - guru needed. References: Message-ID: reh wrote: > Have installed on Redhat 9.0 in the following order; > > Qscintilla > sip > PyQt > > When I install eric3 (python install.py), I get this error; > Sorry, please install QScintilla and/or reinstall > PyQt with QScintilla support. > > It seems the errors occurs in the install.py file at: > from qtext import QextScintilla > > From qtext.py, I have typed in at the python prompt; > >>> import libsip # ok here > >>> from qt import QWidet # ok here > >>> from qt import QObject # ok here > >>> from qt import QPrinter # ok here > >>> import libqtextc # error here > Traceback (most recent call last): > File "", line 1, in ? > ImportError: libqscintilla.so.2: cannot open shared object file: No such > file or directory > >>> > > Been through all readme files, tried just about everything. > Anyone have an idea what's wrong. > Forgot to say that the libqscintilla.so.2 is in; /usr/lib/qt-3.1/lib and the same path is in my /etc/ld.so.conf -- robert redhat 9.0 From peter at engcorp.com Mon Jul 7 10:23:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 10:23:13 -0400 Subject: Reverse Engineering of Windows Distribution References: Message-ID: <3F098251.426DB151@engcorp.com> Markus Stenzel wrote: > > I have a Python software for Windows, packed into a single exe file and > accompanied with a few dll and package files. > > Is there any way to reverse engineer this packet by extracting the > source files so they can be used on Linux/Unix? I have checked the exe > but it seems to be compressed by zlib. > > Some people on the mailing lists told my friend it's possible to get the > code once you can "unpack" the files from the exe. It seems likely that the source to this program would be available to you already, wouldn't it? It *is* open source, right? If it is, you can probably find the source on the web, or just contact the author for it. If it is not, you are probably violating your license agreement in trying to do this. Did it come with a license? Technically it is possible, but it's not trivial, and seems like a pretty bizarre thing to do if the author didn't intend it to be used on Linux in the first place. (Which we can infer from the choice of distribution method.) -Peter From rimbalaya at yahoo.com Wed Jul 23 11:12:55 2003 From: rimbalaya at yahoo.com (Rim) Date: 23 Jul 2003 08:12:55 -0700 Subject: distutils: removing modules Message-ID: <6f03c4a5.0307230712.39fe74d8@posting.google.com> Hi, Can someone explain the process for removing a python module I no longer need? Is there a command like: python setup.py remove ??? Thanks -Rim From kern at taliesen.caltech.edu Sun Jul 20 06:16:21 2003 From: kern at taliesen.caltech.edu (Robert Kern) Date: Sun, 20 Jul 2003 10:16:21 +0000 (UTC) Subject: How to detect user activity - for a screensaver for example. References: Message-ID: In article , Hans Deragon writes: > Greetings. > > > If I want to write a screensaver for Linux using Python, how can I detect > that the user has not touched the keyboard or mouse for the last 5 mins? Use the xscreensaver daemon to handle this for you. From the README: """It is trivially easy to add new display modes to xscreensaver: any program which can be invoked in such a way that it draws on the root window of the screen can be used as a screensaver. You just change a config file -- there's no need to recompile or reinstall anything.""" http://www.jwz.org/xscreensaver/ Your Linux distribution should have it. Now how you write to the root window is up to the graphics toolkit you are using. > Sincerely, > Hans Deragon -- Robert Kern kern at caltech.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From st.brodowski at eucrea.com Tue Jul 8 03:26:23 2003 From: st.brodowski at eucrea.com (Steffen Brodowski) Date: 8 Jul 2003 00:26:23 -0700 Subject: Image Streaming Message-ID: <381a2b17.0307072326.211c21b5@posting.google.com> Hello everyone, since one week, I'm programming with python. Its a realy interesting tool. I wrote a script for generating barcodes in jpg-format. Everything is ok, but my function "CreateBarcode" should write the jpg data into an outstream. All barcodes will be generate online, without saving the jpgs on harddisk. Can you give me a tip witch objects I need and how to put the jpg into an outgoing stream? import Image, ImageDraw def CreateBarcode(SourceString,Linewidth,WriteText): blablabla ... NewImage = Image.new("L",NewSize,Backcolor) ImgDraw = ImageDraw.Draw(NewImage) .... #How to put the image into an stream? best regards Steffen Brodowksi Germany From pythonhda at yahoo.com.replacepythonwithlinux Tue Jul 29 09:41:39 2003 From: pythonhda at yahoo.com.replacepythonwithlinux (pythonhda) Date: Tue, 29 Jul 2003 09:41:39 -0400 Subject: problems in a python script References: Message-ID: <20030729094139.2e7a92a6.pythonhda@yahoo.com.replacepythonwithlinux> Whenever I get an syntax error after editing a file from someone else, it's usually because they used another indenting scheme than I do. For example, I use spaces for indenting and some people use tabs. Check to see what indenting method they're using and make sure you use the same. If you copied the code straight from the browser, make sure you don't have any extra spaces/tabs at the beginning of the line and make sure you use a good (programmer's) text editor to save your files. On Tue, 29 Jul 2003 12:39:06 +0100 M?rio Gamito wrote: > Hi, > > I've downloaded the 30 days trial version of editize and followed the > instructions in http://plone.org/Members/tlynch/HowToIntegrateEditize > to install it. > > Everything runs smoothly until the creation of munge.py as explained in > the above link. I get an error saying > > " Script line 4 > inputvalue = inputvalue.replace("\r", "") > ^ > SyntaxError: invalid syntax" > > A curious thing is that when i save it, not only i get the above error, > but also the lines begining with double cardinal (##) are gone!!! > > Also the text refers to "Note: you might need to edit the line calling > munge in wysiwyg_support to reflect the name of your folder where all > the Editize stuff is stored." > > Where is this is done ? > > Thank you in advance for your time and patience. > > Warm Regards, > M?rio Gamito > > > > > munge.py > ----------------------------------------------------- > ## Script (Python) "munge" > ##bind container=container > ##bind context=context > ##bind namespace= > ##bind script=script > ##bind subpath=traverse_subpath > ##parameters=inputvalue > ##title= > > # to guard against files that might contain only > # returns or linefeeds, we will delete each separately > # rather than trying: replace("\r\n", "") > inputvalue = inputvalue.replace("\r", "") > inputvalue = inputvalue.replace("\n", "") > inputvalue = inputvalue.replace("'", "'") > > return inputvalue > ------------------------------------------------------------ > > From delphiro at zonnet.nl Fri Jul 4 15:14:01 2003 From: delphiro at zonnet.nl (delphiro) Date: Fri, 4 Jul 2003 21:14:01 +0200 Subject: Python is a gem, you need to keep pushing it .... In-Reply-To: <3F05C320.BF195230@engcorp.com> References: <3F05C138.687F5A06@engcorp.com> <3F05C320.BF195230@engcorp.com> Message-ID: <20030704211401.5edeec2e.delphiro@zonnet.nl> > Thus contradicting myself, of course. :-) What I meant to say was "I know what you mean, since I've found it highly suitable as well, but no one with good experience in computing could reasonably claim it will fit *all* problems except hardware drivers." Off course there will always be better solutions for specific computing problems. In our company however there is not a thing that could not be done with Python. And as I think of our company as a very regular IT company ('development keywords'; gui / database / internet / client-server / sorter-system (well the last is not too regular I guess :-)) this will fit for a lot of IT companies. And off course, if someone wants to have a macro for Word of Excel, Python won't do but it *will* for almost any regular IT job. That's my point. -- [-------------delphiro-------------] [-- http://pyciv.sourceforge.net --] [----------------------------------] From vvainio at tp.spt.fi Wed Jul 23 06:28:24 2003 From: vvainio at tp.spt.fi (Ville Vainio) Date: 23 Jul 2003 03:28:24 -0700 Subject: [OnTopic] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: clpy.NOSPAM at russellsalsbury.com (Russ Salsbury) wrote in message news:<4868482a.0307211336.4ca9493a at posting.google.com>... > I realize that this is OT, but SCO's action strikes at the heart of > Open Source. Somebody with the right patents can try to tax or shut It might be slightly on topic in that the future versions of Python could theoretically (and developers willing), shall we say, not pay as much attention for unixware as the target platform... perhaps even drift so far as not being able to compile at all >;-). From op73418 at mail.telepac.pt Mon Jul 21 11:35:48 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 21 Jul 2003 16:35:48 +0100 Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: On 21 Jul 2003 07:26:15 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >After a recent thread on .endswith, I have been thinking about iterators. >I realized that I don't know a satisfactory way to check if an >iterator is empty. In other words I am looking for an >"isempty" function to use in "if" statements such as > >if isempty(iterator): > do_something() > >without side effects. Here are some unsatisfactory ways of implementing >"isempty": > >#1: converting to a list or tuple >def isempty(iterator): > return not list(iterator) > >Easy, but one has to create the entire list, thus defecting the basic >purpose of the iterator, i.e. lazy evaluation. > >#2: checking for StopIteration >def isempty(iterator): > try: > iterator.next() > except StopIteration: > return True > else: > return False > >This works, for instance > >print isempty(iter([])) > >gives True and > >it=iter([1,2,3]) >print isempty(it) > >gives False. However, there is a side effect: after the check, the >iterator has advanced of one step and now "it.next()" gives 2, not 1. >In order this to work without side effects, I should be able to restart >the iterator from the beginning, but I don't know how to do that. >Is it possible? > >#3: comparing with the empty iterator > >emptyiterator=iter([]) > >it=iter([]) > >if it == emptyiterator: print 'Ok!' > >This simply doesn't work. > >I wonder if the itertools module should contain a function to check for >empty iterators, thus simplifying my life ;) Of course, I may well be >missing something obvious, if so, please enlighten me. > I don't think you're missing anything, the iterator protocol is just not designed to answer that question. The best that can be got is your example #2. I always make sure to add __nonzero__ to any iterator I code - and where it makes sense, of course. > > Michele With my best regards, G. Rodrigues From donn at drizzle.com Fri Jul 4 00:03:22 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 04 Jul 2003 04:03:22 -0000 Subject: How to spawn a program with redirection as it parameter References: Message-ID: <1057291400.926913@yasure> Quoth sshark97 at hotmail.com (TH Lim): | How do I do a simple thing like /bin/cat myfile.txt >> yourfile.txt | in unix? I tried with the script shown below but not successful. Am | doing it right? Pls. advise. thank you. | | #!/usr/bin/python | import os | os.spawnl(os.P_WAIT, "/bin/cat" , "/bin/cat", "myfile.txt >> | yourfile.txt") | print "Done" No, the '>>' operator belongs to the shell, and in spawnl there is no shell. As another followup observes, if you want a shell, you can use system() - os.system('cat myfile.txt >> yourfile.txt') is about the same as os.spawnl(os.P_WAIT, '/bin/sh', 'sh', '-c', 'cat myfile.txt >> yourfile.txt') Sometimes we would rather avoid the shell, because there's a risk that when it re-evaluates the command parameters they will come out different than we intend. In that case, there isn't any standard function, you have to write your own. Off the top of my head, maybe try something like def spawnvio(w, file, cmd, iodx): pid = os.fork() if pid: if w == os.P_WAIT: p, s = os.waitpid(pid, 0) return s else: return pid else: try: # Perform redirections for n, u in iodx: if n != u: os.dup2(n, u) os.close(n) os.execve(file, cmd, os.environ) finally: os._exit(113) yrf = os.open('yourfile.txt', os.O_APPEND|os.O_CREAT) spawnvio(os.P_WAIT, '/bin/cat', ['cat', 'myfile.txt'], [(yrf, 1)]) os.close(yrf) Donn Cave, donn at drizzle.com From bokr at oz.net Mon Jul 28 23:31:05 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 03:31:05 GMT Subject: octet string conversion References: Message-ID: On 28 Jul 2003 13:14:50 -0700, ruach at chpc.utah.edu (Matthew) wrote: >I am working on some software that uses SNMP to get information from >routers and switches. I am using the pysnmp module (v2.0.8) to do the >snmp part. The problem that I am having is that when I query a router >for mac addresses pysnmp returns octetstrings like this: > >\000\002\263\254\264\351 >\010\000 \301F\021 >\010\000 \300\303[ >\000\002\263\254\264\241 > >what I need though is hex strings like this: > >0:e0:7d:de:5:48 >0:e0:7d:c8:dc:9f >8:0:36:4:3b:de >0:80:ad:3a:9e:2b > >Can anyone tell me how to convert the octet strings to hex strings? > Assuming that your data is really octal character representations like \nnn, and the spaces, F, and [ in the middle lines are typos, and that your need example has nothing to do with the example data, >>> data = r""" ... \000\002\263\254\264\351 ... \010\000\301\021 ... \010\000\300\303 ... \000\002\263\254\264\241 ... """ >>> for line in data.splitlines(): ... if not line: continue # skip the first \n in data above ... print 'line: %r' %line ... oct3list = line.split('\\')[1:] ... print 'oct3list: %r'%oct3list ... octvals = [int(oct3,8) for oct3 in oct3list] ... print 'octvals: %r'%octvals ... hexstrings = ['%02X'%octval for octval in octvals] ... print 'hexstrings: %r'%hexstrings ... print 'joined with colons => %r' % ':'.join(hexstrings) ... print ... line: '\\000\\002\\263\\254\\264\\351' oct3list: ['000', '002', '263', '254', '264', '351'] octvals: [0, 2, 179, 172, 180, 233] hexstrings: ['00', '02', 'B3', 'AC', 'B4', 'E9'] joined with colons => '00:02:B3:AC:B4:E9' line: '\\010\\000\\301\\021' oct3list: ['010', '000', '301', '021'] octvals: [8, 0, 193, 17] hexstrings: ['08', '00', 'C1', '11'] joined with colons => '08:00:C1:11' line: '\\010\\000\\300\\303' oct3list: ['010', '000', '300', '303'] octvals: [8, 0, 192, 195] hexstrings: ['08', '00', 'C0', 'C3'] joined with colons => '08:00:C0:C3' line: '\\000\\002\\263\\254\\264\\241' oct3list: ['000', '002', '263', '254', '264', '241'] octvals: [0, 2, 179, 172, 180, 161] hexstrings: ['00', '02', 'B3', 'AC', 'B4', 'A1'] joined with colons => '00:02:B3:AC:B4:A1' and I got it wrong because I used fixed 2-char hex in upper case, and I'm showing the repr() of the line, which doubles the \'s, then you can fix it ;-) And get this for the data: line: \000\002\263\254\264\351 joined with colons => '0:2:b3:ac:b4:e9' line: \010\000\301\021 joined with colons => '8:0:c1:11' line: \010\000\300\303 joined with colons => '8:0:c0:c3' line: \000\002\263\254\264\241 joined with colons => '0:2:b3:ac:b4:a1' In future, please post actual data and corresponding output (or if you did this time, explain the anomalies). Otherwise it's a guessing game, and wastes all of our time except for silly finger exercises. Regards, Bengt Richter From glenfant at NOSPAM.bigfoot.com Fri Jul 4 12:22:48 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Fri, 4 Jul 2003 18:22:48 +0200 Subject: loading objects from ZODB References: Message-ID: "Achim Domma" a ?crit dans le message de news: be47oo$621$05$1 at news.t-online.com... > Hi, > > I'm playing around with ZODB but I don't understand when objects are loaded > from the DB. Assume I have an object containing a list of other objects. If > this object is loaded from ZODB, when is the list filled? Only on demand? I > think yes, because otherwise reading the top node would result in loading > the whole database. But I wanted to be sure! > > regards, > Achim > > It seems you don't need to care about this. The persistence of objects is (almost) transparent. You get/set the objects through a transparent cache to the database. The only rule : all objects must be picklable, and watch the doc about _v_xxx and p_xxx attributes. --Gilles From spam at spam.com Fri Jul 25 11:19:42 2003 From: spam at spam.com (Ton K.) Date: Fri, 25 Jul 2003 17:19:42 +0200 Subject: Memory leak with after_cancel() in Tkinter Message-ID: Folks, I'm experiencing this myself with an event driven simulator that makes *heavy* use of after() and after_cancel(). I've seen references to this bug. Has it been fixed in Python 2.2.2? Python 2.3? Thanks Ton K. From duncan at NOSPAMrcp.co.uk Wed Jul 16 05:04:18 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 16 Jul 2003 09:04:18 +0000 (UTC) Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> Message-ID: mwilson at the-wire.com (Mel Wilson) wrote in news:AhCF/ks/KjWP089yn at the- wire.com: > In article , > Duncan Booth wrote: >>The usual way is simply to reverse the list before iterating over it. >> >> l = ['some', 'text', 'in', 'a', 'list' ] >> l_reversed = l.reverse() >> for item in l_reversed: >> do something to item > > Trouble. l.reverse() reverses l in place. So just > > l.reverse() > for item in l: Duh. >>> for i in range(100): print "I must test code before posting it to Usenet" Thanks for correcting that stupid blunder. Yes, if it is safe to reverse the original list, just reverse and iterate over it as corrected above. If not, copy and reverse it: >>> l = ['some', 'text', 'in', 'a', 'list' ] >>> l_reversed = list(l) >>> l_reversed.reverse() >>> for item in l_reversed: print item list a in text some >>> (Both code snippets tested this 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 Vincent.Raaijmakers at ge.com Thu Jul 31 08:43:25 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 31 Jul 2003 07:43:25 -0500 Subject: SQL2000 database vs python Message-ID: <55939F05720D954E9602518B77F6127F02F465D5@FTWMLVEM01.e2k.ad.ge.com> Can someone tell me if there is a module out for using a sql2000 database within python? My python application (runs on Linux) already uses mysql but now I need also to talk to a sql2000 database on another machine. Any suggestions? www.python.org, google couldn't help me. Thanks in advance, Vincent From maxm at mxm.dk Thu Jul 10 07:37:46 2003 From: maxm at mxm.dk (Max M) Date: Thu, 10 Jul 2003 13:37:46 +0200 Subject: Zope problem: objectValues('Folder') In-Reply-To: <3F0D4C74.5040304@gmx.de> References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> <3F0D2405.1070606@gmx.de> <3F0D2EAC.2010605@mxm.dk> <3F0D4C74.5040304@gmx.de> Message-ID: <3F0D500A.8010108@mxm.dk> Jens Riedel wrote: > I used the objectValues('Folder')-method in a DTML-method named > 'navigation'. I include in a > 'standard_html_header' DTML method, and this standard_html_header is > used in the index_html document. Navigation may be used for something else. Does it work if you render only the navigation method? Also, you will find it much easier to find replies to Zope questions on the zope mailing list. regards Max M From klappnase at web.de Wed Jul 30 06:12:38 2003 From: klappnase at web.de (klappnase) Date: 30 Jul 2003 03:12:38 -0700 Subject: Python..Tkinter..PYTHONPATH.. References: Message-ID: usc_dog at yahoo.com (q) wrote in message news:... > Hi... > > I have a Linux RH8.0 system. I installed Python2.2 from the 8.0 ISO > updates. I installed the Tcl 8.3.3 from the Tcl site... I also > installed the tcllib 1.0. > > My goal is to get viewcvs to run. However, when I check to see where > the system thinks things are, the PYTHONPATH env var is blank. > > echo $PYTHONPATH --> produces nothing.... > > So, can anyone tell me what it should say? Can anyone shed any light > as to how this var is populated, and why it might be blank....? Can > anyone suggest what file I need to alter/should modify to have this > properly set whenever a user logs into the system....? > > Thanks > > Bruce > bedouglas at earthlink.net On my Mandrake-9.1 I have the same non-existing $PYTHONPATH, however everything works fine (as far as I have tried), so I think this variable is not really needed. I must admit that I don't know too much about that. If you want to create a PYTHONPATH I think you will have to edit /etc/.bashrc , just add something like "export PYTHONPATH " . To tell the truth I am not quite sure about the details, there may be also rc-files in the home directories that will overwrite the global settings from /etc/.bashrc (btw, that is the file's name on my mandrake box, maybe on RH the filename might differ). Maybe your problem is not PYTHONPATH at all, but sys.path in python. I am sorry that I cannot give you better help, I am just a newbie. Good luck Michael From shalehperry at comcast.net Mon Jul 7 15:24:56 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Mon, 7 Jul 2003 12:24:56 -0700 Subject: looking for UDP package, network programming guidance In-Reply-To: <3F09B124.1070008@ghaering.de> References: <3F09B124.1070008@ghaering.de> Message-ID: <200307071224.56390.shalehperry@comcast.net> On Monday 07 July 2003 10:43, Gerhard H?ring wrote: > > Any good references for learning about > > this stuff, [...] > > Sorry, not that I knew of. There is a (very short) Python Socket > Programming Tutorial, but it only covers the very basics. Probably there > is some good material out there for doing socket programming in C which > you could easily map to Python, because the concepts and even the names > of the functions are pretty much the same. > W. Richard Stevens' "UNIX Network Programming" covers sockets in depth and is one of the authoritative texts on the subject. Yes, it is C. However the sockets API pretty much works the same in every language. From scook at elp.rr.com Tue Jul 1 23:50:10 2003 From: scook at elp.rr.com (Stan Cook) Date: Wed, 02 Jul 2003 03:50:10 GMT Subject: Date issue Win98 vs NT Message-ID: Has anyone else had this or a similar problem and is there a workaround? This piece of code: from time import gmtime, strftime _log = _log + "\\" + strftime("%m%d%y", gmtime()) + ".log" produces a file with the name 'today's date.log' on NT, but creates a file called 'tomorrow's date.log' on Windows 98. I would really like to know why this happens. Any help offered is very much appreciated. Thanks, Stan From klapotec at chello.at Thu Jul 31 23:32:50 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 01 Aug 2003 03:32:50 GMT Subject: A very simple question References: Message-ID: <5cmjivs3aismc9jei9kdbhp781851en8qi@4ax.com> On Thu, 31 Jul 2003 17:13:36 -0800, "Arnaldo Riquelme" wrote: > >I'm getting familiar with Python and I have a simple question: > >class abc: > x = 100 > y = 200 > z = 300 > > >ac = abc() > >Shouldn't I have a attribute named __dict__ for ac that contains a >dictionary of all the variables? > >Instead when I do: >print ac__dict__ > >I get an empty dictionary {} > >However: > >print abc.__dict__ works. > >I'm missing something somewhere, can anyone please enlight me on this >matter. These variables you defined (x, y, z) are class attributes; ac, however is an instance of class abc, and so has no direct access to them. However, the following gets you there in this case. >>> print ac.__class__.__dict__ {'y': 200, 'x': 100, '__module__': '__main__', 'z': 300, '__doc__': None} You can test for instancehood with: >>> isinstance(ac, abc) True However, what you probably wanted was to make x, y, z available to abcs instances, which this will get you: class abc: def __init__(self): self.x = 100 self.y = 200 self.z = 300 >>> ac = abc() >>> print abc.__dict__ {'__module__': '__main__', '__doc__': None, '__init__': } >>> print ac.__dict__ {'y': 200, 'x': 100, 'z': 300} The difference (read the tutorial (http://www.python.org/doc/current/tut/node11.html#SECTION0011320000000000000000) for a better explanation) is that, since you can have many instances of any class, each of those has to have those attributes/variables defined seperately, which you cannot do by just defining them once for the whole class, but must do for each instance at instance creation time (i.e. with ac = abc() in this case). --Christopher From newsgroups at jhrothjr.com Tue Jul 29 21:12:21 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 29 Jul 2003 21:12:21 -0400 Subject: while (assignment): References: Message-ID: "Sybren Stuvel" wrote in message news:slrnbicopb.6gh.sybrenUSE at sybren.thirdtower.com... > Hi there, > > Is it possible to use an assignment in a while-loop? I'd like to do > something like "loop while there is still something to be read, and if > there is, put it in this variable". I've been a C programmer since I > was 14, so a construct like: > > while info = mydbcursor.fetchone(): > print "Information: "+str(info) > > comes to mind. Unfortunately, this doesn't work. Is there a similar > construct in python? For most purposes, there is. Just use a for loop! As long as the source behaves like an iterator, the for loop will automatically assign each result. Something like this: for info in mydbcursor.resultset: print "Information: " + str(info) In this, mydbcursor.resultset has to look like a sequence of some kind (list or tuple), or be an iterator. Since what you presumably have is a result set from a data base query, that's a rather natural fit. You might have to wrap the result set to make it an iterator, but I'd think any good db package would catch up eventually. HTH John Roth > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? From oren-py-l at hishome.net Wed Jul 30 05:57:28 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 30 Jul 2003 05:57:28 -0400 Subject: Bottleneck: easy obscurity "encryption" via xor In-Reply-To: References: Message-ID: <20030730095728.GA52034@hishome.net> On Wed, Jul 30, 2003 at 12:03:06AM +0200, Tino Lange wrote: > Hi! > > I identified a bottleneck in my programs. > > I just want to "encrypt" data by easy xoring. Ok - that's no > encryption at all - I know. But it's hardly readable - and that's > enough :-) Just some quick obscurity. > > It turns out not to be quick at all. I really didn't expect this to be > a bottleneck, but it takes quite some time. If you want higher performance always try to use things that operate on larger chunks. When you do things byte-by-byte you start to notice the fact that Python is really an interpreter. As noted by Bengt Richter xoring with a constant value can be done by str.translate. It doesn't work for variable values, though. This code does around 250kb/second on a Pentium 800. XORing is done 32 bits at a time. Conversion to and from character strings is done in even larger chunks using the array module instead of using ord() and chr(). Oren from __future__ import generators import sha def xor_stream_to_arrays(fin, seed, hashfunc=sha): """ fin is a file-like object. yields arrays that may be written to a stream """ from array import array h = hashfunc.new(seed) maskchunk = h.digest() chunksize = len(maskchunk) while True: datachunk = fin.read(chunksize) if len(datachunk) < chunksize: break yield array('l', [x^y for (x,y) in zip( array('l', maskchunk), array('l', datachunk))]) h.update('x') maskchunk = h.digest() maskchunk = maskchunk[:len(datachunk)] # trim to length of remainder # do the rest by bytes: yield array('b', [x^y for (x,y) in zip( array('b', maskchunk), array('b', datachunk))]) def xor_stream_to_stream(fin, fout, seed): """ fin, fout are file-like objects """ for a in xor_stream_to_arrays(fin, seed): fout.write(buffer(a)) def xor_string_to_string(s, seed): """ gets a string, returns a string """ from cStringIO import StringIO fin = StringIO(s) fout = StringIO() xor_stream_to_stream(fin, fout, seed) return fout.getvalue() From tetra701 at mail.ru Sun Jul 20 00:33:35 2003 From: tetra701 at mail.ru (=?koi8-r?Q?=22?=Petr Evstratov=?koi8-r?Q?=22=20?=) Date: Sun, 20 Jul 2003 08:33:35 +0400 Subject: Tk mainloop() Message-ID: Hi, I have a question: how do you execute an arbitrary function in Tk fooBar.mainloop()? I need to change the contents of a label every second, but I think I will also use some other functions as well... I hope that someone will answer my question, because I have been looking for an answer for 3 days, asking people, searching Google... and still have not found anything useful... Thanks, Pete From max at cNOvSisiPonAtecMh.com Thu Jul 3 12:30:33 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 03 Jul 2003 16:30:33 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> <3F043B22.19FE79AE@engcorp.com> Message-ID: I am not a TDD expert, but from what I understand TDD applies to lower-level code, not to design. Design usually spans separate modules and could have serious impact on the compilation time, while lower-level code can be compiled/tested very quickly, albeit not as quickly as python. And yes, many solutions do indicate that there WAS a problem, but since the solutions actually do work, the problem is not sufficient (IMO) to be a deal breaker in terms of programming language choice. max. -- ======================================== Max Khesin, software developer - max at cNvOiSsPiAoMntech.com [check out our image compression software at www.cvisiontech.com, JBIG2-PDF compression @ www.cvisiontech.com/cvistapdf.html] From jmostei at hotmail.com Thu Jul 17 05:34:39 2003 From: jmostei at hotmail.com (=?iso-8859-1?B?amFpbWUgbW9zdGVpcu1uIGFsZ2FycmE=?=) Date: Thu, 17 Jul 2003 09:34:39 +0000 Subject: chess!!! Message-ID: hi all, here i have the project of a chess program. At the moment i have just implemented the pieces movement. Its an object-oriented script. If someone come and help me perhaps we can do a package for chess which solves the implementation of the highly complex rules of chess. I want to make an inteligent program of chess with a completely new strategy. If someone is interested, please answer. _________________________________________________________________ Melod?as, logos y mil servicios para tu tel?fono en MSN M?viles. http://www.msn.es/MSNMovil/ -------------- next part -------------- A non-text attachment was scrubbed... Name: chess.py Type: application/octet-stream Size: 17959 bytes Desc: not available URL: From spam.trap at btinternet.com Tue Jul 1 08:28:02 2003 From: spam.trap at btinternet.com (michael) Date: Tue, 01 Jul 2003 13:28:02 +0100 Subject: Question regarding naming convention In-Reply-To: References: <1056988215.49928.0@iris.uk.clara.net> Message-ID: <1057062415.13616.0@doris.uk.clara.net> Sean Ross wrote: > http://www.python.org/doc/essays/styleguide.html#names Yeah, thanks for the quote. Unfortunately, this still leaves me with syntax that's a bit unfriendly. Taking the StringIO class as an example, I can either write: import StringIO s = StringIO.StringIO() or: from StringIO import StringIO s = StringIO() Both of the above seem to overcomplicate the syntax. Of the two, I prefer the second, but I'm sure I've read on c.l.py that the from..import.. version is not a preferred way of doing things. Is there no way to write a class, such that the statement: import MyClass would dynamically import the MyClass class from MyClass.py ? It just surprises me that there isn't a neater way around this, as Python seems to encapsulate most everything else in a simple way. Thanks, Michael. From pinard at iro.umontreal.ca Mon Jul 14 09:20:36 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 14 Jul 2003 09:20:36 -0400 Subject: Confusing automated translators. In-Reply-To: <3F12808B.E53193B8@hotmail.com> References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> Message-ID: [Alan Kennedy] > My favourite "phrase designed to mess up machine translation" [...] is > "Time flies like an arrow, but fruit flies like a banana". The "Time flies" is a classic. I heard it a few dozens of years ago. :-) Another similar classic, for French, is "Le pilote ferme la porte.". > If people think it's too much newsgroup abuse to discuss such a > non-python subject, [...] It is Pythonic enough to me :-), as I long intended to rewrite a previous word categoriser of mine, in Python. The categorical ambiguities are always a challenge, and for French at least, there are plenty of those, especially for texts which are loose on diacritical marks. My previous categoriser was written in MoSTex, an (unknown) language and system implemented in Scheme, made in such a way that it was compiling to optimised machine code. I'm quite curious about how speedy, legible and maintainable a Python implementation would be, by comparison. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From FBatista at uniFON.com.ar Mon Jul 14 11:47:37 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 14 Jul 2003 12:47:37 -0300 Subject: Expressing time. Message-ID: #- -----Mensaje original----- #- De: John Hunter [mailto:jdhunter at ace.bsd.uchicago.edu] #- Enviado el: Lunes 14 de Julio de 2003 12:39 PM #- #- #- The mx.DateTime package does what you need: #- Since v2.3, you have datetime: http://www.python.org/dev/doc/devel/lib/module-datetime.html From tjreedy at udel.edu Mon Jul 21 01:22:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jul 2003 01:22:07 -0400 Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: "Bengt Richter" wrote in message news:bffq56$j27$0 at 216.39.172.122... > from types import SliceType # BTW, why is slice a builtin function, not a type? I presume you are asking: Why hasn't slice been converted from a 'mere' function to a callable type like int, str, and float have been? If this has not yet been done for the coming 2.3, I presume it will be as soon as someone capable of doing the conversion decides to do so. Slice was originally added for use by Numerical Extensions and so far has probably seen little use by anyone else. Hence its conversion is of lesser priority. Terry J. Reedy From p-abel at t-online.de Wed Jul 30 06:42:46 2003 From: p-abel at t-online.de (Peter Abel) Date: 30 Jul 2003 03:42:46 -0700 Subject: searching for matches within a word list References: Message-ID: <13a533e8.0307300242.6cc9e9ec@posting.google.com> Rajarshi Guha wrote in message news:... > Hi, > I have a large list of words (each on its own line) > and I would like to find words that contain a specific string. > > I have been trying to use a regexp but I cant see how I can find the > word that contained the regex pattern - all I get is the pattern itself > if I use match or findall. > > I know that I could just go through the list line by line and see if the > regex matches or not - but that method seems horifically inefficient. > > Does anybody have any suggestions as to how I could solve this > efficiently? > > Thanks, > Rajarshi Suppose your words are in one string delimited by newline: >>> import re >>> words='MyPython\nJohn\nPython\nMary\nJython\nNothing' >>> # Suppose youn want to find all the words with the substing "ython" in them. >>> pattern='(.*?ython.*?)' >>> re.findall(pattern, words) ['MyPython', 'Python', 'Jython'] >>> Hope this helps Regards Peter From ray at rays-web.com Sat Jul 19 19:57:40 2003 From: ray at rays-web.com (Ray Smith) Date: Sat, 19 Jul 2003 23:57:40 GMT Subject: Python vs ... Message-ID: <3f19dad1@news.syd.ip.net.au> Just a quick thought I had as a stumbled out of bed this morning ... when I program some tricky piece of code well in another language I say to myself ... "Gee I was clever" when I program a tricky well written piece of code in Python I say to myself ... "Gee Python is Clever" Regards, Ray Smith From adechert at earthlink.net Mon Jul 21 20:00:31 2003 From: adechert at earthlink.net (Alan Dechert) Date: Tue, 22 Jul 2003 00:00:31 GMT Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x65lv31hf.fsf at ruckus.brouhaha.com... > "Alan Dechert" writes: > > > 1. Software chooses 1% of votes to change (big enough to have an > > > effect, small enough to maybe go unnoticed). > > > > > I don't think this is a possible scenario. However, it brings up an > > interesting test for our full blown study (keep in mind, we're trying to > > focus on getting the demo done even though people want to jump ahead to > > speculate on every possible detail). > > But something like that seems to have happened in Escambia County, > Florida, in 2000. Out of 21,500 absentee ballots cast, 296 (1.5% of > the total) were overvotes with three or more presidential candidates > checked. ZERO were overvotes with exactly two candidates checked. > Ballot tampering after the ballots were received is the most plausible > explanation. > But that's a different scenario. As you described it, the voter never had a chance to see the alteration. The scenario Harry described is where the voter has the altered ballot in hand but doesn't notice. > You said that in your system the paper ballots are > supposed to take priority over the electronic count if there is a > dispute (that's the whole point of having the paper ballots). So it > doesn't matter if the paper and electronic results don't match, and > the tampering doesn't have to happen while the voter can still see the > ballot. > I don't see much of a point here. It will be very hard -- if not impossible -- to tamper with the printout in a manner that would go undetected. First of all, overvotes will not be possible at all. I can't quite visualize how you figure someone will alter the printout. Take some whiteout and cover one name and print in a new one? That would look pretty obvious. Furthermore, the bar code would no longer match the text. In my scheme, the tamperer would have no way to know how to alter the bar code to match any alterations in the text. Post election checks (canvass period) would involve hand checks, and scanner checks of the bar code and the text. It all has to match. > Reference: > > http://www.failureisimpossible.com/essays/escambia.htm > > Note: Paul Lukasiak, the main author of that article, did some of the > most thorough analysis of the Florida debacle that I've seen. I hope > you will read a lot of his stuff in designing your real system, so > you'll be able to say how your system deals with the problems that he > identified in Florida. > I read as much as possible and will continue to study all of this. Keep in mind that some of the people on our team are leading experts in the field. They know all this stuff inside out. We'll bring in more experts once the study is funded. Nobody is saying this issue is simple. Almost everyone that has approached the voting mess dilemma and tried to figure it out has grossly underestimated the problem. I have to say I underestimated too but I have stuck with it long enough and hard enough to get a handle on it. Our Election Rules Database (the largest component of our proposed study) will surface inordinate problems -- get them out in the open where we can deal with them. Alan Dechert From staschuk at telusplanet.net Wed Jul 2 10:36:41 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 2 Jul 2003 08:36:41 -0600 Subject: __del__ not working with cyclic reference? (and memory-leaked?) In-Reply-To: ; from janeaustine50@hotmail.com on Tue, Jul 01, 2003 at 10:46:18PM -0700 References: Message-ID: <20030702083641.B595@tibia.amotlpaa.bogus> Quoth Jane Austine: [...] > (I should not use __del__ for singleton patterns, but > any other alternatives?) You could register an atexit procedure; see the atexit module in the standard library. You *can* use __del__ for a singleton as long as there is no cyclic reference, or if the interpreter deals with the cycle anyway. Under 2.2.2 and 2.3b1 this seems to work: # foo.py class MySingleton(object): def __del__(self): print 'foo' mysingleton = MySingleton() The difference is that here the instance is referred to by the module dict rather than the MySingleton class dict. (I think the reason this makes a difference is that interpreter shutdown includes a zapping of module dicts, breaking this cycle: >>> import foo >>> d = foo.__dict__ >>> d['mysingleton'].__class__.__dict__['__del__'].func_globals is d True Note that if your __del__ refers to global variables, they might have been zapped by the time it gets called.) -- Steven Taschuk w_w staschuk at telusplanet.net ,-= U 1 1 From jacob at pajamadesign.org Fri Jul 25 20:48:31 2003 From: jacob at pajamadesign.org (Jacob Singh) Date: Fri, 25 Jul 2003 20:48:31 -0400 Subject: upgrading python to ver 2.2 from 15 Message-ID: <000001c3530f$a5c5e2d0$9300a8c0@JACOB> Hello! I just got a new server and I am trying to migrate my mailman stuff over, but ran into a problem. When trying to install mailman I got the error "mailman requires >= python 2.1xxx" So I downloaded the new SRPMS and installed, but unfortunately these are python2 so it installs okay, won't update the old one and both are on the system. So I can make a link in bin, so I load the right one from the prompt, but this doesn't seem to cut it for mailman, and it still won't install! I need to get this done really soon, if anyone has faced this and knows what to do, I'd be really happy. thanks Jacob Singh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Thu Jul 24 02:05:58 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2003 06:05:58 GMT Subject: python 2.2 string conversion ? References: Message-ID: On Thu, 24 Jul 2003 05:31:17 GMT, "ken" wrote: >I've been looking for a solution to a string to long conversion problem that >I've run into > >>>> x = 'e10ea210' >>>> print x >e10ea210 >>>> y=long(x) >Traceback (most recent call last): > File "", line 1, in ? > y=long(x) >ValueError: invalid literal for long(): e10ea210 >>>> x='0xe10ea210' >>>> print x >0xe10ea210 >>>> y=long(x) >Traceback (most recent call last): > File "", line 1, in ? > y=long(x) >ValueError: invalid literal for long(): 0xe10ea210 >>>> x="e10ea210" >>>> y=long(x) >Traceback (most recent call last): > File "", line 1, in ? > y=long(x) >ValueError: invalid literal for long(): e10ea210 >>>> x="0xe10ea210" >>>> y=long(x) >Traceback (most recent call last): > File "", line 1, in ? > y=long(x) >ValueError: invalid literal for long(): 0xe10ea210 >>>> > >What am I doing wrong? > Need to supply base if converting string that is not base 10 >>> long('123') 123L >>> long('0xe10ea210',16) 3775832592L Regards, Bengt Richter From andymac at bullseye.apana.org.au Sun Jul 6 09:37:59 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 6 Jul 2003 23:37:59 +1000 (EST) Subject: Threading issue: [Error 9]: bad file descriptor In-Reply-To: References: Message-ID: <20030706233323.T71433@bullseye.apana.org.au> On Sun, 6 Jul 2003, Kevin wrote: > Has anyone else run into random IOErrors ([Error 9] bad file descriptor) in > multi-threaded Python apps? Not indicating which of the platforms with Python supported threads you're experiencing this on doesn't give much scope for others to help... -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From hokiegal99 at hotmail.com Sat Jul 12 21:42:56 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 12 Jul 2003 21:42:56 -0400 Subject: removing spaces from front and end of filenames Message-ID: This script works as I expect, except for the last section. I want the last section to actually remove all spaces from the front and/or end of filenames. For example, a file that was named " test " would be renamed "test" (the 2 spaces before and after the filename removed). Any suggestions on how to do this? import os, re, string print " " print "--- Remove '%2f' From Filenames ---" print " " percent2f = re.compile('%2f') #look for this exact string. for root, dirs, files in os.walk('/home/rbt/scripts'): for file in files: badchars = percent2f.findall(file) newfile = '' for badchar in badchars: newfile = file.replace(badchar,'-') #replace %2f with a - if newfile: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) print oldpath print newpath print " " print "--- Done ---" print " " print "--- Remove Bad Characters From Filenames ---" print " " badcharset = re.compile(r'[*?<>/\|\\]') #remove any occurance of *?<>/|\ for root, dirs, files in os.walk('/home/rbt/scripts/'): for file in files: badchars = badcharset.findall(file) newfile = '' for badchar in badchars: newfile = file.replace(badchar,'-') #replace with a dash. if newfile: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) print oldpath print newpath print " " print "--- Done ---" print " " print "--- Remove Spaces From Filenames ---" print " " for root, dirs, files in os.walk('/home/rbt/scripts'): for file in files: fname = (file) fname = fname.strip( ) print fname print " " print "--- Done ---" print " " From jzgoda at gazeta.usun.pl Sat Jul 12 18:02:54 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 12 Jul 2003 22:02:54 +0000 (UTC) Subject: HTML Help (CHM) file for Python 2.2.3 References: Message-ID: L?tez? pisze: > Could you send me a download URL of a compiled > HTML Help (CHM) file for Python 2.2.3 ? I don't know any file of this type, but the documentation for ActiveState's Python distribution comes as chm (along with some additional docs, such as Dive Into Python by Mark Pilgrim). -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From jerf at jerf.org Mon Jul 14 23:07:16 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 15 Jul 2003 03:07:16 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <3F132103.4D18759F@engcorp.com> Message-ID: On Mon, 14 Jul 2003 15:09:38 -0700, Tim Gerla wrote: > You're right--I was under the wrong impression about single & double > quotes. For some reason I recall reading somewhere (can't trust everything > you read online) that XML only allowed double quotes, and I never bothered > to verify it. I recently had this discussion with another co-worked. The confusion probably stems from the fact that as of the latest XHTML specification at the time I read it, every single example XHTML fragment used double quotes. At no point is it ever specified either way in the XHTML specification, except by reference to the XML specification. However, the official W3C validator accepts single quotes, so I'm going with "they're legal". (Which has been hashed out in other messages already, I see, but I wanted to propose a theory as to where the idea came from, because I know I've seen it myself several times.) From ben at dadsetan.com Wed Jul 9 17:36:03 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Wed, 09 Jul 2003 23:36:03 +0200 Subject: Deleting specific characters from a string In-Reply-To: <3F0C851C.4000500@livinglogic.de> References: <3F0C851C.4000500@livinglogic.de> Message-ID: <3F0C8AC3.5010304@dadsetan.com> Walter D?rwald wrote: > Behrang Dadsetan wrote: > >> Hi all, >> >> I would like deleting specific characters from a string. >> As an example, I would like to delete all of the '@' '&' in the >> string 'You are ben at orange?enter&your&code' so that it becomes >> 'benorange?enteryourcode'. >> >> So far I have been doing it like: >> str = 'You are ben at orange?enter&your&code' >> str = ''.join([ c for c in str if c not in ('@', '&')]) >> >> but that looks so ugly.. I am hoping to see nicer examples to acheive >> the above.. > > > What about the following: > > str = 'You are ben at orange?enter&your&code' > str = filter(lambda c: c not in "@&", str) > > Bye, > Walter D?rwald def isAcceptableChar(character): return charachter in "@&" str = filter(isAcceptableChar, str) is going to finally be what I am going to use. I not feel lambdas are so readable, unless one has serious experience in using them and python in general. I feel it is acceptable to add a named method that documents with its name what it is doing there. But your example would probably have been my choice if I was more familiar with that type of use and the potential readers of my code were also familiar with it. Many thanks! Ben. From srovner at us.ibm.com Thu Jul 24 16:00:32 2003 From: srovner at us.ibm.com (Sonia Rovner) Date: 24 Jul 2003 13:00:32 -0700 Subject: How to import hackicon.dll Message-ID: <8a5a6d82.0307240417.494caa13@posting.google.com> Hello, I'm using Python2.2.1 and Tcl/Tk 8.3 running on Win2000. I've been researching how to change the icon on the title bar and found that hackicon is the one I should pursue. However, hackicon package uses a dll. When I run the hi.py, I get an error saying ImportError: DLL load failed: The specified module could not be found. I copied hackicon.dll to various directories in my pythonpath but nothing happens. From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 23 03:31:36 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 23 Jul 2003 08:31:36 +0100 Subject: Tkinter Listbox looses selection on Tab In-Reply-To: <117880a1.0307221040.60a27c0d@posting.google.com> References: <117880a1.0307221040.60a27c0d@posting.google.com> Message-ID: <200307230831.36805.mfranklin1@gatwick.westerngeco.slb.com> On Tuesday 22 July 2003 19:40, J?rgen Hansen wrote: > Hi > > I have a problem with a Listbox in Tkinter. When I tab through several > widgets with the tab-key, the listbox looses its selection, even > though it has been selected with .selection_set. The example below > demonstrates this. Can anyone provide me with some help on this? > > Regards > Jorgen > > Ps. I'm on a W2K machine with Python 2.2.2 > > ---- > from Tkinter import * > > root = Tk() > colors = ['Yellow', 'Black', 'White', 'Green'] > > lb = Listbox(root) Jorgen, Try setting exportselection=0 in the Listbox construction like so: lb = Listbox(root, exportselection=0) This seems to work on my linux box. Martin From kberft at aol.com Thu Jul 10 14:59:43 2003 From: kberft at aol.com (BigSizeXXL) Date: 10 Jul 2003 11:59:43 -0700 Subject: mail receiving + address questions Message-ID: <5808e763.0307101059.25e154f2@posting.google.com> hi, i'm new to python and have a couple of questions about working with smtp. i read that you need a pop3 service for receiving mails. i want to create my own (private) mail service. i'm using a mail server based upon smtps.py, but i'm still looking for a pop3 service to receive mails that also works with smtps.py together. i would be very happy if someone could send me such code. another question: if i have this (smtp server and pop3 mail receiver), what is the mail address someone cand send the mails to? thank you for (hopefully) answering my questions BigSizeXXL From jon+usenet at unequivocal.co.uk Wed Jul 9 05:59:57 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 9 Jul 2003 09:59:57 GMT Subject: Python vs PHP References: Message-ID: In article , A.M. Kuchling wrote: > Jon, there's no point in debating Afanasiy about CGI. He's convinced > packages for Python web programming support are inadequate (*all* of them), > is unable to explain what the problem is or what his requirements are, and > doesn't seem to really understand the subject (e.g. thinking FastCGI is > basically the same as regular CGI). Ignoring him is the best course. Oh, ok, ta ;-) From ssthapa at classes.cs.uchicago.edu Mon Jul 21 14:53:19 2003 From: ssthapa at classes.cs.uchicago.edu (Suchandra Thapa) Date: Mon, 21 Jul 2003 18:53:19 GMT Subject: "Pure Python" MySQL module like Net::MySQL References: <7xk7advy4c.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin <> wrote: > What the heck? If the wire protocol isn't part of the official > external interface, then how on earth are external applications > supposed to talk to the database? They certainly can't expect you to > use black-box client libraries if they're at all serious about being > in the same league with Oracle. Actually, I think they do. With a change to a gpl licensed client library, in mysql 4.x, I think mysql ab is trying to get more revenue from anyone using the mysql database for commercial purposes. Forcing all access to the database to go through their client libraries is one of the things that made this possible. -- ---------------------------------------------------------------------------- Suchandra Thapa s-thapa-11 at NOSPAMalumni.uchicago.edu ---------------------------------------------------------------------------- From ed at UDel.Edu Fri Jul 25 16:22:17 2003 From: ed at UDel.Edu (Ed Phillips) Date: Fri, 25 Jul 2003 16:22:17 -0400 (EDT) Subject: Beefing up socket.ssl(...) In-Reply-To: <16161.36214.435946.860897@montanaro.dyndns.org> References: <84e0f331.0307251036.6504b16a@posting.google.com> <16161.36214.435946.860897@montanaro.dyndns.org> Message-ID: On Fri, 25 Jul 2003, Skip Montanaro wrote: > Ed> From looking at Modules/socketmodule.c in 2.2.2 and 2.2.3, it > Ed> appears that only a tiny bit of support for SSL has been added. > Ed> Specifically, unless I'm misunderstanding the operation of the code, > Ed> there's no way to verify the certificate presented by a server. > > Note that since 2.2.3 is just a bugfix release, you shouldn't expect any > increase in functionality. I'm mildly surprised that you noticed any > functional changes between 2.2.2 and 2.2.3. Sorry, I didn't mean to imply they were different... I just meant that I looked at them both (not realizing they should be the same except for bug fixes). By "only a tiny bit of support for SSL has been added", I meant "... to Python in general as of 2.2.2 and 2.2.3". > I suggest you take 2.3c2 out for a spin and see if it has more of the > features you're after. (2.3final is due out by the end of the month.) Hmmmm... well, I guess I can take a look at socketmodule.c in 2.3c2 and see if it's any different than previous versions as far as the amount of SSL functionality goes. > In any case, if you have patches to submit, please use SourceForge and > note that any functional improvements will be targetted at 2.4 at this > point. You can find more about patch submission at the Patch Submission > Guidelines page: > > http://www.python.org/patches/ I'm not sure whether this "functional change" would be considered a "bug fix" or "feature addition". The SSL support in socketmodule.c seems to be lacking almost to the point of being "unusable"... I can't imagine anyone actually using it for anything "real" in it's current state, and in that sense, it may be legitimate to call my changes a "bug fix". I guess I could attack it either way. I could modify the existing socket.ssl() pieces to work "better" (at least in the normal "act like a web browser and verify server certs" sense), or I could add new "features". It might be nice to have a socket.sslclient() method that would verify the server cert and optionally authenticate with a client certificate (although the client auth part is probably out of my league at this point), along with a socket.sslserver() method which would perform the normal server-side SSL duties. Or I could just hack on socketmodule.c with every new Python release and hope that someone eventually adds better SSL support. Anyone working on that already? Thanks, Ed Ed Phillips University of Delaware (302) 831-6082 Systems Programmer III, Network and Systems Services finger -l ed at polycut.nss.udel.edu for PGP public key From peter.barth at t-online.de Tue Jul 15 11:32:38 2003 From: peter.barth at t-online.de (Peter Barth) Date: 15 Jul 2003 08:32:38 -0700 Subject: Mix lambda and list comprehension? References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> Message-ID: <6f5b3f88.0307150732.1b0a2526@posting.google.com> Thanks a lot, works fine. However, the solution does not really feel "pythonesque". Is it considered a usability bug or fine as is? - Peter "Raymond Hettinger" wrote in message news:... > Try this: > > >>> [lambda x, y=y:x+y for y in range(10)][4](2) > 6 > > > It is important to bind y in a closure at the time > the lambda is defined. Otherwise, y remains unbound > until you invoke the function call. At that time, the most > recent value of y is the last value in the range loop (namely, 9). > > > Raymond Hettinger > > > > "Peter Barth" wrote in message > news:6f5b3f88.0307142302.1a1531f3 at posting.google.com... > > Hi, > > trying to mix lambda expresions and list comprehension > > doesn't seem to work. > > --- > > >>> [lambda x:x+y for y in range(10)][9](2) > 11 > > >>> [lambda x:x+y for y in range(10)][4](2) > > 11 > > --- > > I expected the second expression to return 6. > > What did I do wrong? Any hints? > > Thanks > > - Peter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jul 1 14:01:59 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 01 Jul 2003 20:01:59 +0200 Subject: remove special characters from line In-Reply-To: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> References: <3f01a27d$0$43847$39cecf19@news.twtelecom.net> Message-ID: <3f01cc95$0$49112$e4fe514c@news.xs4all.nl> Chris Rennert wrote: > Hello all, > > If I have a line like this > > ?blah blah blah blah blah > > I know I could do a slice like this [1:] to pull everything but the special > character, but what if I have several lines in a file. > I am not sure how I would detect a special character like that. I would > just like to pull everything from those lines (and the special character > always appears as the first character, but not on every line) except for the > special characters. What about >>> special="*!@" # or whatever characters are special >>> text="*blah blah !! blah blah at blah blah!" >>> ''.join([c for c in text if c not in special]) 'blah blah blah blahblah blah' --Irmen de Jong From newsgroups at jhrothjr.com Sat Jul 26 18:10:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 26 Jul 2003 18:10:47 -0400 Subject: Static typing References: Message-ID: "Alexander Schmolck" wrote in message news:yfssmotnj8p.fsf at black132.ex.ac.uk... > "Michael Muller" writes: > > > Is there currently any plan to introduce static typing in any future > > version of Python? (I'm not entirely sure that "static typing" is the right > > term: what I'm talking about is the declaration of types for variables, > > parameters and function return values). > > > > I know there was a "types SIG" which introduced several proposals, but it > > expired quite a while ago, and I was wondering whether whether some > > consensus has been reached on the subject or if it has just been shelved > > indefinitely. > > I think the traits package hasn't been mentioned so far: > > http://www.scipy.org/site_content/traits/Traits_Users_Guide.htm Interesting. I've bookmarked it for careful consideration. Personally, I'm against static typing in it's generally accepted form, but there are a couple of capabilities I like about it, the biggest of which is the ability to get type information via reflection. I suspect I might also like the ability to have a type inference engine verify some aspects of my program, but since I've never used one, I don't know how it would work in practice. The other major thing I'd like about it is the ability to provide generic support for things like display widgets based on the type information. I just don't like the syntax getting in the way. John Roth > > 'as From jocsch at phreaker.net Sun Jul 6 14:30:22 2003 From: jocsch at phreaker.net (Markus Joschko) Date: Sun, 06 Jul 2003 20:30:22 +0200 Subject: absolute beginners question about API documentation References: Message-ID: Dave Kuhlman wrote: > Markus Joschko wrote: > >> Hi all, >> I' new to python programming but a longtime java programmer. >> Is there an API documentation like the javadoc API from java? >> >> I'm want to know all methods I can use on dictionaries. Where can >> I get an overview about these? >> I looked on python.org but haven't found such an overview. >> > > If you are asking about the *Python* API, then look here: > > http://www.python.org/doc/current/lib/typesmapping.html > Thanks. That's it. I hadn't suspect it there. From gumuz at looze.net Thu Jul 24 09:33:04 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 24 Jul 2003 15:33:04 +0200 Subject: i've been close to python's cradle :) Message-ID: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> recently i've visited SARAH, the academic supercomputer in Amsterdam, Holland. this is next to the CWI, where Guido founded Python.... ...Yeah!... From pinard at iro.umontreal.ca Thu Jul 24 09:19:53 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 24 Jul 2003 09:19:53 -0400 Subject: file.close() In-Reply-To: References: Message-ID: [Bryan] > I'm curious to know how others handle the closing of files. [...] I'm > aware that files will automatically be closed when the process exits. For one, I systematically avoid cluttering my code with unneeded `close'. The advantages are simplicity and legibility, both utterly important to me. However, I do understand that if I ever have to move a Python script to Jython, I will have to revise my scripts for adding the clutter I am sparing today. I'm quite accepting to do that revision if this occurs. Until then, I prefer keeping my scripts as neat as possible. For me, explicitely closing a file, for which the only reference is about to disappear through function exiting, would be very similar to using `del' on any variable I happened to use in that function: gross overkill... The only reason to call `close' explicitly is when there is a need to close prematurely. Absolutely no doubt that such needs exist at times. But closing all the time "just in case" is symptomatic of unsure programming. Or else, it is using Python while still thinking in other languages. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From e.d.andersen at mosek.com Wed Jul 9 05:19:30 2003 From: e.d.andersen at mosek.com (edadk) Date: 9 Jul 2003 02:19:30 -0700 Subject: Python 2.2 build problems on AIX Message-ID: Hi I building Python on AIX using make However, I get some errors when building readline gdbm and -ltermcap is missing. See below. Can those problems be fixed? Erling building 'readline' extension cc_r -DNDEBUG -O -I. -I/mnt/mds/metawrk/edanders/Python-2.2.3/./Include -I/usr/local/include -I/mnt/mds/metawrk/edanders/Pytho 2.2.3/Include -I/mnt/mds/metawrk/edanders/Python-2.2.3 -c /mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c -o build/t p.aix-5.1-2.2/readline.o "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 17.10: 1506-296 (S) #include file not und. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 18.10: 1506-296 (S) #include file not f nd. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 278.21: 1506-045 (S) Undeclared identifier rl_completer_word reak_characters. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 314.36: 1506-045 (S) Undeclared identifier rl_completer_word reak_characters. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 359.36: 1506-045 (S) Undeclared identifier rl_line_buffer. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 510.34: 1506-068 (W) Operation between types "unsigned char* and "int" is not allowed. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 518.9: 1506-045 (S) Undeclared identifier rl_readline_name. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 520.27: 1506-045 (S) Undeclared identifier rl_insert. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 522.35: 1506-045 (S) Undeclared identifier rl_complete. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 522.48: 1506-045 (S) Undeclared identifier emacs_meta_keymap "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 525.38: 1506-275 (S) Unexpected text ')' encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 525.28: 1506-045 (S) Undeclared identifier Function. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 525.54: 1506-277 (S) Syntax error: possible missing ')' or ' ? "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 525.9: 1506-045 (S) Undeclared identifier rl_startup_hook. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 532.9: 1506-045 (S) Undeclared identifier rl_completer_word_ eak_characters. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 580.9: 1506-045 (S) Undeclared identifier rl_event_hook. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/readline.c", line 581.11: 1506-068 (W) Operation between types "unsigned char* and "int" is not allowed. WARNING: building of extension "readline" failed: command 'cc_r' failed with exit status 1 skipping 'crypt' extension (up-to-date) skipping '_socket' extension (up-to-date) skipping 'dbm' extension (up-to-date) building 'gdbm' extension cc_r -DNDEBUG -O -I. -I/mnt/mds/metawrk/edanders/Python-2.2.3/./Include -I/usr/local/include -I/mnt/mds/metawrk/edanders/Pytho 2.2.3/Include -I/mnt/mds/metawrk/edanders/Python-2.2.3 -c /mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c -o build emp.aix-5.1-2.2/gdbmmodule.o "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 12.10: 1506-296 (S) #include file "gdbm.h" not found. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 34.5: 1506-046 (S) Syntax error. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 68.14: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 72.53: 1506-045 (S) Undeclared identifier gdbm_errno. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 84.13: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 85.24: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 92.13: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 97.15: 1506-275 (S) Unexpected text key encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 97.9: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 99.9: 1506-045 (S) Undeclared identifier okey. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 102.36: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 102.14: 1506-045 (S) Undeclared identifier key. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 103.37: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 117.11: 1506-275 (S) Unexpected text drec encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 117.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 119.34: 1506-045 (S) Undeclared identifier krec. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 122.13: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 127.27: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 127.5: 1506-045 (S) Undeclared identifier drec. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 141.11: 1506-275 (S) Unexpected text krec encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 141.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 143.32: 1506-045 (S) Undeclared identifier krec. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 148.13: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 155.29: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 162.36: 1506-045 (S) Undeclared identifier drec. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 168.28: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 168.48: 1506-045 (S) Undeclared identifier GDBM_REPLACE. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 173.47: 1506-045 (S) Undeclared identifier gdbm_errno. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 195.13: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 196.24: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 197.9: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 210.11: 1506-275 (S) Unexpected text key encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 210.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 220.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 226.29: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 226.5: 1506-045 (S) Undeclared identifier key. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 241.36: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 241.9: 1506-045 (S) Undeclared identifier nextkey. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 255.11: 1506-275 (S) Unexpected text key encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 255.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 257.48: 1506-045 (S) Undeclared identifier key. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 259.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 260.50: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 274.11: 1506-275 (S) Unexpected text key encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 274.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 278.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 279.29: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 279.5: 1506-045 (S) Undeclared identifier key. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 306.11: 1506-275 (S) Unexpected text key encountered. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 306.5: 1506-045 (S) Undeclared identifier datum. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 308.48: 1506-045 (S) Undeclared identifier key. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 310.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 311.32: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 311.5: 1506-045 (S) Undeclared identifier nextkey. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 336.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 338.29: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 342.53: 1506-045 (S) Undeclared identifier gdbm_errno. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 359.5: 1506-022 (S) "di_dbm" is not a member of "struct {. }". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 360.19: 1506-022 (S) "di_dbm" is not a member of "struct { .}". "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 445.18: 1506-045 (S) Undeclared identifier GDBM_READER. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 448.18: 1506-045 (S) Undeclared identifier GDBM_WRITER. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 451.18: 1506-045 (S) Undeclared identifier GDBM_WRCREAT. "/mnt/mds/metawrk/edanders/Python-2.2.3/Modules/gdbmmodule.c", line 454.18: 1506-045 (S) Undeclared identifier GDBM_NEWDB. WARNING: building of extension "gdbm" failed: command 'cc_r' failed with exit status 1 skipping 'termios' extension (up-to-date) skipping 'resource' extension (up-to-date) skipping 'nis' extension (up-to-date) building '_curses' extension skipping /mnt/mds/metawrk/edanders/Python-2.2.3/Modules/_cursesmodule.c (build/temp.aix-5.1-2.2/_cursesmodule.o up-to-date) ./Modules/ld_so_aix cc_r -bI:Modules/python.exp build/temp.aix-5.1-2.2/_cursesmodule.o -L/usr/local/lib -lcurses -ltermcap -o ild/lib.aix-5.1-2.2/_curses.so ld: 0706-006 Cannot find or open library file: -l termcap ld:open(): No such file or directory *** WARNING: renaming "_curses" since importing it failed: from module build/lib.aix-5.1-2.2/_curses.so No such file or direct y error: No such file or directory make: The error code from the last command is 1. From bokr at oz.net Mon Jul 21 20:15:48 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2003 00:15:48 GMT Subject: recognizing empty iterators References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> Message-ID: On 21 Jul 2003 07:26:15 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >After a recent thread on .endswith, I have been thinking about iterators. >I realized that I don't know a satisfactory way to check if an >iterator is empty. In other words I am looking for an >"isempty" function to use in "if" statements such as > >if isempty(iterator): > do_something() > >without side effects. Here are some unsatisfactory ways of implementing >"isempty": > >#1: converting to a list or tuple >def isempty(iterator): > return not list(iterator) > >Easy, but one has to create the entire list, thus defecting the basic >purpose of the iterator, i.e. lazy evaluation. > >#2: checking for StopIteration >def isempty(iterator): > try: > iterator.next() > except StopIteration: > return True > else: > return False > >This works, for instance > >print isempty(iter([])) > >gives True and > >it=iter([1,2,3]) >print isempty(it) > >gives False. However, there is a side effect: after the check, the >iterator has advanced of one step and now "it.next()" gives 2, not 1. >In order this to work without side effects, I should be able to restart >the iterator from the beginning, but I don't know how to do that. >Is it possible? > >#3: comparing with the empty iterator > >emptyiterator=iter([]) > >it=iter([]) > >if it == emptyiterator: print 'Ok!' > >This simply doesn't work. > >I wonder if the itertools module should contain a function to check for >empty iterators, thus simplifying my life ;) Of course, I may well be >missing something obvious, if so, please enlighten me. > If iterators had a .peek() method for 1-item lookahead, maybe that would be easy to implement. If empty, it could raise StopIteration, and otherwise return what next() would return, without disturbing the state w.r.t. next(). Alternatively, it could return [nextitem] vs [] if at the end (without raising StopIteration). Regards, Bengt Richter From postmaster at 127.0.0.1 Wed Jul 16 09:25:46 2003 From: postmaster at 127.0.0.1 (David McNab) Date: Thu, 17 Jul 2003 01:25:46 +1200 Subject: How about using python to write a CMS? References: <3f153a2b$0$97201$edfadb0f@dread12.news.tele.dk> Message-ID: On Wed, 16 Jul 2003 13:44:35 +0200, Max M paused, took a deep breath, then came out with: > ?????? wrote: > >> To write a CMS, everyone is thinking about PHP, but, what do you think if I >> am using python to write a Content Management System? > > > It can be done, and better than in PHP, but do yourself the favour of > checking out Plone. > > www.plone.org > > > regards Max M Plone looks nice. *really* nice! But it runs on top of Zope - a requirement which locks it out of a lot of hosting situations. From mickel at csc.fi Fri Jul 4 01:15:17 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 4 Jul 2003 08:15:17 +0300 (EEST) Subject: Python Code Snippets In-Reply-To: References: Message-ID: On Thu, 3 Jul 2003, Aur?lien G?ron wrote: > Does anyone know where I can find a lot of Python code snippets? Try: http://www.faqts.com/knowledge_base/index.phtml/fid/538 Cheers, /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From staschuk at telusplanet.net Wed Jul 23 18:40:00 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 23 Jul 2003 16:40:00 -0600 Subject: How does Mr. Martelli's Borg recipe work ? In-Reply-To: ; from bokr@oz.net on Wed, Jul 23, 2003 at 09:05:50PM +0000 References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <20030723164000.A1684@tibia.amotlpaa.bogus> Quoth Bengt Richter: [borg vs singleton] > How about just > > import zerolengthfile as borginstancename > > and using it? E.g., [...] That would be fine in many cases, I'm sure. Modules don't do properties (or other descriptor magic), though. -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From romany at actimize.com Sun Jul 27 09:23:50 2003 From: romany at actimize.com (Roman Yakovenko) Date: Sun, 27 Jul 2003 16:23:50 +0300 Subject: datetime 2 win variant datetime Message-ID: <91BFE89EFFA2904E9A4C3ACB4E5F2DF5027AFB@exchange.adrembi.com> Hi. It seems I need a little help with this subject. I am trying to convert python datetime ( 2.3 ) to windows variant that keeps date and time but I failed. Can smbd give me a hint? Thanks. From andy at wild-flower.co.uk Sun Jul 20 10:25:16 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sun, 20 Jul 2003 15:25:16 +0100 Subject: Thanks comp.lang.python!!! In-Reply-To: <3F1A0F15.101@hotmail.com> References: <3F1A0F15.101@hotmail.com> Message-ID: <200307201524.47584.andy@wild-flower.co.uk> On Sunday 20 Jul 2003 4:40 am, hokiegal99 wrote: > While migrating a lot of Mac OS9 machines to PCs, we encountered several > problems with Mac file and directory names. Below is a list of the > problems: > > 1. Macs allow characters in file and dir names that are not acceptable > on PCs. Specifically this set of characters [*<>?\|/] > > 2. Mac files and dirs that contained a "/" in their names would ftp to > the server OK, but the "/" would be translated to "%2f". So, a Mac file > named 7/19/03 would ftp as 7%2f19%2f03... not a very desirable filename, > especially when there are hundreds of them. > > 3. The last problem was spaces at the beginning and ending of file and > dir names. We encountered hundreds of files and dirs like this on the > Macs. They would ftp up to the Linux server OK but when the Windows PC > attempted to d/l them, the ftp transaction would stop and complain about > not finding files whenever it tried to transfer a file. Dirs with spaces > at the beginning or ending would literally crash the ftp client. > Shame on Apple for allowing subversive filenames! ;-) > These were problems that we did not expect. So, we wrote a script to > clean up these names. Since all of the files were bring uploaded to a > Linux ftp server, we decided to do the cleaning there. Python is a > simple, easily readable programming language, so we chose to use it. > Long story short, attached to this email is the script. If anyone can > use it to address Mac to PC migrations, feel free to. > You never do, until they bite you! > The only caveat is that the script uses os.walk. I don't think Python > 2.2.x comes with os.walk. To address this, we d/l 2.3b2 and have used it > extensively with this script w/o any problems. And, someone here on > comp.lang.python told me that os.walk could be incorporated into 2.2.x > too, but I never tried to do that as 2.3b2 worked just fine. > There is os.path.walk, instead. > Thanks to everyone who contributed to this script. Much of it is > straight from advice that I received here. Also, if anyone sees how it > can be improved, let me know. For now, I'm satisfied with it as it works > "well enough" for what I need it to do, however, I'm trying to become a > better programmer so I appreciated feedback from those who are much more > experienced than I am. > You're welcome. We all come here to learn... :-)) > Special Thanks to Andy Jewell, Bengt Richter and Ethan Mindlace Fremen > as they wrote much of the code initially and gave a lot of great tips!!! :-)) Some additional comments on your source-code, if I may. The following points will help you make your program much more efficient: 1) You'd normally place your functions in a separate section, usually at the top of your program, rather than 'in the middle'. It will work fine this way, but it's a bit less readable. 2) There seem to be some indentation anomalies, probably because of using a combination of tabs and spaces. This WILL bite you sometime in the future: best to stick to one or t'other, preferably just spaces: the convention in Python is to indent by 4 spaces for each 'suite', or logical 'block' of code. 3) I'm not sure you quite get the recursive bit yet! Simply calling your function lots of times in succession doesn't cut it... all that happens is that each time you call it, it does the same thing, effectively doing the job 10 times... What you'd have to do is call the function from *WITHIN* itself, i.e. in the body, like: def recurse(dir,depth=0): """ walk dir's subdirectories recursively, printing their name """ # process list of files in dir... for entry in os.listdirs(dir): # if the current one is a directory... if os.path.isdir(os.join(dir,entry)): print " "*depth+"+"+entry # recurse (call ourselves) recurse(os.join(dir,entry),depth+1) ** NOTE: Looking at the docs, if you use os.walk, you don't need to do the recursion yourself, as os.walk does it for you! 3) You're still repeating yourself several times, too. You can get away with JUST ONE os.walk() loop: for root, dirs, files in os.walk(setpath): for thisfile in dirs+files: badchars=bad.findall(thisfile) newname=thisfile.strip() # strip off leading and trailing whitespace # replace any bad characters... for badchar in badchars: newname=neaname.replace(badchar,"-") # rename thisfile ONLY if newname is different... if newname != thisfile: # check if it's changed: print renaming thisfile,newname,"in",root os.rename(os.path.join(root,thisfile),os.path.join(root,newname) !! that replaces what your four for loops do... 8-0 hope you find this useful :-) -andyj From bdesth.nospam at removeme.free.fr Sun Jul 13 18:15:44 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sun, 13 Jul 2003 22:15:44 +0000 Subject: How to crash Python in 1 easy step (python 2.2.2) References: <2e363c08.0307130944.4c470bc3@posting.google.com> Message-ID: <3F11DA10.6000601@removeme.free.fr> Paul Miller wrote: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > everything about the system is standard except for what's been updated > by RedHat itself. If anyone who has the time and ability to track > down this bug needs more information, please email me. No problem here with Python 2.2.x (where x = cantRememberAndToLazyToCheckButThinkIts1) Bruno From delobelle at blueyonder.co.uk Tue Jul 8 08:12:46 2003 From: delobelle at blueyonder.co.uk (Arnaud Delobelle) Date: 08 Jul 2003 13:12:46 +0100 Subject: robot programming game in python Message-ID: <878yr9tdxd.fsf@blueyonder.co.uk> Hi all, I have written a little while ago in Python a game whose aim is to program a (or several) robots so that they move around in a maze and collect some flags. They only have a limited amount of instructions at their disposal (depending on the level). It is meant to be an introduction to two things: - programming - boolean expressions At the moment I have written the `maze engine' and `maze rendering' classes and a level editor/level player making use of those classes. It needs Python >=2.2 (new style classes), Tkinter, and the Python Imaging Library. Now (I hope it is not inappropriate to post this here) I'd really like to get some feedback and criticism before I clean it up and try to enhance it, as I happen to have lots of free time these days. I'm having trouble finding people around me who have python :( Description of the project (24kbytes): http://marooned.myby.co.uk/marooned/showpage.php?page=readme&style=test The project (64 kbytes): http://marooned.myby.co.uk/pytobor/pytobor.tgz Then $tar zxvf pytobor.gz (or any other way) $cd pytobor0.5.1 $python editlevel.py There are a few (simple) sample levels called level0.rob to level7.rob. Thanks for any feedback (in private!). -- Arnaud Delobelle d e l o b e l l e AT b l u e y o n d e r . c o . u k From rastm2 at aol.commorespam Sun Jul 20 19:30:24 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 20 Jul 2003 23:30:24 GMT Subject: List of declared variables in interactive Python session? References: <3F1AEAFB.3C62F613@engcorp.com> Message-ID: <20030720193024.13089.00000249@mb-m10.aol.com> >"Raymond Arthur St. Marie II of III" wrote: >> >> >>> vars( ) >> >> {'d': 'pywin', '__builtins__': , >'__name__': >> '__main__', 'pywin': > 'C:\PYTHON22\lib\site-packages\Pythonwin\pywin\__init__.pyc'>, '__doc__': >None} >> >> >>> for v in vars(): print v >> ... >> >> Traceback (most recent call last): >> File "", line 1, in ? >> RuntimeError: dictionary changed size during iteration > >for v in vars().copy(): print v > >works fine... > >-Peter > Very nice Peter, I didn't see that coming (sad for me). But it amounts to the same thing, really. Newbies might like to know that you work with a variable declared specially for this "for" iterater in hopes that you won't stomp all over a variable you might otherwise clobber. Only, I love a good one-liner. :-) Ray -- From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 4 14:36:41 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 04 Jul 2003 20:36:41 +0200 Subject: How to get CGI request-URL In-Reply-To: References: Message-ID: <3f05c935$0$49111$e4fe514c@news.xs4all.nl> Hallvard B Furuseth wrote: > How can I get the URL the user typed (except the part after '?') with > the cgi module? try the REQUEST_URI environment variable --Irmen From martin at v.loewis.de Fri Jul 18 11:10:06 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Jul 2003 17:10:06 +0200 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F177D72.FF10EAEA@alcyone.com> Message-ID: Erik Max Francis writes: > Yeah, but that only works if everyone's expecting the same encoding. I > just see garbage non-ASCII characters, for instance, with my lowly > Netscape 4 newsreader. No, that is not a prerequisite. Instead, the prerequisite is that the news reader/MUA knows what MIME (Multipurpose Internet Mail Extensions) is. In the MIME header, I clearly identified the encoding of this message as UTF-8, so any news reader *should* be capable of converting this to the local encoding (perhaps using replacement characters where glyphs are missing). > Looked like it was probably was here, I saw what looked very strongly > like eight double-byte characters (and two bytes each). But then, you were able to read the English parts of my message just fine, right? The ASCII letters in this message did not take up two bytes per letter, as they would have if the message was encoded in UTF-16. Regards, Martin From mike at nospam.com Wed Jul 30 16:07:11 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 30 Jul 2003 13:07:11 -0700 Subject: streams (was: Re: Itertools) References: Message-ID: Beni Cherniavsky wrote: > Any feedback welcome. I'd like to make it as Pythonic as possible. > An perhaps make it standard. Particular open questions: > - The linked lists are called "streams" by me because they are lazy > and that's what such beasts are called in functional languages. Stream is used differently in Tcl and Unix. Minded separation Python from functional approach (deprecation of filter, map; doubtfulness of implementing tail recursion optimization) probably it is not so inspiring for regular python programmer. Lazy "streams" are a good thing provided they can be easily used for organizing data pathes and connections. > - `Cons` still requires lisp background but I don't know any name > that would be recognizable to non-lispers anyway. And it's not > a bad name. Construct, Glue, Merge? Taken readability any whole word is better. > - I called the operation for creating new iterator from same place > "forking". Alternative names: `split`, `copy`, `clone`, `dup`, > "lookahead", etc. What's best? copy is already using construct in python. Why not use it? > - Anything else anybody needs? If I got the intend of Stream correctly, I wish use them as Tcl streams, so I'd need combining and filtering and i/o. Just 0.02 Mike From kfettig at state.nd.us Thu Jul 24 14:58:11 2003 From: kfettig at state.nd.us (Ken Fettig) Date: Thu, 24 Jul 2003 13:58:11 -0500 Subject: Tokenize Message-ID: <8%VTa.133$313.72262@news.uswest.net> Does Python have an equivelent to the Java StringTokenizer? If so, what is it and how do you implement it? Thanks Ken Fettig kenfettig at btinet.net kfettig at state.nd.us From aahz at pythoncraft.com Sat Jul 12 10:40:34 2003 From: aahz at pythoncraft.com (Aahz) Date: 12 Jul 2003 10:40:34 -0400 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: <3F0FC088.3C56EDEA@alcyone.com> Message-ID: In article <3F0FC088.3C56EDEA at alcyone.com>, Erik Max Francis wrote: >Raymond Hettinger wrote: >> >> ACT III -------------------------------------------- >> >>> class Prohibited(Exception): >> ... def __init__(self): >> ... print 'This class of should never get initialized' >> ... >> >>> raise Prohibited() >> This class of should never get initialized >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> raise Prohibited() >> Prohibited: >> >>> raise Prohibited >> This class of should never get initialized >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> raise Prohibited >> Prohibited: > >Is this some IDLE-specific thing? Nope, the point here is that raise Prohibited will always create a Prohibited() instance. (See also Peter's post about One True Way for exceptions.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From ta-meyer at ihug.co.nz Sun Jul 20 20:18:56 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 21 Jul 2003 12:18:56 +1200 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F89E8@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AB6B@its-xchg4.massey.ac.nz> > > > 3) When "WRITE-IN CANDIDATE" is selected, a large widow > > > (maybe the full screen) will pop up with a QWERTY keyboard > > > in the upper half. This keyboard > > > will have only three rows with the alpha keys (no punctuation or > > > numbers needed except for perhaps the hyphen... no shift, all CAPS). > > > > No apostrophe? What if I want to vote for "O'Reilly" > > > As a matter of fact, we won't let you vote for O'Reilly. On > second thought, you're right, I guess. Okay we'll have an > apostrophe available. Anything else? What about non-English names? Names with umlauts, accents, Asian characters, and so on? =Tony Meyer From tim.harford at rogers.com Sun Jul 6 14:44:42 2003 From: tim.harford at rogers.com (Tim) Date: Sun, 06 Jul 2003 18:44:42 GMT Subject: help! - cmd line interpreter gone "dumb" Message-ID: Maybe I've been working too long, but has anyon had their python interpreter stop taking commands. The IDLE version works fine, but under Windoze: 1) execute "python" in teh command shell 2) ...interpreter comes up fine 3) type in anything and you get "SyntaxError: invalid syntax" Literally, you could type in "import sys" or anything common and you get the same results. Any help greatly appreciated--thanks. Tim From jschilens at seawest.com Fri Jul 18 08:34:38 2003 From: jschilens at seawest.com (Schilens, Jeremiah) Date: Fri, 18 Jul 2003 08:34:38 -0400 Subject: activex unhandled data type error Message-ID: Hello, I'm using Python as an asp language and I've run into an error. I'm trying to import MySQLdb and I get this error on the web page: Error Type: Python ActiveX Scripting Engine, ASP 0106 (0x80020009) An unhandled data type was encountered. /computers/test.asp, line 5 Line 5 is just the import statement. Does anyone know how to fix this or know of another way that works to query a mysql database? Thanks, Jeremiah From woodsplitter at rocketmail.com Fri Jul 18 09:00:16 2003 From: woodsplitter at rocketmail.com (David Rushby) Date: 18 Jul 2003 06:00:16 -0700 Subject: Create another Excel instance References: <9ee55987.0307101339.701965a7@posting.google.com> <9ee55987.0307111159.6978676e@posting.google.com> Message-ID: <7876a8ea.0307180500.11e370d4@posting.google.com> yvan_charpentier at hotmail.com (yvan) wrote in message news:<9ee55987.0307111159.6978676e at posting.google.com>... > Basically, my problem is that the object uses the same process > if an instance of Excel already exists. > How can i create the new instance in a different process? I just encountered the same problem. How about this as a solution? --------------------------------------------------------------- # For an explanation of makepy and gencache, see: # http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html # (Chapter 12 of _Python Programming on Win32_) from win32com.client import gencache gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, 2) xlApplicationClass = gencache.GetClassForProgID('Excel.Application') # Create a new instance of the Excel.Application class--don't reuse an # existing instance. xlApp = xlApplicationClass() xlApp.Visible = False xlApp.DisplayAlerts = False try: wbk = xlApp.Workbooks.Add() sht = wbk.Sheets(1) sht.Cells(1,1).Value = 'blah' raise Exception('Deliberately raise an exc to test tidiness of cleanup.') finally: try: wbk.Close() del wbk except: pass xlApp.Quit() del xlApp --------------------------------------------------------------- From donn at drizzle.com Thu Jul 3 01:39:47 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 03 Jul 2003 05:39:47 -0000 Subject: Haskell distutils-type system References: Message-ID: <1057210786.171236@yasure> Quoth Isaac Jones : ... | One idea for this distribution system, which we're calling the Library | Infrastructure Project, is to create a nice gmake-based build system, | document it, and leave it at that. If it can be plain make, instead of gmake, that would be closer my idea of "nice". That has been one of Python's strengths since early on, easy to build on a variety of platforms and doesn't impose gratuitous requirements like needing GNU make or Perl (can you imagine?) | ... Another idea is to use a | Haskell-based Distutils type system. ... | What about configuration, do you typically interface with autoconf | somehow, or does distutils have its own way to figure out | configuration details? This is not one of distutils' strengths. I think the answer to both is "no" - there isn't any useful interface to autoconf, and it doesn't have a comparable ability to figure out configuration details. The path of least resistance would probably be something analogous to config.h.in, a config.hs.in that allows autoconfig to account for all the options and environmental variables. Donn Cave, donn at drizzle.com From ee01b092 at ee.iitm.ernet.in Thu Jul 17 02:59:36 2003 From: ee01b092 at ee.iitm.ernet.in (Vinoo Vasudevan) Date: 16 Jul 2003 23:59:36 -0700 Subject: Securing the Pyton Interpreter? References: Message-ID: <45f7ff62.0307162259.64acb832@posting.google.com> Steven Taschuk wrote in message news:... > Quoth Mel Wilson: > > seem to recall there are complications with suid on scripts > > .. though I don't recall what they are. > > A simple example: Let the file insecure_script contain > #!/bin/sh > grep 'f.*bar' $* > This script must not be made setuid-root. Consider: > $ cat >grep > #!/bin/sh > cp /etc/shadow . && chmod 0666 ./shadow > ^D > $ chmod +x ./grep > $ export PATH=.:$PATH > $ insecure_script > > You could deal with this particular problem by using absolute path > names for everything in the script, and/or by setting $PATH in the > script itself. [clip] I didn't see this post before I posted the one with the naive shell script. As clear as I can make it, the problem seems to be two-fold :- Not allowing normal users to access the python interpreter directly, and making sure they run only a certain set of scripts. One solution that may work is to set up the interpreter so that _only_ you have read and execute permissions(maybe installing it in your home directory), and then putting a shell script which has your UID but has read and execute permissions for all users in a commonly accessible place. The path to the interpreter and the python scripts must be absolute in this script to avoid security problems as mentioned above. Hope this works, Vinoo From martin at v.loewis.de Thu Jul 31 02:09:05 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2003 08:09:05 +0200 Subject: Ver 2.3 install over 2.2? References: <4c877253.0307301628.7d73a1a6@posting.google.com> Message-ID: garth at deadlybloodyserious.com (Garth T Kidd) writes: > Make sure you have VC6 installed, else you'll be unable to build extensions > for Python23. VC7 worked for building Python22 extensions, but no longer > (and if anyone can explain why, I'd love to know). VC7 did not work for building Python22 extensions. You end up linking different versions of the CRT, and as soon as you pass FILE* from the extension to Python, you get crashes. Regards, Martin From intentionally at blank.co.uk Sun Jul 13 17:41:20 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Sun, 13 Jul 2003 22:41:20 +0100 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: On Sun, 13 Jul 2003 17:16:08 -0400, "Terry Reedy" wrote: >> You could use the same argument to rationalise a language which used >> the + operator to express subtraction. > >Bogus comparison with name binding. I am not aware that Python does >anything quite so backwards. Using an exaggeration as an analogy. Possibly. Though terms like 'assignment', 'variable' and 'value' seems pretty fundamental to me, so the exaggeration is not that huge. >> The fact is that 'assignment' has a common meaning separate from the >> choice of programming language, and that the way Python handles name >> binding means that meaning is not respected by Python for mutable >> objects. > >From what others have posted, Python is not the only language in which >'name=object' means "assign 'name' to that object". This is much >closer to the common idea of object having names than the idea that >names can only name value holders (blocks of linear memory) and not >values or objects themselves. Many languages have *explicit* ways to create what computer science calls pointers. Sometimes they have implicit dereferencing. Sometimes they come prepackaged in a 'pointer to' or 'reference to' style object. But the fact that you are dealing with something that semantically behaves as a pointer is always explicit in some way or another. Or rather, it should be. The fact that a few other languages are broken in much the same way does not mean that Python is doing the right thing. The right thing does not mean imitating Java or whatever any more than it means imitating C++. If you want a good example to imitate, though, look to Haskell. I don't know how it binds variables to values, but I do know that in general it can't a simple mapping from identifier to memory location. Even so, I don't care. Why should I? The implementation of the binding is irrelevant - I only care that the value bound to the variable is the one that I specified and that it doesn't get changed behind my back. From pyth at devel.trillke.net Fri Jul 25 14:33:22 2003 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 25 Jul 2003 20:33:22 +0200 Subject: path module In-Reply-To: <1059155133.24478.10738.camel@lothlorien>; from ianb@colorstudy.com on Fri, Jul 25, 2003 at 12:45:33PM -0500 References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> Message-ID: <20030725203322.P6906@prim.han.de> Ian Bicking wrote: > Jason had walkers both for all files, just non-directory files, and > directory files. This seems useful to me, and by making it explicit I > might just start distinguishing text from binary (which I don't now > because I am forgetful). And a globbing walker, though I don't know how > much of an advantage that would be over list comprehension. Actually, > all his walkers have a globbing option. We currently only have one 'visit' method that accepts a filter for returning results and a filter for recursing into the tree. You can use and combine multiple filters like so: root = Path('...) for path in root.visit(AND(isdir, nolink)): # iterates over all non-link dirs in the tree (breadth-first) or for path in root.visit(AND(isfile, endswith('.txt')), nodotfile): # iterates over all '*.txt' files but not recursing into ".*" and so on. This proved to be flexible and convenient and mostly avoids the need for multiple walk-methods. cheers, holger From bokr at oz.net Fri Jul 18 00:53:43 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 04:53:43 GMT Subject: Regular expression help References: Message-ID: On Fri, 18 Jul 2003 04:31:32 GMT, David Lees wrote: >Andrew Bennetts wrote: >> On Thu, Jul 17, 2003 at 04:27:23AM +0000, David Lees wrote: >> >>>I forget how to find multiple instances of stuff between tags using >>>regular expressions. Specifically I want to find all the text between a >> >> ^^^^^^^^ >> >> How about re.findall? >> >> E.g.: >> >> >>> re.findall('BEGIN(.*?)END', 'BEGIN foo END BEGIN bar END') >> [' foo ', ' bar '] >> >> -Andrew. >> >> > >Actually this fails with the multi-line type of file I was asking about. > > >>> re.findall('BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') >[' bar '] > It works if you include the DOTALL flag (?s) at the beginning, which makes . also match \n: (BTW, (?si) would make it case-insensitive). >>> import re >>> re.findall('(?s)BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') [' foo\nmumble ', ' bar '] Regards, Bengt Richter From pronovic at skyjammer.com Tue Jul 22 17:57:36 2003 From: pronovic at skyjammer.com (Kenneth Pronovici) Date: Tue, 22 Jul 2003 21:57:36 GMT Subject: ANNOUNCE: WordUtils 0.7.0 released Message-ID: <20030722215959.GI6753@skyjammer.com> Version 0.7.0 of the WordUtils package is now available from: http://cedar-solutions.com/software/wordutils/ The WordUtils package provides pure-Python objects related to word searching and matching. The eventual goal is to develop a suite of objects that are suitable for building word games in the tradition of Scrabble (tm). All of the objects provide similar functionality with a similar interface, but are implemented in terms of different underlying data structures. Currently, objects implementing two different data structures are complete: the Dawg object, which implements a directed acyclic word graph, and the TernarySearchTree object, which implements a ternary search tree. The URL listed above contains further information about the package, as well as a link to Epydoc source code documentation for the package. The package requires Python 2.2 or better. It is distributed in Python distutils format and as a Debian .deb. It should be portable to all Python platforms, but has only been thoroughly tested under Debian GNU/Linux. A unit test suite is included. This is the first public release of the WordUtils package. From bokr at oz.net Sat Jul 5 17:11:04 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Jul 2003 21:11:04 GMT Subject: Bewildered graphs References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: On Sat, 05 Jul 2003 08:07:24 -0400, Mark Fenbers wrote: >This is a multi-part message in MIME format. >--------------3C30E07F2D1A81BA8EE2E6DB >Content-Type: text/plain; charset=us-ascii >Content-Transfer-Encoding: 7bit > >I am investigating Python for the sake of ultimately generating hydrographs >(such as this: http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) >on-the-fly from a web server cluster. I have not used Python previously and do >not yet know if Python is very useful for this or if I am wasting my time. > >Quite frankly, I am a little bewildered. Not only is there Python, but there >are many extention modules which cloud up my view as to what I will need. >There's Scientific Python, which sounds promising, but there's also SciPy which >in itself has gnuplot, xplt and plt modules. I know enough about gnuplot to >know that it won't meet my needs because I need to be able to shade regions >above certain values such as done in yellow on the example hydrograph (the link >above). It also doesn't have many font options or the ability to place an image >such as the NOAA logo. > >Can someone kindly guide me as to what I would most likely need to replicate the >graph shown via the link above? > Have you asked them what they use to generate it? If it's free software, chances are someone has done a Python interface (noaa.gov is paid for with taxes AFAIK, so it ought to be free at least for US citizens, IWT ;-) If not, it would at least make searching for a clone/workalike easier. Regards, Bengt Richter From bokr at oz.net Tue Jul 15 01:10:56 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2003 05:10:56 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: On Tue, 15 Jul 2003 00:22:15 +0100, Stephen Horne wrote: [...] >>> C++ references are tellingly also called self-dereferencing pointers. >>> They are not a distinct concept - they are syntactic sugar. I suspect >>> they mainly arise out of the modern desire to disguise pointers and >>> fantasize that they're not there, though they certainly work very well >>> in certain contexts. >> >>Syntactic sugar or no, they still behave differently than other >>datatypes and are therefore not consistent... IMHO. > >They behave exactly like pointers. You just use different notation to >get that behaviour. That is what makes them syntactic sugar. > BZZT. C++ references do not behave *exactly* like pointers. Try to make one point to a different place than it was initialized to point to. Regards, Bengt Richter From andreas.kuntzagk at mdc-berlin.de Wed Jul 2 06:54:48 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Wed, 02 Jul 2003 12:54:48 +0200 Subject: os.fork() different in cgi-script? Message-ID: Hi, following code: #!/usr/bin/python import os import sys def main(): print "Content-Type: text/plain\n\n" print os.getpid() childPID = os.fork() if childPID == 0: sys.exit() else: os.wait() if __name__ == "__main__": main() when run on a shell, gives the result: --------------------------- Content-Type: text/plain 20953 ---------------------------- but run as a cgi-script it gives: --------------------------- 21039 Content-Type: text/plain 21039 --------------------------- So it looks the main() is run 2 times. Is it so? And if yes, why? I googled for this but only found a similar question from 1997 and no answer. Ciao, Andreas From mwilson at the-wire.com Sun Jul 20 15:28:16 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 20 Jul 2003 15:28:16 -0400 Subject: [OT] sentances with two meanings References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <2259b0e2.0307170416.e2bc998@posting.google.com> Message-ID: In article <2259b0e2.0307170416.e2bc998 at posting.google.com>, mis6 at pitt.edu (Michele Simionato) wrote: >JanC wrote in message news:... >> mis6 at pitt.edu (Michele Simionato) schreef: >> > Now, Latin had to verbs for "to know": "scire" and "cognoscere". >> >> And "cognovisse". (I still have a latin dictionary too... :) > >Huh? "cognovisse" cannot be a verb, what would be the paradigma? Me too, but it's in Bantam's _The New College Latin & English Dictionary_. 'Cognovisse' seems to be some modification of cognoscere. No guidance as to use. Could it be some non-verbal form like 'To know it is to misunderstand it'? Regards. Mel. From psimmo60 at hotmail.com Wed Jul 2 09:32:09 2003 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 2 Jul 2003 06:32:09 -0700 Subject: My Big Dict. References: <20030702073735.40293ba2.christophe.delord@free.fr> Message-ID: <94974e1a.0307020532.1cb19956@posting.google.com> "Aur?lien G?ron" wrote in message news:... > "drs" wrote... > > "Christophe Delord" wrote in message > > news:20030702073735.40293ba2.christophe.delord at free.fr... > > > Hello, > > > > > > On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote: > > > > I need advice on how I can convert a text db into a dict. Here is an > > > > example of what I need done. > > > > > > > > some example data lines in the text db goes as follows: > > > > > > > > CODE1!DATA1 DATA2, DATA3 > > > > CODE2!DATA1, DATA2 DATA3 > > > > Any idea on how I can convert 20,000+ lines of the above into the > > > > following protocol for use in my code?: > > > > > > > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'} > > > > > > > > > > If your data is in a string you can use a regular expression to parse > > > each line, then the findall method returns a list of tuples containing > > > the key and the value of each item. Finally the dict class can turn this > > > list into a dict. For example: > > > > and you can kill a fly with a sledgehammer. why not > > > > f = open('somefile.txt') > > d = {} > > l = f.readlines() > > for i in l: > > a,b = i.split('!') > > d[a] = b.strip() > Your code looks good Christophe. Just two little things to be aware of: I think I'm right in saying Christophe's approach was using the 're' module, which has been snipped, whereas the approach was the above using split was by "drs". > 1) if you use split like this, then each line must contain one and only one > '!', which means (in particular) that empy lines will bomb, and also data > must not contain any '!' or else you'll get an exception such as > "ValueError: unpack list of wrong size". If your data may contain '!', > then consider slicing up each line in a different way. If this is a problem, use a combination of count and index methods to find the first, and use slices. For example, if you don't mind two-lined list comps: d=dict([(l[:l.index('!')],l[l.index('!')+1:-1])\ for l in file('test.txt') if l.count('!')]) > 2) if your file is really huge, then you may want to fill up your dictionary > as you're reading the file, instead of reading everything in a list and then > building your dictionary (hence using up twice the memory). Agreed. The above list comprehension has the disadvantages that it finds how many '!' characters for every line, and it reads the whole file in at once. Assuming there are going to be more data lines than not, this is much faster: d={} for l in file("test.txt"): try: i=l.index('!') except ValueError: continue d[l[:i]]=l[i+1:] It's often much faster to ask forgiveness than permission. I measure it about twice as fast as the 're' method, and about four times as fast as the list comp above. HTH, Paul > > But apart from these details, I agree with Christophe that this is the way > to go. > > Aur?lien From ben at dadsetan.com Tue Jul 15 14:40:50 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Tue, 15 Jul 2003 19:40:50 +0100 Subject: Waiting for processes to finish under Solaris Message-ID: <3F144AB2.10703@dadsetan.com> Hi all, please note that once I finished writing the script someone explained me that there is a command pwait under Solaris... anyway it was fun to write and it did not take long (while I am not a python guru..). And my version is MUUUCH better :) Is there no standard interfaces to the process table? I only found examples of how to do it on the win32 platform. So I parse with re the output of /usr/ucb/ps... Because I am still at the begining of learning python, I wanted to have some advice here how I could have done the following code better... Thanks in advance, Ben. ------waitPID.py--------------------------------------------- #!/usr/local/bin/python import os import time import re import getopt import sys def usage(): print >>sys.stderr, sys.argv[0] + " Usage" print >>sys.stderr, """waits until the specified processes have finished -r | --regexp= will watch the processes matching with at their beginning -p | --pid= will watch the processes with the pid -h | --help will display this screen """ try: opts, args = getopt.getopt(sys.argv[1:], "hr:p:", ["help", "regexp=", "pid="]) except getopt.GetoptError: usage() sys.exit(2) regexps = [] pids = [] for o, a in opts: if o in ("-r", "--regexp"): regexps.append(re.compile('^' + a)) if o in ("-p", "--pid"): pids.append(a) if o in ("-h", "--help"): usage() sys.exit() def ps(): stdout = os.popen("/usr/ucb/ps -auxwwww") allprocesses = stdout.readlines() stdout.close() return allprocesses _psline = re.compile(r"^(\S{1,10})\s*(\d+)\s+(\d+\.\d+)\s+(\d+\.\d{1,2})\s*(\d{1,6})\s *(\d{1,8})\s+(\?|\S+)\s+([A-Z])\s+(\d+:\d+:\d+|\S\S\S \d+)\s+(\d+:\d+)\s+(.*)$") def splitpsline(line): match = _psline.search(line) if match: owner, pid, cpu, mem, sz, rss, tt, s, start, time, command = match.groups() return owner, pid, cpu, mem, sz, rss, tt, s, start, time, command watchedforpids = {} processesmatrix = [ p for p in map(splitpsline, ps()) if p ] for owner, pid, cpu, mem, sz, rss, tt, s, start, cputime, command in processesmatrix: basenamecmd = os.path.split(command)[1] for watchedpid in pids: if watchedpid == pid: watchedforpids[pid] = command for watchedforcmd in regexps: if watchedforcmd.search(command) or watchedforcmd.search(basenamecmd): watchedforpids[pid] = command while 1: time.sleep(2) foundpids = {} processesmatrix = [ p for p in map(splitpsline, ps()) if p ] for owner, pid, cpu, mem, sz, rss, tt, s, start, cputime, command in processesmatrix: for watchedpid in watchedforpids.keys(): if watchedpid == pid: foundpids[pid] = command if not foundpids: break print for pid, command in foundpids.items(): print "PID[%s]:COMMAND[%s] still alive" % (pid, command) time.sleep(58) ------------------------------------------------------------------------------ From ianb at colorstudy.com Tue Jul 22 23:19:16 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 22 Jul 2003 22:19:16 -0500 Subject: How does Mr. Martelli's Borg recipe work ? In-Reply-To: <764b8294.0307221520.18017b09@posting.google.com> References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: <1058930355.28096.6402.camel@lothlorien> On Tue, 2003-07-22 at 20:37, Mars wrote: > I have looked long and hard at Mr. Martelli's Borg recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 > > It is a very useful substitute for a Singleton, but I can't figure out > how it works. While I don't want to discourage you from learning more about the internals of Python objects (certainly a worthwhile goal), "singletons" are usually thought about too hard by people new to Python. This is a good way to make a singleton: class _Something: ... TheSomething = _Something() Then just never refer to _Something again. Import TheSomething (calling it whatever you want), and use it, not its class. It's a singleton because there's only one of them. Simplicity! Ian From belred1 at yahoo.com Wed Jul 23 23:17:30 2003 From: belred1 at yahoo.com (Bryan) Date: Thu, 24 Jul 2003 03:17:30 GMT Subject: file.close() Message-ID: i'm curious to know how others handle the closing of files. i seem to always end up with this pattern even though i rarely see others do it. f1 = file('file1') try: # process f1 finally: f1.close() which explicitly closes f1 or for multiple files: f1 = file('file1') try: f2 = file('file2') try: # process f1 & f2 finally: f2.close() finally: f1.close() which explicitly closes f1 & f2 any exceptions opening f1 or f2 is handled outside of this structure or is allowed to fall out of the program. i'm aware that files will automatically be closed when the process exits. i'm just curious how others do this for small scripts and larger programs. is what i'm doing is overkill? thanks, bryan From martin at v.loewis.de Sun Jul 20 17:16:39 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Jul 2003 23:16:39 +0200 Subject: xml processing and sys.setdefaultencoding References: Message-ID: "christof hoeke" writes: > using non-ascii characters was a problem. so i set the defaultending to > UTF-8 and now everything works (at least it seems so, need to do more > testing though). Can you please be more precise as to what problem exactly you have observed? Regards, Martin From ajs at optonline.net Sat Jul 5 10:40:43 2003 From: ajs at optonline.net (Arthur) Date: Sat, 05 Jul 2003 09:40:43 -0500 Subject: Least used builtins? Message-ID: <001901c34303$6a61e7f0$1a02a8c0@BasementDell> Lulu writes - >Yet a fourth matter is that I think it would be slightly easier to teach >Python to beginners if __builtins__ did not include a number of >functions that were extremely difficult to explain to novices... and >that are really only of use to fairly expert Pythoneers. I find that >callable, classmethod, id, intern, and a number of others fall in this >category. My thinking is that anything meant for experts should need to >get imported by specific request. Python and beginners. As usual where I feel qualified to pop-up with a position. My experience was such that, in retrospect, the only place I feel Python "betrayed" me as someone learning to program with Python and outside of a formal curricula, was in the *absence* of a built-in - "copy". To me, that absence left a conceptual hole in the core (not filled, I contend, by the availability of list[:]). I don't think it is necessary to elaborate in too much detail as to the why the issue is an issue. The full implications of moving something like copy to become a built_in is not something I pretend to have a handle on. As to the limited question, effect on learning (especially self-directed learning) - I believe I have a point. Guido's position seems to be that the presence of copy as a built-in would lead to its overuse by the newbie. My counter-position is that it necessary to understand why one is not using it, and that can only happen if one understand it exists. The thinking along the lines of a more limited set of built_ins might actually serve some resolution of the issue - at least to the extent it is an issue, beyond my own perception of the matter. That is, one will understand sooner that there is functionality conceptually "fundamental", that might not exist in __builtins__. I also happen to agree with the direct point being made. As I happen to be working on a short tutorial for an app, which assumes no prior knowledge of Python. And one the the first things I do - maybe 10 lines into the tutorial - is a dir(__builtins__) from the interactive prompt. Just to give some lay of the land. Three or four years into Python, and I do notice there are a number of items I can't explain to myself, much less to sombody else. And have gotten a fairly long way along writing acutal working apps, with the "more fundamental" subset of __builtins_ which are in common use. This whole area, I think, deserving of attention - especially as I do think something siginificant might be accomplished without really disturbing anything. And perhaps the concept of whittling down the _builtins__, makes more sense than the addition of a new built-in, as I had been advocating. And would accomplish something along the lines that my experience indicates to be advisable - i.e., with respect to "copy" Art From max at alcyone.com Tue Jul 15 20:34:31 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Jul 2003 17:34:31 -0700 Subject: [OT] sentances with two meanings References: Message-ID: <3F149D97.C8192A2@alcyone.com> Syver Enstad wrote: > Does "to know" in english also mean to feel someone? In my own > language > the direct translation of the english know also means to feel. I could > say (translated) "I know the cold", meaning I feel the cold > weather. I don't know that usage. (Har, har.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Nine worlds I remember. \__/ Icelandic Edda of Snorri Sturluson From rastm2 at aol.commorespam Sat Jul 26 23:59:31 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 27 Jul 2003 03:59:31 GMT Subject: Del's "except"ional PEP Rejection Message-ID: <20030726235931.05032.00000547@mb-m26.aol.com> Del's "except"ional PEP Rejection Ladieees and Gentilmen and Pyth-O-neers of all ages. Step right up. Don't be shy. Come one come all. Be the first on your block TO GROK *THE* one *THE* only Exception you won't find any where but here! The Exception that's Exceptional! It's the "elif from lamdba except" Exception. (The only Exception that don't need an "except" clause, Because it *IS* one.) It's the story of Del, an intermitantly deaf, intermitantly nauseated importation executive with Print Global Inc. Del's a company man, and the 150 year old, family owned company needs someone to lead them all into the 21'st Century. Having over heard... ( It's amazing how some people who seem deaf at times can hear things from what was supposed to be a closed door meeting between ) ...the VP of Statis talking down to the 85 year old Chief of Data Processing ... ( History Note--that's what they used to call them you know -- worked his way up from crank turner -- but I digress ) ... what was I saying oh yeah Del over heard the VP telling the old guy, "Hell, my 12 year kid stuck *some* kinda snake, wait it was a python, yeah he stuck a python in an old Apple II that was in the attic a week ago Sunday and started typeing like mad and by Thursday he was telling me that he had gone GLOBAL and wouldn't need his allowance anymore. No it's time to upgrade. Shut down the ENIAC." Cut to the "ever butt kissing" Del, half deaf, sitting in Python school. Well, sorta sitting 'cuz' Del's got bowel problems and he needs another pass from the Instructor to go to the lav. Sitting on the pot, like a splash, a thought hits him. ( gosh I hope it was just a thought ) Ya see, Dan didn't just volenteer for this mission, he was holding back from the company. He new a litte "c" code. Just enough to be dangerous, and it made him sick to his stomach. But this Python Language! He truely understood and liked what he was learing. Python was indented so you could read it like a self respecting human being. It was impressive to him, the way you could write your code in the interpreter, and did't have to declare anything or agonize while you waited to see if it worked. He liked the way "elif" statements made case switches easier to code and understand. How "from" this "import" that made code re-usable. How "lamda" could define a function in a function without having to define a function for a function. How exceptions could be used to make programs that worked the first time. He loved the "while loops" and the list comprehensions that had little "for loops" and "if"s in them. He like how any one on the planet, with enough money to maintain a computer and an internet connection, could just be so very proud that they had their PEP rejected by the most intelligent, helpful, thoughtful, and kindest people on Earth. Sitting right there on the throne of inspiration he came up with the only exception that uses all the keywords, types all in one color in the editor, and makes sense to only him, so he sent in a PEP to be rejected... wait for it wait for it Bam! The elif from lambda except: statment elif from lambda except: while del is not def: [import exec for print global] try: and continue or else: return break pass in class finally: yeild if assert *PYTHON* *THE*WAY *GUIDO* *INDENTED* *IT*TO*BE* By Raymond St. Marie (Rastm2 at aol.com -- don't laugh, it's been free since I lost my job in January) From abbeflabbe at InospamIhotmail.com Fri Jul 18 13:43:18 2003 From: abbeflabbe at InospamIhotmail.com (Linkages) Date: Fri, 18 Jul 2003 17:43:18 GMT Subject: gui References: Message-ID: Il Fri, 18 Jul 2003 20:16:35 +0950, Ben Finney ha scritto: > On Fri, 18 Jul 2003 05:19:35 GMT, Linkages wrote: >> a good GUI for linux ? > > XFree86 is a pretty good one. > > > > Did you have something more Python-specific in mind? yes a had :)) bye bud linka From tchur at optushome.com.au Wed Jul 9 16:12:23 2003 From: tchur at optushome.com.au (Tim Churches) Date: 10 Jul 2003 06:12:23 +1000 Subject: python + cluster computing In-Reply-To: References: Message-ID: <1057781543.1171.10.camel@emilio> On Thu, 2003-07-10 at 00:27, Uwe Schmitt wrote: > Hi, > > I found several Python bindings for the MPI protocol, > can anybody report some opinions and experiences ? Peter Christen and I have used Ole Nielsen's PyPar package (see http://datamining.anu.edu.au/~ole/pypar/) in our Febrl probabilistic record linkage engine (see http://datamining.anu.edu.au/projects/linkage.html) with excellent results. I have also been experimenting with its use in a parallel data summarisation engine. It is easy to install and is very easy to use, mainly because it only wraps a small portion of MPI - but just those parts you really need (at least we haven't missed anything yet). Its ability to pass any picklable Python object around the cluster is a real bonus, and the speed at which it passes Numeric Python arrays using "raw" mode is very impressive. Ole is also very helpful, and is actively involved in parallel computing work on a daily basis (using PyPar, no doubt). -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bignose-hates-spam at and-zip-does-too.com.au Thu Jul 3 00:57:04 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Thu, 03 Jul 2003 04:57:04 GMT Subject: Copying files in Python References: Message-ID: On Thu, 03 Jul 2003 03:26:33 GMT, Russell Lear wrote: > A simple question from a python beginner: How do I do 'cp -p source > destination' where source could be a list of files and destination > could be a file or directory (I could break the operation up if it > must be file to file)? Perserving file creation time is important. > Platform independence also nice. The 'shutil' module is your friend: -- \ "Truth would quickly cease to become stranger than fiction, | `\ once we got as used to it." -- Henry L. Mencken | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ianb at colorstudy.com Wed Jul 23 20:49:43 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 23 Jul 2003 19:49:43 -0500 Subject: ndiff In-Reply-To: References: Message-ID: <1059007783.28094.8013.camel@lothlorien> On Wed, 2003-07-23 at 18:55, Bryan wrote: > 3. is there a simple method that just returns true or false whether two > files are different or not? i was hoping that ndiff/compare would return an > empty list if there was no difference, but that's not the case. i ended up > using a simple: if file1.read() == file2.read(): but there must be a smarter > faster way. Maybe something like: def areDifferent(file1, file2): while 1: data1, data2 = file1.read(1000), file2.read(1000) if not data1 and not data2: return True if data1 != data2: return False You still have to go through the entire file if you really want to be sure. If you use filenames, of course, you can take some shortcuts: def filesDiffer(filename1, filename2): if os.stat(filename1).st_size != os.stat(filename2).st_size: return False else: return areDifferent(open(filename1), open(filename2) You could also try a quick comparison from somewhere not at the beginning (using .seek(pos)), if you think it is likely that files will have common headers. But you'd still have to scan the entire file to be sure. Ian From dexter at socha.net Mon Jul 28 07:13:06 2003 From: dexter at socha.net (Matthias Wiehl) Date: Mon, 28 Jul 2003 13:13:06 +0200 Subject: List Question References: Message-ID: <79lluioqf1.fsf@buug.mind.de> "Bill Loren" writes: > Assume I have a list named heck_of_a_list. > > how would I extract the number of elements out of?it ? len(heck_of_a_list) From martin at v.loewis.de Fri Jul 11 19:33:03 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 Jul 2003 01:33:03 +0200 Subject: Windows XP - Environment variable - Unicode In-Reply-To: <3f0ed1ba@epflnews.epfl.ch> References: <3f0ed1ba@epflnews.epfl.ch> Message-ID: sebastien.hugues wrote: > So the question is how to get the default encoding of the system ? On Windows, the system encoding is always called "mbcs". Actually, there are two system encodings: the ANSI code page (CP_ACP), and the OEM code page (CP_OEMCP). "mbcs" is CP_ACP. CP_ACP is used everywhere except in terminal windows and when encoding FAT file names on disk. Regards, Martin From andrew-pythonlist at puzzling.org Wed Jul 2 08:59:25 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 2 Jul 2003 22:59:25 +1000 Subject: Assign to True / False in 2.3 In-Reply-To: <3F02ADD3.6047F561@alcyone.com> References: <3F02ADD3.6047F561@alcyone.com> Message-ID: <20030702125925.GC17479@frobozz> On Wed, Jul 02, 2003 at 03:02:59AM -0700, Erik Max Francis wrote: > Culley Angus wrote: > > > I was a little suprised to find that I could assign a value to 'True', > > and 'False' without warning though, and was wondering if this is > > deliberate. > > This is true of pretty much all Python features. The only special > dispensation goes to None, which is a warning now (in the 2.3 beta): > > Python 2.3b2 (#1, Jun 29 2003, 20:30:58) > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> None = 0 > :1: SyntaxWarning: assignment to None Incidentally, the reason why a SyntaxWarning isn't raised for True and False is that there is a lot of existing code for older pythons that do tricks like: True = (1 == 1) False = not True Or something similar, and the Python team didn't want to break code, or cause spurious warnings for code that might otherwise work perfectly well with 2.3 and 2.2 or even 1.5.2 (depending on what else it did, of course). -Andrew. From BartolomeSintes at ono.com Sun Jul 20 05:48:33 2003 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Sun, 20 Jul 2003 09:48:33 GMT Subject: non-ASCII characters IDLE 1.0 rc1 bugs Message-ID: Hi, I have downloaded and installed Python 2.3 RC1 in a Windows 98 SE computer. IDLE 1.0 does not work very well: a) When I open with IDLE 1.0 RC1 a program written with IDLE 0.8, non-ASCII characters (like voyels with accents) are changed to wrong characters. b) If a program has non-ASCII characters, save or save as work when a new file is created, but if I open a file with non-ASCII characters and I modify it, then I can not save it (neither save it as). Do you know if these problems will be adressed before 2.3 final or I have to configure something to solve these problems? Thanks, Barto P.S.: I am Spanish, so I use several non-ASCII characters... From vze4rx4y at verizon.net Wed Jul 23 15:02:41 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 23 Jul 2003 19:02:41 GMT Subject: Python Mystery Theatre -- Episode 3: Extend this References: <3f1ea08e_2@corp-news.newsgroups.com> Message-ID: [Chris Reedy] < > I tried these out myself after making my guesses. Here's what I found: [Raymond] > > def real(z): > > return hasattr(z, 'real') and z.real or z > > def imag(z): > > return hasattr(z, 'imag') and z.imag or 0 > > for z in 3+4j, 5, 0+6j, 7.0, 8+0j, 9L: > > print real(z), imag(z) [Chris] > I spotted the error in this one (I've been bitten by this more than > once) if z.real or z.imag is false, I get z or 0. That results is two > problems: > > For 0+6j, the answer is 6j and 6.0, definitely not what was expected. > For 8+0j, the answer is 8.0 and 0, not 8.0 and 0.0. This is close to > what was expected and, if a bug at all, would be a rather subtle one. > > I would certainly expect that Raymond's been bitten by this one. I would > guess that every experienced Python programmers been bitten by some form > of this one. Yes, this snippet came directly from an early version of my matrix algebra tool that has been in production for several years. It is essentially the class mistake with and/or. The code has been replaced with a try: except AttributeError:. The point of the code was to allow complex operators to be applied to a matrix of mixed types and only coerce to complex when necessary. > > ACT II --------------------- > > uniq = {} > > for k in (10, 'ten', 10+0j, u'ten', 'Ten', 't'+'en', 10.0): > > uniq(k) = 1 > > print len(uniq) > > I had to experiment with this one. I guessed 3, which turned out to be > right. I was a little surprised that 'ten' and u'ten' hash the same. > However, after thinking about that, I decided I was happy with that result. > > I was more surprised that 10 and 10.0 came out the same. One of these > days I'll take the time to look up the hash algorithm for floats to see > how this was achieved. The lesson is that objects that compare equal are expected to hash equal. Since 10 == 10+0j == 10.0, they will hash to the same value. Since 'ten' == u'ten' == 't'+'en', they will hash to the same value. Since 'Ten' does not compare equal to the others (case-sensitive), it is distinct. > > ACT III --------------------- > > s = 'abracadabra' > > for i in [3, 2, 1, 0]: > > print s[i:], s[-i:] > > Got this one the first time. -0 == 0, so s[-0:] == s[0:] == s. I'll bet > that this is one that burned Raymond. Yes. This came-up in an early version of random.shuffle. I was looping backwards over an array and was choosing samples from the range [0:-i]. The error did not surface in testing because an alternate selection method is used in cases that include i==0. The aspiring bug was caught by Tim during a code review. Things like this are particularly hard to spot when your comprehensive test code runs flawlessly. > > > ACT IV --------------------- > > pets = list('cat ') > > pets += 'dog ' > > pets.extend('fish ') > > print pets + 'python' > > I guessed ['c', 'a', 't', ' ', 'd', 'o', 'g', ' ', 'f', 'i', 's', 'h', ' > ', 'p', 'y', 't', 'h', 'o', 'n']. I tried it to discover that the print > statement at the end throws. I decided that not concatenating strings to > lists doesn't bother me since I would believe that this is an error > more often than not and pets + list('python') would hopefully make the > intent clear. That is in-fact the reason for it throwing an exception. > On the other hand, if I saw pets = list('cat') in code I > was reviewing I suspect that I would want to assure myself that ['c', > 'a', 't'] was what was intended and not ['cat']. That is a proper reaction to a code smell. > I also much bothered by pets += 'dog ' working but pets + 'python' not. > What's the justification for the checking in one place and not the other? Because, as you pointed out, the second form is often an error but the first is usually intended. Also, I think the += behavior got set in stone before the difference between the two was noticed. > > INTERMISSION (with output included, oh yeah! ------------ > > > >>>>import operator > >>>>1 - reduce(operator.add, [1e-7]* 10**7) > > > > 2.4983004554002264e-010 > > Round off error. Welcome to the world of floating point arithmetic! Representation error amplified by the instantaneous relays of the computer (phrase from StarTrek). The important point is that errors in the last bit can accumulate rather than cancel. > I predicted that the > result of both print statements would be: > > 5 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] > > When I tried it I got: > > 2 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] > 3 ['shirt', 'bananas', 'nuts', 'socks', 'pretzels'] > > After thinking about it (and reviewing the Reference Manual), I realized > that self.contents += items does an in place update of Bin.contents, but > the augmented assignment self.numitems += 1, is the same as > self.numitems = self.numitems+1 (since there is no in place update for > integers or immutable objects in general), which has the result of > creating the attribute numitems on the laundry and groceries instances. An in-place add is really a read and a write. The read finds the name in the enclosing scope and the write puts the result in the local scope. That is why the numitems count works. But for mutables, the in-place add modifies the existing copy which happens to be shared by both instances. > > ACT VI ----------------------------------------- > > print "What is the technical name for this algorithm or transformation?" > > a = range(0, 100, 10) > > import random > > random.shuffle(a) > > print "Input:", a > > swaps = 0 > > for i in range(len(a)): > > for j in range(i+1, len(a)): > > if a[i] > a[j]: > > i, j, a[i], a[j], swaps = j, i, a[j], a[i], swaps+1 > > print "Output:", a > > print "Workload;", swaps > The assignment i,j, ... = j,i, ... . Kept me guessing. Why do that? I gave to much a clue here. > At this point I convinced myself that this was an interchange sort gone > wrong and would just produce garbage. When I tried it, I discovered that > the correct technical name for this program is the identity > transformation. That is, nothing happened. Yes. Identity is real answer. Selection sort was the bait answer. > > Reexamining the code, I realized that flipping the two indices has the > effect of assigning the two array elements back to themselves, resulting > in no effect. > > About this point in time, I also realized that the sort should work if > you take away the spurious assignments to i and j. That is, > > a[i], a[j], swaps = a[j], a[i], swaps . . . > What's the real lesson here? Unfortunately, the example was too simple in that the i, j interchange was superfluous. I should have used the indices in a subsequent line, so that folks would be guided to the more interesting fix: a[i], a[j], swaps, i, j = a[j], a[i], swaps+1, j, i The point of the exercise was to note that the order of arguments on the left-hand side matters -- they are assigned left to right. The right hand side gets evaluated first (in left-to-right order), the results are saved in a tuple, then the left hand assignments are made one by one. If one of the assignments changes an index or key, the subsequent assignments are affected. > OK, which three did Raymond personnally stumble over. I'll guess I, III, > and VI. Why VI? Well, because V, while subtle in some ways, doesn't look > to me like one you'd run into until you knew what you were doing, at > which point: why this missing __init__ method. VI looks like something > you might do by accident while trying to write a sort routine. You guessed exactly right; however, number VI is a contrived example. The actual code was a heap sort demo derived from from logic assertions and program transformations. Multiple assignment is frequently used in the type of design so that invariants are maintained at every step. > Chris Great job. Nice analysis. Also, I enjoyed the playful exploratory style which captured the spirit of what the mystery series is all about. Raymond Hettinger From spam at rjs.org Tue Jul 1 02:44:30 2003 From: spam at rjs.org (RJS) Date: Tue, 01 Jul 2003 06:44:30 GMT Subject: problem w/ numarray & py2exe... Message-ID: Hi all, I can't get a py2exe compiled app to run with numarray (numarray-0.5.win32- py2.2). Also wxPythonWIN32-2.3.3.1-Py22 and ActivePython-2.2.1-222. In the sample below, commenting out "import numarray" allows the exe to run. Left in, I get "4.exe has generated errors" etc. I'm going around and around and there isn't much on Google. py2exe output is last. With "Python 4.py" from the shell, all is well. Any ideas? Older numarray? Numeric? Ray http://rjs.org ############################### setup.py ############# from distutils.core import setup import py2exe setup(name="tf.4", scripts=["4.py"], ) ############################# 4.py code ################ from wxPython.wx import * import numarray import array import operator from random import Random ID_STUB = 10 ID_IMPORT_XRC = 100 ID_PLOT = 111 ID_TRAIN = 122 ID_EXPORT_ONEREV= 124 ID_EXIT = 199 ID_ABOUT = 141 ############################# Class defs ############################# class MainFrame(wxFrame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(800, 400)) if wxPlatform == '__WXMSW__': self.icon = wxIcon('imagery/rotor.ico', wxBITMAP_TYPE_ICO) self.SetIcon(self.icon) self.Centre(direction = wxBOTH) self.CreateStatusBar() self.SetStatusText("Status: ready") ## create the menubar fileMenu = wxMenu() fileMenu.Append(ID_IMPORT_XRC, "Import &*.xrc", "Import an xrc data file") fileMenu.AppendSeparator() fileMenu.Append(ID_EXPORT_ONEREV, "&Export", "Export One Rev data") fileMenu.AppendSeparator() fileMenu.Append(ID_EXIT, "E&xit", "Terminate the program") toolsMenu = wxMenu() toolsMenu.Append(ID_STUB, "Color", "Change the color scheme") toolsMenu.AppendSeparator() toolsMenu.Append(ID_PLOT, "Plot", "Plot the data") toolsMenu.Append(ID_TRAIN, "Train", "Train on the data") helpMenu = wxMenu() helpMenu.Append(ID_STUB, "&Help", "Index and glossary") helpMenu.AppendSeparator() helpMenu.Append(ID_ABOUT, "&About", "More information about this program") menuBar = wxMenuBar() menuBar.Append(fileMenu, "&File"); menuBar.Append(toolsMenu, "&Tools"); menuBar.Append(helpMenu, "&Help"); self.SetMenuBar(menuBar) EVT_MENU(self, ID_IMPORT_XRC, self.OnImportXRC) EVT_MENU(self, ID_PLOT, self.createPlot) EVT_MENU(self, ID_TRAIN, self.OnTraining) EVT_MENU(self, ID_EXPORT_ONEREV, self.OnExport) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.ExitFrame) ##### create and add notebook pages #################################################################### self.nb = wxNotebook(self, -1) self.fontObj = wxFont(11, wxMODERN, wxNORMAL, wxNORMAL, false) def OnAbout(self, event): dlg = wxMessageDialog(self, "Welcome to\n" "Turbine v.1\n", "Welcome", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() self.nb.DeletePage(0) def ExitFrame(self, event): self.Close(true) # ---------------------------------------------------------------------- ------------------ # handlers. # ---------------------------------------------------------------------- ------------------ def OnImportXRC(self, event): self.dataPoints = 5000 # open the header file dlg = wxFileDialog (self, "Select the XRC file for import", "data", "", "*.xrc", wxOPEN) if dlg.ShowModal() == wxID_OK: try: self.filePath = dlg.GetPath() except IOError: dlg_m = wxMessageDialog (self, 'There was an error opening the new xrc file.', 'Error!', wxOK) dlg_m.ShowModal() dlg_m.Destroy() dlg.Destroy() def createDataArray(self): # create the XRC tabs self.nb.xrcHeader = wxTextCtrl(self.nb, -1, "",wxPoint(0, 0), wxSize(75, 20), wxTE_MULTILINE|wxTE_RICH ) self.nb.xrcHeader.SetStyle(0, self.nb.xrcHeader.GetLastPosition(), wxTextAttr("BLACK", wxNullColour, self.fontObj)) self.nb.AddPage(self.nb.xrcHeader, "XRC Header: "+self.filePath) self.nb.xrcHeader.LoadFile(self.filePath) def createPlot(self, event=NULL): plotWidthPoints = 5000 def OnExport(self, event): self.nb.SetSelection(1) def OnTraining(self, event=NULL): firstSet = TRUE def createOneRevPlot(self, pointsPerRev, revs): plotWidthPoints = int(pointsPerRev) self.nb.AdvanceSelection() def OnExport(self, event): self.nb.SetSelection(3) def histogram(self,a, bins): return 1 ############### Main application class ########### class App(wxApp): def OnInit(self): frame = MainFrame(NULL, -1, "Turbine ") frame.Show(true) self.SetTopWindow(frame) return true app = App(0) app.MainLoop() ################# py2exe output ##################### D:\projects\fingerprinting>python setup.py py2exe running py2exe running build running build_scripts not copying 4.py (up-to-date) running install_scripts creating build\bdist.win32\winexe creating build\bdist.win32\winexe\lib creating build\bdist.win32\winexe\lib\Python creating build\bdist.win32\winexe\lib\Python\Scripts copying build\scripts-2.2\4.py -> build\bdist.win32\winexe\lib\Python\Scripts copying build\scripts-2.2\tf.4.py -> build\bdist.win32\winexe\lib\Python\Scripts copying build\scripts-2.2\tf.5.py -> build\bdist.win32\winexe\lib\Python\Scripts +---------------------------------------------------- | Processing script 4.py with py2exe-0.3.4 +---------------------------------------------------- creating build\bdist.win32\winexe\collect creating build\bdist.win32\winexe\collect\4 creating build\bdist.win32\winexe\collect\4\Scripts.py2exe Searching modules needed to run '4.py' on path: ['D:\\projects\\fingerprinting\\build\\bdist.win32\\winexe\\lib\\Python\\Li b\\si te-packages', '', 'D:\\Python\\Lib\\site-packages\\Pythonwin', 'D:\\Python\\Lib\ \site-packages\\win32', 'D:\\Python\\Lib\\site-packages\\win32\\lib', 'D:\\Pytho n\\Lib\\site-packages', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python\\lib\ \lib-tk', 'D:\\Python', 'D:\\Python\\lib\\site-packages\\numarray'] force_imports = Resolving binary dependencies: D:\Python\lib\site-packages\numarray\_numarray.pyd D:\Python\lib\site-packages\numarray\_operator.pyd D:\Python\Lib\site-packages\py2exe\run.exe D:\Python\Lib\site-packages\wxPython\utilsc.pyd D:\Python\lib\site-packages\numarray\_conv.pyd D:\Python\lib\site-packages\numarray\_bytes.pyd D:\Python\lib\site-packages\numarray\_ufunc.pyd D:\Python\lib\site-packages\numarray\_converter.pyd D:\Python\Lib\site-packages\wxPython\wxmsw233h.dll D:\Python\Lib\site-packages\wxPython\wxc.pyd C:\WIN2000\System32\python22.dll D:\Python\lib\site-packages\numarray\_ndarray.pyd D:\Python\lib\site-packages\numarray\memory.pyd D:\Python\lib\site-packages\numarray\_sort.pyd D:\Python\Lib\site-packages\wxPython\wxmsw232h.dll D:\Python\DLLs\_sre.pyd ext_mapping = { '_conv': ('_conv.pyd', ('.pyd', 'rb', 3)) '_ndarray': ('_ndarray.pyd', ('.pyd', 'rb', 3)) '_sort': ('_sort.pyd', ('.pyd', 'rb', 3)) '_converter': ('_converter.pyd', ('.pyd', 'rb', 3)) '_numarray': ('_numarray.pyd', ('.pyd', 'rb', 3)) '_ufunc': ('_ufunc.pyd', ('.pyd', 'rb', 3)) '_operator': ('_operator.pyd', ('.pyd', 'rb', 3)) '_bytes': ('_bytes.pyd', ('.pyd', 'rb', 3)) 'memory': ('memory.pyd', ('.pyd', 'rb', 3)) 'wxPython.utilsc': ('utilsc.pyd', ('.pyd', 'rb', 3)) '_sre': ('_sre.pyd', ('.pyd', 'rb', 3)) 'wxPython.wxc': ('wxc.pyd', ('.pyd', 'rb', 3)) } copying D:\Python\Lib\site-packages\py2exe\support.py -> build\bdist.win32\winex e\collect\4\Scripts.py2exe byte-compiling D:\Python\lib\pre.py to pre.pyc byte-compiling D:\Python\lib\__future__.py to __future__.pyc byte-compiling D:\Python\lib\copy_reg.py to copy_reg.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\fonts.py to wxPython\fonts.p yc byte-compiling D:\Python\Lib\site-packages\wxPython\windows.py to wxPython\windo ws.pyc byte-compiling D:\Python\lib\locale.py to locale.pyc byte-compiling D:\Python\lib\random.py to random.pyc byte-compiling D:\Python\lib\popen2.py to popen2.pyc byte-compiling D:\Python\lib\stat.py to stat.pyc byte-compiling D:\Python\lib\imputil.py to imputil.pyc byte-compiling D:\Python\lib\site-packages\numarray\_ufuncall.py to _ufuncall.py c byte-compiling D:\Python\Lib\site-packages\wxPython\events.py to wxPython\events .pyc byte-compiling D:\Python\Lib\site-packages\wxPython\utils.py to wxPython\utils.p yc byte-compiling D:\Python\lib\site-packages\numarray\arrayprint.py to arrayprint. pyc byte-compiling D:\Python\lib\string.py to string.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\printfw.py to wxPython\print fw.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\misc.py to wxPython\misc.pyc byte-compiling D:\Python\lib\re.py to re.pyc byte-compiling D:\Python\lib\tempfile.py to tempfile.pyc byte-compiling D:\Python\lib\warnings.py to warnings.pyc byte-compiling D:\Python\lib\site-packages\numarray\typeconv.py to typeconv.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\streams.py to wxPython\strea ms.pyc byte-compiling D:\Python\lib\sre_constants.py to sre_constants.pyc byte-compiling D:\Python\lib\ntpath.py to ntpath.pyc byte-compiling D:\Python\lib\sre_compile.py to sre_compile.pyc byte-compiling D:\Python\lib\getopt.py to getopt.pyc byte-compiling D:\Python\lib\site-packages\numarray\ufunc.py to ufunc.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\controls2.py to wxPython\con trols2.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\windows3.py to wxPython\wind ows3.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\stattool.py to wxPython\stat tool.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\controls.py to wxPython\cont rols.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\__version__.py to wxPython\_ _version__.pyc byte-compiling D:\Python\lib\UserDict.py to UserDict.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\wx.py to wxPython\wx.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\sizers.py to wxPython\sizers .pyc byte-compiling D:\Python\lib\repr.py to repr.pyc byte-compiling D:\Python\lib\sre_parse.py to sre_parse.pyc byte-compiling D:\Python\lib\copy.py to copy.pyc byte-compiling D:\Python\lib\site-packages\numarray\numerictypes.py to numericty pes.pyc byte-compiling D:\Python\lib\types.py to types.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\filesys.py to wxPython\files ys.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\windows2.py to wxPython\wind ows2.pyc byte-compiling D:\Python\lib\dospath.py to dospath.pyc byte-compiling D:\Python\lib\sre.py to sre.pyc byte-compiling D:\Python\lib\site-packages\numarray\numarray.py to numarray.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\misc2.py to wxPython\misc2.p yc byte-compiling D:\Python\lib\site-packages\numarray\ndarray.py to ndarray.pyc byte-compiling D:\Python\lib\linecache.py to linecache.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\frames.py to wxPython\frames .pyc byte-compiling D:\Python\Lib\site-packages\wxPython\__init__.py to wxPython\__in it__.pyc byte-compiling D:\Python\lib\posixpath.py to posixpath.pyc byte-compiling D:\Python\lib\site-packages\numarray\numinclude.py to numinclude. pyc byte-compiling D:\Python\Lib\site-packages\wxPython\cmndlgs.py to wxPython\cmndl gs.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\image.py to wxPython\image.p yc byte-compiling D:\Python\Lib\site-packages\wxPython\mdi.py to wxPython\mdi.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\gdi.py to wxPython\gdi.pyc byte-compiling D:\Python\lib\os.py to os.pyc byte-compiling D:\Python\Lib\site-packages\wxPython\clip_dnd.py to wxPython\clip _dnd.pyc copying 4.py -> build\bdist.win32\winexe\collect\4\Scripts.py2exe\__main__.py changing into 'build\bdist.win32\winexe\collect\4' zip -rq D:\projects\fingerprinting\build\bdist.win32\winexe\4.zip . creating 'D:\projects\fingerprinting\build\bdist.win32\winexe\4.zip' and adding '.' to it changing back to 'D:\projects\fingerprinting' creating dist\4\4.exe warning: py2exe: could not parse version number '' No VersionInfo will be created not copying D:\Python\lib\site-packages\numarray\_numarray.pyd (output up- to-dat e) not copying D:\Python\lib\site-packages\numarray\_operator.pyd (output up- to-dat e) not copying D:\Python\Lib\site-packages\wxPython\utilsc.pyd (output up-to- date) not copying D:\Python\lib\site-packages\numarray\_conv.pyd (output up-to- date) not copying D:\Python\lib\site-packages\numarray\_bytes.pyd (output up-to- date) not copying D:\Python\lib\site-packages\numarray\_ufunc.pyd (output up-to- date) not copying D:\Python\lib\site-packages\numarray\_converter.pyd (output up- to-da te) not copying D:\Python\Lib\site-packages\wxPython\wxmsw233h.dll (output up- to-dat e) not copying D:\Python\Lib\site-packages\wxPython\wxc.pyd (output up-to- date) not copying C:\WIN2000\System32\python22.dll (output up-to-date) not copying D:\Python\lib\site-packages\numarray\_ndarray.pyd (output up- to-date ) not copying D:\Python\lib\site-packages\numarray\memory.pyd (output up-to- date) not copying D:\Python\lib\site-packages\numarray\_sort.pyd (output up-to- date) not copying D:\Python\Lib\site-packages\wxPython\wxmsw232h.dll (output up- to-dat e) not copying D:\Python\DLLs\_sre.pyd (output up-to-date) warning: py2exe: *************************************************************** ********** warning: py2exe: * The following modules were not found: warning: py2exe: * cmndlgsc warning: py2exe: * imagec warning: py2exe: * clip_dndc warning: py2exe: * windows3c warning: py2exe: * filesysc warning: py2exe: * eventsc warning: py2exe: * windows2c warning: py2exe: * controlsc warning: py2exe: * misc2c warning: py2exe: * os.path warning: py2exe: * windowsc warning: py2exe: * stattoolc warning: py2exe: * printfwc warning: py2exe: * gdic warning: py2exe: * sizersc warning: py2exe: * mdic warning: py2exe: * fontsc warning: py2exe: * streamsc warning: py2exe: * miscc warning: py2exe: * controls2c warning: py2exe: * framesc warning: py2exe: *************************************************************** ********** removing 'build\bdist.win32\winexe\collect\4' (and everything under it) Built File dist\4\4.exe removing 'build\bdist.win32\winexe' (and everything under it) From kmj9907 at cs.rit.edu Wed Jul 30 16:02:28 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Wed, 30 Jul 2003 20:02:28 GMT Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> Message-ID: On Wed, 30 Jul 2003 17:25:05 +0000, max wrote: > The problem with spaces is that you need to do 5 times the work of a tab > to get decent-looking indentation :). Not if you have a good editor.. Use vim or emacs. In vim, try :h sts (I think, or :h softtabstop) ...it would suck to have to type all the time, but you don't. :) From aahz at pythoncraft.com Wed Jul 30 10:02:13 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Jul 2003 10:02:13 -0400 Subject: Thank you developers for 2.3 References: Message-ID: In article , David Lees wrote: > >Flawless install and it ran my very simple minded (try not to laugh) >nested loop integer arithmetic benchmark twice as fast as 2.2.3 >version 2.3 5.04 sec >version 2.2.3 9.77 sec > >import time > >def speedTest(N): > t1 = time.time() > k = 0 > for i in xrange(N): > for j in xrange(N): > k += (i+j) > > t2 = time.time() > return t2-t1 > >print speedTest(3000) That primarily tests the speed of the warnings module. Test starting with 0L instead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From kern at taliesen.caltech.edu Fri Jul 25 22:14:52 2003 From: kern at taliesen.caltech.edu (Robert Kern) Date: Sat, 26 Jul 2003 02:14:52 +0000 (UTC) Subject: LGPL and Java, and Python? References: Message-ID: In article , Alexandre Fayolle writes: > Hello, > > Reading Debian Weekly News, I learnt that there seem to be a problem > when importing an LGPL'd java library (this forces the importer to be > LGPL'd too), making the LGPL license equivalent to the GPL for Java > programs. Apparently, this whole mess was a misunderstanding. The LGPL works as expected with Java. http://lists.debian.org/debian-legal/2003/debian-legal-200307/msg00234.html -- Robert Kern kern at caltech.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From alan.gauld at btinternet.com Wed Jul 9 14:40:18 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jul 2003 18:40:18 GMT Subject: Odp: Newbie - No module named stdwin References: Message-ID: <3f0c60c1.172901258@news.blueyonder.co.uk> On Wed, 9 Jul 2003 17:07:18 +0200, "K" wrote: > > includes Tkinter; the other interfaces would be add-on packages. > > > > --amk > ok thanks so how command can open a window ? See my previous post, however usually in Python you don't need to open a window, unless you are writing a full GUI program. So maybe we need to ask what it is you are doing that requires that you "open a window"? To get user input use raw_input() function To present info(error messages and results etc) to the user use print statements. If you want to draw graphics then OK maybe you do need a window, but maybe the turtle package would do? While programming GUI style is quite possible in Python, its usually best to master the basics first! Alan g. From rnd at onego.ru Mon Jul 21 10:40:41 2003 From: rnd at onego.ru (Roman Suzi) Date: Mon, 21 Jul 2003 18:40:41 +0400 (MSD) Subject: Be Honest about LC_NUMERIC (PEP proposal), was Re: [Python-Dev] LC_NUMERIC and C libraries In-Reply-To: <20030721141005.GC756@async.com.br> Message-ID: On Mon, 21 Jul 2003, Christian Reis wrote: > Title: Be Honest about LC_NUMERIC (to the C library) I recall once I mistakenly set LC_NUMERIC="ru_RU" After that it was impossible to attach files in pine mailer, because it showed file size with "," instead of "." and at the same time understood "," as a file list separator... So I'd prefered all these peculiarities to be ignored as much as possible. Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From MatthewS at HeyAnita.com Mon Jul 28 14:45:18 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 28 Jul 2003 11:45:18 -0700 Subject: How to properly package/distribute a pure python module? Message-ID: <5ab0af73.0307281045.6cb13cfe@posting.google.com> Are there any guidelines for packaging a pure python module? Specifically, say I have a set of 10 functions, all of varying behaviors (no unifying theme to bind them together into clear subsets), that I would like to make available to others. What is the best structure for the distributed module? A single file called "functions.py" that people can put in "site-packages"[1]? A subdirectory called "MyFunctions" with an "__init__.py" and the "functions.py" files[2]? Or should the functions be broken out into individual files[3]? I'm sure it depends on some other factorsbut are there general rules for constructing a nice, logical package for others to use? [1] site-packages/functions.py (from functions import f1) [2] site-packages/MyFunctions/functions.py, __init__.py (from MyFunctions.functions import f1) [3] site-packages/MyFunctions/__init__.py, f1.py, f2.py, f3.py (from MyFunctions.f1 import f1) From bokr at oz.net Thu Jul 31 10:45:19 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2003 14:45:19 GMT Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> Message-ID: On 30 Jul 2003 18:40:30 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >John Machin wrote: >> >>So ... could we please change that to "much kudos"? > >Nope. Kudos is a mass noun, but it's a discrete mass noun. So you need >to say "many kudos". This bit of pedantry is brought to you by "much >kudo about nothing". """ kudos, Greek for glory, became an English slang word of limited currency at a time when Greek was more widely learnt, and is now, it seems, sometimes mistaken for a plural. """ H.W.Fowler, in "A Dictionary of Modern English Usage," 2nd ed., 1965 (Elsewhere it does acknowledge that Edmund Wilson wrote of American usage in 1963, "Kudos seems now to be well established as the plural of a word meaning "honourable mention or prize or something of the sort.") Regards, Bengt Richter From bokr at oz.net Sun Jul 13 20:38:56 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 00:38:56 GMT Subject: removing spaces from front and end of filenames References: <93f5c5e9.0307130843.3e3e3daa@posting.google.com> Message-ID: On 13 Jul 2003 09:43:46 -0700, hokiegal99 at hotmail.com (hokiegal99) wrote: >Ha!! > >Fixed it with this bit of code: > >for root, dirs, files in os.walk('/home/BradTill/python'): > for file in files: > fname = (file) > fname = fname.strip( ) > newfile = fname > if newfile: for fname in files: newfile = fname.strip() if newfile!=fname: > newpath = os.path.join(root,newfile) > oldpath = os.path.join(root,file) > os.rename(oldpath,newpath) > print oldpath > print newpath > I'd suggest using four spaces instead of tabs ;-) Why not do the whole thing in one loop? (Ignore my prev post suggestion for final renaming loop just for spaces): #XXX# untested !! import re, os percent2f_n_bad = re.compile(r'%2f|[*?<>/|\\]') # look for bad chars too for root, dirs, files in os.walk('/home/rbt/scripts'): for fname in files: newfile = percent2f_n_bad.sub('-', fname) newfile.strip() # and the space thing if newfile != fname: # you really only need to know if something changed, right? newpath = os.path.join(root,newfile) oldpath = os.path.join(root,fname) os.rename(oldpath,newpath) print `oldpath` # backticks to get quoted repr, to see spaces print `newpath` Or am I missing something? Regards, Bengt Richter From andrew.henshaw at gtri.gatech.edu Sun Jul 27 23:07:07 2003 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Sun, 27 Jul 2003 23:07:07 -0400 Subject: wxPython wxListBox problem References: Message-ID: nabugoon wrote: > How can I add 100000 lists in wxListBox? > > When I tried, it stop because of overhead. > > In demo application, Some Grid Control handles 1000000 data. > > So I think it is possible that I add 100000 lists. > > Do I have to use another control? > > Any idea? > > TIA. Check the wxListCtrl_virtual example in the Demo app. -- Andy From fredrik at pythonware.com Thu Jul 10 16:49:06 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Jul 2003 22:49:06 +0200 Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: Steve Pinard wrote: > New to Python, so please bear with me. > > >>> import sys > >>> print sys.modules.keys() # works fine > ['code', ...snip... ] > >>> print sys.modules.keys().sort() # returns None, why? > None > > According to my reference (Nutshell), keys() returns a > "copy" of the dict keys as a list, so I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? because sort returns None, not a reference to the list. see the FAQ for details: http://www.python.org/doc/FAQ.html#6.20 to fix this, use the return key: keys = sys.modules.keys() keys.sort() print keys From usenet at soraia.com Thu Jul 10 13:47:41 2003 From: usenet at soraia.com (Joe Francia) Date: Thu, 10 Jul 2003 17:47:41 GMT Subject: replace value of a specific position In-Reply-To: References: Message-ID: <3F0DA6FB.90603@soraia.com> Tom wrote: > Hi, > > I want to replace a specific part of a string. I tried replace but this > doesn't work the way I want it, because it checks and replaces all > values and not the position (index). > > t = '010010101001001110100101010111' > t = t.replace(t[5], '2') > > This is just a bad example of what I tried. It produces this output: > > 212212121221221112122121212111 > > But I wanted: > > 010012101001001110100101010111 > > I couldn't find anything in the python library. I probably looked at the > wrong place! :-) That's why I would appreciate your help. > > Thank you very much, Tom > Strings are immutable in Python. Try something like: >>> t = '010010101001001110100101010111' >>> t = string.join([t[:5], '2', t[6:]], '') >>> t 010012101001001110100101010111 jf From michael at foord.net Fri Jul 11 19:00:53 2003 From: michael at foord.net (Fuzzyman) Date: Sat, 12 Jul 2003 00:00:53 +0100 Subject: The ASPN compiler Message-ID: What's the score on this (the ASPN python compiler) - is it a true compiler for python ? - what does it output - binary or C++ for .NET framework............ if the latter then it could be very cool as it may work with the PocketPC 2003 SDK.... for producing binaries for PDAs from python... cool... (I'm sure my terminology is way out of line here... sorry) Does it work yet ? Fuzzyman --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera http://www.voidspace.org.uk Where Headspace Meets Cyberspace Cyberpunk and Science Resource Site Exploring the worlds of Psychology, Spirituality, Science and Computing -- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz http://www.learnlandrover.com From m at moshez.org Wed Jul 16 07:08:09 2003 From: m at moshez.org (Moshe Zadka) Date: 16 Jul 2003 11:08:09 -0000 Subject: How about using python to write a CMS? In-Reply-To: References: Message-ID: <20030716110809.3711.qmail@green.zadka.com> On Wed, 16 Jul 2003, wrote: > To write a CMS, everyone is thinking about PHP They are? Some[0] would find it surprising[1]... [0]http://www.zope.org [1]http://www.plone.org -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From bokr at oz.net Mon Jul 28 12:59:01 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2003 16:59:01 GMT Subject: Seeing next character in an file References: Message-ID: On Mon, 28 Jul 2003 12:54:57 +0100, Richie Hindle wrote: > >[Keith] >> def peek(self, cnt): >> data = self.read(cnt) >> self.seek(cnt * -1, 1) >> return data >> >> def peekline(self): >> pos = self.tell() >> data = self.readline() >> self.seek(pos, 0) >> return data > >[Bengt] >> if you're going to seek/tell, best to do it in binary, and deal with the platform dependent EOLs. > >seek() works perfectly with text-mode files as long as you only seek to >places given to you by tell(). So if Keith's peek() function had used >tell() and then seek()ed (sought()? 8-) back to that point like his >peekline() does, there would be no problem. > Can you cite a C or C++ standard section that guarantees that seek/tell will work that way in text mode? (I'm not saying there isn't one, but I couldn't find one quickly ;-) Regards, Bengt Richter From florian.konnertz at web.de Mon Jul 7 18:49:18 2003 From: florian.konnertz at web.de (Florian Konnertz) Date: Tue, 08 Jul 2003 00:49:18 +0200 Subject: doublequotes in regexp 1.5.2 - zope/externalmethod Message-ID: Hi, I have to do a little script for an old zope website running on python1.5.2 and have a regexp problem. (for those who know zope: I have to change all stx links in a dtml doc to html which is not done for any reason. It's an old zope (2.3.2) :( python is 1.5.2 I tried with string.find, but i get a "string object has no atribute 'find'" error - find is documented for python-1.5.2 :-/ So i guesses i have to use an External Method where i can use re.) In this method i do a re.findall for the stx link, i tried with several expressions, and one i need to use does not work which seems quite strange to me. I tried to track this down to the simplest parts, but up to now unsuccessfully so i need your help, please. BTW in cli mode everything is fine if i start the same script with python1.5 Apparently it's a fault of the '"' character, the double quotes. Here are the most simple pattern i tried, the double quotes quoted with \ and not, in triple quotes and not etc. Everytime i add the double quotes, my pattern fails. And my text definetly has several stx links in it!! pattern = r'"\S+' pattern = r'''"\S+''' pattern = r'''\"\S+''' Everything without d.quotes is ok, i.e. urlchars = r'[A-Za-z0-9/:@_%~#=&\.\-\?\+\$,]+' urlendchar = r'[A-Za-z0-9/]' url = r'["=]?((about|gopher|http|https|ftp|mailto|file):%s' % urlendchar this is the pattern i need: link = r'(".+?"):%s' % (url) which works fine on the cli. TIA, Florian -- Florian Konnertz --- http://www.florian-konnertz.de http://openspirit.homelinux.net/noowiki/FrontPage ZWiki about all topics, especially consciousness research and wisdom traditions From ofnap at nus.edu.sg Fri Jul 11 11:16:33 2003 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 11 Jul 2003 08:16:33 -0700 Subject: Python in Excel References: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> <873chm9w7o.fsf@pobox.com> Message-ID: <37ee60c8.0307110716.74f7c4c9@posting.google.com> This looks very useful to Excel users who would like to tap the power of Python. However, not knowing enough about VBA syntax it was not possible to proceed beyond step(a). Is it possible to provide an Idiot's guide to steps (b), (c),(d) and (e)? In other words, what is the explicit VBA code/steps need to do (b) and (c) and could simple (even trivial) examples be given of steps (d) and (e). Thanks in advance. hannibal wrote in message news:... > You can use Microsoft Script Control. If you have the win32 extensions > of python, you can use python in place of vb in this control > > -(a)open the VBA script editor - In menus/Tools/References add Microsoft > Script Control > -(b)Make a new module and declare a new MsScriptControl.ScriptControl > Global sc as new MsScriptControl.ScriptControl > -(c)Initialize the language attibute with python - Note that you and users > of your document must have python and its win32 extensions installed. > Activestate python distribustion include it. > You can put > sc.language="python" > in the routine Workbook_Open() > > (d)Now you can import python modules using ExecuteStatement method of the > control in vba and have results from python functions with eval method. > (e)One interesting thing is that you can pass an object to the control with > AddObject method and have python manipulate it. And so on.. > > > > John J. Lee a ?crit : > > "Tom Locke" writes: > > > > > >>>>Can I write Excel macros/scripts using Python? > >>>> > >>>>I mean to actually put Python into an Excel document, not using > >>>>Python to access data, for example, from some Excel document. > >> > >>These days you can script office with any .NET language, and that includes > >>Python: > > > > [...] > > > > Or use good old COM. There's an example of controlling Excel (the > > version from Office 2000) in the Python for Windows Extensions (aka > > win32all) COM test code. IIRC, it'll be somewhere like > > C:\Python\win32com\tests\. > > > > > > John > > --- > Posted via news://freenews.netfront.net > Complaints to news at netfront.net From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 29 08:08:50 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 29 Jul 2003 12:08:50 GMT Subject: variable assignment in "while" loop Message-ID: Hi there, Is it possible to use an assignment in a while-loop? I'd like to do something like "loop while there is still something to be read, and if there is, put it in this variable". I've been a C programmer since I was 14, so a construct like: while info = mydbcursor.fetchone(): print "Information: "+str(info) comes to mind. Unfortunately, this doesn't work. Is there a similar construct in python? Sybren PS: This is a supersede. If it didn't work out and you saw two messages with the same content, please ignore the oldest one. -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From jepler at unpythonic.net Thu Jul 17 14:03:59 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Jul 2003 13:03:59 -0500 Subject: anything like C++ references? In-Reply-To: References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: <20030717180354.GA30143@unpythonic.net> On Thu, Jul 17, 2003 at 01:15:03PM -0400, Terry Reedy wrote: > > "Adam Ruth" wrote in message > news:f0f51c80.0307150921.7b6667e2 at posting.google.com... > > register int x = 5; > > int *y = &x; > > > > This also cannot be done. Why? Different semantics for register > > variables. > > Minor nit: 'register' is not a mandate, but an ignorable suggestion. > So a compiler either could or must ignore 'register' in able to make > '&x' possible. I suspect that the compiler *must* issue a diagnostic for the code in question. That phrase, common in the C standard, doesn't mean that the compiler can't also go on to produce an object file/executable, or that it might not be operating in conformant mode by default (gcc does many things a conformant C compiler could not, unless -ansi is specified) But yes, 'register' was never a mandate. I suspect that the reason it was included in C originally was twofold: First, the compiler was not powerful enough to take two passes over a function body, one to determine whether the addressof operator was ever used for a particular variable, and a second to generate code. Second, the compiler was also not powerful enough to do the kind of analysis needed to choose registers for variables. With those constraints, suddenly code like while(*p++ = *q++) ; improves by a factor of two or more as soon as you write register char *p, *q; instead of just char *p, *q; ... well, that hasn't been the case for 15 years or more now. > Of course, the idea of ignorable keyword suggestion is itself somewhat > strange ;-) Not at all. Many proposals for efficient translation from Python to native code include a notion of type hints. Python can freely ignore them (or translate them into runtime 'assert isinstance' or 'assert hasattr' statements) but the new compiler would use them to generate efficient code using native datatypes... def fact(n): if n == 0: return 1 return fact(n-1) * n typeassert(RETURN_VALUE, fact, union(int,long)) typeassert(PARAMAETERS, fact, (int,)) Jeff From petri.savolainen at iki.fi Tue Jul 1 18:43:03 2003 From: petri.savolainen at iki.fi (Petri Savolainen) Date: Tue, 01 Jul 2003 22:43:03 GMT Subject: how to dynamically create a function object (from a code object)? Message-ID: After reading the manuals and googling around a bit, I thought I'd use the 'compile' built-in to create a code object. Then, using either new.function() or types.FunctionType(), create a function object out of the code object. The function object can then be turned into a method for example using types.MethodType(). Right? Well, on Windows 98, using python 2.2.2 (or 2.3b2): >>> c=compile('def a(msg): return msg','','exec') >>> f=types.FunctionType(c,globals(),'a') >>> f >>> ", line 1> >>> f('hello') Traceback (most recent call last): File "", line 1, in -toplevel- f('hello') TypeError: ?() takes no arguments (1 given) >>> f() >>> >>> a('hello') >>> 'hello' >>> This is, well, not what I would have expected. After peeking around in the code object, I found out its 'co_const' instance variable also contains a code object - which, it seems, should really be fed to the function creation methods: >>> c.co_consts (", line 1>, None) >>> f=types.FunctionType(c.co_consts[0],globals(),'a') >>> f('hello') 'hello' >>> Which is the behaviour I would have expected in the first place! I would really like to know what I am doing wrong here, or any clarification regarding what is going on above... I dare not hope having found a bug :-P Thanks, Petri From wettering at comcast.net Thu Jul 31 14:11:13 2003 From: wettering at comcast.net (Mark VandeWettering) Date: Thu, 31 Jul 2003 18:11:13 GMT Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: In article <899f842.0307310555.56134f71 at posting.google.com>, Anthony_Barker wrote: > I have been reading a book about the evolution of the Basic > programming language. The author states that Basic - particularly > Microsoft's version is full of compromises which crept in along the > language's 30+ year evolution. > > What to you think python largest compromises are? > > The three that come to my mind are significant whitespace, dynamic > typing, and that it is interpreted - not compiled. These three put > python under fire and cause some large projects to move off python or > relegate it to prototyping. I don't view any of these as "compromises". That word suggests that something was conceded, or that an intermediate position between two extremes was chosen to appease. I don't think that either sense really applies to these features. The three items that you listed are merely design choices. While arguments over them are continuous, two of the design choices (interpreter, dynamic typing) are consistent with Python's intended use as a language which excels at rapid prototyping. The third (white space) is merely a stylistic choice which is designed to encourage readable programs. "Compromises" in language design occur usually when a committee tries to standardize a language, and each has differing views about how the language should be used. While this occurs somewhat in Python, other languages have suffered more mightily from this particular disorder. Mark > Anthony > http://xminc.com/anthony From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jul 24 00:06:00 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Jul 2003 13:56:00 +0950 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> <3F1F5CB2.7FB4C205@alcyone.com> Message-ID: Bryan (original poster) wrote: > f1 = file('file1') > try: > f2 = file('file2') > try: > # process f1 & f2 > finally: > f2.close() > finally: > f1.close() On Wed, 23 Jul 2003 21:12:34 -0700, Erik Max Francis wrote: > Ben Finney wrote: >> It seems that nesting the 'try' clauses doesn't scale well. What if >> fifty files are opened? Must the nesting level of the 'try' clauses >> be fifty also, to close them promptly? > > If you're manipulating fifty files in one block, presumably you're > doing so in a uniform way: > > allFiles = [...] > try: > ... > finally: > for eachFile in allFiles: > eachFile.close() This doesn't match Bryan's nested structure above, which you blessed as not "overkill" (in his words). It was this that I considered a poorly-scaling structure, or "overkill" since only one 'try' block is required. Do you disagree? -- \ "Too many Indians spoil the golden egg." -- Sir Joh | `\ Bjelke-Petersen | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From bokr at oz.net Fri Jul 11 01:45:39 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Jul 2003 05:45:39 GMT Subject: sort() doesn't work on dist.keys() ? References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: On 10 Jul 2003 13:14:01 -0700, spinard at ra.rockwell.com (Steve Pinard) wrote: >(Got a comm error trying to post first time, sorry if this >is a duplicate) > >New to Python, so please bear with me. > >>>> import sys >>>> print sys.modules.keys() # works fine >['code', ...snip... ] >>>> print sys.modules.keys().sort() # returns None, why? >None > >According to my reference (Nutshell), keys() returns a >"copy" of the dict keys as a list, so I would expect when >I aply sort() to that list, I would get an in-place sorted >version of that list. Why do I get None? > It's a reasonable question. Some would probably like it to work that way, but it doesn't. Try it with any list: >>> any = [3,1,5,2,4,0] >>> any [3, 1, 5, 2, 4, 0] >>> print any.sort() None >>> any [0, 1, 2, 3, 4, 5] The sort happens, but a reference to the result is not returned, just None. In your example the temporary list gets sorted but doesn't get bound to a name or other place so you can't get to it. So do it in two steps: any = sys.modules.keys() any.sort() Now any should be what you want. Regards, Bengt Richter From eric.brunel at pragmadev.com Wed Jul 2 04:31:19 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 02 Jul 2003 10:31:19 +0200 Subject: How do I get the fractions of the visible part of a canvas? References: Message-ID: Mickel Gr?nroos wrote: > Hi, > > I have a Tkinter.Canvas of variable width. Is there a standard way of > asking the canvas which parts of it that is visible? I.e. on the > horizontal scale, I would like to know at what fraction from the left the > left visibility border is and from what fraction to the right the right > visibility border is. > > Consider this ascii picture as an example > > +-------------------------------+ > | |<-- the full canvas > | a------------------+ | > | | |<--------- the currently visible part > | +------------------b | > | | > +-------------------------------+ > > I would like to be able to ask the canvas something like: > > t = canvas.visiblebox() > > and it would return a two-tuple of two-tuples with coordinates (of the > a and b points in the picture above), say: > > t = ((10,10), (90,30)) > > Using these values I could calculate the fractions myself. > > Any ideas? This should do what you want: -------------------------------- from Tkinter import * ## Initialize Tk root = Tk() root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) ## Create the canvas cnv = Canvas(root, scrollregion=(0, 0, 1000, 1000), width=200, height=200) cnv.grid(row=0, column=0, sticky='nswe') ## Create the scrollbars hs = Scrollbar(root, orient=HORIZONTAL, command=cnv.xview) vs = Scrollbar(root, orient=VERTICAL, command=cnv.yview) cnv.configure(xscrollcommand=hs.set, yscrollcommand=vs.set) hs.grid(row=1, column=0, sticky='we') vs.grid(row=0, column=1, sticky='ns') ## This is the function you want: def showVisibleRegion(): x1, y1 = cnv.canvasx(0), cnv.canvasy(0) w, h = cnv.winfo_width(), cnv.winfo_height() x2, y2 = cnv.canvasx(w), cnv.canvasy(h) print x1, y1, x2, y2 b = Button(root, text='Show', command=showVisibleRegion) b.grid(row=2, column=0, columnspan=2) root.mainloop() -------------------------------- The methods canvasx and canvasy on a Canvas convert a coordinate in the displayed canvas to a coordinate in the underlying region: +------------------------------+ | | | | | +----------------------+ | | | | | | |<--x-->| | | | | + | | | | | | | | +-------|--------------+ | |<---xx---->| | | | +------------------------------+ Here, cnv.canvasx(x) = xx So, taking the canvasx and canvasy of (0, 0) gives you the coordinates for the top-left corner of the region you want, and taking the canvasx and canvasy of the canvas's dimensions gives you the bottom-right one. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From klappnase at freenet.de Sun Jul 20 19:29:10 2003 From: klappnase at freenet.de (klappnase) Date: 20 Jul 2003 16:29:10 -0700 Subject: Newbie! I'm a newbie! What's wrong with this program? References: <5da8e4b3.0307191800.48dc0a6d@posting.google.com> Message-ID: <9a410299.0307201529.4485efa@posting.google.com> InsaneStewy at hotmail.com (Id0x) wrote in message news:<5da8e4b3.0307191800.48dc0a6d at posting.google.com>... > There are 300 > None minutes in 5 hours <--- Problem occurs here > > [\|End Running of Program|/] > > Now the problem is... where does the "None" come from? And why is it > there? Here is the code. Please email me if you can. Your help is > appreciated. The "None" comes from: > def newLine(): > print What you meant was: def newLine(): print "\r" (I must admit that I am not familiar with line endings on windoze, in linux it is "\n", on windoze it might be "\r" or "\r\n", I don't know for sure, however you don't need this function at all) You might try something like: print "There are " + str(minHour(x_hours)) + " minutes in " + str(x_hours) + " hours" Michael From peter at engcorp.com Tue Jul 8 16:15:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Jul 2003 16:15:01 -0400 Subject: id = -1 in wxpython References: Message-ID: <3F0B2645.E069A087@engcorp.com> Luiz Siqueira Neto wrote: > > id -1 for some object mean that this object have a default id, but how I > can work with this kind of id? Not "default", I think, but "auto-assigned". So use GetId() as Cliff said... From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 24 10:32:21 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 24 Jul 2003 16:32:21 +0200 Subject: i've been close to python's cradle :) In-Reply-To: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> References: <3f1fdf40$0$8301$4d4ebb8e@news.nl.uu.net> Message-ID: <3f1fedf5$0$49108$e4fe514c@news.xs4all.nl> Guyon Mor?e wrote: > recently i've visited SARAH, the academic supercomputer in Amsterdam, > Holland. You meen SARA: "Stichting Academisch Rekencentrum Amsterdam". They have multiple academic (super)computers, there is no "the" supercomputer... http://www.sara.nl/products/products_eng.html --Irmen From isaac at blueapples.org Thu Jul 24 15:36:28 2003 From: isaac at blueapples.org (Isaac Raway) Date: Thu, 24 Jul 2003 14:36:28 -0500 Subject: SSH and Windows Message-ID: <3F20353C.1090004@blueapples.org> Hello. I'm writing a Python program that connects to servers through telnetlib to execute a few commands. I've discovered that some of the servers that I have to connect to with this program run only SSH, so I need to add support for SSH to the program. I'm looking for a library that behaves similarly to telnetlib for SSH connections. Does anyone know of one? I was going to try using pexpect to control the Windows telnet command, but pexpect only works on Unix. Any help is appreciated. From roy at panix.com Sun Jul 13 10:30:05 2003 From: roy at panix.com (Roy Smith) Date: Sun, 13 Jul 2003 10:30:05 -0400 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: Stephen Horne wrote: > One of the few things I hate about Python is that mutable objects are > implicitly shared using a reference system whereas immutable objects > are not. It is unnecessarily confusing and error prone. There's a bit of confusion in the above regarding mutability vs. call by reference (they're orthogonal ideas), but I think I know what you were trying to say. In ancient versions of Fortran, even constants (i.e. immutables) were pass by reference. You could write something like this (forgive me if I've forgotten some of the syntax details): subroutine x (i) i = 42 end subroutine main x (5) write (6, 100) 5 100 format (1i6) end and it would print 42. There was a single instance of the constant 5 for main, and it was passed by reference to x(), which in turn changed its value to 42. I don't remember if Fortan 66 did this, or if that only happened in even older versions. Talk about confusing and error prone! The Python version of that would be: def mutateString (s): s = "some other string" s ("foo") print "foo" If strings were pass by reference, the above would print "some other string". Unless, of course, you got away from the idea that multiple instances of a string constant with the same value are really the same object, in which case: x = "foo" x is "foo" would print 0 instead of 1 like it does now. From imbosol at aerojockey.com Thu Jul 31 19:17:47 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Thu, 31 Jul 2003 23:17:47 GMT Subject: handle
tags References: Message-ID: Luca Calderano wrote: > Hi guys... > > I've done a subclass of SGMLParser > to handle the contents of a web page, > but i'm not able to handle the
tag > > can someone help me??? I'm very familiar with sgmllib. Can you describe the problem you're having? If you are using
as a self-closing tag as is done in XHTML (i.e.,
), then this cannot be done with sgmllib. You should use HTMLParser instead--only you might have to make some minor changes to your code. -- CARL BANKS From alanmk at hotmail.com Sat Jul 12 11:04:53 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 12 Jul 2003 16:04:53 +0100 Subject: socket problem References: Message-ID: <3F102395.8C3E3395@hotmail.com> Gordon Wetzstein wrote: > I have a problem with python sockets. > I broadcast a lot of pickled objects with socket. sendto(...), that > works. > Ireceive them on the other site with socket.recvfrom(16384) > The pickled objects are smaller (like 10000 bytes) than the max bytes. > > The problem appears if I send too many pickled objects very quickly one > after another, > then I only receive a part of the sent objects. As Jp Calderone pointed out, UDP is an unreliable protocol. Therefore, it *will* drop packets occasionally. Worse, it doesn't guarantee ordering of delivery of packets, meaning that your pickles could arrive all jumbled up and unusable. You have three main choices to get around this problem. 1. Use TCP, which guarantees delivery to the destination address once and only once, guarantees that packets will be received in the order in which they were sent. However, you can't broadcast with TCP: it's a point to point protocol. 2. Implement your own guaranteed delivery protocol over UDP. This is usually done by assigning packets a sequence number as they are transmitted from the publisher. All consumers then keep track of the sequence numbers they receive, and re-request any packets they missed. Implementing your own such protocol can get quite tricky, depending on how complex your requirements. 3. Use a pre-made, highly efficient python library which is custom designed for the job: spread. Spread is designed to solve all of the problems of reliable broadcasting over UDP, and gives you a wide range of options for how to balance efficiency versus reliability. And more importantly, it's industrial-strength robust, stable and platform independent. Also, it's configurable to work with a wide range of network topologies. More info from http://www.python.org/other/spread/ If I were you, I'd seriously consider spending an hour getting up and running with Spread: could be the most productive hour you'll spend in this area. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bdelmee at advalvas.REMOVEME.be Fri Jul 4 07:20:30 2003 From: bdelmee at advalvas.REMOVEME.be (Bernard Delmée) Date: Fri, 4 Jul 2003 13:20:30 +0200 Subject: Python Code Snippets References: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> Message-ID: <3f05631f$0$6529$afc38c87@sisyphus.news.be.easynet.net> > Aur?lien> I wish it had a better ordering than just a list, but > it's Aur?lien> full of good stuff. > > You can always buy the book. It has both an index and a table of > contents. IMO not ideally suited to learning the language, but an invaluable compendium of idioms and advanced topics Sample chapter available at http://www.oreilly.com/catalog/pythoncook/ Other multi-language code samples repositories I know of: http://sourceforge.net/snippet/ and http://pleac.sourceforge.net/ CHeers, Bernard. From tsurusennin at softhome.net Tue Jul 15 22:31:25 2003 From: tsurusennin at softhome.net (Tetsuo) Date: 15 Jul 2003 19:31:25 -0700 Subject: Foreign characters Message-ID: How do I get Python to work with foreign characters? When I try to print them, I get a unicode error (characters not ASCII). Wasn't unicode invented for the express purpose of working with non-ASCII characters? From mal at lemburg.com Tue Jul 1 12:37:55 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 01 Jul 2003 18:37:55 +0200 Subject: eGenix mxODBC Zope DA for FreeBSD Message-ID: <3F01B8E3.2040203@lemburg.com> _______________________________________________________________________ ANNOUNCEMENT EGENIX.COM mxODBC Zope Database Adapter Version 1.0.6 Beta 1 for FreeBSD 4.8 _______________________________________________________________________ INTRODUCTION The eGenix mxODBC Zope Database Adapter (Zope DA) allows you to easily connect your Zope installation to just about any database backend on the market today, giving you the reliability of the commercially supported eGenix.com product mxODBC and the flexibility of the ODBC standard as middle-tier architecture. One Interface on all Platforms... Unlike Zope's ZODBC Zope DA, the mxODBC Zope DA works on Windows XP/NT/2000/98/95, Linux, Solaris and now FreeBSD using the same interface on all platforms High Performance... The mxODBC Zope DA implements thread-safe connection pooling and multiple physical connects per logical Zope connection. You can safely run Z SQL Methods in parallel, achieving a much better performance than ZODBC Zope DA or similar Zope database adapters under heavy load. This makes it ideal for deployment in Zope Clusters and Zope hosting environments where stability and high performance are a top priority. _______________________________________________________________________ BETA TESTING Please report any bugs you find to support at egenix.com. Evaluation licenses can be had from licenses at egenix.com. _______________________________________________________________________ MORE INFORMATION For more information on the mxODBC Zope DA, licensing and download instructions, please visit our web-site: http://www.egenix.com/ You can buy mxODBC Zope DA licenses online from the eGenix.com shop at: http://shop.egenix.com/ _______________________________________________________________________ Thank you, -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Jul 01 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2003-07-01: Released mxODBC Zope DA for FreeBSD 1.0.6 beta 1 From see at my.signature.com Wed Jul 2 17:36:03 2003 From: see at my.signature.com (Andrei) Date: Wed, 02 Jul 2003 21:36:03 +0000 Subject: Tkinter + Python 2.3b2 on WinXP Message-ID: <3068875.1057181763@dbforums.com> I've installed Python 2.3b2 on Windows XP (in "e:\programming\Python2.3"). I also have an older ActivePython 2.2.2 distro on my C-drive and Ruby which apparently installs tcl as well. Now I'm trying to run Idle and get this little beauty (similar for other Tkinter apps): ===== E:\Programming\Python2.3\Lib\idlelib>idle.py Traceback (most recent call last): File "E:\Programming\Python2.3\Lib\idlelib\idle.py", line 23, in ? idlelib.PyShell.main() File "E:\Programming\Python2.3\lib\idlelib\PyShell.py", line 1253, in main root = Tk(className="Idle") File "E:\Programming\Python2.3\lib\lib-tk\Tkinter.py", line 1562, in __init__ self.tk = _tkinter.create(screenName, baseName, className) _tkinter.TclError: Can't find a usable init.tcl in the following directories: {e:\programming\ruby\tcl\lib\tcl8.3;E:\Programming\Python2.3\tcl\t- k8.4} {e:\ programming\ruby\tcl\lib\tcl8.3;E:\Programming\Python2.3\tcl\tk8.4} {e:/programm ing/ruby/tcl/lib/tcl8.3;E:Programming/Python2.3/tcl/tcl8.4} E:/PROGRA~1/Python2. 3/lib/tcl8.4 E:/PROGRA~1/lib/tcl8.4 E:/lib/tcl8.4 E:/PROGRA~1/library E:/library E:/../tcl8.4.3/library This probably means that Tcl wasn't installed properly. ===== init.tcl is present in "E:\Programming\Python2.3\tcl\tcl8.4", which is also listed in the mumbo jumbo above. Idlefork worked OK on ActivePython before I installed 2.3b2. What should I do to make Tkinter work again? Andrei -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From jflanigan at netzero.net Fri Jul 4 11:25:32 2003 From: jflanigan at netzero.net (jose flanigan) Date: 4 Jul 2003 08:25:32 -0700 Subject: Problems getting Tkinter to work while installing python as non-root Message-ID: I don't have root access, but managed to install Tcl/Tk in my local directory. I've also managed to install python 2.2 in my local directory. The problem is that for some reason Tkinter isn't working. I've looked through the various messages in the python installation and it seems like part of the installation is trying to write something to a directory that I don't have write-permission to I think this might be causing the problem. Is there a way around this? I need to set up a purely non-root installation. Thanks in advance. From amk at amk.ca Wed Jul 9 10:43:13 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 09 Jul 2003 09:43:13 -0500 Subject: Newbie - No module named stdwin References: Message-ID: On Wed, 9 Jul 2003 16:20:47 +0200, > When i wanna open a window (like windows) i write > > inport stdwin > stdwin.open ('my window') Stdwin is very old and very dead; what document are you reading that suggests using it? Most GUI development in Python is done using Tkinter, though there's also wxWindows, PyQt, and Gtk+ interfaces available. If you downloaded a binary Windows installer from somewhere, it probably includes Tkinter; the other interfaces would be add-on packages. --amk From bitbucket at electron.me.uk Fri Jul 4 19:15:01 2003 From: bitbucket at electron.me.uk (Geoffrey Clements) Date: Sat, 05 Jul 2003 00:15:01 +0100 Subject: Eric3 segfaulting References: <3f060811$0$56603$bed64819@pubnews.gradwell.net> <3f06093a$0$56603$bed64819@pubnews.gradwell.net> Message-ID: <3f060a73$0$56603$bed64819@pubnews.gradwell.net> Geoffrey Clements wrote: > Some more info: > If I make line 75 a blank line by putting a return in it stills fails on > that line! > oooppss that wasn't right - sorry -- Geoff Registered Linux user 196308 Replace bitbucket with geoff to mail me. From mcherm at mcherm.com Tue Jul 15 08:02:43 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 15 Jul 2003 05:02:43 -0700 Subject: Python Mystery Theatre -- Episode 1: Exceptions Message-ID: <1058270563.3f13ed639c441@mcherm.com> First of all, Raymond THANK YOU. This is lots of fun, and educational too. In fact, I'm nominating it for my favorite c.l.py posting so far this year! So... here's how I did. [** SPOILERS BELOW **] ACT I: This one stumped me the longest... I stared and stared and just couldn't figure it out. But when I came back the next morning it was obvious. "except foo, bar" catches things of type foo, and binds bar to the object caught. To catch multiple types you stick them in a tuple. (This beats out Java where there's no way I know of to catch multiple types.) Design wise, I think the syntax is a little odd, but not worth changing. ACT II: Easy... when you write "raise foo, bar" Python executes foo(bar) and then raises that object. So of course the object, when you catch it, is an instance. ACT III: It took me a while to figure out what you were EXPECTING here, I guess a more complete sumary would be that "raise foo, bar" raises the object "foo(bar)", while "raise foo" either raises the object "foo" or the object "foo()". The rules for which to do are simply that if foo is of type "type" (ie, it's an old-style class) then it raises "foo()", otherwise "foo". In my opinion, this is an unnecessary bit of DWIM (DoWhatIMean), and things would be much cleaner if you just always said "raise foo" and it raised the object "foo" -- at worst you'd need an extra set of parenthesees -- but we recently discussed this in PEP-317 and in the end, Guido (and others) succeeded in convincing me (and others) that it's not worth changing, and he mapped out a plan for how to make the DWIM decision (to raise "foo" or "foo()") after the change to new-style classes. I do, however, consider if a minor wart. Anyhow, it's thanks to the PEP-317 discussions that I understood this one. http://mail.python.org/pipermail/python-dev/2003-June/036162.html ACT IV: I was EXPECTING this one, since it's an exceptions "gotcha" that I already know about. Exception catching is done by object identity, not equality. Normally, you catch with the CLASS of the instance that got raised, so that's OK, but if you raise string exceptions then it's got to be the same object, not just an equivalent string. Solution? Don't raise strings. ACT V: Puzzled me for a couple of minutes, but then I realized that LookupError is an ancestor class of KeyError. That design is a GOOD thing... if your exceptions are in a meaningful hierarchy then you can catch whole sections of the hierarchy without having to name each and every exception individually. So there we have it... it took me one overnight of cogitation, but I got them all without even cracking a reference book (although I admit I had to fire up the interpreter to double-check how to catch multiple exception types together). For those who are just hungering for more, here's another (not quite so good as Raymond's, but might confuse someone): >>> try: ... raise IndexError ... except IndexError, errObject: ... print errObject ... >>> -- Michael Chermside From alan.gauld at btinternet.com Thu Jul 10 17:12:45 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Jul 2003 21:12:45 GMT Subject: QUESTION References: <4e.1efa9c3f.2c3d7c25@aol.com> Message-ID: <3f0dd614.268472713@news.blueyonder.co.uk> On Thu, 10 Jul 2003 00:01:02 +0100, Andy Jewell wrote: > >I have a Compaq 5184 with OEM Win 98 installed...I do not > > ever recall seeing "python" in the programs.=20 This could be key since I seem to recall Digital (or was it HP?) using Python in some of their system configuration applications. Since Compaq swallowed Digital maybe your PC is of the right vintage to have those applications installed... If you do rename the directory don't forget to try the Compaq system tweaking utilities before deleting it! Alan G. Alan g. http://www.freenetpages.co.uk/hp/alan.gauld/ From mcfletch at rogers.com Fri Jul 18 18:00:40 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 18 Jul 2003 18:00:40 -0400 Subject: properties + types, implementing meta-class desciptors elegantly? In-Reply-To: <1058564534.28066.28.camel@lothlorien> References: <3F17ECAC.30104@rogers.com> <1058564534.28066.28.camel@lothlorien> Message-ID: <3F186E08.2030507@rogers.com> Ian Bicking wrote: ... >>which would seem to suggest that the only way to use the regular >>descriptors would be to do the (annoying) '_'+name thing so that there's >>a proliferation of names in the class (which I *really* don't want). >>So, does anyone have a pattern which allows setting an attribute on a >>class which doesn't go through the setattr machinery (i.e. can be used >>within a descriptor)? >> >> > >Maybe you could create just new attribute. Call it _shadow, perhaps. >Then the setter does setattr(client._shadow, name, value). The shadow >could be a plain class like: > >class Shadow(object): pass > I'm doing the rough equivalent with a dictionary, was really looking for something more elegant, in particular, something that would make use of the already-existing class' dictionary, rather than creating a new one. ... >May or may not be more elegant, but you can decide for yourself. > > Basically the same, still want more elegance :) , Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bens at replytothegroupplease.com Wed Jul 30 22:35:06 2003 From: bens at replytothegroupplease.com (Ben S) Date: Thu, 31 Jul 2003 03:35:06 +0100 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: Skip Montanaro wrote: > kylotan> Is there any chance of these modules becoming somewhat > combined kylotan> in the future? > > Maybe. Perhaps you would like to write a PEP? I would think that is best left up to those who know what they're doing... I'm just a newbie who's found date and time handling in Python to be confusing, and thought I'd mention it. (And I am the original poster, btw.) If nobody else agrees, maybe it's not really a problem. > kylotan> Right now it seems a little awkward to find the function > you kylotan> want. The main culprit is 'timegm' which is the only > thing I kylotan> need from the calendar module but which should > probably be in kylotan> the time module. > > I've never used it, but it looks like you're right. It's the GMT/UTC > equivalent of time.mktime(), right? Possibly... I am not intimately familiar with all the different functions. It would help if there was some sort of table in the docs that laid the various time functions side by side for an easy comparison. > kylotan> PS. I use 'time.strptime(myTime, '%a %b %d %H:%M:%S > %Y')' as a kylotan> reverse-asctime(), and was surprised that I > couldn't find this kylotan> wrapped in a function in any of the > modules. Maybe such a kylotan> function would be considered for > future addition? > > Seems simple enough to not be needed. What makes asctime() all that > special? Well, one could say that its very existence makes it special. Technically asctime() is redundant as you can achieve the same effect with time.strftime(). Yet it's in the library. Since time.asctime() exists as a special case, we're assuming that the use of that particular string format has some intrinsic merit. In particular, a lot of programs written in C may use it for logfiles. Therefore it makes sense (to me) to implement the inverse ("timeasc"?). -- Ben Sizer http://pages.eidosnet.co.uk/kylotan From http Thu Jul 10 13:07:18 2003 From: http (Paul Rubin) Date: 10 Jul 2003 10:07:18 -0700 Subject: Python vs PHP References: <3F0D2827.4070501@mxm.dk> Message-ID: <7xisqagvjt.fsf@ruckus.brouhaha.com> Max M writes: > Ahem ... How os Python web development fragmented? Most of it probably > takes place in the Zope world. Nonsense, look at all the Python web platforms there are that don't use Zope. > But mod_python is an official Apache module. Wich sets it about on par > with PHP. Nonsense, it's not on a par with PHP. It doesn't include any template system, any sessions, etc. > It has a standard library that beats the socks of PHP's builtin functions. Nonsense, it doesn't include any SQL database interfaces and you're left on your own to find one, install it, and get it working. > On top on this there are severeal modules for templating etc. PHP does > not have these modules, so everybody has to do it in PHP's own faulty > way. Nonsense, you're trying to spin a deficiency as an advantage. PHP is its own template system, for better or worse. Python doesn't include any template system and you're left on your own to find or write one, install it, and get it working. > Python is not fragmented, but there are more high level modules for > doing things. Nonsense, of course Python (for web development) is fragemented, look at all these different Python web modules we've been discussing. Python does have a lot of modules (like Numeric) that PHP doesn't, but they're not that useful for web programming. PHP is narrowly focused on web programming and is far superior to Python for that purpose unless you spend a lot of time enhancing Python with add-ons before you even start writing your applications. > There are more PHP developers, that's right, but they are all starting > from scratch, with a poor language. So it's their loss. Nonsense, Python is a better language than PHP, but that's the only advantage Python has for web development. The language is a small part of the overall system. And it's Python developers who must start from scratch, not PHP developers. Python could catch up by adding more stuff to the standard library, but it hasn't done that yet and most of the suitable Python modules for PHP-like usage aren't really ready for prime time. From st.brodowski at eucrea.com Wed Jul 9 10:22:04 2003 From: st.brodowski at eucrea.com (Steffen Brodowski) Date: 9 Jul 2003 07:22:04 -0700 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: <381a2b17.0307090622.2e22a716@posting.google.com> Hi Ian, > > > > import Image, ImageDraw > > def CreateBarcode(SourceString,Linewidth,WriteText): > > blablabla > > ... > > NewImage = Image.new("L",NewSize,Backcolor) > > ImgDraw = ImageDraw.Draw(NewImage) > > .... > > > > #How to put the image into an stream? > > have that function return the image object. Then, assuming you are > doing this in CGI (easily adapted if not), do something like (untested): > > import sys > image = CreateBarCode(...) > print 'Content-type: image/jpeg\n' > image.save(sys.stdout, 'JPEG') I think its more difficult. The function CreateBarcode has to return the image directly. Additional you have to know, that I have to implement it into Zope. So I use the script as an "external method". Modulname=Barcode, functionname=CreateBarcode. I'm using the following line in Zope DTML or "> to generate the barcode and for showing it on a html-site. But is doesn't run. Do you have any ideas? Greetings Steffen Brodowski From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jul 30 22:25:20 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 31 Jul 2003 12:15:20 +0950 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> Message-ID: On 30 Jul 2003 19:28:57 -0700, Asun Friere wrote: > I believe it is customary to use the construction 'great kudos,' > which, in any case, you all deserve. Or 'totally mega kudos, d00dZ' depending which decade you're living in. -- \ "He may look like an idiot and talk like an idiot but don't let | `\ that fool you. He really is an idiot." -- Groucho Marx | _o__) | Ben Finney From csad7 at yahoo.com Tue Jul 22 13:34:52 2003 From: csad7 at yahoo.com (christof hoeke) Date: Tue, 22 Jul 2003 19:34:52 +0200 Subject: python startup on XP very slow Message-ID: hi, for some days now i have problems with python taking a lot of time to start up or run programs. today i installed the python 2.3rc1 but still the same problem. e.g. starting pythonwin 1.53 on winXP (athlon 1200 with 512MB) which normally took only a few seconds now takes at least 15-20 seconds. has anybody had a similar problem or knows where the delay comes from? any help would be great thanks chris From news at yebu.de Fri Jul 18 08:28:05 2003 From: news at yebu.de (Karl Scalet) Date: Fri, 18 Jul 2003 14:28:05 +0200 Subject: "\n" in ASCII-file In-Reply-To: References: Message-ID: Martin P schrieb: > Hello, > > for a short exercise-program I have to read the lines in an ASCII-file. > > But every line has a new-line-feed ("\n") at the end of the line. (The > ASCII-file was made with Windows Notepad). > Is this only because I used Windows (and Notepad)? > > And... is there any special method to read lines from a file without "\n"? > > Bye, > Martin > > beside the issue about large or not-so-large files, there is another difference between Gerhard's line.rstrip() and my splitlines() method: entire_file.splitlines() preserves trailing whitespace characters while line.rstrip() doesn't. Just for the rare case it matters :-) Karl From belred1 at yahoo.com Thu Jul 24 01:20:15 2003 From: belred1 at yahoo.com (Bryan) Date: Thu, 24 Jul 2003 05:20:15 GMT Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> Message-ID: > > If you need 50 open files, you almost certainly want to have a way of > organizing them. Probably they'll be in a list or dictionary. So, if > they're in a list, for example, you can do this: > > > filelist = [] > try: > filelist.append(open(filename[0])) > filelist.append(open(filename[1])) > ... > do_something(filelist) > finally: > for f in filelist: > f.close() > erik, carl... thanks... this is exactly what i was looking for bryan From heafnerj at spam.vnet.net Thu Jul 17 22:12:41 2003 From: heafnerj at spam.vnet.net (Joe Heafner) Date: Thu, 17 Jul 2003 21:12:41 -0500 Subject: Mac OS X, Fink, Python, and web browser References: <2b012c5e.0307151342.e5db114@posting.google.com> <7h3n0fd123r.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > IIRC, webbrowser.py uses internet config on the mac, so you certainly > should get the default browser. I've had trouble getting with > webrowser.py on Mac OS X before now, though, but I didn't dig. > I have the file webbrowser.py in two places, one with the python that ships with OS X and one with Fink's Python22 and they're virtually identical. I'm lost as to what to do. JH From staschuk at telusplanet.net Mon Jul 21 20:37:01 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 21 Jul 2003 18:37:01 -0600 Subject: classes In-Reply-To: <2259b0e2.0307210451.203db2ef@posting.google.com>; from mis6@pitt.edu on Mon, Jul 21, 2003 at 05:51:16AM -0700 References: <2259b0e2.0307210451.203db2ef@posting.google.com> Message-ID: <20030721183701.C188@tibia.amotlpaa.bogus> Quoth Michele Simionato: > Steven Taschuk wrote in message news:... [...] > > _the_instance = None > > class MySingleton(object): > > def __new__(self): > > global _the_instance > > if _the_instance is None: > > _the_instance = object.__new__(self) > > return _the_instance > > Why are you using a global here and not [a class attribute] The memory of that thread a little while back about using __del__ with singletons. If the instance is referenced by a class attribute, the cyclic reference prevents the __del__ from being used. If the cycle goes through a module attribute, though, the zapping of module dicts during shutdown breaks the cycle and lets the __del__ run. (Whether all this is true depends on the version of Python, I think, but I don't know the details.) This might be relevant to the OP, whose example was a singleton representing the single database connection used by an entire application -- in such a case, __del__ would be a natural place to make sure the connection is closed properly. I should have explained this bit of trickery. :( [...] > > Second approach: Use a metaclass. See > > > > > Unfortunately, I see that this recipe is not very recommendable. I have > just submitted a fix which seems to work: [...] Nice! -- Steven Taschuk Aral: "Confusion to the enemy, boy." staschuk at telusplanet.net Mark: "Turn-about is fair play, sir." -- _Mirror Dance_, Lois McMaster Bujold From pipen at beast_tu_kielce.pl Tue Jul 15 07:05:19 2003 From: pipen at beast_tu_kielce.pl (Artur M. Piwko) Date: Tue, 15 Jul 2003 11:05:19 +0000 (UTC) Subject: wxPython - question References: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> <4737hvob87b2699fvqkhl61i9ufqm1jnc4@4ax.com> Message-ID: In the darkest hour on Mon, 14 Jul 2003 22:13:20 -0700, Tim Roberts screamed: >>I am writing Jabber/others messenger. In this case, tray icon is not a sign of >>guruness, but user friendliness. > > I disagree. That is strictly a matter of opinion. > > Now, a tray icon that does not exist until some actionable event occurs is > probably a very natural UI, but the same thing could be achieved by > plopping up a dialog box. Even if I am running your messenger, yours is > not the only application I'm running by a long shot. > And all this is the matter of user configuration. Artur -- Before the Goat of Mendes... we all must take our turn | Artur M. Piwko Into the magic circle... where still the fire burns | mailto:s/_/./ We're spinning round and round... until one takes a fall | -- Mercyful Fate The fallen one will not return, the fallen one must burn | "Witches' Dance" From MK at foo.com Tue Jul 1 08:23:36 2003 From: MK at foo.com (MK) Date: Tue, 1 Jul 2003 14:23:36 +0200 Subject: PyQT and Mandrake 9.1 References: Message-ID: "Gilles Lenfant" wrote > I've been very excited by PyQT evangelists. Be careful. QT is controlled by one company, and it costs money. YMMV, however. From nirina at mail.blueline.mg Mon Jul 21 00:43:40 2003 From: nirina at mail.blueline.mg (Raseliarison nirinA) Date: Mon, 21 Jul 2003 07:43:40 +0300 Subject: If stereo WAV file's both channels are identical, change format to mono for all files recursively References: <9a410299.0307191620.7fe274ab@posting.google.com> <3F1A0B51.F69B258A@mega-nerd.com> Message-ID: <007101c34f43$692f0c40$f3a2383e@raseliar> "Erik de Castro Lopo" wrote: > klappnase wrote: > > > > Hi, > > > > I think there might be at least 24 bit wav-files, if you have a > > soundcard that supports 24 bit, may be even more, for professional use > > or so. > > Yep, both 24 bit PCM and 32 bit floating point encoded files > are un common use in professional and semi-pro audio recording. > > Erik "Erik de Castro Lopo" wrote: > Yes, dozens. > > As well as 8 and 16 bit integer PCM files, there are also 24 > and 32 bit integer PCM, 32 and 64 bit floating point PCM, > A-law, u-law, at least 6 different forms of ADPCM (adaptive > differential PCM), GSM6.10, MP3 and many, many more. > > Fortunately other than the ones listed above, all the others > are pretty rare. i found in my win98box a stereo wave file encoded in ADPCM 4 bits. of course, an unknown format for wave module. among all those file formats, i'm wondering which are supported by wave module or can be manipulated with chunck module. maybe a silly question but i'm neither a professional nor a semi-pro one. -- nirinA From mike at nospam.com Wed Jul 30 20:30:13 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 30 Jul 2003 17:30:13 -0700 Subject: Dict to "flat" list of (key,value) References: Message-ID: Mike Rovner wrote: > Nicolas Girard wrote: >> Forgive me if the answer is trivial, but could you tell me how to >> achieve the following: >> >> {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...] > > [list(i) for i in d.items()] Sorry, I missed v1,v2 flattening. From me at privacy.net Wed Jul 30 08:34:41 2003 From: me at privacy.net (Heather Coppersmith) Date: 30 Jul 2003 08:34:41 -0400 Subject: Is there a standard module library function to access /etc/passwd or /etc/group References: <16469f07.0307300416.351ba776@posting.google.com> Message-ID: On 30 Jul 2003 05:16:43 -0700, robin.cull at pace.co.uk (Robin Cull) wrote: > ... Something that gives access to the C standard libarary > functions get[pw|group]ent(), for example ... Right out of the table of contents of Python's Library Reference: 8.2 pwd -- The password database 8.3 grp -- The group database When all else fails, read the manual.... ;-) Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From staschuk at telusplanet.net Tue Jul 1 15:47:57 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 13:47:57 -0600 Subject: Question regarding naming convention In-Reply-To: <1057062415.13616.0@doris.uk.clara.net>; from spam.trap@btinternet.com on Tue, Jul 01, 2003 at 01:28:02PM +0100 References: <1056988215.49928.0@iris.uk.clara.net> <1057062415.13616.0@doris.uk.clara.net> Message-ID: <20030701134757.A16188@tibia.amotlpaa.bogus> Quoth michael: [...] > Is there no way to write a class, such that the statement: > > import MyClass > > would dynamically import the MyClass class from MyClass.py ? Not recommended, but: # MyClass.py import sys class MyClass(object): pass sys.modules['MyClass'] = MyClass This is a dangerous hack; I'm sure there's lots of code which expects sys.modules to contain only modules. Better, if you really want this kind of behaviour, is to write a custom __import__ function. See > It just surprises me that there isn't a neater way around this, as > Python seems to encapsulate most everything else in a simple way. It's fairly rare for a module to contain only one entity of interest to importers. (StringIO is unusual in this respect.) Since you're coming from a Java background, you might try thinking of modules as analogous to leaf-level Java packages. For example, where Java has java/ util/ LinkedList.java AbstractList.java # etc. Python would have java/ __init__.py # to make java a package; probably just has docstring util.py # contains classes LinkedList, AbstractList, etc. -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From heikowu at ceosg.de Tue Jul 15 21:03:40 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 16 Jul 2003 03:03:40 +0200 Subject: UDP client-server problem In-Reply-To: <538fc8e.0307151318.12551933@posting.google.com> References: <538fc8e.0307151318.12551933@posting.google.com> Message-ID: <1058317420.619.85.camel@d168.stw.stud.uni-saarland.de> This should work: Server ====== import socket import time # Constants. PORT = 37 # Create and bind the socket which listens for packets. srvsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) svrsocket.bind(('',PORT)) while 1: # Block waiting for packet. data, address = svrsocket.recvfrom(256) print "Client sent:", data print "Client at:", address # Got a packet, reply to address packet came from. srvsocket.sendto(str(time.time()),address) Client ====== import socket # Constants. PORT = 37 # Create new socket, let it bind to an OS-chosen port. clisocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while 1: data = raw_input("Enter what the server receives.") if data: # Send data to server, irrelevant what. clisocket.sendto(data,("localhost",PORT)) # Block waiting for reply. data, address = clisocket.recvfrom(256) print "Server sent time:", data else: break Look at the above code. There were several errors in your original implementation, e.g. that time never got updated while the server ran, and several other things. I also don't see the need for a Tijd class. HTH! Heiko. PS: The above code is untested, if there's something wrong, my bad... :) PPS: Read the UNIX TCP/IP Network Programming FAQ if you're into socket programming! Google for it, I currently don't know the URL... From ngps at netmemetic.com Sat Jul 5 10:26:15 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 5 Jul 2003 14:26:15 GMT Subject: Apache mod_python and Sessions References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> Message-ID: According to Dale Strickland-Clak : > Markus Schaber pushed the bounds of literature with: > > Does anybody know a module that works with Apache 1.3 mod_python and > > provides session tracking? > > This is pretty easy to do by hand using MD5 and a cookie. Throw in a secret and get HMAC-MD5. See AuthCookies in M2Crypto, http://www.post1.com/home/ngps/m2 -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://www.post1.com/home/ngps -+- Open Source Python Crypto & SSL From martin at v.loewis.de Mon Jul 14 01:39:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 14 Jul 2003 07:39:57 +0200 Subject: Qualified appology (was Re: anything like C++ references?) References: <1br3hv4434gn7p2pdg1bgtg8dtlak3id3s@4ax.com> Message-ID: Stephen Horne writes: > I've said my piece on meanings derived from computer science (and in > turn from mathematics, as it happens - variables as placeholders for > values predate electronic computers by quite some time. And so does mine: Variables are *not* containers of values, in traditional mathematics. They are bound to values instead. > Even so, you can think of immutable objects as achieving 'expected' > assignment semantics simply because they are immutable. That does not > apply to mutable objects. So you can claim that Python behaviour is > consistent within itself, but only by claiming that it is consistently > different from this 'expected' behaviour. I am firmly convinced that your understanding of assignment is in complete contradiction with traditional computer science, and the notion of variables from a time that predates electronic computers. So your expectation is wrong. Assignment does not mean that something is copied, it means that something is *bound*. > That's not the same thing as saying they are doing 'the right thing' > or that the computer science definitions don't exist You haven't given proof that these definitions do exist in "computer science", and that the definitions match your understanding. To do so, you would have to refer to some widely-used literature where a precise definition of "variable" and "assignment" is given. So far, you didn't show such proof - and anybody claiming that literature fails to give proper definition, is inconsistent across authors, or typically gives definitions that are different from your understanding might be just as right as you might be. > All variables are implemented as references, but that is not the same > as saying that all values are references. That's true. Values are not references, in Python. Values are values. > As Guidos own words reveal (I already posted the link twice) the > purpose of using immutables tuples is performance optimisation to > save copying while still defending against against accidental > mutation (ie it provides the computer theory standard assignment > semantics efficiently). > > The same rationale should equally apply to all types, including the > mutable types. What is "the same" here: That mutable values should save copying when being assigned? This is the case. That mutable values should be protected against accidental mutation? That would be pointless - they are mutable on purpose. > I shouldn't need to force copying of class instances in the > container for the exact same reason that Guido highlights for > tuples. It is a good thing that you need to invoke explicit code to perform copying of objects. For objects, in general, you have the choice of shallow or deep copies. Either may be meaningful, depending on the context, and the language should not guess. Also, some objects (files, windows) don't have a meaningful copy semantics in the first place. Assignment has nothing to do with copying. > Having copy-on-write for all objects (obviously the actual copying > never happening for immutables) would be both fully self-consistent > and consistent with the computer science definitions. I can only repeat myself here: Assignment has nothing to do with copying. Regards, Martin From justinjohnson at fastmail.fm Wed Jul 9 08:30:05 2003 From: justinjohnson at fastmail.fm (Justin Johnson) Date: Wed, 09 Jul 2003 06:30:05 -0600 Subject: process.py problems In-Reply-To: <20030708170131.C13603@ActiveState.com> References: <20030708153117.127C0326C0@www.fastmail.fm> <20030708094057.C9520@ActiveState.com> <20030708210829.B3BBE3886D@www.fastmail.fm> <20030708170131.C13603@ActiveState.com> Message-ID: <20030709123005.C0B58374AF@www.fastmail.fm> After replacing my process.py I still get an error with the dir command (see below). I'm getting some wierd results with normal .exe commands though. Commands that don't have much output come back just fine, but commands that have more output, even if they don't take long to run necessarily, seem to get stuck and just hang, never returning. E:\ccase\python\uhg\uht>python ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import process >>> p = process.ProcessOpen("dir") process: info:ProcessOpen.__init__(cmd='dir', mode='t', cwd=None, env=None) process.res: info:[11054544] ProcessOpen._start(): create child stdin: <_FileWra pper: file:None fd:3 os_handle:> process.res: info:[11054544] ProcessOpen._start(): create child stdout: <_FileWr apper: file:None fd:4 os_handle:> process.res: info:[11054544] ProcessOpen._start(): create child stderr: <_FileWr apper: file:None fd:5 os_handle:> process: debug:_whichFirstArg: first='dir', rest='' Traceback (most recent call last): File "", line 1, in ? File "process.py", line 1118, in __init__ self._startOnWindows() File "process.py", line 1289, in _startOnWindows cmd = _fixupCommand(cmd, self._env) File "process.py", line 516, in _fixupCommand cmd = _whichFirstArg(cmd, env) File "process.py", line 325, in _whichFirstArg candidate = which.which(first) File "which.py", line 251, in which raise WhichError("Could not find '%s' on the path." % command) which.WhichError: Could not find 'dir' on the path. >>> >>> p = process.ProcessOpen("cleartool lsvob -l") process: info:ProcessOpen.__init__(cmd='cleartool lsvob -l', mode='t', cwd=None, env=None) process.res: info:[18469440] ProcessOpen._start(): create child stdin: <_FileWra pper: file:None fd:3 os_handle:> process.res: info:[18469440] ProcessOpen._start(): create child stdout: <_FileWr apper: file:None fd:4 os_handle:> process.res: info:[18469440] ProcessOpen._start(): create child stderr: <_FileWr apper: file:None fd:5 os_handle:> process: debug:_whichFirstArg: first='cleartool', rest='lsvob -l' process: debug:_SaferCreateProcess(appName=None, cmd='"C:\\Program Files\\Rational\\ClearCase\\bin\\cleartool .EXE" lsvob -l', env=None, cwd=None) os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' process: info:_registerprocess(process=) ***** It doesn't return here ***** On Tue, 8 Jul 2003 17:01:32 -0700, "Trent Mick" said: > > Yup, process.py is expected a which.py <1.0. Crappy. I need to put up a > new process.py. To work around in it in your current build you need to > changes process.py's usages of which.which() to expect a single hit > instead of a list of a all hits. In other words, which.which() changed > from: > >>> which.which("python") > ["C:\\Python22\\python.exe", "C:\\Python21\\python.exe", ...] > to: > >>> which.which("python") > "C:\\Python22\\python.exe" > > This is a little bit of a pain to do though. I have attached an untested > process.py that should have this fixed. I apologize for the informalness > of this. I'll try to get a new process.py version up on > when I get a chance. > > Cheers, > Trent > > > [Justin Johnson wrote] > > Thanks for the reply! > > > > which 1.0.2 > > > > Here's the log output with the dir command > > ----------------------- > > process.res: info:[18392288] ProcessOpen._start(): create child stdin: > > <_FileWra > > pper: file:None fd:3 os_handle:> > > process.res: info:[18392288] ProcessOpen._start(): create child stdout: > > <_FileWr > > apper: file:None fd:4 os_handle:> > > process.res: info:[18392288] ProcessOpen._start(): create child stderr: > > <_FileWr > > apper: file:None fd:5 os_handle:> > > process.res: info:[18392288] ProcessOpen.__del__() > > process: info:[18392288] ProcessOpen.close() > > process: info:[18392288] ProcessOpen: closing stdin (<_FileWrapper: > > file:None fd > > :3 os_handle:>). > > process: debug:[18400496] _FileWrapper.close() > > process: debug:[18400496] _FileWrapper.close: close handle > > process: debug:[18400496] _FileWrapper.close: closing handle raised > > process: debug:[18400496] _FileWrapper.close: done closing handle > > process: info:[18392288] ProcessOpen: closing stdout (<_FileWrapper: > > file:None f > > d:4 os_handle:>). > > process: debug:[18400720] _FileWrapper.close() > > process: debug:[18400720] _FileWrapper.close: close handle > > process: debug:[18400720] _FileWrapper.close: closing handle raised > > process: debug:[18400720] _FileWrapper.close: done closing handle > > process: info:[18392288] ProcessOpen: closing stderr (<_FileWrapper: > > file:None f > > d:5 os_handle:>). > > process: debug:[18403024] _FileWrapper.close() > > process: debug:[18403024] _FileWrapper.close: close handle > > process: debug:[18403024] _FileWrapper.close: closing handle raised > > process: debug:[18403024] _FileWrapper.close: done closing handle > > process: debug:[18400720] _FileWrapper.close() > > process: debug:[18400496] _FileWrapper.close() > > process: debug:[18403024] _FileWrapper.close() > > ---------------- > > > > I also get the following results running commands that are in my path... > > ------------------ > > g`"apper: file:None fd:5 os_handle:> > > process: debug:_SaferCreateProcess(appName=None, > > cmd='C lsview -s', > > env=None, > > cwd=None) > > os.getcwd(): 'E:\\ccase\\python\\uhg\\uht' > > > > process.res: info:[18680944] ProcessOpen.__del__() > > process: info:[18680944] ProcessOpen.close() > > process: info:[18680944] ProcessOpen: closing stdin (<_FileWrapper: > > file:None fd > > :3 os_handle:>). > > process: debug:[18696880] _FileWrapper.close() > > process: debug:[18696880] _FileWrapper.close: close handle > > process: debug:[18696880] _FileWrapper.close: closing handle raised > > process: debug:[18696880] _FileWrapper.close: done closing handle > > process: info:[18680944] ProcessOpen: closing stdout (<_FileWrapper: > > file:None f > > d:4 os_handle:>). > > process: debug:[18696832] _FileWrapper.close() > > process: debug:[18696832] _FileWrapper.close: close handle > > process: debug:[18696832] _FileWrapper.close: closing handle raised > > process: debug:[18696832] _FileWrapper.close: done closing handle > > process: info:[18680944] ProcessOpen: closing stderr (<_FileWrapper: > > file:None f > > d:5 os_handle:>). > > process: debug:[18699984] _FileWrapper.close() > > process: debug:[18699984] _FileWrapper.close: close handle > > process: debug:[18699984] _FileWrapper.close: closing handle raised > > process: debug:[18699984] _FileWrapper.close: done closing handle > > process: debug:[18696832] _FileWrapper.close() > > process: debug:[18696880] _FileWrapper.close() > > process: debug:[18699984] _FileWrapper.close() > > --------- > > > > > > -- > Trent Mick > TrentM at ActiveState.com From toofat at world.com Wed Jul 16 06:21:38 2003 From: toofat at world.com (À±°Ç¦ò) Date: Wed, 16 Jul 2003 18:21:38 +0800 Subject: How about using python to write a CMS? Message-ID: To write a CMS, everyone is thinking about PHP, but, what do you think if I am using python to write a Content Management System? From adalke at mindspring.com Mon Jul 21 13:33:08 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 21 Jul 2003 11:33:08 -0600 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: Message-ID: Alan Dechert: > > "greyed" in normal UI parlance means the option is no longer selected. > > What happens if someone pressed the wrong button? How is the correct > > selection made? > > > Point (or click on) again to de-select. Agreeing with Ian Bicking in his followup, there's no need to grey out the unselected fields, just emphasize the selected one. > > No apostrophe? What if I want to vote for "O'Reilly" > > > As a matter of fact, we won't let you vote for O'Reilly. He-he, I was thinking of O'Reilly as the book publisher, forgetting there's another one more closely involved with politics. I brought it up because I remember on our old Plato system (last 1980s), the Plato admin for the department was a "O'Something" and rewrote some code which didn't allow him to use an apostrophe for his name. > Okay we'll have an apostrophe available. Anything else? I don't think there's need for accents, umlauts, tildes, and other such marks, even if it does mean leaving it out is technically a misspelling. > Mercuri (Mercuri-Neumann, more accurately), suggests the paper ballot be > inaccessible to the voter -- viewable behind glass. This involves some > expensive and proprietary hardware since paper handling must also deal with > rejected printouts. Huh. Well, like I said, I know just enough to be dangerous. I like your method instead. > My scheme is cheaper and lower tech. It allows the voter to handle the > ballot. This involves a minor security issue (then again, since when have > we decided we can't trust voters to touch their ballots?). Agreed. We're trusting people to make a vote, so the little bit of extra trust needed to handle a ballot seems appropriate. > It is a real life problem. We've given a lot of thought to this issue. The > printout will be designed so that counterfeits can be detected easily. Cool! I'm feeling all warm and fuzzy about your work now. :) > > Isn't that overkill? I seem to recall that already there are provisions > > for people with special needs to have someone in the booth to help. > > > I don't think it's overkill. One of the current [lame] arguments against a > "voter-verified paper trail" is that "Mandating Voter-Verified Paper Trails > Could Deny Voters With Disabilities the Right to Cast a Secret Ballot." Indeed, and you're right. Objection withdrawn. > > Python would do this just fine. There are the various GUI projects, but > > this sounds like a good place for pygame. > > > Okay, thanks for your input. BTW, another possibility for a demo is to use Flash. I've never used it, but I hear it has some sort of authoring environment and it's pretty popular and documentation about it is widely available. It might be best to start with this for a demo. Andrew dalke at dalkescientific.com From stefan.behrens.usenet at gmx.net Wed Jul 9 09:27:02 2003 From: stefan.behrens.usenet at gmx.net (Stefan Behrens) Date: Wed, 09 Jul 2003 15:27:02 +0200 Subject: Detecting user activity in Python Message-ID: Hi all, does anyone know a way to detect whether the user is "active" at the desktop? What I mean is, whether he/she is actively using the machine by typing or moving the mouse. What I am looking for is some kind of trigger to subscribe for. I'd need to distinguish cases where the screen is locked and someone just touched the mouse unwantedly. I rather doubt that such functionality is in Python itself, i.e. can be used platform independently. So in that case, has anyone examples of how to do that in native C++ for Windows and Linux? TIA /Stefan. From jon+usenet at unequivocal.co.uk Thu Jul 10 19:36:52 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 10 Jul 2003 23:36:52 GMT Subject: Sample Web application References: Message-ID: In article , A.M. Kuchling wrote: > Someone should write a specification for the communication protocol > (a protocol simpler than FastCGI, which has a specification but is > too complicated) I think you've said this before, but I still don't understand it. The FastCGI protocol is very simple, and even if it wasn't you only have to implement it once and then everyone can use that code. jonpy implements the entire protocol, including all optional features, in 500 lines of Python, which includes a lot of debugging code. If you didn't implement the optional features, which most people don't, then it's even simpler. From staschuk at telusplanet.net Wed Jul 30 13:21:52 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 30 Jul 2003 11:21:52 -0600 Subject: Python..Tkinter..PYTHONPATH.. In-Reply-To: ; from usc_dog@yahoo.com on Tue, Jul 29, 2003 at 11:54:16AM -0700 References: Message-ID: <20030730112152.B361@tibia.amotlpaa.bogus> Quoth q: > I have a Linux RH8.0 system. I installed Python2.2 from the 8.0 ISO > updates. I installed the Tcl 8.3.3 from the Tcl site... I also > installed the tcllib 1.0. > > My goal is to get viewcvs to run. However, when I check to see where > the system thinks things are, the PYTHONPATH env var is blank. > > echo $PYTHONPATH --> produces nothing.... > > So, can anyone tell me what it should say? [...] This variable is analogous to $PATH; it lists directories in which the Python import mechanism will search for modules. The interpreter supplements this list with some paths it knows itself; for the complete result, launch the Python interpreter (by typing 'python' at your shell prompt) and type import sys sys.path Unlike $JAVA_HOME, for example, $PYTHONPATH does *not* give the path to the Python installation. I don't know what viewcvs is, but a typical application does not require any modification to $PYTHONPATH unless it is installed in a weird place. Normally Python modules get installed into, e.g., /usr/lib/python2.2/site-packages, which is among the directories the interpreter uses automatically. > [...] Can anyone shed any light > as to how this var is populated, and why it might be blank....? [...] It is populated like any shell variable. It should be blank when the interpreter's default paths are sufficient. > [...] Can > anyone suggest what file I need to alter/should modify to have this > properly set whenever a user logs into the system....? The obvious places are /etc/profile and ~/.bashrc, as appropriate. ... but none of this seems obviously relevant to your objective. Is viewcvs not working? If not, what is the problem? -- Steven Taschuk staschuk at telusplanet.net "I'm always serious, never more so than when I'm being flippant." -- _Look to Windward_, Iain M. Banks From llothar at web.de Wed Jul 9 15:06:21 2003 From: llothar at web.de (Lothar Scholz) Date: 9 Jul 2003 12:06:21 -0700 Subject: Sample Web application (Re: Python vs PHP) References: Message-ID: <6ee58e07.0307091106.5744a6eb@posting.google.com> "A.M. Kuchling" wrote in message news: > The Java Pet Store was suggested, but it was pointed out that it's a very > large application, requiring too much effort for an author to do in their > spare time. But you can see the difference only in larger application. Not everything scales good when programming in the large is necessary. I never found that simple benchmarks really helps. > I think I like the store best, because the first three applications are > all text-oriented, and the content manager doesn't do much beyond spitting back Yes, me too. It should be something that is usefull for comparison in larger commercial applications. And it should have test generators to check the system under heavy system load. From tamer.higazi at web.de Tue Jul 22 09:49:18 2003 From: tamer.higazi at web.de (Tamer Higazi) Date: Tue, 22 Jul 2003 15:49:18 +0200 Subject: How do i run an external program in an python script? Message-ID: Hi! I have no idea about python. I got a c++ program which i want to be called from an python script. How do i do that? My programs path under Linux is: /bin/Prinit For any help, Thank you Tamer From ageron at HOHOHOHOvideotron.ca Thu Jul 3 16:26:08 2003 From: ageron at HOHOHOHOvideotron.ca (Aurélien Géron) Date: Thu, 3 Jul 2003 22:26:08 +0200 Subject: Python Code Snippets References: <3f044c20$0$8303$4d4ebb8e@news.nl.uu.net> Message-ID: Hey thanks ! I wish it had a better ordering than just a list, but it's full of good stuff. Aur?lien "Guyon Mor?e" a ?crit dans le message de news:3f044c20$0$8303$4d4ebb8e at news.nl.uu.net... > You're gonna love this :) > > http://aspn.activestate.com/ASPN/Cookbook/Python > > > "Aur?lien G?ron" wrote in message > news:be1hs0$111s$1 at biggoron.nerim.net... > > Hi, > > > > Does anyone know where I can find a lot of Python code snippets? > > > > I searched the Python wiki and Internet but could not find more than five > or > > ten code snippets at a time. > > > > I'm looking for a kind of organized list (GUI snippets, database access > > snippets, I/O snippets, etc.). I find that there's no better way to learn > a > > language than to be able to cut&paste actual working bits of code. > > > > Thanks, > > Aur?lien > > > > > > From peter at engcorp.com Wed Jul 2 15:04:12 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Jul 2003 15:04:12 -0400 Subject: import/from import question References: Message-ID: <3F032CAC.6822C9AA@engcorp.com> "Artur M. Piwko" wrote: > > Is there a way to detect if module was imported by 'from import ' > or by 'import '? Why do you want to do that? It's likely to be a bad idea... From sandskyfly at hotmail.com Sun Jul 6 10:21:11 2003 From: sandskyfly at hotmail.com (Sandy Norton) Date: 6 Jul 2003 07:21:11 -0700 Subject: Least used builtins? References: Message-ID: [John Roth] > Reducing the number of builtins doesn't seem like the > right direction. I'd prefer to see something in the > official documentation that tries to bring some > conceptual order to the builtins. While my mind *likes* > to read down a list of dispariate things and try to bring > some order out of the mess, I know that others are > put off by the task. > > Although I agree with you that builtins could well benefit from some improved conceptual grouping within the official documentation, I think your point that the number of builtins should not be reduced doesn't seem to coincide with Guido's explicit plans to "reduce feature duplication" in Python 3.0 [1] I also second Dr. Mertz's suggestion that some of the existing builtins should be moved to appropriate modules within the standard library. This would accomplish at least two things in my mind: it would keep python minimal and allow additional features/functions to be added without the risk of namespace pollution. [1] http://www.europython.org/Talks/Slides/Slides_Guido_python_euro2003.ppt Cheers, Sandy From adechert at earthlink.net Mon Jul 21 12:59:15 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 16:59:15 GMT Subject: Python voting demo discussion References: <5penhv47e8plbm07dd615s5e0kj8hsfu7o@4ax.com> Message-ID: "L. A. Jackson" wrote in message news:5penhv47e8plbm07dd615s5e0kj8hsfu7o at 4ax.com... > > Sounds like an interesting project btw. Hope it has good auditing > features ;) > Thanks for your input, Lee. The ultimate [funded] product will have excellent auditing features. This is just a demo so that's not so important. It just has to look good and work smoothly. We've decided to go with Python for the demo. Alan Dechert From BPettersen at NAREX.com Fri Jul 25 17:56:47 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 25 Jul 2003 15:56:47 -0600 Subject: Static typing Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019202CE4738@admin56.narex.com> > From: Shane Hathaway [mailto:shane at zope.com] > > Scott David Daniels wrote: > > You _might_ want some static typing information as program > > documentation or to enable efficient program translation. The > > types sig was interested in allowing type annotation where > > possible. Remember, the type you might want may be more like > > "what protocol must these objects (the ones passing through > > this variable) follow" than "what are the construction details > > of these objects". > > > > I would like to see interface descriptions describing what > > kinds of parameters are required and results produced for > > packages that I am considering using. If there were a single > > central-python-endorsed form for those descriptions even better. > > If the descriptions can be mechanically read, and at least > > sometimes mechincally checked (possibly slowly, possibly only > > for slow execution), I might use such a system to check a module > > before announcing it to the world. > > Well, here's a pattern I've been trying out for this purpose: > use assert > statements at the top of the function. > > def foo(bar, baz): > assert isinstance(bar, int) > assert isinstance(baz, str) [...] ...which means you can't use foo with unicode strings or UserStrings, etc., etc. This is C programming in Python, ugly, inefficient, inflexible, and un-Pythonic. -- bjorn From edlsoft at adelphia.net Fri Jul 18 11:26:03 2003 From: edlsoft at adelphia.net (Burt Leavenworth) Date: Fri, 18 Jul 2003 15:26:03 GMT Subject: TKINTER problem Message-ID: <3f18102e.209114@news2.news.adelphia.net> Have used TKINTER for years with Python v1.5.2 with great success. But after installing verson 2.0 (and most recently 2.2.3) I have a problem exiting widgets by clicking on the exit button (x on upper right --- )---the system hangs. It's driving me nuts. Can some kind soul indicate what PATH statement they're using which deals with TCL/TK, etc? Burt Leavenworth. From owski at hotmail.com Wed Jul 16 10:15:58 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 14:15:58 +0000 (UTC) Subject: anything like C++ references? References: <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <20030714173855120-0600@news.xmission.com> <9mh6hv45v18apgn6lp7bo6mm63e5oba9rd@4ax.com> Message-ID: <20030716081550053-0600@news.xmission.com> In Duncan Booth wrote: > owski at hotmail.com (Adam Ruth) wrote in > news:f0f51c80.0307150921.7b6667e2 at posting.google.com: > >> 2) C++ makes a strong distinction between the initialization operator, >>=, and the assignment operator, =. Both const and reference variables >> use them differently. To me, that's a really big violation of proper >> 'computer science', because conceptually they're the *same* thing. >> But because of context, C++ makes a distinction. Python has no such >> distinction, initialization and assigment are always the same. >> >> (This is true of all static languages with the concept of a constant, >> and I don't really disagree with it as a valuable idiom, but it is >> inconsistent internally, where Python is consistent. Do any >> languages use a different operator for initialization?) > > Yes, Algol68. > > My Algol68 is more than rusty, but: > > Declare a name 'pi' to represent 3.1415926, i.e. declare a constant: > > REAL pi = 3.1415926; > > Declare a name 'x' to represent a local variable, and assign it a > value: > > REF REAL x = LOC REAL; > x := 3.1415926; > > Shorthand for the above: > > REAL x; > x := 3.1415926; > > or even: > > REAL x := pi; > > Initialisation uses '=', assignment uses ':='. Note that the constant > is defined as a real and initialised with one, but the variable is a > reference to a real and initialised with a storage location. The last > example is not initialising x with the value, it is implicitly > initialising x with a location then assigning the value into that > location. > That's interesting. What does it use for an equality operator? From martin at v.loewis.de Sat Jul 12 17:10:51 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 Jul 2003 23:10:51 +0200 Subject: Windows XP - Environment variable - Unicode In-Reply-To: References: <3f0e77fc@epflnews.epfl.ch> Message-ID: <3F10795B.9000501@v.loewis.de> John Roth wrote: > I don't think encoding is an issue. Windows XP stores all character data as > unicode internally, so whatever you get back from os.environ() is either > going to be unicode, or it's going to be translated back to some single byte > code by Python. Read the source, Luke. Python uses environ, which is a C library variable pointing to byte strings, so no Unicode here. > In the latter case, you may not be able to recover non-ascii > values, so Rob Willscroft's workaround to get the unicode version may be > your only hope. You are certainly able to recover non-ascii values, as long as they only use CP_ACP. > If you're getting a standard string though, I'd try using Latin-1, or the > Windows equivalent first (it's got an additional 32 characters that aren't in > Latin-1.) That, in general, is wrong. It is only true for the Western European and American editions of Windows. In all other installations, CP_ACP differs significantly from Latin-1. > Note that Release 2.3 fixes the unicode problems for files under XP. > It's currently in late beta, though. I don't know if it fixes the > os.environ() It doesn't. "Fixing" something here is less urgent and more difficult, as environment variables rarely exceed CP_ACP. If people get support for Unicode environment variables, they want Unicode command line arguments next. Regards, Martin From tomas at fancy.org Sun Jul 13 03:39:01 2003 From: tomas at fancy.org (Tom Plunket) Date: Sun, 13 Jul 2003 00:39:01 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: Ian Bicking wrote: > To be more specific, you would achieve the same effect with: > > def change(val): > return val + 1 > i = change(i) Yeah, thanks. I don't recall off-hand why it is that I wanted this functionality, but something came up a few weeks ago that seemed to beg for it. This was the solution that I used, but it was non-optimal for some reason. The question came to mind because of that global question posted just previously, to which I made a good response if I may say so myself. :) > There is no direct Python equivalent to the C++ function, for all > sorts of reasons (most of them very deliberate). Ok. I'd love to see the reasons for it. To me it just seems like there's a somewhat arbitrary line between immutables and mutables. > Is there someplace in particular to reference people who need to > learn about what Python variables are (that they are bindings, > etc)? Yeah, this is actually less a stumbling block, and more a desire to want to bind to another variable instead of that variable's value. I mean, if I do this: a = [ ] b = a a.append(4) print b [ 4 ] This seems inconsistent to me, although I understand that the two variables are just binding to the same list. No different than binding to the same tuple or integer or string, it's just that changing the value of a tuple, an integer, or a string means rebinding your variable to a different object. I suppose one "solution" would be a class that wraps the value, so the value can change but the object stays the same. Similar is using a list, but these two options make it a little less convenient, and one must exercise extreme caution lest one accidentally reassign as an int instead of changing the internals of the wrapper object. > This question comes up in many forms all the time, particularly > from people with a C background. Or rather, there are many > questions all of which are answered by that explanation... IMHO the variable binding discussion doesn't answer the question, it just provokes more questions. :) thanks to all who responded. -tom! From http Thu Jul 10 23:24:30 2003 From: http (Paul Rubin) Date: 10 Jul 2003 20:24:30 -0700 Subject: Securing 'pickle' References: Message-ID: <7xu19t21ap.fsf@ruckus.brouhaha.com> Ian Bicking writes: > A much easier way to secure your pickle is to sign it, like: > > cookie = dumps(object) > secret = 'really secret!' > hasher = md5.new() > hasher.update(secret) > hasher.update(cookie) > cookie_signature = md5.digest() That method is vulnerable to an "appending" attack against md5. I'll spare the gory details, but you should call md5 through the HMAC module to make the signature instead of using md5 directly. HMAC is designed to stop that attack. > You may then wish to base64 encode both (.encode('base64')), pop them > into one value, and you're off. Though I suppose at that point you may > be hitting the maximum value of a cookie. Hidden fields will work > nicely, though. You could split the session info into several cookies, but in that situation you should authenticate the whole cookie set with a single signature. Otherwise someone could paste together several cookies from separate sessions, and possibly confuse your server. From roy at panix.com Thu Jul 3 18:49:21 2003 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jul 2003 18:49:21 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: Dave Brueck wrote: > If Python were to become too slow or too weird I'd migrate to > another high-level language I can certainly see situations were Python might be too slow, but too weird? When would it be too weird? From mcherm at mcherm.com Wed Jul 2 19:07:00 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 2 Jul 2003 16:07:00 -0700 Subject: Clever One Liners Message-ID: <1057187220.3f036594d7404@mcherm.com> Hannu Kankaanp?? writes: > Could be even written as a perverted one-liner. I'm not picking on you in particular, there have been several people doing this lately, but I'd like to ask folks to please lay off the quest for one-liners. I understand the neat, oh-so-clever feeling one gets by trying to cram the most functionality into the least space, but if you're going to try that, do it in Perl (or better yet, APL) where it works so much better. I'm not putting down the exercise... I realize that it's all in good fun... but people who are new to Python and who read this newsgroup might get the wrong idea if they see a clever one-liner proposed as the solution for every easy question. It's simply NOT Pythonic to try to write clever one-liners, and we don't want to let newbies think it's appropriate. > ...Maybe a real 'for' loop for getting the words would be better > in this case though. So that the input could be verified too. See, I can bring this up in response to Hannu's posting without pointing fingers since he clearly understands (and points out) the advantages of a less compact style. Donning-my-asbestos-suit-now lly, -- Michael Chermside From tim.harford at rogers.com Sun Jul 6 20:02:39 2003 From: tim.harford at rogers.com (Tim) Date: Mon, 07 Jul 2003 00:02:39 GMT Subject: mod_python/good documentation? Message-ID: ...just starting to work with mod_python. There are a number of details and pitfalls: any suggestions on where to get some decent tips and tricks. I can comprehend the provided docs but...they are not that great. :-( Feel free to comment/recommend any other Apache modules for py. T From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 28 13:58:17 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 28 Jul 2003 19:58:17 +0200 Subject: Defining/declaring constants in Python In-Reply-To: References: Message-ID: <3f256437$0$49108$e4fe514c@news.xs4all.nl> Sriram Chadalavada wrote: > I am currently using raw numerical values and was wondering if > there is an equivalent of #define in Python for declaring constants. > Is there an elegant way of defining constants in Python? Please let > me know. First, #define is not declaring constants in C or C++. It is a preprocessor instruction that tells the compiler to replace a piece of source code text by another piece. That aside, there is no such thing as a preprocessor or constant declarations in Python. You can just define a bunch of attributes. That's what I do usually, for example in the constants.py module of my Pyro project: RIF_Varargs = (1<<0) RIF_Keywords = (1<<1) RIF_Oneway = (1<<2) RIF_VarargsAndKeywords = RIF_Varargs | RIF_Keywords DENIED_UNSPECIFIED=0 DENIED_SERVERTOOBUSY=1 DENIED_HOSTBLOCKED=2 DENIED_SECURITY=3 ...and so on. If you need 'constants' in a stricter sense, have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 --Irmen From jar at mminternet.com Thu Jul 31 22:31:17 2003 From: jar at mminternet.com (james roush) Date: Thu, 31 Jul 2003 19:31:17 -0700 Subject: Trustudio plugins for Eclipse IDE Message-ID: Earliear this week I asked for information regarding downloading Trudio's plugins for the Eclipse IDE. Several people emailed me with help including one kind soul who actually emailed the plugina themselves. I intended to email these people back to thank them, but I accidentally deleted their messages when I was digging out from under the constant avalanche of email. To those who emailed me thanks for your help. the problem is solved. -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From ebolonev at rol.ru Sat Jul 5 18:15:10 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Sun, 6 Jul 2003 09:15:10 +1100 Subject: execute scripts on GUI References: Message-ID: Hello, Thomas! You wrote on Sat, 05 Jul 2003 19:45:50 +0200: TW> I want to start a script via an Icon on the Desktop, TW> and I wonder how I can execute my GUI-scirpts (Tk on KDE) TW> without the "Pyhton Shell" window popping up... In the Windows you have to rename script extension: .py -> .pyw. With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From bhards at bigpond.net.au Mon Jul 21 06:32:08 2003 From: bhards at bigpond.net.au (Brad Hards) Date: Mon, 21 Jul 2003 10:32:08 GMT Subject: pythonic malloc References: Message-ID: Karl Scalet wrote: > kjockey schrieb: >> I have some simple UDP code that does: >> s.sendto("\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",addr) >> >> This is OK, except that I'd like to change the text in the middle >> ("rachel", which is the hostname FWIW), and the NUL padding needs to go >> out to make the length 25 bytes (so the padding depends on the length of >> the name). >> >> So I could do something like: >> retpacket = "\xf0\x00\x02\x00"+socket.gethostname() >> while len(retpacket) < 26: > > shouldn't that be 25? Yes. >> retpacket += "\x00" >> s.sendto(retpacket, addr) >> >> But that feels "wrong". And Python in a Nutshell says its a bad idea - >> "anti-idiom". >> >> Can anyone show me the true path? > > No idea, if it's the true path: > > hn = socket.gethostname() > retpacket = '\xf0\x00\x02\x00%s%s' % (hn, (25-4-len(hn))*chr(0)) > s.sendto(retpacket, addr) Probably better for efficiency, but not much for readability.... Anyone else? From peter at engcorp.com Tue Jul 15 10:28:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 10:28:14 -0400 Subject: Securing the Pyton Interpreter? References: Message-ID: <3F140F7E.32F0544E@engcorp.com> Stephen VanDahm wrote: > > I'm looking for a way to install Python on a UNIX machine in a way such > that any user on the system can use it, but only to execute scripts that > are located in a certain directory. I do not have root access on the > machine that will be running Python, so my options are limited. I thought > about hacking the Python interpreter itself so that it will examine the > argument array and exit with an error if the script to be executed isn't > in the appropriate directory, but this seems pretty risky. The module > 'site.py' is imported automatically upon initialization -- I've thought of > adding the check there instead. I don't think either of these solutions > are very elegant. Is there a better way? You want something this freaky, *and* you want it elegant?! :-) Anyway, just go with site.py. Judging by the name, it's perfectly suited for the task. Of course, you know about the -S option, don't you? And PYTHONPATH? And PYTHONHOME? And someone installing their own interpreter? And.... -Peter From faizan at jaredweb.com Wed Jul 30 00:04:23 2003 From: faizan at jaredweb.com (Fazer) Date: 29 Jul 2003 21:04:23 -0700 Subject: Showing IP address of a user... References: <7b454334.0307291005.53ee8c07@posting.google.com> Message-ID: <7b454334.0307292004.53ee96a8@posting.google.com> Thank you Marnanel and everyone who replied. This gives me a better understanding. From spam at magnetic-ink.dk Sun Jul 6 17:32:22 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Sun, 6 Jul 2003 21:32:22 +0000 (UTC) Subject: python -c option References: Message-ID: <3f089566-aab89149-1d91-41c5-86d0-70c5d0a15f3e@news.szn.dk> Mike wrote: > I am very new to Python and read the docs section about having > python run commands from the command line. I have been successful > with: > > python -c "print 'Hello'" > > It prints Hello > > In the interpreter I can type 2+2 and it will return 4 but how do > I do that from the command line? #v+ python -c 'print 2+2' #v- > What I am really after is to do some command line processing where > the output of grep is returning "prog=.01234" and I want to beautify > it so it prints "12%" Assuming the output is "prog=.1234", you _could_ do ugly things like #v+ python -c 'import sys; exec(sys.stdin.readline()); print "%d%%" % (prog*100,)' #v- but why not write a small python script instead? // Klaus -- ><> unselfish actions pay back better From cybersamurai at mac.com Tue Jul 8 12:21:14 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Tue, 08 Jul 2003 13:21:14 -0300 Subject: Form using HTML on PythonCard Message-ID: <3F0AEF7A.6070509@mac.com> An embedded and charset-unspecified text was scrubbed... Name: mail.txt URL: From bens at replytothegroupplease.com Thu Jul 31 06:09:18 2003 From: bens at replytothegroupplease.com (Ben S) Date: Thu, 31 Jul 2003 11:09:18 +0100 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: Steven Taschuk wrote: > Quoth Kylotan: > [...] >> And does datetime.timetuple() actually return something equivalent to >> a struct_time as used by the time module? At first glance this looks >> to be true, but it isn't clearly documented as such. > > Isn't it? > > timetuple() > Return a 9-element tuple of the form returned by > time.localtime(). > > Problem is, time.localtime() doesn't return a 9-element tuple any more, it returns a struct_time. (Since 2.2, I think.) -- Ben Sizer http://pages.eidosnet.co.uk/kylotan From paul.moore at atosorigin.com Mon Jul 14 17:19:37 2003 From: paul.moore at atosorigin.com (Paul Moore) Date: 14 Jul 2003 14:19:37 -0700 Subject: path module References: <1057651068.5348.386.camel@lothlorien> Message-ID: <182bcf76.0307141319.7b6fed7a@posting.google.com> holger krekel wrote in message news:... > I agree that something like Jason Orendorff's path module should go into > the standard library. I've coded a similar module and i think that > a discussion about certain design decisions would probably improve our > approaches. Is it available anywhere? It would be nice to be able to try both, for comparison. Paul. From t.leeuwenburg at removme.bom.gov.au Wed Jul 16 22:29:13 2003 From: t.leeuwenburg at removme.bom.gov.au (Tennessee James Leeuwenburg) Date: Thu, 17 Jul 2003 12:29:13 +1000 Subject: Jython classpath question Message-ID: Hi all, Sorry for the newb question, but Googling and FAQing didn't work. Is it correct that Jython can only access Java classes which are inside JAR archives in the JYTHON_HOME directory? IT doesn't seem to be documented. I ask because I want to do groovy prototyping using Jython, and save myself a lot of coding overhead to try something a little out-of-the-box. I have a working directory where all my code lives, and because my app is under rapid development, I would prefer to avoid creating a JAR file every time I want to do some Python scripting? What do people suggest I do? Thanks, -Tennessee From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 9 10:44:47 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 09 Jul 2003 15:44:47 +0100 Subject: Tkinter question - proper output in Text widget In-Reply-To: <3F0C2030.40405@snafu.de> References: <3F0C2030.40405@snafu.de> Message-ID: <200307091544.47558.mfranklin1@gatwick.westerngeco.slb.com> On Wednesday 09 July 2003 15:01, T. Kaufmann wrote: > Hi there, > > I have some lines of code in a Tkinter programm - I want to list every > single file of a zip-archive in a Text widget: > > fp = os.popen("%s %s" % ('unzip -vl ', 'anyarchiv.zip', 'r') > for line in fp: > textWidget.insert(END, "%s" % (line)) > > The result is that the columns are not really proper if the file-size of > the listed files is different. An output example: > > > Length Method Size Ratio Date Time CRC-32 Name > -------- ------ ------- ----- ---- ---- ------ ---- > 1175 Defl:N 513 56% 05-23-03 13:51 084e4103 charset.py > 972 Defl:N 427 56% 04-05-03 18:42 b8bb850d controller.py > > > Here it looks good but not in my application (in the Text widget). Whats > wrong? How can I made a better result (proper columns). > > o-o > > Thomas Thomas, It did not look so good in my email client (I do not use fixed width fonts...) which is the problem I guess you are seeing in the Tkinter Text widget try setting the font to a fixed width font eg. Courier. You should also look at the zipfile module. This module allows you to do away with the os.popen("%s %s" % ('unzip -vl ', 'anyarchiv.zip', 'r') call like so: import zipfile zf = zipfile.ZipFile("'anyarchiv.zip") for name in zf.namelist(): ##blah textWidget.insert(END, "%s" % (line)) HTH Martin From pedro.werneck at bol.com.br Tue Jul 29 10:32:44 2003 From: pedro.werneck at bol.com.br (Pedro Werneck) Date: 29 Jul 2003 07:32:44 -0700 Subject: Debugging Python ? References: <3c91a864.0307282013.2acb2d1f@posting.google.com> Message-ID: That's a nice idea... I done something similar to redirect print statements to a text widget in a debug environment I am developing... but my point here is not to redirect output... I think a statement that simply does: if __debug__: print "..." would ease debugging... that: def _print(*args): for arg in args: print arg return True assert _print("bla", "bla bla") is very interesting but it would be nice to have a standard way to do that... a new statement, a modified assert statement or a new builtin... I am not that experienced on python, so I don't know... what do you Python gurus think ? Is this worth the effort ? From mwright at pro-ns.net Tue Jul 8 11:18:06 2003 From: mwright at pro-ns.net (Mark Wright) Date: 8 Jul 2003 08:18:06 -0700 Subject: Unexpected (by me) exec behavior Message-ID: I have a script that I use to control our build process. It is a general purpose script that exec's other scripts that contain project specific python code. In one of those other, project-specific, scripts I exec a third script. That third script is failing because it can't seem to 'import' successfully. It seems that if one 'exec's a string that in turn 'exec's another string, the 'import's don't work in the second string. I'm assuming that I'm misunderstanding something about Python namespaces, but here's an example that illustrates the problem: ---------------------------- # filename = t.py s1 = """ s2 = \"\"\" import socket def xyz(): print socket.gethostbyname('somehost') if __name__ == '__main__': xyz() \"\"\" def abc(): exec s2 if __name__ == '__main__': abc() """ exec s1 ----------------------------- Traceback (most recent call last): File "t.py", line 24, in ? exec s1 File "", line 13, in ? File "", line 11, in abc File "", line 6, in ? File "", line 4, in xyz NameError: global name 'socket' is not defined Can anyone explain this to me? Mark From andy47 at halfcooked.com Tue Jul 29 12:04:15 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 29 Jul 2003 17:04:15 +0100 Subject: variable assignment in "while" loop In-Reply-To: References: Message-ID: sismex01 at hebmex.com wrote: >>From: Andy Todd [mailto:andy47 at halfcooked.com] >>Sent: Martes, 29 de Julio de 2003 10:23 a.m. >> >>Spot on, with one (minor) correction. With a for loop you have to >>iterate over the results of a call to a method on the cursor, e.g.; >> >>for info in mydbcursor.fetchall(): >> print "Information:", info >> >>You could replace fetchall() with fetchmany() or, if you are feeling >>contrary, fetchone() ;-) >> >>Regards, >>Andy >> > > > Are you sure about this? Because, if you have to iterate > through .fetchall() (for example), then the cursor isn't > actually an iterable object, the result of fetchall() is > (it's a list, which is iterable), same goes for fetchmany(); > BUT, if you iterate over the results of fetchone() then > you're gonna do a columnwise iteration over a single row. > > :-) > > So... anyone... do cursors have an __iter__() method? > I don't have a DB module at hand to check it out... > > -gustavo > > Technically, cursor objects are not iterators, and the DB-API specification has this to say about the various methods that return data; """ .fetchone() Fetch the next row of a query result set, returning a single sequence, or None when no more data is available. ... .fetchmany([size=cursor.arraysize]) Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. ... .fetchall() Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). """ Which means that the cursor object itself is not an iterator, and the methods need only return a sequence (or sequence of sequences). But, thats not to say that the db modules can't implement a generator to produce the results from the 'fetch' methods if they want to. I don't know if any of the database modules do, but then thats up to the module authors and I tend not to worry about it too much, I just trust the module. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From MK at foo.com Tue Jul 1 08:26:09 2003 From: MK at foo.com (MK) Date: Tue, 1 Jul 2003 14:26:09 +0200 Subject: Python hosting? Message-ID: Can anybody recommend a good hosting package for Python? Must be cheap, that is max. $5 per month. If the solution offers Java+MySQL as well, that would be great! From newsgroups at jhrothjr.com Sat Jul 26 18:15:17 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 26 Jul 2003 18:15:17 -0400 Subject: Standard behaviour of a getSomething method References: Message-ID: "Stefan Schwarzer" wrote in message news:bfulr8$5mi$1 at online.de... > Mike Rovner wrote: > > Batista, Facundo wrote: > > > >> When I want to know about a attribute (e.g.: myAttrib) of an object, I > >> should use the specific method (e.g.: getMyAttrib). > > > > Python don't enforce nor encourage attribute hiding, > > so don't do it unless you have a good reason. > > Plain access to attributes is simple: > > myObject.myAttribute > > I think, you should hide an attribute if it doesn't refer to the > object's abstract interface but instead merely depends on the > implementation. In that case, you shouldn't provide any means to > access the attribute directly, be it via direct attribute access or > accessor methods. I agree with the general principle: implementation details shouldn't be generally availible in the same way as the public API. > Somewhat, I dislike the sometimes recommended __getattr__/__setattr__ > approach. I wouldn't like to have something like That sounds more than a bit heavyhanded to me. The more general practice is simply to name private attributes with a leading underscore. Then you can verify that there aren't any improper references by scanning the source for references to underscored variables that don't start with "self._". John Roth From h.b.furuseth at usit.uio.no Sun Jul 6 11:16:43 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 06 Jul 2003 17:16:43 +0200 Subject: M2Crypto: How to check server certificate? Message-ID: Does anyone know how I check the server certificate with M2Crypto? Currently a program I have inherited does this: #!/local/bin/python2.2 import xmlrpclib from M2Crypto.m2xmlrpclib import Server, SSL_Transport svr = Server('http://my.machine.no:8000', SSL_Transport(), encoding='iso8859-1') # TODO: check server certificate secret = svr.login('myuser', 'mypassword') -- Hallvard From skip at pobox.com Tue Jul 29 12:08:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 29 Jul 2003 11:08:10 -0500 Subject: variable assignment in "while" loop In-Reply-To: References: Message-ID: <16166.39914.404838.939106@montanaro.dyndns.org> Sybren> Is it possible to use an assignment in a while-loop? Nope. To learn why, read question 6.30 of the FAQ: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.030.htp Skip From anton at vredegoor.doge.nl Wed Jul 16 16:27:12 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 16 Jul 2003 22:27:12 +0200 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: Duncan Booth wrote: >At this year's ACCU conference, Guido talked somewhat about the history of >Python. He said it was based on ABC, "other influences: Modula-3, C/C++ and >even Smalltalk, Icon, Pascal, Algol-68". By my reckoning that makes two of >the answers to question 4 correct. Sorry to read that, poor Guido must have been lost in Time-loop complexities. In fact Python is a direct descendant from Frank Ostrowki's GFAbasic for the atari ST series. Once Guido realizes it he will doubtlessly clear up the few remaining inconsistencies and we can expect the magical Python 3000 to be fully compliant :-) Anton From johnroth at ameritech.net Wed Jul 2 07:23:48 2003 From: johnroth at ameritech.net (John Roth) Date: Wed, 2 Jul 2003 07:23:48 -0400 Subject: Date issue Win98 vs NT References: Message-ID: "Stan Cook" wrote in message news:SDsMa.38974$hV.2346862 at twister.austin.rr.com... > Has anyone else had this or a similar problem and is there a workaround? > > This piece of code: > > from time import gmtime, strftime > _log = _log + "\\" + strftime("%m%d%y", gmtime()) + ".log" > > produces a file with the name 'today's date.log' on NT, but creates a file > called 'tomorrow's date.log' on Windows 98. I would really like to know > why this happens. Any help offered is very much appreciated. I just tried it (Win 98SE, Python 2.2) and it works properly. Have you checked your date settings on the Win 98 machine? John Roth > > Thanks, > > Stan > > From tim.one at comcast.net Fri Jul 25 02:01:10 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 25 Jul 2003 02:01:10 -0400 Subject: Python 2.3C1 Fails to build ? In-Reply-To: Message-ID: [Holden Caulfield] > I am trying to build Python 2.3 RC1 (2.3c1) on Cray SV1 running > UNICOS 10.0. And I am difficulty building it on this architecture. Please open a bug report on SourceForge. > Background > -------------- > > . Python 2.2.3 builds withs no problem. (without any changes). > . This architecture has all C-datatypes as 8 bytes. > > Try 1: > ------- > > I got this error message first time around. > > ~~~~ Cut ~~ > cc -h nomessage=450 -h nostdc -h noconform -c -DNDEBUG -h scalar0 -h > vector0 -I. -I./Include -DPy_BUILD_CORE -o Parser/grammar.o > Parser/grammar.c > CC-513 cc: ERROR File = Parser/grammar.c, Line = 45 > A value of type "int" cannot be assigned to an entity of type "char > *". > > d->d_name = strdup(name); > ^ > > CC-513 cc: ERROR File = Parser/grammar.c, Line = 105 > A value of type "int" cannot be assigned to an entity of type "char > *". > > lb->lb_str = strdup(str); > ^ > > Total errors detected in Parser/grammar.c: 2 > make: *** [Parser/grammar.o] Error 1 > > ~~~~~~ > > - For some reason the strdup prototype does not get picked by the > python build. strdup isn't a standard C function, so there's no header file that can be counted on to contain its prototype across platforms. > Anyways, since strdup is there in libc, I just #ifdef'ed the > prototype for _CRAY and proceeded. Please open that bug report and identify the header file this system wants you to include for strdup, and a preprocessor symbol we can use to conditionalize the include of that header file. > It went further this time around, but now I get this error in > obmalloc.c, which seems more problematic to fix. > > ~~~ Error message cut ~~~ > cc -h nomessage=450 -h nostdc -h noconform -c -DNDEBUG -h scalar0 -h > vector0 -I. -I./Include -DPy_BUILD_CORE -o Objects/obmalloc.o > Objects/obmalloc.c > CC-61 cc: ERROR File = Objects/obmalloc.c, Line = 371 > The integer operation result is out of range. > > PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) > ^ > > CC-61 cc: ERROR File = Objects/obmalloc.c, Line = 371 > The integer operation result is out of range. > > PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) > ^ > > Total errors detected in Objects/obmalloc.c: 2 > make: *** [Objects/obmalloc.o] Error 1 > ~~~~~~~~~~~~~~ > > Any ideas what is going on? I'm surprised this hasn't triggered a (bogus) error on some other platform before! Those macros expand to a pretty hairy initializer. But I don't think there's anything wrong with it, so you should file a bug report against the Cray compiler. obmalloc was present in 2.2.3 but not enabled by default. That's why you didn't see this problem before. In 2.3 obmalloc is enabled by default. You can get unstuck by disabling it again (I don't know how to disable it on your platform -- file the Python bug report and someone will be able to respond to you there). While obmalloc is a big win on most platforms, I wouldn't enable it on a Cray of this sort before doing serious with-and-without performance testing. From elainejackson7355 at home.com Sun Jul 13 01:59:35 2003 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 13 Jul 2003 05:59:35 GMT Subject: new in town References: <2a897f11.0307121139.21470fbb@posting.google.com> Message-ID: David McNab wrote in message news:pan.2003.07.13.03.27.44.711790 at 127.0.0.1... | Don't be intimidated if the Tkinter docs you come across urge you to | approach it from a Tk viewpoint- there's an excellent guide at: | http://www.astro.washington.edu/owen/TkinterSummary.html | David Thanks for the tip. From richie at entrian.com Fri Jul 11 03:47:49 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 11 Jul 2003 08:47:49 +0100 Subject: Collective memory In-Reply-To: <1fxw51u.2b4m6zc39wulN%proto@panix.com> References: <3F09F136.6060000@srv.net> <3F0B2857.6EE3A30F@ev1.net> <1fxw51u.2b4m6zc39wulN%proto@panix.com> Message-ID: <7eqsgvs1tj2h55lork2jmhv0itssudq93j@4ax.com> [Charles] > y = x/*p; > > is quite different from: > > y = x / *p; > > The first way, "/*" will begin a comment...the second way, > you get the integer "x" divided by the integer pointed to by "p". [Walter] > Ouch!! That is one reason code coloring is *important*. Me too. In the (not too distant) days when syntax colouring was rare and C would quietly declare undeclared variables as 32-bit integers, we lost several man days to a piece of code like this: void function() { short x; /* Some X thing /* short y; /* Some Y thing */ functionExpectingPointersToShorts(&x, &y); } Dragging us back on topic, this is why languages should only have single-line comments, and shouldn't let you reference variables before they're defined. -- Richie Hindle richie at entrian.com From printers at sendme.cz Mon Jul 14 16:10:46 2003 From: printers at sendme.cz (A) Date: Mon, 14 Jul 2003 22:10:46 +0200 Subject: Is there any clever solution? Message-ID: <3F132A66.3211.D9B4A60@localhost> Hi, I use a free webhosting. The problem is that if a user visits my website, together with index.html( my first webpage) also 2 other web pages with ads are open. Is it possible somehow to prevent that? Or is it possible to close those 2 web pages (more or less full of advertisements) and let only mine available? Thanks for help. Ladislav From h.b.furuseth at usit.uio.no Fri Jul 18 09:21:31 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 18 Jul 2003 15:21:31 +0200 Subject: path module References: Message-ID: Ian Bicking wrote: >On Mon, 2003-07-14 at 06:44, Hallvard B Furuseth wrote: >>Ian Bicking wrote: >>> Interesting, but I think a bad idea. (...) If someone was using VMS >>> paths, I would assume they would subclass path for that OS, adding the >>> portions that applied. >> >> It would be pointless to include _data structures_ for components that >> are not supported on any system Python is ported to, but for subclassing >> to make sense, some of the _interface_ would have to be in place. Like >> the possibility of usin path.joindir() vs. path.joinfile() or something >> depending on whether the result should be a file or directory path. And >> just path.join() for people who don't care. Assuming there will be a >> join method, of course. > > Since *no one* will ever use joindir or joinfile, why would it be > helpful? Because we disagree about whether or not anyone will use it:-) >> Also, you may need some special handling of 'device:' on Windows. > > Yes, and the network portion as well (\\server\...). However, it would > still be handled textually. FIne by me. I wasn't thinking of what the internals would look like at all. >>> I think it's unreasonable to expect people programming on normal >>> platforms to pay attention to components like version, so even >>> including it in a structured manner is asking for trouble. >> >> I dunno. People have already mentioned coming systems where versions >> will be availbale. > > But we have no idea what it will look like, or how it may be represented > in a filename (if at all!) -- so implementing something based on that > would be a little optimistic. You're likely to create an interface that > won't make sense. Better to leave it unspecified until there's an > actual system you want to support, at which point the interface will > seem much clearer. Predictive design is a very bad idea. Actually I disagree here. The danger of designing to an existing system is that another system may come along where the versioning doesn't fit our design. I think it's a good idea to design it - but not necessaril implement it - before we see how it works on a real system. Then the real system comes will either prove that we did good enough, or that we didn't. In the latter case, it may be better to leave it out anyway. -- Hallvard From andymac at bullseye.apana.org.au Thu Jul 10 08:26:58 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 10 Jul 2003 22:26:58 +1000 (EST) Subject: Shared vs static link performance hit --and Windows? In-Reply-To: References: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> Message-ID: <20030710221220.P91892@bullseye.apana.org.au> On Thu, 9 Jul 2003, Martin v. [iso-8859-15] L?wis wrote: > On such systems, use of PIC is only for performance, to save the > relocations. Notice that this use is often questioned, as you have to > trade runtime efficiency due to the loss of general-purpose registers > to the PIC implementation, on particular on x86. So for long-running > applications, it would be better to accept the relocations at start-up > time, and get better performance during the computations. Thanks, again, for taking the time to correct my obsolete understanding. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From dkuhlman at rexx.com Fri Jul 18 20:36:48 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 18 Jul 2003 17:36:48 -0700 Subject: Documentation examples needed References: Message-ID: Stuart D. Gathman wrote: > On Thu, 17 Jul 2003 00:44:44 -0400, Dave Cole wrote: > >> Stuart> Is there a small project with documentation in the Python >> Stuart> standard that I can use as an example? >> >> We have some: >> >> http://www.object-craft.com.au/projects/albatross/ >> http://www.object-craft.com.au/projects/sybase/sybase/ > > Thank you. Your Makefile is much less confusing than the one that > comes > with Python! It also points out a shortcoming of the RPM > packaging. The python2-devel package includes everything you need > to compile python extension modules, but does not include what is > needed to "compile" > python documentation! Are third party module writers not supposed > to document anything? :-) It looks like I'll have to download the > Python sources and create my own RPMs. > > Presumably, I do not need *everything* in the Doc directory to > compile my > own docs. Probably just the tools directory, and maybe texinputs > and > templates. Is the list of what is needed for 3rd party docs > documented > somewhere? The file Doc/README (in the Python source code distribution) has some of this information. You will have to scan down a ways for it, though. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From smethells at llnl.gov Thu Jul 31 13:29:45 2003 From: smethells at llnl.gov (Greg Smethells) Date: 31 Jul 2003 10:29:45 -0700 Subject: What does "*list" mean? Message-ID: What exactly does "*values" mean in the following code? Is this a pointer to a PyList? Why can I not find good documentation on this any where? I must be blind: >>> from struct import * >>> format = "dl" >>> values = [3.14, 42] >>> foo = pack(format, *values) >>> foo '\x1f\x85\xebQ\xb8\x1e\t@*\x00\x00\x00' >>> unpack(format, foo) (3.1400000000000001, 42) >>> More importantly still, how would you write the same code in C? If you wanted to instead call struct_pack(PyObject *tuple), what would the tuple look like in C? Thanks to anyone who can clear all this up for me. Greg From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 31 06:04:07 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 31 Jul 2003 12:04:07 +0200 Subject: RELEASED Python 2.3 (final) In-Reply-To: References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> Message-ID: <3f28e998$0$49107$e4fe514c@news.xs4all.nl> Ben Finney wrote: > Or 'totally mega kudos, d00dZ' depending which decade you're living in. rather, "Thanx 2 all developers 4 ur 1337 c0D1ng Skilzz!!!" From belred1 at yahoo.com Thu Jul 24 21:48:30 2003 From: belred1 at yahoo.com (Bryan) Date: Fri, 25 Jul 2003 01:48:30 GMT Subject: file.close() References: Message-ID: "Francois Pinard" wrote in message news:mailman.1059052897.16526.python-list at python.org... > [Bryan] > > > I'm curious to know how others handle the closing of files. [...] I'm > > aware that files will automatically be closed when the process exits. > > For one, I systematically avoid cluttering my code with unneeded `close'. > The advantages are simplicity and legibility, both utterly important to me. > > However, I do understand that if I ever have to move a Python script > to Jython, I will have to revise my scripts for adding the clutter I am > sparing today. I'm quite accepting to do that revision if this occurs. > Until then, I prefer keeping my scripts as neat as possible. > > For me, explicitely closing a file, for which the only reference is about > to disappear through function exiting, would be very similar to using > `del' on any variable I happened to use in that function: gross overkill... > > The only reason to call `close' explicitly is when there is a need to close > prematurely. Absolutely no doubt that such needs exist at times. But > closing all the time "just in case" is symptomatic of unsure programming. > Or else, it is using Python while still thinking in other languages. > > -- > Fran?ois Pinard http://www.iro.umontreal.ca/~pinard > you are correct this is so awesome... at least for me it is... now i remove a lot of my clutter too :) i just did some tests on windows by trying to delete file1 at the command prompt when raw_input is called. f = file('file1') raw_input('pause') ### the file is NOT closed file('file1') raw_input('pause') ### the file IS closed f = file('file1') del f raw_input('pause') ### the file IS closed def foo(): f = file('file1') foo() raw_input('pause') ### the file IS closed can you explain to me how the file gets closed? i'm sure that garbage collection hasn't happed at the point that i call raw_input. it must have something to do with the reference count of the file object. does python immediately call close for you when the reference count goes to zero? i want the dirty details... thanks, bryan From exarkun at twistedmatrix.com Wed Jul 9 05:21:38 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Wed, 9 Jul 2003 05:21:38 -0400 Subject: Python Global Constant In-Reply-To: References: Message-ID: <20030709092127.GA7500@intarweb.us> On Wed, Jul 09, 2003 at 09:49:15AM +0200, Krisztian Kepes wrote: > Hi ! > > I want to create an module and I want to use some Global Constant in it. > How to I create an global constant in module what is accessable in from other modules ? Python does not have constant variables. If you remove the "const " on each of the two lines in your dirs module and use the equality test operator ("==") instead of the assignment operator ("="), your code should work. As a convention, variables which the author intends not to be changed are often spelled entirely in capitals, e.g., CONST_DOWN. > > like this example: > > *** module dirs *** > const Const_Up=1 > const Const_Down=1 > > *** module any *** > import dirs; > def CheckDir(Dir): > if Dir=dirs.Const_Up: xxx > Jp -- "I quite agree with you," said the Duchess; "and the moral of that is -- Be what you would seem to be' -- or, if you'd like it put more simply -- Never imagine yourself not to be otherwise than what it might appear to others that what you were or might have been was not otherwise than what you had been would have appeared to them to be otherwise.'" -- Lewis Carrol, "Alice in Wonderland" From ianb at colorstudy.com Sat Jul 12 02:47:09 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2003 01:47:09 -0500 Subject: The "intellectual property" misnomer In-Reply-To: References: Message-ID: <1057992428.28467.89.camel@lothlorien> On Sat, 2003-07-12 at 01:09, Ben Finney wrote: > On 12 Jul 2003 00:27:49 -0500, Ian Bicking wrote: > > Functionally, though, I think the term intellectual property here > > works. > > Only by accepting the fallacy that there is a meaning to the term > "intellectual property". There is no such thing -- not in law, not in > reality. While I agree with your dislike of the term, intellectual property *does* mean something -- it is a category of legal rights, several of which potentially apply to Python. The rights are diverse, but they have been categorized in this way, and that categorization does apply and convey the correct meaning. To the degree those rights apply to Python, they are held by PSF. Just because a term is not specific does not mean it is meaningful. Intellectual property is similar to a term like mammal or sea creature -- it's a category. Ian From ferrell at diablotech.com Tue Jul 29 11:21:41 2003 From: ferrell at diablotech.com (Robert Ferrell) Date: 29 Jul 2003 08:21:41 -0700 Subject: Factories in Python Message-ID: <73b00f0c.0307290721.7a19e3d0@posting.google.com> I'm wondering how Python cognoscenti use/implement factory patterns in Python. In my limited C++ experience, one reason to use a factory method is to make it easier to create instances of classes derived off a base class. The instance is declared to be an instance of the base class. The factory returns an instance of a derived class, and everything is groovy. In Python, since type declarations need not be static, it seems there is no need to have a factory method. However, I'm guessing that I'm not understanding other benefits of using factories in Python. Does anybody have examples or pointers on how use of factories in Python? thanks -robert From creedy at mitretek.org Mon Jul 14 13:17:03 2003 From: creedy at mitretek.org (Chris Reedy) Date: Mon, 14 Jul 2003 13:17:03 -0400 Subject: Python Mystery Theatre -- Episode 1: Exceptions In-Reply-To: References: Message-ID: <3f12e5bc$1_2@corp-news.newsgroups.com> Ok. I'll give this a try. For reference, I fall into the class of users who have read the docs more than once. (I also have been a college professor at one point in my career.) Chris P.S. I've already read other peoples answers; but, I'll try not to let that affect mine too much. Raymond Hettinger wrote: > ACT I --------------------------------------- > >>>>s = list('abc') >>>>try: > > ... result = s['a'] > ... except IndexError, TypeError: > ... print 'Not found' > ... > > Traceback (most recent call last): > File "", line 2, in -toplevel- > result = s['a'] > TypeError: list indices must be integers I didn't have to think about this one. It comes up often enough on c.l.py and I've been personally bitten by it as well. The first question that struck me is why the user was trying to use a string index on a list. Two possible answers: (1) This was included by Raymond just to trigger the exception. (2) The individual is actually confused about the differences between lists and dictionaries and was expecting something like this to happen: >>> s = list('abc') >>> s['a'] 0 In the latter case, I don't have any blindingly obvious comment except to review the differences between lists and dictionaries. The second question (the one I expect Raymond was really getting at) is why the TypeError was not caught. The answer is that: except IndexError, TypeError: is syntactically the same as: except IndexError, foo: that is that the variable TypeError is created as a new local variable which is assigned the exception that was raised, the same as what you expected to happen when you used foo instead. The fix is: except (IndexError, TypeError): or maybe even to do: except (IndexError, TypeError), foo: to provide an additional visual clue as to exactly what is happening. > ACT II -------------------------------------------- > >>>>class MyMistake(Exception): > > ... pass > > >>>>try: > > ... raise MyMistake, 'try, try again' > ... except MyMistake, msg: > ... print type(msg) > ... > > I learned something on this one. (I had to try this one to confirm my suspicions.) The user is expecting this to print something like 'MyMistake', or maybe something like: The problem here is that Exception is an old-style class and type(x) when x is an instance of an old-style class is always 'instance'. What the user should do is: print msg.__class__ > ACT III -------------------------------------------- > >>>>class Prohibited(Exception): > > ... def __init__(self): > ... print 'This class of should never get initialized' > ... > >>>>raise Prohibited() > > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited() > Prohibited: > >>>>raise Prohibited > > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited > Prohibited: This one contains (at least) three issues that I could find. 1. The print statement 'This class should never get initialized', appears to be an attempt to write an abstract class. Unfortunately, this is not done properly. One problem here is that the Exception aspect of prohibited is not initialized. This is what causes the '' behavior when instances of Prohibited are printed. 2. (After some experimenting on my part.) The phrase '' is produced when the __str__ method applied to an exception when printing a traceback raises an exception. (I would assume that this is required to avoid problems with recursive exceptions.) 3. (I already knew this one.) The fact that 'raise Prohibited()' and 'raise Prohibited' exhibit the same behavior is the result of the fact that raising an instance of a class will raise that instance, raising a class will cause an instance of that class to be constructed and then raised. > ACT IV ----------------------------------------------- > >>>>module = 'Root' >>>>try: > > ... raise module + 'Error' > ... except 'LeafError': > ... print 'Need leaves' > ... except 'RootError': > ... print 'Need soil' > ... except: > ... print 'Not sure what is needed' > ... > > Not sure what is needed This one is easy. (I knew this already from my second reading of the documentation.) String exceptions are compared by object identity, that is when 'RootError' is theException, rather than when 'RootError' == the Exception, which is almost surely what the user was expecting. In general when the string is constructed, like in this example, it becomes very difficult no way to catch the exception. If you want to throw string exceptions which are subsequently caught (I can't think of a reason for doing this as opposed to defining a subclass of Exception) you can try: foo = 'My Error' try: ... raise foo except foo: print 'Foo caught' which guarantees that the strings are identical. Aside: (I wouldn't want to raise this to anyone who didn't already understand the above.) This example also reveals that funny aspect of the Python about the interpreter automatically interning strings that look like variable names. Thus, in the example, the string 'RootError' had to be constructed. If it was a literal, the example would have behaved as "expected". > ACT V ----------------------------------------------- > >>>>try: > > ... raise KeyError('Cannot find key') > ... except LookupError, msg: > ... print 'Lookup:', msg > ... except OverflowError, msg: > ... print 'Overflow:', msg > ... except KeyError, msg: > ... print 'Key:', msg > > > Lookup: 'Cannot find key' (I had to confirm my guess on this one.) KeyError is a sub-class of LookupError. So the except LookupError clause caught the exception before the except KeyError clause was even checked. If you want to catch both KeyError and LookupError in the same set of exceptions (which in my mind is a questionable proposition), you would do: except KeyError, msg: ... except LookupError, msg: ... Since the except clauses are processed serially, this would cause the check for KeyError to occur before the one for LookupError. From tim.one at comcast.net Tue Jul 29 18:06:47 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 29 Jul 2003 18:06:47 -0400 Subject: bisect uses __cmp__()? In-Reply-To: Message-ID: [Gary Robinson] > I'm wondering if bisect.insort is guaranteed to use a __cmp__ method, > for now and for future python versions, if it exists, for the items > being inserted? Well, it doesn't use __cmp__ directly now, and never has: it uses Python's infix "<" operator. While not documented, it's deliberate that bisect *only* uses "<", so that instances of a class implementing only __lt__ can use bisect. This is the same (also undocumented) rule used in CPython's list.sort() implementation. Similarly, list.index(object) uses only "==", so that instances of classes defining only __cmp__ or only __eq__ work fine. Ditto for dict key lookups. > That would be good to know because then you don't have to define > __lt__ etc. if all you care about is being able to use bisect.insort. Or, it so happens, you can define only __lt__, and skip defining __cmp__ etc. Defining only __cmp__ works too. > If true, I suggest that it might be good to mention the bisect > library docs. In any case, if there is a clear answer to my question > I'd appreciate knowing what it is... You never have to define __lt__ (to use bisect or anything else in the core distribution). There may be a good performance to reason to define __lt__ instead of __cmp__, though, if some type can implement __lt__ more efficiently than it can implement __cmp__. I think that's rare. More common is that __eq__/__ne__ can be implemented more efficiently. From aahz at pythoncraft.com Fri Jul 4 14:55:43 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Jul 2003 14:55:43 -0400 Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> <840592e1.0307040900.14e3e668@posting.google.com> <3F05C39D.3F65B89C@engcorp.com> Message-ID: In article <3F05C39D.3F65B89C at engcorp.com>, Peter Hansen wrote: > >Google Groups likely takes its feed directly of a Usenet site, and Usenet >in general suffers from large propagation delay. It is that delay, caused >by messages filtering slowly across the Usenet network, which leads to the >"5 answers" problem, not Google Groups itself. Actually, Google uses at least two or three feeds (including stanford.edu, which has a super-competent news admin), and Usenet propagation is actually little short of e-mail speeds these days, depending on where you're located. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From rreagan at attbi.com Sun Jul 6 23:27:04 2003 From: rreagan at attbi.com (Russell Reagan) Date: Mon, 07 Jul 2003 03:27:04 GMT Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: I didn't investigate the python chess program a great deal, since I'm still learning the language, but it is very likely that it wasn't an efficient implementation. It takes years to learn how a chess program works, and to learn all of the tricks you can do to speed things up (and even then you have to have the programming skill to implement those things). I agree that it is not good to worry about optimization prematurely, but computer chess might be a bit of a unique area. Computer chess is the most heavily researched area of artificial intelligence ever, and as such, there are tons of "standard" low level tricks or data representations that you can use to your advantage. For instance, you can use board representation A and get thing B for "free" (B might be fast attack detection, or the ability to evaluate some complex aspect of a position quickly). When designing a chess engine, you have to decide what you want to do, then use the data representation that gives you the most things you want to do for "free". This is also why OOP might not be of much use for chess programming. The goal of OOP is to write correct code by being able to more easily make modifications to the code by data hiding, writing generalized routines, etc. Computer chess is so heavily researched, that there are several "standard" board representations that people use, and they're low level, involving lots of bit fiddling. Making a board object that doesn't know how a piece object is implemented serves little purpose other than to slow things down. Part of a fast chess program is that every part knows how everything else is implemented, and exploiting that. I'm not discounting anything you said. I'm just saying that computer chess may be one of the few areas where the generally good advice doesn't always apply, due to the ridiculous amount of research. Heck, computer chess was being researched before computers even existed! > - Write a program that does the job at all, paying attention to > simplicity and readability and *no* attention to optimisation. In general, this is good advice, but for reasons explained above, paying no attention to optimization might be the equivalent of choosing a bad design for this specific problem. By not paying any attention to efficiency early on, you effectively limit your top speed later on. > - Once the program is correct, and not before, profile it to see where > it's slow. Since computer chess is so heavily researched, I can tell you that the area consuming the biggest chunk of time will be position evaluation, unless your program doesn't use a lot of the well known tricks for things like attack detection, in which case it might spend a ton of time doing that, ensuring that a move doesn't leave your king in check, that kind of stuff. There is really not a lot you can do to improve either of those short of starting over from scratch and creating your data structures in such a way as to exploit lots of low level tricks. > at least you've debugged a working algorithm, > and can treat it as pseudocode for the port to C. For reasons explained above, I'm not sure that you can make the direct translation between "python pseudocode" to "C/C++". It sounds like you're thinking, "I'll just implement this python program in C/C++, and then it will be faster," but I'm not sure that is the case. Sure it will be faster, but probably still pretty slow. Making a really fast chess program would require changing the data structures significantly, and I'm not sure what use the python code would be after you made a big overhaul of the data representations. What do you think? I may be way off. Maybe I'm putting too much emphasis on speed. From gh at ghaering.de Tue Jul 22 17:16:06 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 22 Jul 2003 23:16:06 +0200 Subject: Zlib problem on Windows XP?? In-Reply-To: References: Message-ID: <3F1DA996.9050500@ghaering.de> Kevin Ollivier wrote: > Hi all, > > When using the latest Python 2.2.x releases as well as the Python 2.3 > betas and rc1 on Win XP, I cannot import zlib. When I try, I get an > error about the dynamic module not having an 'initzlib' symbol. The > strange thing is that this problem seems to be XP-specific - on Windows > 2K I do not get this error. I've installed Python 2.2.3 on two XP > machines with the same results. I installed the latest beta on one of > the machines, but the results were the same. (Haven't tried RC1 yet.) [...] I cannot confirm this. Windows XP Professional SP 1 (English): - Python 2.3b2 works - Python 2.3c1 works -- Gerhard From rastm2 at aol.commorespam Tue Jul 22 04:52:03 2003 From: rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) Date: 22 Jul 2003 08:52:03 GMT Subject: Stopping a loop with user input. in curses References: Message-ID: <20030722045203.23831.00000293@mb-m27.aol.com> ALEX wrote >Hello Ray, > >After trying the code, I got the same problem... Ray says>> not really the same problem. Last time you couldn't stop the function. This time you couldn't get it to display with out a key press. You see that right? : ) >...which prompted me to >post to the newsgroup. The clock would properly display but it >wouldn't update every second. If I hit the up-arrow key (or any >other key besides 'q'), Ray says>> But did it quit or close when you would hit 'q', just curious. wait I know it did 'cuz' it does now - stupid question.Sorry. >the program would then update the time. I >would have to continuously hit a key to get the clock to update >every second. Ray says>> Good to know because the only curses I get to work with are the ones I use when I am having a frusrtating problem like you were facing. : ) > >I have a theory about programming in curses which I've described to >yet another Ray [...] Ray says >> Hi Alex You got your answer to the second part of the problem from-- From: "Dr. Peer Griebel" griebel at konzept-is.de Credit where credit is due ! Thank you Doctor, and thank you Alex. You both taught me that... if you don't HAVE half the answer then you don't haLve the answer. Get it. have cut in halves by a big L---ooser --> me. little pun there sorry i will shut up now. No wait a minute Yes Yes if you don't haLve the answer then keep breaking it down till ya do. Thats it I think Ray St. Marie Rastm2 at aol.com HA = Half Answer (problem???) L = link VE = Very Easy I'm hurting my self. In Python there are no real problems, are there?? Just bad posts! From grante at visi.com Thu Jul 24 10:35:38 2003 From: grante at visi.com (Grant Edwards) Date: 24 Jul 2003 14:35:38 GMT Subject: How to do raw Ethernet under Win32? References: <3f1ed31a$0$181$a1866201@newsreader.visi.com> <3f1ee77f$0$160$a1866201@newsreader.visi.com> Message-ID: <3f1feeba$0$169$a1866201@newsreader.visi.com> In article , Gerhard H?ring wrote: > Grant Edwards wrote: >> In article , Gerhard H?ring wrote: >> >>>>It looks like I can _almost_ do what I want with the python >>>>wrapper around the windows pcap lib. >>> >>>Where's PyLibpCap for Windows available? >> >> Here's where I got it from: >> >> http://ghaering.de/python/unsupported/pylibpcap/ ;) >> >> I'd take a whack at finishing it, but I don't have a Windows C compiler. > > The guy you got this from used MINGW, the free GNU compiler for Windows > to do the original port: > > http://mingw.sourceforge.net/ > >:) Cool! Be sure to thank him for the work if you see him. I've never done any SWIG stuff before, but it looks like all I have to do is add some stuff to the .i file to export the pcap_sendpacket() function. -- Grant Edwards grante Yow! I LIKE Aisle 7a. at visi.com From jdhunter at ace.bsd.uchicago.edu Mon Jul 7 12:27:12 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 07 Jul 2003 11:27:12 -0500 Subject: anything new on the ternary operator? In-Reply-To: ("Tim Peters"'s message of "Mon, 7 Jul 2003 00:41:27 -0400") References: Message-ID: >>>>> "Tim" == Tim Peters writes: Tim> There were many creative interpretations of the vote counts, Tim> but none of them showed the consensus Guido said at the start Tim> would be needed for adoption. Perhaps there is a lesson for the next time a vote count comes around. Although there wasn't a consensus on the syntactical form of a ternary operator, there may be a consensus for the existence of one. This suggests a runoff step is needed Vote 1 0) choice 0 1) choice 1 ... N-1) choice N-1 N) No ternary operator Vote 2 if sum(votes[:N])>votes[-1] 0) winner of vote 1 1) No ternary operator I suspect many of not most of those who voted for some syntax of ternary operator would prefer the first choice of the vote rather than no choice, even if their pet candidate didn't win. Perhaps the python community couldn't stand being dragged through a 2-tiered voting procedure, but it looks like a fairer test. John Hunter From anton at vredegoor.doge.nl Tue Jul 29 06:20:50 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 29 Jul 2003 12:20:50 +0200 Subject: Papers on Python References: <8b36138c.0307281644.f6569ea@posting.google.com> Message-ID: rick_hunter357 at hotmail.com (Rick) wrote: >PS. Before someone starts on how college kids are using the internet >(or the help available on the 'net) to do the work for them, No I am >not cheating. The actual assignment is to select 9 papers that you >find interesting and write a report on each of them. I already have my >9 papers selected. Now I want to know if I would like to replace some >from my collection. Why not take 9 threads in this newsgroup or the Python developers mailing list and write a report on that? Of course you'd have to convince your teacher somehow that this is the way things work nowadays and that the days where a single author wrote a monolithic paper are gone. Knowledge production and decision making are much more interactive and hands-on than before, and discussions involve a lot more people of varying degrees of expertise and having a more diverse background. If it makes any difference: I would love to see some threads reviewed, especially threads that have had some time to cool down and that can be viewed from some distance now. Post the result of your assignment here, you'll get free error checking this way and at the same time you prove that the system works by interacting with it. Isn't it Pythonic :-) Anton. From mcfletch at rogers.com Sun Jul 6 18:18:20 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 06 Jul 2003 18:18:20 -0400 Subject: Search for mapping solution In-Reply-To: References: Message-ID: <3F08A02C.4010405@rogers.com> Since you know the indices, you can just do this: for record in lines: costs[record[nameIndex]] = costs.setdefault(record[nameIndex],0)+float(record[priceIndex]) Enjoy, Mike Markus Joschko wrote: >>lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] >>costs = {} >>for name,number,price in lines: >> costs[name] = costs.setdefault(name,0)+float(price) >>print costs >> >> >> >thanks it works. But maybe I can complicate the example a little bit >(because in real world it's more complicated): > >What if I every list in lines has 20 or more entries and I have only the >index number to access the name, e.g. > >lines = [['elem1','elem2','fred','elem3',.......;'elem >17','333','elem18','0.10'],[...],[...]] > > >what I want to say: I can't be sure that the name is always on the third >position. That's dynamic. I know it before I parse the list, but >I can't say > >for elem1,elem2,name,.... cause it can also be > >for elem1,name,elem3 .... > > >Thanks for the answer, > Markus > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From ben at dadsetan.com Thu Jul 31 17:54:48 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Thu, 31 Jul 2003 23:54:48 +0200 Subject: handle
tags In-Reply-To: References: Message-ID: Luca Calderano wrote: > Hi guys... > > I've done a subclass of SGMLParser > to handle the contents of a web page, > but i'm not able to handle the
tag > > can someone help me??? > > S.G.A S.p.A. > Nucleo Sistemi Informativi > Luca Calderano > > I do not know SGMLParser.. but HTML is not SGML nor any subset. It is some ill language which one even rarely finds "pure" (written in the way the spec says it MUST be) I believe SGML does not like none closing tags. BR is one of the many none closing tags in HTML (also look at IMG or HR) Depending on what you are doing you should maybe use XHTML as an input if you can (XML well-formed HTML, XML being a subset of SGML) or you should probably look for a completely different parser "technology". Maybe HTMLParser will help you a little more. Do not forget, random downloaded HTML from Internet is often broken. You might rather want to use tidylib (corrects broken HTML code into XHTML) and a XHTML/SGML parser or a DOM. Hope it helps even though the effort I took to check my statements was small :) Regards, Ben. From jdhunter at ace.bsd.uchicago.edu Thu Jul 3 12:41:02 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 03 Jul 2003 11:41:02 -0500 Subject: getting a submatrix of all true In-Reply-To: (bokr@oz.net's message of "3 Jul 2003 04:25:40 GMT") References: Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> If I understand your original optimality definition, that Bengt> would be suboptimal. I.e., how about the 16-element Bengt> matrix? (x's mark the corresponding zeroes) Bengt> Or do they have to be adjacent? No, in general they won't be. I missed that one. Just goes to show that my "solution" is not one, which I knew. But it does efficiently deliver good solutions, where good means large but not optimal. Bengt> Brute force seems to work on this little example. Maybe it Bengt> can be memoized and optimized and/or whatever to handle Bengt> your larger matrix fast enough? Thanks for the example. Unfortunately, it is too slow even for moderate size matrices (30,10). I've been running it for over two hours for a 30x10 matrix and it hasn't finished. And my data are 1000x100! Here is a little code to generate larger matrices for testing.... from Numeric import zeros, array, Int, put, reshape from RandomArray import uniform numRows, numCols = 30,10 numMissing = int(0.05*numRows*numCols) # 5% missing X = zeros( (300,)) ind = uniform(0, numRows*numCols, (numMissing,)).astype(Int) put(X,ind,1) X = reshape(X, (numRows,numCols)) # turn it into a list for your code.... X = [ [val for val in row] for row in X] for row in X: print row Last night, I began to formulate the problem as a logic statement, hoping this would give me an idea of how to proceed. But no progress yet. But I have come to the conclusion that with P ones, brute force requires 2^P combinations. With 1000x100 with 5% missing that gives me 2^5000. Not good. Thanks for your suggestion, though. If you have any more thoughts, let me know. John Hunter From jlh at cox.net Thu Jul 10 23:18:53 2003 From: jlh at cox.net (Jeff Hinrichs) Date: Fri, 11 Jul 2003 03:18:53 GMT Subject: Deleting specific characters from a string References: Message-ID: First off, (holding hat in hand), I reread the profile module and then set my profiler up correctly with the proper bias setting. Things have changed but only slightly. Duncan Booth's maketrans/translate is edging out the stringReplace for first place in speed. Looks to be with in the margin of error for timing on my windows platform. I am rerunning the entire test suite with the profiler set up correctly. I am also throwing Paul Rubin's RegEx entry in to the race as well. I've got a web page going together now with all the mind numbing details. The short story is that Duncan's suggestion of maketrans/translate looks like it will pull ahead when the number of substitutions increase beyond some number N. Right now, I don't know what N is going to be. In terms of the OP's original request for replacing 2 chars, Duncan's and stringReplace are dead even. With my vote going for stringReplace. +0 I'll post the url when it's complete along with my test harness and the code for everyone to pick apart. If I've made mistakes I would appreciate anyones assistance in pointing them out. Personally, I'm using this as a chance to beef up my profiling knowledge. more to follow, Jeff Hinrichs From danb_83 at yahoo.com Thu Jul 10 19:33:13 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 10 Jul 2003 16:33:13 -0700 Subject: keep original date and time of unzipped files References: Message-ID: "Bartolom? Sintes Marco" wrote in message news:... > Hi, > > In this mail, > http://www.mail-archive.com/kragen-hacks at canonical.org/msg00030.html > Kragen Sitaker explained how to unzip a file in Python ... > The unzipped files date and time are not the original ones, but > when the unzipping is done. Is there a way to keep the > original files date and time? You can change a file's date and time with os.utime(filename, (accessTime, modificationTime)) From tomas at fancy.org Mon Jul 14 19:44:09 2003 From: tomas at fancy.org (Tom Plunket) Date: Mon, 14 Jul 2003 16:44:09 -0700 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: <3qf6hvcl1j48rnt3m74av0on4ftvd07upd@4ax.com> Noah wrote: > As others have explained, you just return the value. > It's just a different point of view. Instead of > change (v) > you have: > v = change (v) Ahh, now I remember what I wanted to do, and you're right- it's more verbose and didn't really seem to add anything. I wanted to in-place clamp integers in a range, or maybe they were even member variables; def Color: def SomeOperation(): # modify self.r, g, b self.r = clamp(self.r, 0, 255) self.g = clamp(self.g, 0, 255) self.b = clamp(self.b, 0, 255) ...that was just more typing than I wanted at that point, although I'm sure that the keystrokes I burned were more than made up for by Python's allowing me to do: def clamp(val, lowVal, highVal): if (lowVal <= val <= highVal): return val :) -tom! From dmbkiwi at yahoo.com Fri Jul 11 19:16:12 2003 From: dmbkiwi at yahoo.com (dmbkiwi) Date: Sat, 12 Jul 2003 11:16:12 +1200 Subject: Python - if/else statements References: Message-ID: On Fri, 11 Jul 2003 20:33:19 +0000, Bengt Richter wrote: > On Sat, 12 Jul 2003 07:34:18 +1200, dmbkiwi wrote: > Thanks for helping me with this. >>def meterClicked(widget, meter, button): >> #print "meterclick" >> global dayshow, daypicrem, ddon, ddcon, buttonpressed > # these globals -- where do they come from? What module? # Note that each > module has its own globals, so is are there different modules # that think > they're sharing globals but really aren't? There are ways to solve that, # > but first, is that relevant? They don't come from a module, they come from different functions within the script. To be honest, I don't think I've ever quite understood globals, so I insert them where I think they should go - probably quite incorrecly. Will this matter? > > # Second, are the globals accessible from multiple threads? Are you seeing > hard-stuck errors or blue-moon errors? Now my newbiness will be evident. Multiple threads? I am not consciously creating threads. Should I? Does python automatically create multiple threads? What are hard-stuck/blue-moon errors? > >> if (meter == mainpic) and (button == 1): > # always here? # yes >> if ddcon == 0: > # and here ? # yes >> if ddon == 1: > # and here? # no >> deleteDayDetail(widget, dayshow) >> karamba.redrawWidget(widget) >> createCurrentDetail(widget) >> karamba.redrawWidget(widget) >> else: > # never here, you're saying, right? # always here > # >> else: > # never here either, right? always here > # > # get here though? # yes >> buttonpressed = 1 >> > I used tabs above to line up (maybe ;-) with your text, but maybe you > should run your code through tabnanny or something to check for consistent > usage. I never use tabs (though I use the tab key and gvim puts in 4 space Tabs seem to be fine in the actual code - I think it's the word wrapping in either your/my newsreader that is causing problems, but your tab positioning is correct. > indentation for me ;-) so I haven't used the tab checkers, but you might > benefit, perhaps. I'm using kate here under KDE/linux. It has syntax highlighting for python, and seems to deal with tabs nicely. > >>What these users are experiencing is that this portion of code is being >>processed, and evaluating all if statements as true, however, as you can >>see, they cannot all be true each time this function is called. Their >>versions of python also ignore the else construct. >> >>Can anyone shed any light on what might be going on with these users? >> > I'd check on the globals and threading issues first. Then see about > building a mousetrap. Why would these affect the interpretation of the if/else. Seems to me, that if the if statement evaluates to true, then the else statement should be ignored. However, it appears that for these users, python is just ploughing right on through, and running the else statement also. Or am I missing something. What is a mousetrap? Any further help would be greatly appreciated. > > Regards, > Bengt Richter -- Regards Matt Everyone is more or less mad on one point. -- Rudyard Kipling From tzot at sil-tec.gr Tue Jul 22 04:53:54 2003 From: tzot at sil-tec.gr (TZOTZIOY remotely) Date: 22 Jul 2003 01:53:54 -0700 Subject: [OT] On the TimBot References: <62slgvsljos7v5snie6toc4qucv5nt1n15@4ax.com> Message-ID: oren at REMOVETHIS1.hishome.net (Oren Tirosh) wrote in message news:... > > Henry Spencer is well known around the sci.space.* newsgroups for > being very rarely wrong. About as rarely as the TimBot. People that > manage to correct Henry get the coveted "I Corrected Henry" virtual > T-shirt. > > May I propose the "I Corrected Timbot" award? A great idea, a la "I got the babelfish". Great line for a signature too... if you can take the heat afterwards :) From abelikov72 at hotmail.com Thu Jul 10 15:13:47 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 10 Jul 2003 19:13:47 GMT Subject: Embedding Python, threading and scalability References: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> <1057814773.188737@yasure> Message-ID: <7kergv8u1q5oib600e4ino24tf9fioo2gc@4ax.com> On Thu, 10 Jul 2003 05:26:14 -0000, "Donn Cave" wrote: >Quoth Jeff Epler : >At any rate, it sure isn't because Guido can't scare up an SMP machine. Is this the absolute truth or just something people like to say? If it is true I am very surprised... I think getting Guido an SMP machine will not be very difficult, and could well be very cheap. From kylotan at hotmail.com Wed Jul 9 05:41:46 2003 From: kylotan at hotmail.com (Kylotan) Date: 9 Jul 2003 02:41:46 -0700 Subject: urllib2 for HTTPS/SSL References: <153fa67.0307080233.2f7abdf5@posting.google.com> Message-ID: <153fa67.0307090141.67061a69@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > > [Kylotan] > > ........................Is there any chance of the official > > documentation on this useful-looking module being improved? > > It is one of the biggest problems with Python that not enough people > like to write good documentation about how to use the Python Standard > Library. It's a shame about the documentation, but then this stuff is generally provided for free and so I think we're all grateful that it exists at all, documented or not. :) Maybe it would be beneficial for the official online documentation to allow users to add annotations in much the same way that the PHP and SDL docs do? Then not only people can get more use out of the docs, but the official maintainers of each module can easily see about integrating any useful errata or examples into their source documentation. K. From stark7 at sbcglobal.net Thu Jul 24 16:53:33 2003 From: stark7 at sbcglobal.net (David Stark) Date: Thu, 24 Jul 2003 20:53:33 GMT Subject: Tkinter and Mac OS X Message-ID: I have Mac OS 10.2 which ships with python. I downloaded TclTkAqua from ActiveState and installed it. Then I get: >>> import Tkinter Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> After digging around on www.python.org I get the impression that I have to download the source and do my own build. Do I really have to go through this? Is the OS X distribution of python different (for a reason)? From adalke at mindspring.com Fri Jul 18 04:04:19 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 18 Jul 2003 02:04:19 -0600 Subject: OT: Genetic Algorithm Recipe Bug Fix References: Message-ID: Anton Vredegoor: > Anyway it seems to be possible to solve a maximum clique problem like > this: I haven't followed the thread, just pinged on 'maximum clique problem.' Does this help? http://starship.python.net/crew/dalke/clique/ It's code I wrote years ago. Don't ask me any more questions about it .... unless you want to pay me for it. :) Andrew dalke at dalkescientific.com From Mike at kordik.net Fri Jul 4 18:37:48 2003 From: Mike at kordik.net (Mike) Date: Fri, 04 Jul 2003 22:37:48 GMT Subject: RTS/CTS and DTR/DTS control References: Message-ID: I am running Linux, Python 2.2.2. It would be nice (not mandatory) to be cross platform though. Thanks, Mike On Fri, 04 Jul 2003 18:30:11 +0000, Mike wrote: > Is there a library in Python that will give me control over the > handshaking lines directly? > > Thanks From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Jul 2 07:37:33 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 02 Jul 2003 15:37:33 +0400 Subject: how to dynamically create a function object (from a code object)? In-Reply-To: References: Message-ID: Petri Savolainen wrote: > After reading the manuals and googling around a bit, I thought I'd use > the 'compile' built-in to create a code object. Then, using either > new.function() or types.FunctionType(), create a function object out of > the code object. The function object can then be turned into a method > for example using types.MethodType(). Right? Well, on Windows 98, using > python 2.2.2 (or 2.3b2): > > >>> c=compile('def a(msg): return msg','','exec') > >>> f=types.FunctionType(c,globals(),'a') > >>> f > >>> ", line 1> > >>> f('hello') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > f('hello') > TypeError: ?() takes no arguments (1 given) > > >>> f() > >>> > >>> a('hello') > >>> 'hello' > >>> > > This is, well, not what I would have expected. > > After peeking around in the code object, I found out its 'co_const' > instance variable also contains a code object - which, it seems, should > really be fed to the function creation methods: > > >>> c.co_consts > (", line 1>, None) > >>> f=types.FunctionType(c.co_consts[0],globals(),'a') > >>> f('hello') > 'hello' > >>> > > Which is the behaviour I would have expected in the first place! > > I would really like to know what I am doing wrong here, or any > clarification regarding what is going on above... I dare not hope having > found a bug :-P > > Thanks, > > Petri > Unfortunately, I didn't manage to do it the way you described above. But if you just want to create a function there is much simplier way: def create_id(): def _(s): return s return _ x = _() x("xxx") hth, anton From max at alcyone.com Sat Jul 5 16:08:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 05 Jul 2003 13:08:48 -0700 Subject: Python's CGI and Javascripts uriEncode: A disconnect. References: <2c60a528.0307051007.bc1c98b@posting.google.com> Message-ID: <3F073050.9F3E73B2@alcyone.com> Andrew Clover wrote: > This is part of the specification for the media type > application/x-www-form-urlencoded, defined by HTML itself (section > 17.13.4.1 of the 4.01 spec). This states that spaces should normally > be encoded as '+', however really using '%20' is just as good and > causes less confusion, so that's what newer browsers (and I) do. > > Elsewhere, spaces should not be encoded as '+'. Right. As part of the query string, + for space is fine. Elsewhere in the URL, it is not. > The reasoning for this initial decision is unclear - presumably it is > intended to improve readability, but URIs with query parts are > generally not going to be very readable anyway. Well, an obvious reason would be that + is a perfectly legal character in many filesystems, as is a space. Actual spaces in URIs are illegal; they should be replaced with either %20 or + (depending where in the URI they appear). Probably he's encountering frustrating bugs in some browsers where it doesn't bother replacing spaces with the proper equivalent so that they will be well-formed URIs. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Life imitates art far more than art imitates life. \__/ Oscar Wilde From jimmy at retzlaff.com Sun Jul 13 17:45:45 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 13 Jul 2003 14:45:45 -0700 Subject: anything like C++ references? Message-ID: Stephen Horne wrote: >... >Of course, if you really believe that pointer/reference behaviour >should be arbitrarily tied to mutability then you can claim that I am >wrong, but you still can't claim the high ground as this is still an >arbitrary and bizarre thing to do. The ability to change part or all >of a value in-place has nothing to do with whether that value is >referenced using a pointer or whatever in computer theory - any link >between pointers/references and mutability should be related to the >implementation of the language - not the semantics. >... Assignment, and therefore parameter passing, is entirely consistent between mutable/immutable types. That is to say, assignment and mutability are orthogonal and unrelated concepts in Python, just as you suggest they should be. Perhaps some folks who only partially understand Python's parameter passing semantics would be surprised by: >>> def f(x): ... x = [4, 5, 6] ... >>> a = [1, 2, 3] >>> f(a) >>> print a [1, 2, 3] Note that the assignment within f did not affect a in any way despite the fact that a was an instance of a mutable type. It works exactly the same way with a tuple. With similar consistency you can call any method on an object passed as a parameter. Where the distinction between mutable and immutable types comes in is that there don't happen to be any methods of immutable objects that actually modify the value of the object; mutable objects do offer such methods. For example, tuples don't have "append" or "sort" methods that modify the object's value in place, but lists do. Now where some more of the assignment related confusion might come in is with things like this: >>> def f(x): ... x[0] = 10 ... >>> a = [1, 2, 3] >>> f(a) >>> print a [10, 2, 3] The body of f may look like it contains an assignment, but that's not the typical name-binding that is referred to when discussing assignment (or parameter passing) in Python. That is really just syntactic sugar for calling a method of the parameter x, namely the __setitem__ method. List objects are mutable and so, by definition, some methods like __setitem__ will change their value. Tuples don't have __setitem__ methods so the above assignment in f won't work if you pass in a tuple. Note that the same "assignment" outside of f wouldn't work for a tuple either; this is a property of the tuple (i.e., it doesn't offer a __setitem__ method), not of Python's parameter passing / assignment semantics. Jimmy From tayss_temp at yahoo.com Tue Jul 29 09:18:13 2003 From: tayss_temp at yahoo.com (Tayss) Date: 29 Jul 2003 06:18:13 -0700 Subject: Static typing References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> <3f23ae06$0$21093$626a54ce@news.free.fr> <5627c6fa.0307270537.1afc94d3@posting.google.com> <3f244c06$0$21113$626a54ce@news.free.fr> Message-ID: <5627c6fa.0307290518.58d844aa@posting.google.com> In case I wasn't clear, you can say I'm against static typing in Python. I'm for purely optional typing, and I don't mind it in docstrings (as a way for both humans and compilers to gain info). I even like the fact you can add vars at runtime to objects, as well as use the __slots__ declaration for safety. A Ruby advocate listed this as an unsafe failure of Python, but it's certainly interesting to use objects as a dictionary with bite if nothing else. From vivek at cs.unipune.ernet.in Wed Jul 9 05:22:41 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Wed, 9 Jul 2003 14:52:41 +0530 Subject: Application Development in Python In-Reply-To: <3089454.1057738936@dbforums.com>; from ____indru_june@yahoo.com____ on Wed, Jul 09, 2003 at 08:22:16AM +0000 References: <3089454.1057738936@dbforums.com> Message-ID: <20030709145241.A27673@cs.unipune.ernet.in> On Wed, Jul 09, 2003 at 08:22:16AM +0000, indru wrote: > > Hi all, > I am new to Python programming. I am from C,C++,Perl background. I am > quite convinced by the possibilities python as a very high level > language is offering. I am seriously thinking of using python in my > project which is to create a accounting software. First thing came to my > mind was C++ but the time required could be enormous and my people are > not ready to wait that long. The project is a medium sized one but > bigger than something like gnucash and KMyMoney2. Do any body have > experience with application development using python and their > experiences ?. Also please advice me whether Python can be used for > such purposes. > Thanks in advance > Indru Yes you can use python for application development. I have created an application that generated various reports, certificates, interacts with database and provides a GUI, all in python :-). For GUI I used Tkinter but you can use any other library as per your choice. I haven't done any project like accounting package. But I am sure you can easily do that in python and in a very less time as compared to developing that in C++. Moreover you get os independent code free of cost with Python :-). Regards Vivek Kumar From postmaster at bluetiger.com Sun Jul 13 12:50:51 2003 From: postmaster at bluetiger.com (postmaster at bluetiger.com) Date: Sun, 13 Jul 2003 09:50:51 -0700 Subject: Delivery Status (Failure) Message-ID: This is an automatically generated Delivery Failure Notification. Delivery to the recipient failed. Status Code: 5.1.1 User Unknown If you are trying to reach Blue, please send email to newaddress at bluetiger.com. From mis6 at pitt.edu Wed Jul 16 19:20:46 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Jul 2003 16:20:46 -0700 Subject: Mix lambda and list comprehension? References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> <2259b0e2.0307150441.22921165@posting.google.com> Message-ID: <2259b0e2.0307161520.9081514@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > On 15 Jul 2003 05:41:02 -0700, mis6 at pitt.edu (Michele Simionato) wrote: > > >peter.barth at t-online.de (Peter Barth) wrote in message news:<6f5b3f88.0307142302.1a1531f3 at posting.google.com>... > >> Hi, > >> trying to mix lambda expresions and list comprehension > >> doesn't seem to work. > >> --- > >> >>> [lambda x:x+y for y in range(10)][9](2) > 11 > >> >>> [lambda x:x+y for y in range(10)][4](2) > >> 11 > >> --- > >> I expected the second expression to return 6. > >> What did I do wrong? Any hints? > >> Thanks > >> - Peter > > > >It is a scope issue. The last value for y is used for all > >the created lambdas. All lambdas users are bitten by that, > >soon or later. The solution is to make y local to the > >lambda function, with the optional argument trick: > > > >>>> [lambda x,y=y:x+y for y in range(10)][4](2) > >6 > > or you could capture y as constants in the lambdas ;-) > > >>> [eval('lambda x:x+%s'%y) for y in range(10)][4](2) > 6 > > > Regards, > Bengt Richter Thanks to God, there is a smile in your post!! ;) Michele From theller at python.net Thu Jul 24 15:55:46 2003 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2003 21:55:46 +0200 Subject: [ANN] py2exe 0.4.1 released Message-ID: py2exe is a distutils extension to convert python scripts into windows exe-files (plus a few dlls), able to run on computers without requiring a python installation. New in release 0.4.1: Integrated support for dll and exe COM servers, contributed by Mark Hammond. Thanks! Much better modulefinder module from Python 2.3 included. The build process should now give a lot less warnings and better results. py2exe now is compatible with PyXML, for example. The support of Python 2.3 is still preliminary, and has to be improved. I intend to use the new zipimport feature instead of good old imputil. Thanks to Just van Rossum for his work on both the zipimport and the improved modulefinder. Download from the usual location: http://starship.python.net/crew/theller/py2exe/ Enjoy, Thomas From marc.engel at recif.com Wed Jul 30 05:19:13 2003 From: marc.engel at recif.com (Marc ENGEL) Date: 30 Jul 2003 02:19:13 -0700 Subject: pythoncom: STA python COM server randomly does not receive event from other objects : deadlock Message-ID: <6411841c.0307300119.46bc0159@posting.google.com> Hi all, I coded a python COM object that runs in a pythonw local server as a STA. This object creates and advises a VC++ COM object to receive its event. Those events are sent by worker threads. The VC++ object is free threaded. As a consequence call between my STA python object and apartment are marshalled through proxy. The python COM object regularly calls a blocking method on the VC++ object to synchronize. But, as it is a cross apartment call, during the call it can gets the event handler called thanks to the message pump operated by COM. But sometimes events are no received and it seems that I enter a deadlock. When I attach to the VC+ object, I can see that the thread that made the Fire_XX is still waiting for the call to end. Does somedy know the reason? Does the COM message pump may be different from the pythoncom message pump located in localserver.py : pythoncom.PumpMessages ? Thanks in advance for any hint, because this is a very blocking issue for my project. Marc From andreas.kuntzagk at mdc-berlin.de Thu Jul 31 04:33:22 2003 From: andreas.kuntzagk at mdc-berlin.de (Andreas Kuntzagk) Date: Thu, 31 Jul 2003 10:33:22 +0200 Subject: how to gunzip a string ? References: Message-ID: On Wed, 30 Jul 2003 16:16:32 +0200, Bill Loren wrote: > I guess I really need some sort of library that will do a gzip decoding to > a compressed string. > assume that I have a gzipped_string_reply I got from an HTTP server, It'd > be superb to have a gunzip class that takes it and return its decoded > equivalent. You could put your string in an cStringIO: c_string= cStringIO.StringIO(compressed_string) gzip_handle=gzip.GzipFile(fileobj=c) gzip_handle.read() HtH, Andreas From dave at pythonapocrypha.com Wed Jul 2 18:18:22 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 2 Jul 2003 15:18:22 -0700 Subject: Remote db connections possible with DCOracle2? In-Reply-To: <16131.19186.190625.679324@montanaro.dyndns.org> References: <16131.19186.190625.679324@montanaro.dyndns.org> Message-ID: <200307021518.22410.dave@pythonapocrypha.com> On Wednesday 02 July 2003 02:13 pm, Skip Montanaro wrote: > Connections to remote Oracle databases doesn't seem possible with > DCOracle2. I have no problem making remote connections using Perl's > DBI::Oracle package, so I know it's possible in theory. Is this capability > available in DCOracle2 but just not documented perhaps? Actually, I've never used a _local_ database with DCOracle2, so it's very possible but, IMO, very underdocumented too. :) Use this style of connection string (all one line if it wraps): user/password@(description=(address=(host=10.20.30.40)(protocol=tcp)(port=1521))(connect_data=(sid=dbsid))) (changing the values of user, password, 10.20.30.40, and dbsid of course). -Dave From Vincent.Raaijmakers at ge.com Thu Jul 31 09:28:27 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 31 Jul 2003 08:28:27 -0500 Subject: SQL2000 database vs python Message-ID: <55939F05720D954E9602518B77F6127F02F46771@FTWMLVEM01.e2k.ad.ge.com> You are THE man!! Thanks. Vincent -----Original Message----- From: Gerhard H?ring [mailto:gh at ghaering.de] Sent: Thursday, July 31, 2003 8:53 AM To: Raaijmakers, Vincent (IndSys, GE Interlogix) Cc: python-list at python.org Subject: Re: SQL2000 database vs python Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Can someone tell me if there is a module out for using a sql2000 database within python? > My python application (runs on Linux) already uses mysql but now I need also to talk to a sql2000 database on another machine. > > Any suggestions? www.python.org, google couldn't help me. http://www.object-craft.com.au/projects/mssql/ -- Gerhard From aahz at pythoncraft.com Wed Jul 16 10:41:24 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 Jul 2003 10:41:24 -0400 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: In article , Duncan Booth wrote: > >On question 8, I'm not aware that Python borrowed anything from Java. Lib/threading.py, line 1 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From mis6 at pitt.edu Tue Jul 22 22:11:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 22 Jul 2003 19:11:33 -0700 Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: <2259b0e2.0307221611.44b29664@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > I think I'd prefer > > if any_true(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > dosomething() > > I suspect it will more often make sense read aloud in the general > > if any_true(pred, seq): > > than > > if the(pred, seq) > > I guess the full set of functions might be > any_true, any_false, all_true, and all_false. > > or maybe someone can think of better short phrase? > > Regards, > Bengt Richter I think in the specific case I was talking about "the" was quite readable; however I agree that in the general case "any_true" etc. would be better. I would not be opposed to add these convenience functions in itertools. The advantage is standardization (i.e. I don't have to invent my own name, different from the name chosen by anybody else), the disadvantage is more things to learn; however, with such descriptive names, it would be difficult to not grasp what those functions are doing, even without looking at the documentation. Anyway, I am sure many will be opposed, saying that such functions are so simple that they do not deserve to be in the library. This would be a sensible opinion, BTW. Michele From kfettig at state.nd.us Thu Jul 24 15:00:29 2003 From: kfettig at state.nd.us (Ken Fettig) Date: Thu, 24 Jul 2003 14:00:29 -0500 Subject: running python References: Message-ID: As I understand it, you have to have the Python interpreter installed on your machine before you can run Python Scripts... I don't think anyone will dispute that..... Thanks Ken Fettig kenfettig at btinet.net "Iain Macalister" wrote in message news:bfp9uh$76a$1 at news7.svr.pol.co.uk... > How do you run files written with python if you don't have the compiler and > stuff on your computer? > > From tomas at fancy.org Tue Jul 15 18:09:38 2003 From: tomas at fancy.org (Tom Plunket) Date: Tue, 15 Jul 2003 15:09:38 -0700 Subject: wxPython - question References: <3cp1hvgjkfeih2k3f0mo0he7mn4lmt7u7q@4ax.com> <4737hvob87b2699fvqkhl61i9ufqm1jnc4@4ax.com> Message-ID: JanC wrote: > > but the same thing could be achieved by plopping up a dialog box. > > That's why almost everybody is using a pop-up stopper these days. Heh no doubt. I love nothing more than furiously coding away on something, a dialog pops up from somewhere, and the next that I type dismisses the dialog before I even notice it on screen. -tom! -- There's really no reason to send a copy of your followup to my email address, so please don't. From http Fri Jul 11 11:52:14 2003 From: http (Paul Rubin) Date: 11 Jul 2003 08:52:14 -0700 Subject: Embedding Python, threading and scalability References: Message-ID: <7xvfu983ip.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Not particularly. Most threading at the application level is done for > one or more of three purposes: > > * Allowing background work and fast response in a GUI application > > * Scalable I/O > > * Autonomous sections of code for algorithmic simplicity (e.g. > simulations) Um, concurrent access by multiple clients for server applications? > Python does quite well at all three out of the box (the second because > all standard Python I/O modules release the GIL, as do most 3rd-party > extensions that deal with I/O (e.g. mxODBC)). The only thing Python > doesn't do is computational threading, and Python's overhead makes it a > poor choice for that purpose. Finally, there are so many distributed > computing solutions that multiple processes are a viable technique for > managing computational threading. Yeah, but now you need complicated and possibly slow mechanisms for sharing global state between processes. From djc at object-craft.com.au Sun Jul 20 06:58:24 2003 From: djc at object-craft.com.au (Dave Cole) Date: 20 Jul 2003 20:58:24 +1000 Subject: Albatross 1.10 released Message-ID: OVERVIEW Albatross is a small toolkit for developing highly stateful web applications. The toolkit has been designed to take a lot of the pain out of constructing intranet applications although you can also use Albatross for deploying publicly accessed web applications. In slightly less than 3000 lines of Python (according to pycount) you get the following: * An extensible HTML templating system similar to DTML including tags for: - Conditional processing. - Macro definition and expansion. - Sequence iteration and pagination. - Tree browsing. - Lookup tables to translate Python values to arbitrary template text. * Application classes which offer the following features: - Optional server side or browser side sessions. - The ability to place Python code for each page in a dynamically loaded module, or to place all page processing code in a single mainline. * The ability to deploy applications either as CGI or via mod_python by changing less than 10 lines of code. The toolkit application functionality is defined by a collection of fine grained mixin classes. Nine different application types and five different execution contexts are prepackaged, you are able to define your own drop in replacements for any of the mixins to alter any aspect of the toolkit semantics. Application deployment is controlled by your choice of either cgi, FastCGI, mod_python, or BaseHTTPServer Request class. It should be possible to develop a Request class for Medusa or Twisted to allow applications to be deployed on those platforms with minimal changes. Albatross comes with over 160 pages of documentation. HTML, PDF and PostScript formatted documentation is available from the toolkit homepage. The toolkit homepage: http://www.object-craft.com.au/projects/albatross/ The Albatross mailing list subscription and archives: http://object-craft.com.au/cgi-bin/mailman/listinfo/albatross-users CHANGES SINCE 1.01 There have been many improvements and bug fixes since release 1.01. The following page describes the changes in detail. http://www.object-craft.com.au/projects/albatross/albatross/rel-1.10.html (There were no changes to 1.10pre4) -- http://www.object-craft.com.au From klapotec at chello.at Thu Jul 31 16:21:53 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 31 Jul 2003 20:21:53 GMT Subject: list indexing References: Message-ID: <76uiivkl7vlr98ggp1p7i4h8m8h2s0sbs0@4ax.com> On 31 Jul 2003 12:53:09 -0700, ruach at chpc.utah.edu (Matthew) wrote: >Hello, I am rather new to python and I have come across a problem that >I can not find an answer to any where I my books. What I would like to >know is if there is a way to get the index number of a list element by >name. Sort of the inverse of the .index() method. > >For example > >list = ['this', 'is', 'a', 'list'] >for item in list: > if item = 'list': > print ???? > >???? Is where I want to be able to get the index number, in this case >3 from the list in a simple fasion. > > >I know that I could do this > >list = ['this', 'is', 'a', 'list'] >counter = 0 >for item in list: > if item = 'list': > print counter > else: > counter = counter + 1 > >But is there an easier way? > Using a recent Python you can use enumerate (built-in): list = ['this', 'is', 'a', 'list'] for cnt, item in enumerate(list): if item == 'list': print cnt --Christopher From logistix at cathoderaymission.net Tue Jul 29 13:23:19 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 29 Jul 2003 10:23:19 -0700 Subject: Debugging Python ? References: <3c91a864.0307282013.2acb2d1f@posting.google.com> Message-ID: <3c91a864.0307290923.415b642a@posting.google.com> pedro.werneck at bol.com.br (Pedro Werneck) wrote in message news:... > That's a nice idea... I done something similar to redirect print > statements to a text widget in a debug environment I am developing... > but my point here is not to redirect output... I think a statement > that simply does: if __debug__: print "..." would ease > debugging... that: def _print(*args): for arg in args: > print arg return True assert _print("bla", "bla bla") is very > interesting but it would be nice to have a standard way to do that... > a new statement, a modified assert statement or a new builtin... I am > not that experienced on python, so I don't know... what do you Python > gurus think ? Is this worth the effort ? The logging package in the soon-to-be-released 2.3 should take care of you, and might even be overkill ;) http://www.python.org/doc/2.3c2/whatsnew/node9.html From robin at jessikat.fsnet.co.uk Sun Jul 13 05:52:17 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 13 Jul 2003 10:52:17 +0100 Subject: floating point control in extensions Message-ID: <92tOKLARvSE$Ewh9@jessikat.fsnet.co.uk> Is there a preferred way to intercept floating point exceptions in python extensions? I assume one should be careful to restore any existing error handler. Does python have a standard mechanism for setting up fpu control words etc? -- Robin Becker From exarkun at intarweb.us Thu Jul 24 21:08:11 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 24 Jul 2003 21:08:11 -0400 Subject: Standard behaviour of a getSomething method In-Reply-To: References: Message-ID: <20030725010811.GA19318@intarweb.us> On Thu, Jul 24, 2003 at 02:56:24PM -0700, Mike Rovner wrote: > Batista, Facundo wrote: > > [snip] > > Usualy statement > x=y > creates a new object y referencing to old object y. Neither `x' nor `y' above are objects. Hence, the statement does not create a new object. What it does do is create a new binding (`x') to an object which already exist (referenced by `y'). Jp -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From logiplex at qwest.net Tue Jul 22 17:16:07 2003 From: logiplex at qwest.net (Cliff Wells) Date: 22 Jul 2003 14:16:07 -0700 Subject: wxpython display jpg in a frame In-Reply-To: References: Message-ID: <1058908566.1448.42.camel@software1.logiplex.internal> On Tue, 2003-07-22 at 12:32, max4 wrote: > hello > i would like to know if there is a good tutorial about how to do this > or if someone could explain > [ i want to add a jpg to an existing about dialog] Capture the PAINT event and use a PaintDC to draw to the dialog: class MyDialog(wx.Dialog): def __init__(self, ...): ... EVT_PAINT(self, self.OnPaint) def OnPaint(self, event): dc = wxPaintDC(self) dc.DrawBitmap(bitmap, ...) event.Skip() BTW, questions about wxPython are better asked on the wxPython list: http://www.wxpython.org/maillist.php Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From andrew-pythonlist at puzzling.org Fri Jul 18 01:07:40 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 18 Jul 2003 15:07:40 +1000 Subject: Regular expression help In-Reply-To: References: Message-ID: <20030718050740.GH7618@frobozz> On Fri, Jul 18, 2003 at 04:31:32AM +0000, David Lees wrote: > Andrew Bennetts wrote: > > > >How about re.findall? [...] > Actually this fails with the multi-line type of file I was asking about. > > >>> re.findall('BEGIN(.*?)END', 'BEGIN foo\nmumble END BEGIN bar END') > [' bar '] Oh! So it does. I presumed it took an optional flags argument, like re.search, but it doesn't. Compiling the pattern with re.M doesn't seem to help (and I can't figure out how to include the flag inline -- "(?M)" doesn't seem to work). On the other hand, this hack does work: >>> re.findall('BEGIN((?:.|\\n)*?)END', 'BEGIN foo\nmumble END BEGIN bar END') [' foo\nmumble ', ' bar '] (There's probably a more elegant way to do that, but I'm not a re expert) -Andrew. From adechert at earthlink.net Sun Jul 20 21:58:41 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 01:58:41 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xllus94t8.fsf@ruckus.brouhaha.com> <7x1xwk8z14.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x1xwk8z14.fsf at ruckus.brouhaha.com... > "Alan Dechert" writes: > > Right. This receipt problem is way overblown. If we really thought this > > was a big problem, absentee voting would be illegal. There are problems > > with absentee voting but then look at Oregon -- they have gone to > > vote-by-mail entirely. > > In fact absentee ballots are just about the favorite mechanism of > ballot fraud. .... > I think that is correct. > Absentee voting should be greatly curtailed if not > banned outright. Instead, voters away from home should be allowed to > cast their ballots at any official polling place they happen to be > near, not just at the one in their home district. > Our system, if implemented, would replace the current absentee system as well as the current poll site system. http://home.earthlink.net/~adechert/ucvs-proposal.rtf The absentee system would work very much like the poll site system. The voter would see exactly the same screens with either one. The printout would look exactly the same. The ballot electronic record would wind up in exactly the same format as poll site ballots. Here are some advantages highlighted in the proposal: ? Voter does not need to plan ? Avoids mailing of absentee request as request is made and granted on-the-spot ? No need for the county to print and mail costly absentee ballot materials ? Tabulation of absentee votes available on Election Day ? Seamless integration with poll site system ? Secret ballot and voter anonymity preserved ? Greatly reduces potential for absentee vote fraud > I have doubts about Oregon but its problems don't see nearly as bad as > places like Florida (try Googling for "Xavier Suarez" and "fraud"). > If they did mail-in voting in Florida, they would never get a reliable > election result again. > > As for the receipt problem being overblown, IIRC, Benaloh's original > paper described its motivation, citing examples of the Mafia telling > people how to vote in Italian elections and demanding to see receipts. > There would be similar problems in the US military from what I've heard. > There are still important issues there. Generally, we've cracked down on blatant coersion and vote buying. Still, some good sting operations are probably in order. The most persistent type of corruption has to do with campaigns that overwork the absentee ballots -- helping voters make sure they vote. Sometimes it's a fine line. A campaign worker might stop by an elderly voter to make sure s/he has mailed in the absentee ballot, and the voter asks for assistance -- or the campaign worker offers assistance. How much assistance constitutes fraud where a voter is really not sure what to do? I don't have any numbers but in 2000 a lot of older folks in Florida were getting assistance with obtaining and sending in their absentee ballots. Alan Dechert From duncan at NOSPAMrcp.co.uk Tue Jul 15 10:11:02 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 15 Jul 2003 14:11:02 +0000 (UTC) Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> <3f13bd77$1@mail.hmgcc.gov.uk> <3f13f674$1@mail.hmgcc.gov.uk> Message-ID: "richardc" wrote in news:3f13f674$1 at mail.hmgcc.gov.uk: > I wanted to scan the lines backwards until I found %%EOF (as its > likley to be the last line) and do it that way. I might do that or > might use a regex and just let that find it. Ok, try this. (On Windows systems the file has to be opened in binary mode for this to work.) ----- cut here ----- from __future__ import generators def readbackwards(aFile, blocksize=1024): def blocks(length, blocksize): for pos in range(length, 0, -blocksize): yield pos, 1024 yield 0, pos aFile.seek(0, 2) # Seek to end eof = aFile.tell() residue = None for pos, size in blocks(eof, blocksize): aFile.seek(pos, 0) block = aFile.read(blocksize) if residue is not None: block += residue lines = block.split('\n') lines.reverse() residue = lines.pop() for line in lines: if line.endswith('\r'): line = line[:-1] yield line if residue is not None: yield residue if __name__=='__main__': input = file('test.txt', 'rb') for line in readbackwards(input, blocksize=8192): if line.startswith("%%EOF"): print line break input.close() ----- end cut ------ -- 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 kmj9907 at cs.rit.edu Tue Jul 29 14:19:22 2003 From: kmj9907 at cs.rit.edu (Keith Jones) Date: Tue, 29 Jul 2003 18:19:22 GMT Subject: PyQt Help and Advice References: Message-ID: On Tue, 29 Jul 2003 15:17:40 +0000, Ilya Knizhnik wrote: > However since PyQt is rather new, I have not found much documentation on > it, or examples in it. The only useful tutorial/book I have found is at > www.opendocspublishing.com/pyqt/ but it is not always clear for someone > with almost no GUI experience. > Does anyone have any suggestions? > > Ilya If you're at all familiar with C++, or even if you're not, you'll find Qt's API docs, http://doc.trolltech.com/3.0/ , very handy. I've found that pyQt correlates almost exactly with them, except for some str QString conversion issues. I refer to that all the time when I'm doing PyQt code. Also, I don't know what OS or distro you're on, but there is a set of pyqt examples out there. In redhat, I used the PyQt-examples rpm (case sensitive), which installs a bunch of example programs to /usr/share/doc/PyQt-examples-[version]. Also. as Sybren mentioned, the Qt tutorial itself should be useful.. Finally, I'll say that the book you mentioned is excellent, and a wonder source of example code. I liked it enough that I bought it, and I'm happy I did. Good luck with PyQt! The only issues I've had were related to QCanvas not deleting canvas items (and therefore my program leaking them) if I don't reuse them. I still haven't figured that out, so I just keep track of the ones I create and reuse them, in order to prevent memory leaks. Keith From max at alcyone.com Wed Jul 2 04:43:37 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 01:43:37 -0700 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: <3F029B39.FA1DBBAE@alcyone.com> Mirko Zeibig wrote: > it's even simpler and maybe to obvious for a C++-afficinado: > > > class SomeClass: > > def __init__(self): > > self.countdown = Countdown() > > self.countdown.SetCallback(30, lambda s=self: s.Callback) > > self.countdown.SetCallback(30, self.Callback) > > You don't need lambda here, just give the Countdown class a reference > to your > callback-method by specifying it's name *without* parentheses :-). > > If you print self.Callback, you will the information, that this is a > instance-bound method object. This feature of bound vs. unbound methods is one of the things that, early on, made me really warm up to Python. The example you provide is in fact the situation in which they're often the most useful: when needing callbacks, usually for event-based systems (including GUIs). C++ has member function pointers, but it doesn't have the standalone concept of bound member functions, so functors are in fact usually used for precisely this case, where you want to get a single callable object that binds a member function pointer to an instance pointer/reference. Python's builtin ability to usefully distinguish between bound and unbound methods usually eliminates that need entirely; that is to say, a bound method _is_ in fact a "functor," in that it's simply a callable object that has the desired effect. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I'm trying to forget / But I can't act as if we never met \__/ Chante Moore From joerg.maier at rz.uni-mannheim.de Mon Jul 28 19:50:32 2003 From: joerg.maier at rz.uni-mannheim.de (=?ISO-8859-15?Q?J=F6rg?= Maier) Date: Tue, 29 Jul 2003 01:50:32 +0200 Subject: python on windos os.popen and standart in and out References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 thanks, i am so stupid, thats the right stuff, just read the moules documentation and there was something like But down there they say thats what i need now bye joerg nneo wrote: > On Sun, 27 Jul 2003 23:54:18 +0200, J?rg Maier wrote: > >> when giving 'w' as second parameter, i just can write, >> but not read. ssh is installed by cygwin. i dont want to use ssh-keys, >> because user shold be able to use the program on different machines >> without much key-copying. > > Instead of os.popen try os.popen2 which gives > back 2 pipes , one to read and onother to write to you application . > > p1 , p2 = os.popen2("foo") - -- Hi I am a signature virus. Please copy me to your .signature file to help me spread. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2-rc1-SuSE (GNU/Linux) iD8DBQE/JbbNTYj8eXbs1acRArKcAKCeb5qP4Psd8VFA+KlZh1FVAweLOgCgyYiZ 7M1g4m+q5J8cWOXF8PVxHHs= =z7vi -----END PGP SIGNATURE----- From rshaw2 at midsouth.rr.com Fri Jul 25 14:36:23 2003 From: rshaw2 at midsouth.rr.com (Richard) Date: 25 Jul 2003 11:36:23 -0700 Subject: How to detect typos in Python programs References: Message-ID: <84e0f331.0307251036.6504b16a@posting.google.com> Manish Jethani wrote in message news:... > Hi all, > > Is there a way to detect typos in a Python program, before > actually having to run it. Let's say I have a function like this: > > def server_closed_connection(): > session.abost() > > Here, abort() is actually misspelt. The only time my program > follows this path is when the server disconnects from its > end--and that's like once in 100 sessions. So sometimes I > release the program, people start using it, and then someone > reports this typo after 4-5 days of the release (though it's > trivial to fix manually at the user's end, or I can give a patch). > > How can we detect these kinds of errors at development time? > It's not practical for me to have a test script that can make > the program go through all (most) the possible code paths. > > -Manish Two words! Unit Testing! Just do a google search on "Python unit testing" and I'm sure you'll get more information than you ever wanted to know. Richard From daniel.dittmar at sap.com Wed Jul 23 07:20:41 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 23 Jul 2003 13:20:41 +0200 Subject: [OnTopic] SCO is Going After End Users References: <4868482a.0307211336.4ca9493a@posting.google.com> Message-ID: Ville Vainio wrote: > It might be slightly on topic in that the future versions of Python > could theoretically (and developers willing), shall we say, not pay as > much attention for unixware as the target platform... perhaps even > drift so far as not being able to compile at all >;-). SCO doesn't want you to actually use unixware. You should only pay them as if you do. Daniel From danb_83 at yahoo.com Sat Jul 19 22:26:08 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Jul 2003 19:26:08 -0700 Subject: classes References: Message-ID: "Pablo" wrote in message news:... > Hello everyone > > I have a problem with classes and hope someone can help me. > I'm used to Java and want to make a singleton class which would allow to > create only one instance of the class. ...[snip]... > How can I do the same in Python? > My main problems are: > 1) how to declare a static field (class field not object field) You can't. There are no variable declarations in Python. You can use static fields, though. >>> class HasStaticField: ... field = 4 ... >>> HasStaticField.field 4 > 2) how to declare a static method class HasStaticMethod: def method(arg0, arg1): # note the lack of "self" # do something with arg0 and arg1 method = staticmethod(method) > 3) how to declare a private constructor (is it possible?) It's not possible (afaik) to define a private constructor. But it is possible to enforce that a constructor can be called only once. class SingletonError(Exception): pass class Singleton: __instance = None def __init__(self): if Singleton.__instance is None: # initialization code Singleton.__instance = self else: raise SingletonError() def getInstance(): if Singleton.__instance is None: Singleton() return Singleton.__instance getInstance = staticmethod(getInstance) From jjl at pobox.com Sun Jul 27 20:51:21 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Jul 2003 01:51:21 +0100 Subject: Cookie.py troubles. References: Message-ID: <87fzkra2ye.fsf@pobox.com> Ben Hearsum writes: [...] > I set my cookie like this: > > mycookie = Cookie.SimpleCookie() > mycookie['key'] = "foobar" > > print mycookie > print("Content-Type: text/html\n\n") > print("meow") > > Now, to retrieve it, the documentation says I parse the HTTP_COOKIE > environment variable. Makes sense to me. But when I print it out I get > "Set-Cookie: key=foobar;". I was thinking of parsing it with cgi.parse_qs, > but even if i do print(mycookie.output(header="")) there's still a ; at > the end of the cookie. Why do you want to parse Set-Cookie if you're writing a CGI script? Set-Cookie is what the server sends to the client. HTTP_COOKIE is set by the server, not by Python, to the value than was sent by the client to the server. I guess SimpleCookie has a __str__ method that makes it print out Set-Cookie: key=foobar; -- seems like useful behaviour. > Here's what I use to print them out: > > cookie = Cookie.SimpleCookie() > cookie.load(os.environ['HTTP_COOKIE']) Yep, in comes the Cookie: header, I presume SimpleCookie parses it, and then... > print("Content-Type: text/html\n\n") > print(mycookie.output(header="")) You send the cookie back to the client again. > Output: > > key=foobar; This seems to contradict what you said before ("key=foobar;" vs. "Set-Cookie: key=foobar;"). John From staschuk at telusplanet.net Tue Jul 22 18:41:29 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 22 Jul 2003 16:41:29 -0600 Subject: recognizing empty iterators In-Reply-To: <2259b0e2.0307220744.156c95bf@posting.google.com>; from mis6@pitt.edu on Tue, Jul 22, 2003 at 08:44:52AM -0700 References: <2259b0e2.0307210626.11a1bbf1@posting.google.com> <2259b0e2.0307220744.156c95bf@posting.google.com> Message-ID: <20030722164129.B393@tibia.amotlpaa.bogus> Quoth Michele Simionato: > Steven Taschuk wrote in message news:... [...] > > I don't have anything substantial to add to others' posts, but I > > wonder: under what circumstances do you want to do this? > > I wanted to check the output of ifilter or imap; [...] Ah. And then, if there were elements in the iterator, I assume you would then process them somehow, right? Why not just do that with a for loop, say, and check afterwards whether anything has been done? A silly example: processed = 0 for x in iterator: process(x) processed = processed + 1 if processed: # ... > [...] at the end I solved > my problem in another way, nevertheless I am surprised there is no > way to check for an empty iterator in current Python, it seems to be > a quite legitimate question, isn't it? Absolutely. I was just curious what the original problem was. (I haven't read the iterators PEP in a while, but it seems to me the iterator protocol is deliberately minimalistic. Makes it easier to write them; and if you do frequently need lookahead, writing a wrapper as others have suggested seems easy enough.) -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From tjreedy at udel.edu Mon Jul 28 13:05:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jul 2003 13:05:00 -0400 Subject: urn scheme References: Message-ID: "Duncan Smith" wrote in message news:bg38sa$e6r$1 at news7.svr.pol.co.uk... > Hello, > I'm currently doing some simulations where I need to sample without > replacement from a list of counts. (Actually it's a Numeric array, but I'm > currently converting the array to a list, using the following function and > converting back to an array.) I *desperately *need to speed this up > (simulations currently take over 24 hours). This sampling is a real > bottleneck, and accounts for about 90% of the time cost. If I can get a > 10-fold speed up I might be in business, and a 100-fold speed up might even > allow me to meet a deadline. Using psyco appears to give me no speed up > whatsoever (that can't be right, can it?). I am currently working on > reducing the number of function calls to urn(), but the biggest speed up > will still come from improving the performance of this function. Any ideas > for a significant speed up? TIA. Do the minimum needed for each call and minimize intermediate structures. Among other things, this means specializing the function -- no options. Instead separate with and without replacement functions. Consider writing urn() as a generator returning one draw at a time instead of a list. Assuming that 'bins' means 'colors' (number of each), I suggest constructing an single urn list as follows: contents = [] for i in range(len(bins)): contents.extend(bins[i]*[i]) This replaces cum_bins and the multiple comparisons and adjustments. It can go inside or outside urn() depending upon whether a given configuration is used just once or muptiple times. Then: sampling one item with replacement: random.choice(contents). sampling all without replacement: random.shuffle(contents) sampling some without replacement: random.shuffle(contents)[:draws] or, if draws is small enough (test timings for switch point) def urn_swor(colors, draws): '''Construct multicolor urn and destructively sample without replacement (swor) 'draws' items by successively removing random element thereof. Colors is array of number of each color. ''' ncolors = len(colors) contents = [] for i in range(ncolors): contents.extend(colors[i]*[i]) n = len(contents) rand = random.randrange res = ncolors * [0] while draws: i = rand(n) res[contents[i]] += 1 contents[i] = contents[-1] n -= 1 draws -= 1 return res >>> urn_swor((0,2,5,3,4), 10) [0, 2, 2, 0, 6] >>> urn_swor((0,2,5,3,4), 10) [0, 1, 4, 1, 4] >>> urn_swor((0,2,5,3,4), 10) [0, 1, 3, 1, 5] >>> urn_swor((0,2,5,3,4), 10) [0, 2, 1, 1, 6] > ----------------------------------------------------------- > import random > > def urn(bins, draws, drawn=0, others=0): > > """Bins is a sequence containing the numbers > of balls in the urns. 'drawn' and 'others' Sampling one urn with k colors (variable number of each) is the same as a weighted sampling from k urns with 1 color each but should be much faster when done as described above. > define how the contents of the bins should > be updated after each draw in draws. The > default arguments correspond to sampling > with replacement. e.g. drawn = -1 corresponds > to sampling without replacement""" 'others' not defined > len_bins = len(bins) > res = [0] * len_bins > cum_bins = [bins[0]] + [0] * (len_bins-1) > for i in range(1, len_bins): > cum_bins[i] = cum_bins[i-1] + bins[i] > for i in range(draws): > balls = random.random() * cum_bins[-1] > adj = 0 > for j in range(len_bins): > if adj == 0 and cum_bins[j] > balls: > res[j] += 1 > cum_bins[j] += drawn> else: > cum_bins[j] += (j - adj) * others + adj * drawn I have no idea what this is about. > return res > ---------------------------------------------------------------- > >>> urn((0,2,5,3,4), 10, -1) > [0, 1, 4, 1, 4] Terry J. Reedy From jdhunter at ace.bsd.uchicago.edu Tue Jul 22 08:12:20 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Jul 2003 07:12:20 -0500 Subject: How to save web pages for offline reading? In-Reply-To: (hwlgw@hotmail.com's message of "21 Jul 2003 23:38:12 -0700") References: Message-ID: >>>>> "Will" == Will Stuyvesant writes: Will> I thought this whole thing would be easy with all those Will> Python internet modules in the standard distro: httplib, Will> urllib, urllib2, FancyURLxxx etc. Being able to download a Will> "complete" page *from Python source* would be very nice for Will> my particular application. Have you seen websucker, in the Tools/webchecker/websucker.py subdir of the python src dir? It does something very close to what you want. JDH From pythonguy at Hotpop.com Wed Jul 16 02:53:56 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 15 Jul 2003 23:53:56 -0700 Subject: Python Quiz Message-ID: <84fc4588.0307152253.20858619@posting.google.com> Hi Pythonistas, I have placed a quiz on Python on the trivia site www.funtrivia.com. Here is the link. http://www.funtrivia.com/quizdetails.cfm?id=139672 Looks like it is the first quiz on Python on this site. Please try it out if you like quizzing. Let me know if there are any factual errors. Thanks ~Anand From bart.NOSPAM.de.waal at quicknet.nl Tue Jul 1 02:53:44 2003 From: bart.NOSPAM.de.waal at quicknet.nl (bart) Date: Tue, 01 Jul 2003 08:53:44 +0200 Subject: I need a lot of help! In-Reply-To: References: <31ef0f43.0304011336.1d2777ac@posting.google.com> Message-ID: <1057042341.278407@cache2> Martijn Faassen wrote: > Jewlz408 wrote: > > I know about 50% of what there is to know about Arrays. They're usually > green but occasionally blue. They generally have big eyes. >>3) Dim C$( 12) > > > Trick question! This will be one Perl. > I don't know the answer to this one. I suspect it has to do with advanced > quantum numerology. > > It is a dishwasher. > > >>And what is the output? > > > Dirty water, and clean dishes. You can also put in cookies however, > in which case you will get chocolate chips. > ROTFLMAO From light at soton.ac.uk Wed Jul 2 08:41:03 2003 From: light at soton.ac.uk (Mark Light) Date: Wed, 2 Jul 2003 13:41:03 +0100 Subject: splitting a string into 2 new strings References: Message-ID: that works great - many thanks. "trp" wrote in message news:vg5jjqcc8d2r1f at corp.supernews.com... > Mark Light wrote: > > > Hi, > > I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2 > > strings > > 'C H O' and '6 12 6'. I have played with string.split() and the re module > > - but can't quite get there. > > > > Any help would be greatly appreciated. > > > > Thanks, > > > > Mark. > > I'm, assuming that these are chemical compounds, so you're not limited to > one-character symbols. > > Here's how I'd do it > > import re > > re_pat = re.compile('([A-Z]+)(\d+)') > text = 'C6 H12 O6' > > # find each component, returns list of tuples (e.g. [('C', '6'), ...] > component = re_pat.findall(text) > > #split into separate lists > symbols, counts = zip(*component) > > # create the strings > symbols = ' '.join(symbols) > counts = ' '.join(counts) > > --Andy > > > > > From max at alcyone.com Sat Jul 12 04:02:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 01:02:16 -0700 Subject: Python Mystery Theatre -- Episode 1: Exceptions References: Message-ID: <3F0FC088.3C56EDEA@alcyone.com> Raymond Hettinger wrote: (I've pasted in code I needed to use to illustrate or understand the problems.) > ACT I --------------------------------------- > >>> s = list('abc') > >>> try: > ... result = s['a'] > ... except IndexError, TypeError: > ... print 'Not found' > ... > > Traceback (most recent call last): > File "", line 2, in -toplevel- > result = s['a'] > TypeError: list indices must be integers This one's easy. You didn't try to catch IndexErrors and TypeErrors, you tried to catch an IndexError and, if caught, assign the exception instance to TypeError. The except clause takes an exception class or tuple of exception classes, and then an optional instance variable name, and then some other optional things. So: ... except (IndexError, TypeError): ... will fix this. > ACT II -------------------------------------------- > >>> class MyMistake(Exception): > ... pass > > >>> try: > ... raise MyMistake, 'try, try again' > ... except MyMistake, msg: > ... print type(msg) > ... > > I'm not sure what mystery you're trying to get at here. This is what Python prints for all instances: >>> class C: ... pass ... >>> c = C() >>> type(c) An exception is an instance of an exception class, so it looks like an instance like any other. If you wanted the name of the class, then use __class__: >>> c.__class__ >>> c.__class__.__name__ 'C' > ACT III -------------------------------------------- > >>> class Prohibited(Exception): > ... def __init__(self): > ... print 'This class of should never get initialized' > ... > >>> raise Prohibited() > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited() > Prohibited: > >>> raise Prohibited > This class of should never get initialized > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise Prohibited > Prohibited: Is this some IDLE-specific thing? I don't see this at all: >>> class Prohibited(Exception): ... def __init__(self): ... print 'This class should have never gotten initialized' ... >>> raise Prohibited() This class should have never gotten initialized Traceback (most recent call last): File "", line 1, in ? __main__.Prohibited>>> >>> raise Prohibited This class should have never gotten initialized Traceback (most recent call last): File "", line 1, in ? __main__.Prohibited>>> There is indeed no newline between the printed names of the class and the following prompt, this is not a pasting error, which strongly suggests to me that it's what you're trying to get at but is exhibiting itself in a different way in the interactive interpreter vs. IDLE. Undoubtedly it happens because Prohibited overrides Exception, and Prohibited needs an __init__ method, but that method does not call Exception.__init__. At the very least, fixing this for me makes the output a little more sane: >>> class Proscribed(Exception): ... def __init__(self): ... Exception.__init__(self) ... print "That information is proscribed. Enter your DNA#." ... >>> raise Proscribed() That information is proscribed. Enter your DNA#. Traceback (most recent call last): File "", line 1, in ? __main__.Proscribed >>> raise Proscribed That information is proscribed. Enter your DNA#. Traceback (most recent call last): File "", line 1, in ? __main__.Proscribed > ACT IV ----------------------------------------------- > >>> module = 'Root' > >>> try: > ... raise module + 'Error' > ... except 'LeafError': > ... print 'Need leaves' > ... except 'RootError': > ... print 'Need soil' > ... except: > ... print 'Not sure what is needed' > ... > > Not sure what is needed You used string exceptions and so deserve punishment :-). In this case, string exceptions in except clauses are tested by identity, not equality, so building them with concatenation is unlikely to create a string with the same ID: >>> s = "dataspace retrieval" >>> t = "dataspace " + "retrieval" >>> s is t 0 >>> s == t 1 Equality and identity aren't the same thing, and this is one of the rare cases in Python where identity really matters (usually, it's merely an optimization implementation detail). Short answer: Don't use string exceptions. Long answer: Seriously, don't use string exceptions. > ACT V ----------------------------------------------- > >>> try: > ... raise KeyError('Cannot find key') > ... except LookupError, msg: > ... print 'Lookup:', msg > ... except OverflowError, msg: > ... print 'Overflow:', msg > ... except KeyError, msg: > ... print 'Key:', msg > > Lookup: 'Cannot find key' This means that KeyError is a subclass of LookupError (something I wouldn't have known off the top of my head but which was easy to verify): >>> issubclass(KeyError, LookupError) 1 Except clauses go in order and test to see whether the exception object is an instance of the specified class or any of its subclasses. Since KeyError is a subclass of LookupError, all KeyErrors are LookupErrors too, and that's the except clause that gets executed. If you actually _did_ want to distinguish between KeyErrors and LookupErrors, you can put the KeyError clause first: ... except KeyError, e: ... except LookupError, e: ... ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ God said: "Let Newton be"; and all was light. \__/ Alexander Pope From vze4rx4y at verizon.net Mon Jul 14 01:42:13 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 14 Jul 2003 05:42:13 GMT Subject: Python Mystery Theatre -- Episode 2: Así Fue Message-ID: Here are four more mini-mysteries for your amusement and edification. In this episode, the program output is not shown. Your goal is to predict the output and, if anything mysterious occurs, then explain what happened (again, in blindingly obvious terms). There's extra credit for giving a design insight as to why things are as they are. Try to solve these without looking at the other posts. Let me know if you learned something new along the way. To challenge the those who thought the last episode was too easy, I've included one undocumented wrinkle known only to those who have read the code. Enjoy, Raymond Hettinger ACT I ----------------------------------------------- print '*%*r*' % (10, 'guido') print '*%.*f*' % ((42,) * 2) ACT II ----------------------------------------------- s = '0100' print int(s) for b in (16, 10, 8, 2, 0, -909, -1000, None): print b, int(s, b) ACT III ---------------------------------------------------- def once(x): return x def twice(x): return 2*x def thrice(x): return 3*x funcs = [once, twice, thrice] flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)] flam = [lambda x:f(x) for f in funcs] print flim[0](1), flim[1](1), flim[2](1) print flam[0](1), flam[1](1), flam[2](1) ACT IV ---------------------------------------------------- import os os.environ['one'] = 'Now there are' os.putenv('two', 'three') print os.getenv('one'), os.getenv('two') From skip at pobox.com Thu Jul 31 14:58:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 13:58:55 -0500 Subject: [Newbie] FAQ? In-Reply-To: References: Message-ID: <16169.26351.560607.12435@montanaro.dyndns.org> Simone>is there a FAQ for this NG? Christopher> http://www.faqs.org/faqs/by-newsgroup/comp/comp.lang.python.html Christopher> Have you heard of Google? Simone> sure I did! Pardon... Don't apologize too profusely. The dates on the two FAQs listed there (one for c.l.py and one for c.l.py.announce) are 1996 and 1999, respectively. The c.l.py FAQ probably is going to be all that useful unless you're a Python historian. Skip From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 18:28:22 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 31 Jul 2003 00:28:22 +0200 Subject: plug: pyBoards.com In-Reply-To: <191e20c8.0307300703.6e84b9ed@posting.google.com> References: <191e20c8.0307300703.6e84b9ed@posting.google.com> Message-ID: <3f284687$0$49105$e4fe514c@news.xs4all.nl> Kyle Babich wrote: > > pyBoards.com is a community for all of you Python programmers out > there. So, why not take a minute to stop by and register? > Because I then have to check yet another source of Python discussion material... From kp at kyborg.dk Thu Jul 10 08:33:01 2003 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 10 Jul 2003 14:33:01 +0200 Subject: mx odbc In-Reply-To: <3F0D4728.45284530@hotmail.com> References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> <3f0bce6d$0$13245$edfadb0f@dread15.news.tele.dk> <3f0d32e5$0$13253$edfadb0f@dread15.news.tele.dk> <3F0D4728.45284530@hotmail.com> Message-ID: <3f0d5cfd$0$13154$edfadb0f@dread15.news.tele.dk> Alan Kennedy wrote: > Kim Petersen wrote: > > >>I have no idea about the support (obviously) - but then i hardly ever >>buy/use support for development tools [especially not open-source ones]. > > > Well, that just about says it all for the theory that "open source > developers should make their money from services". > > What many people seem to forget is that maintaining high quality > software *is* a service: in the case of mxODBC, a very high quality > service. If M-A-L didn't charge licensing fees, then he'd be providing > a high quality service, i.e. well designed, maintained and up-to-date > software, without any income at all, since, in general, developers > don't buy support for development tools, unless they absolutely must. It *is* a service - i agree completely and even if i don't use the support i'll prolly patch the problem and send the result upstream - that really isn't an argument to use in the below. The reason for that statement was simply that in opensource situations, we'll _maybe_ locate the bug ourselves (or patch the product to do what we want - which *cannot* be done in closed-source) and i'm not talking beer! > > Kim Petersen wrote: > > >>[snip] paying 70$ pr. >>customer, is the equivalent of paying you for 1hr of support for each >>customer [not installation mind you], where our own licence/supportcost >>is already getting lower and lower > > > It's a free market: pick another (cheaper) ODBC driver and use that > instead. Just make sure that your customers understand that they will > get a poorer quality product from you because they're paying you less > money, so you have to use lower quality components in your software: > I wonder how long they'll be your customers. Regarding the free marked - i agree - against the other - what is it *exactly* that makes mxODBC a better quality product - noone has seemed to be able to tell (and yes - you do in the above claim that...). So i can't even tell my customers that [even if i believed that your argument of telling customers about developing methods have any substance for them *at all* (its the product that counts - not the methods)]. > > Kim Petersen wrote: > > >>We work in teams - so that would be 1250*4 making the below calculation >>18*4 (and we're not able to pull in freelancers on this kinda stuff then >>- other than paying another 1250). > > > And how much would you pay these freelancers? Probably quite a > substantial amount over the weeks or months that you retain them, > and probably *far* in excess of the developer license cost for mxODBC. > How much improved productivity will you get from those developers > because they're not spending a week chasing weird bugs in the > database/ODBC code? essence of my argument - the pricing of this *little* (but essential) component drives the pricing of the end-product up a substantial amount - that imho is not corresponding to the usefulnes of the product. [and to use your argument from before - i need to find another product then]. > > I feel quite annoyed when people give out about having to pay money > for software: someone, somewhere has to write that software: that > someone has to pay the rent, the utility bills, etc, etc, etc, etc. > Demanding that everyone work for nothing is completely unreasonable: > just because you're too stingy to pay for what you get. Some OSS > developers are fortunate enough that they don't have to charge money > for their software, because the government, or the education system, > or some charitable foundation, pays their wages. But that's not true > for all OSS developers. We already pay substantial amounts for software - including donations for opensource projects - so your tirade falls on a wrong spot. [In our endsystems i estimate around 60% goes to hardware 30% goes to royalties etc. (as we implement in OSS software a large amount of this returns - not as much as i would wish - but then thats something for my boss to decide)]. > > To those who continue to complain about having to pay for software, > I say: If you don't like paying, fork the software, maintain your > own product and let it be free (both in the free-speech and the > free-beer senses): see how you long *you* last. Can you mention even on spot where i complained against paying for software ? (hint: the amount - not that it has a price). TANSTAAFL! > > not-biting-the-hand-that-feeds-ly yrs. > From owski at hotmail.com Wed Jul 16 18:14:12 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 22:14:12 +0000 (UTC) Subject: anything like C++ references? References: <20030715200433927-0600@news.xmission.com> <1058328099.572993@yasure> <20030716081156943-0600@news.xmission.com> <20030716123907246-0600@news.xmission.com> <20030716142716509-0600@news.xmission.com> Message-ID: <20030716161405965-0600@news.xmission.com> In Donn Cave wrote: > In article <20030716142716509-0600 at news.xmission.com>, > Adam Ruth wrote: >> In Donn Cave >> wrote: >> > In article <20030716123907246-0600 at news.xmission.com>, > .... >> > OK, there really aren't any situations where you can't avoid >> > pointers ... so you're ready with a solution to the problem >> > I posed above? > .... >> As for your problem on the subscript operator, I think my solution is: >> there's no problem. Having the get and set asymetric is preferrable, >> in my view. For example, I use it in a number of places where I >> cache the set operation: > > So after all it should be "there aren't any situations that I care > about where you can't avoid pointers." That's fine, it's really > where we all come down in the end - life is too short to worry > about solving problems you don't care about. One should be clear > about it, though. > > Donn Cave, donn at u.washington.edu > "there aren't any situations that I care about where you can't avoid pointers." is certainly true. But I still believe that there aren't any situations where the use of a pointer would provide a substantially better solution to the non-pointer route. Any examples I've seen so far have non-pointer implementations that are just as good or better (of course, 'better' is a completely loaded word). In your example, the current implementation provides for a flexibility that doesn't exist in the pointer version. The pointer version would provide for slightly more concise code, and possibly a slight performance boost, but I think that the flexibility outweighs both. The point of my response wasn't to show that there's a good way to achieve what you're looking for without a pointer, but to show that there are better things to be looking for, and they don't require pointers. So, I'll change my statement to this, "there aren't any situations where the use of a pointer would provide a significantly better solution". From Adrien.DiMascio at logilab.fr Wed Jul 9 02:29:55 2003 From: Adrien.DiMascio at logilab.fr (Adrien Di Mascio) Date: Wed, 9 Jul 2003 08:29:55 +0200 Subject: Unexpected (by me) exec behavior In-Reply-To: References: Message-ID: <20030709062955.GA20087@logilab.fr> Hi, > ---------------------------- > # filename = t.py > s1 = """ > s2 = \"\"\" > import socket > def xyz(): > print socket.gethostbyname('somehost') > if __name__ == '__main__': > xyz() > \"\"\" > > def abc(): > exec s2 > if __name__ == '__main__': > abc() > """ > > exec s1 > ----------------------------- I'll try to explain things as best as I can : - (1) When defining a variable in a new scope, it is added to the locals() dict. - (2) Calling exec without specifying any dict will cause to call it with globals() as global dict and locals() as local dict - (3) When you'll execute your script (t.py), globals() and locals() dict will be the same (they'll have the same id) Consequences : When you execute s1, globals() and locals() dict will be used, and they are the same. When entering the abc() func, a new local dict will be created (an "empty" one), so when you call exec s2, the two dict that will be taken will be globals(), and locals(), but they are not representing the same dict anymore since you're in the 'abc' scope and the locals() dict is thus "empty". When Python tries to execute s2, it will add socket into your local dict (not into the global one), then he will enter in the xyz() function, where it will create a new local dict because it will have just entered a new scope. Then in xyz(), neither globals(), nor locals() have a reference to 'socket', that's why you have your NameError. To prevent this, you can always call "exec s2 in globals()" in the abc function. Then, both globals and locals will have the same id, so when Python will add "socket" to the locals dict, it will also add it to the globals() one, and "socket" will be found in the global dict. Anyway, you're doing tricky things ... Hope this helps. Cheers, -- Adrien Di Mascio LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From bokr at oz.net Tue Jul 29 00:30:02 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Jul 2003 04:30:02 GMT Subject: pretty printing graphs References: Message-ID: On 29 Jul 2003 02:07:14 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >====< pphunter.py >============================================== [...] >class Node: [...] > > def showInPage(self, pageHeight=6*11, pageWidth=78): > return '\n'.join(self.boxlines(PageHeight, PageWidth)) > should be -- def showInPage(self, pageHeight=6*11, pageWidth=78): return '\n'.join(self.boxlines(pageHeight, pageWidth)) -- [...] Sorry. Regards, Bengt Richter From kericks272 at earthlink.net Thu Jul 24 01:31:17 2003 From: kericks272 at earthlink.net (ken) Date: Thu, 24 Jul 2003 05:31:17 GMT Subject: python 2.2 string conversion ? Message-ID: I've been looking for a solution to a string to long conversion problem that I've run into >>> x = 'e10ea210' >>> print x e10ea210 >>> y=long(x) Traceback (most recent call last): File "", line 1, in ? y=long(x) ValueError: invalid literal for long(): e10ea210 >>> x='0xe10ea210' >>> print x 0xe10ea210 >>> y=long(x) Traceback (most recent call last): File "", line 1, in ? y=long(x) ValueError: invalid literal for long(): 0xe10ea210 >>> x="e10ea210" >>> y=long(x) Traceback (most recent call last): File "", line 1, in ? y=long(x) ValueError: invalid literal for long(): e10ea210 >>> x="0xe10ea210" >>> y=long(x) Traceback (most recent call last): File "", line 1, in ? y=long(x) ValueError: invalid literal for long(): 0xe10ea210 >>> What am I doing wrong? TIA From skip at pobox.com Sun Jul 20 12:23:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 20 Jul 2003 11:23:52 -0500 Subject: non-ASCII characters IDLE 1.0 rc1 bugs In-Reply-To: References: Message-ID: <16154.49688.415680.385013@montanaro.dyndns.org> Barto> I have downloaded and installed Python 2.3 RC1 in a Windows 98 SE Barto> computer. IDLE 1.0 does not work very well: Can you post a bug report to Sourceforge? Skip From alanmk at hotmail.com Fri Jul 11 06:06:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Jul 2003 11:06:49 +0100 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> Message-ID: <3F0E8C39.E36233B6@hotmail.com> sebastien.hugues wrote: > I would like to retrieve the application data directory path of the > logged user on windows XP. To achieve this goal i use the > environment variable APPDATA. > > The logged user has this name: s?bastien. > I would like to first decode this string and then re-encode it in > utf-8, but i am not able to find out what encoding is used when i > make: > > appdata = os.environ ['APPDATA'] > > Any ideas ? Are you setting the environment at a windows command prompt, i.e. under cmd.exe? If yes, then type following command to find out what character set encoding is in use in that terminal: chcp Most likely it will be "cp850", i.e. "Code page 850". Assuming that "chcp" does report "cp850", then this code should achieve what you need (tested on Win2k only, not XP, but should be same) C:\>set APPDATA="s?bastien" C:\>python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> username = os.environ['APPDATA'].decode('cp850') >>> username u'"s\xdabastien"' >>> Of course, you will get a "UnicodeError: ASCII encoding error: ordinal not in range(128)" if you try to print that, but it should be usable for making up filenames. Of course, this may not work if the APPDATA environment variable is set outside a command window. If, for example, it was set through the control panel, then it should be in the system default encoding. But we'll cross that bridge when we come to it. Note also that "chcp" stands for "change code page", meaning that you can change the character set used by the terminal. A list of character sets supported can be found here: http://www.microsoft.com/globaldev/reference/wincp.mspx Let us know if that works. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From matthias.oberlaender at VOID.daimlerchrysler.com Fri Jul 4 09:57:35 2003 From: matthias.oberlaender at VOID.daimlerchrysler.com (Matthias Oberlaender) Date: 4 Jul 2003 13:57:35 GMT Subject: cooperation of buitlin methods usingtsuper References: <2259b0e2.0307020855.478300c2@posting.google.com> <2259b0e2.0307030652.697001dd@posting.google.com> <2259b0e2.0307040511.1eb91faa@posting.google.com> Message-ID: In <2259b0e2.0307040511.1eb91faa at posting.google.com> Michele Simionato wrote: > To add trickyness to trickyness, I show you a couple of examples where > the same problems appear. These examples (or examples similar to them) > where pointed out to me by Bjorn Pettersen. The real problem seems to be > in the lookup rule for len(x) which is not always equivalent to > x.__len__() when tricks with __getattr__ are performed: > > First example: defining __len__ on the object does not work > > class E(object): > def __getattr__(self,name): > if name=='__len__': return lambda:0 > > >>> e=E() > >>> e.__len__() > 0 > >>> len(e) > Traceback ... > > Second example: defining __len__ on the class does not work: > > class M(type): > def __getattr__(self,name): > if name=='__len__': return lambda self:0 > > class F: __metaclass__=M > > >>> f=F() > >>> F.__len__(f) # okay > 0 > >>> len(f) # TypeError: len() of unsized object > f.__len__() # AttributeError: 'F' object has no attribute '__len__' > > As you see, the problem is that len(x) is not calling x.__len__(), > nor x.__class__.__len__(x); I really would like to know how ``len`` > (or ``str``, ``repr``, etc.) work: I think this is the core of > the problem, whereas ``super`` is probably a red herring. > > Michele > Yes, I very nuch support this question: How do the builtins work exactly? Where is all this documented? Nevertheless, my impression remains that builtins and super do not play consistently together. Again, there is not much documentation concerning super either. It's still listed under 'Built-in Functions' in section 21 of the Library Reference, but actually t's a type. Well, Python's evolutionary character is both its strength and weakness. P.S. I will remain silent for the next couple of days. Thanks for the discussion so far. And I'll think about the idea of filing a (documentation) bug report as suggested by Michele. Would be my first one so I have to figure out how to do that. -- ____ __ _/_/ . ( / / ( / / / / ===================================================================== Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm RIC/AP (Machine Perception) Wilhelm-Runge-Str. 11, P.O. Box 2360, 89013 Ulm, Germany Phone: +49 731 505 2354 Fax: +49 731 505 4105 Email: matthias.oberlaender at REMOVE.daimlerchrysler.com ===================================================================== From dave at boost-consulting.com Mon Jul 28 10:20:59 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 28 Jul 2003 10:20:59 -0400 Subject: boost::python> exposing instances from c++ References: <20030727162245.07099.00000480@mb-m12.aol.com> Message-ID: Dear Mr. Handheld Vacuum, You will probably get better answers to your Boost.Python questions if you post them to the C++-sig. See http://www.boost.org/more/mailing_lists.htm#Cplussig. thedustbustr at aol.com (TheDustbustr) writes: > I'm writing a game in C++ which calls out to python for scripting. I'd like to > expose the instance of my Game class (a singleton) to python (so that the > instances of Clock, Camera, etc are available to the scripts). > > I ran into trouble trying to expose a specific instance (or even a function > returning the instance). Here is a simplification of my problem in code (c++): > > > class A{ > public: > int i; > }; > class B{ > public: > A a; > }; > B b; > B getb() {return b;} //return the instance > > int main() { > getb().a.i = 42; > return 0;} > #include > #include > #include > using namespace boost::python; > BOOST_PYTHON_MODULE(hello) > { > class_("A",init<>()) > .def("i", &A::i); > class_("B",init<>()) > .def("a", &B::a); > def("getb", getb); > } > > > Of course, I would be calling any python script using these classes from within > main(). > > This doesn't compile (using bjam with msvc). If I return by reference or > pointers in getb it gets ugly (like pages and pages of error messages). Am I > doing this the right way? How do I expose an instance to python? -- Dave Abrahams Boost Consulting www.boost-consulting.com From sjmachin at lexicon.net Fri Jul 18 09:13:21 2003 From: sjmachin at lexicon.net (John Machin) Date: 18 Jul 2003 06:13:21 -0700 Subject: scanf string in python References: Message-ID: lehrig wrote in message news:... > I have a string which is returned by a C extension. > > mystring = '(1,2,3)' > > HOW can I read the numbers in python ? That's a very strange C extension, which returns a string that just happens to look similar to the repr() of a tuple ... What's the name of the C extension? Where did you get it from? If you are the author, would you like to be shown how to make it return a tuple? That way, all the caller has to do is: x, y, z = my_extn.some_func(.........) From hahaha at iol.it Mon Jul 28 05:22:09 2003 From: hahaha at iol.it (nneo) Date: Mon, 28 Jul 2003 11:22:09 +0200 Subject: python on windos os.popen and standart in and out References: Message-ID: On Sun, 27 Jul 2003 23:54:18 +0200, J?rg Maier wrote: > when giving 'w' as second parameter, i just can write, > but not read. ssh is installed by cygwin. i dont want to use ssh-keys, > because user shold be able to use the program on different machines > without much key-copying. Instead of os.popen try os.popen2 which gives back 2 pipes , one to read and onother to write to you application . p1 , p2 = os.popen2("foo") From newsgroups at jhrothjr.com Thu Jul 24 15:45:59 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 24 Jul 2003 15:45:59 -0400 Subject: Associating file types to my Python program References: Message-ID: "Psymaster" wrote in message news:Xns93C2BBA60F6BEt45fs6vve at 130.133.1.4... > How could I do that? I'm writing an image viewer and I would > want to associate all images to be opened with my proggie when > they are double-clicked. Do you really want to do that? I'd advise going a bit slow, and just get an item on the context menu for starters. Look at HKCR\SystemFileAssociations\Image\Shell and put your command in there. It will pop up on the context menu for all file extensions that have a "PercievedType" of "Image", at least under Windows XP. Then if you want to make some of them the default, you can go ahead, but that's actually a bit more difficult since it has to be done file type by file type; there's no way of doing it wholesale. Just remember one thing: learn the registry editor thoroughly first. Appendix A of the Microsoft Windows XP Registry Guide can be quite helpful if you want to hack file associations. John Roth From robin at jessikat.fsnet.co.uk Tue Jul 15 05:45:27 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 15 Jul 2003 10:45:27 +0100 Subject: Python Mystery Theatre -- Episode 2: Así Fue References: <8f35dab2.0307141258.3da9b9d4@posting.google.com> <6qvfu4jgh1.fsf@salmakis.intevation.de> Message-ID: In article <6qvfu4jgh1.fsf at salmakis.intevation.de>, Bernhard Herzog writes >"Raymond Hettinger" writes: > >> [Jason Trowbridge] >> > Act I >> > I didn't know that python formatting could do that! I've always >> > treated it like C's printf-style of statements, as that seems to be >> > what it's primarily based off. >> >> That's why this one was included. >> Hope everyone learned something new. > >C's printf can do this too. At least the one in the GNU libc can. It's >docs don't say anything about this being a GNU extension so I guess it >can be found in other libcs as well, though probably not in all. > > Bernhard > I know that it's in microsoft the print width description contains '''If the width specification is an asterisk (*), an int argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. A nonexistent or small field width does not cause the truncation of a field; if the result of a conversion is wider than the field width, the field expands to contain the conversion result.''' -- Robin Becker From bgailer at alum.rpi.edu Mon Jul 7 09:21:14 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 07 Jul 2003 07:21:14 -0600 Subject: anything new on the ternary operator? In-Reply-To: <%G4Oa.22187$Ey6.10119@rwcrnsc52.ops.asp.att.net> References: Message-ID: <5.2.1.1.0.20030707071708.0240c188@66.28.54.253> At 02:13 AM 7/7/2003 +0000, Russell Reagan wrote: >"Bob Gailer" wrote > > > I was looking forward to having it. > >"Sean Ross" wrote > > > - (if C: x else: y) won the vote > >I'm still learning python, so don't flame too much :-) > >What is superior about using the proposed ternary operator instead of using >the 'and' and 'or' operators to simulate inline logic? The ternary op if a: b else: y would implement if a:result = b else: result = c which is not identical to result = a and b or c Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From grobinson at transpose.com Tue Jul 29 16:05:46 2003 From: grobinson at transpose.com (Gary Robinson) Date: Tue, 29 Jul 2003 16:05:46 -0400 Subject: bisect uses __cmp__()? Message-ID: I'm wondering if bisect.insort is guaranteed to use a __cmp__ method, for now and for future python versions, if it exists, for the items being inserted? That would be good to know because then you don't have to define __lt__ etc. if all you care about is being able to use bisect.insort. If true, I suggest that it might be good to mention the bisect library docs. In any case, if there is a clear answer to my question I'd appreciate knowing what it is... --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From sross at connectmail.carleton.ca Sun Jul 6 16:18:45 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 6 Jul 2003 16:18:45 -0400 Subject: Search for mapping solution References: <3F087E85.9D8018E9@hotmail.com> Message-ID: "Alan Kennedy" wrote in message news:3F087E85.9D8018E9 at hotmail.com... > >>> lines = [['fred','333','0,10'],['sam','444','1'],['fred','333','0,50']] > >>> d = dict([(x[0], x[2]) for x in lines]) > >>> d > {'sam': '1', 'fred': '0,50'} > >>> Hi. You've left out the accumulating part of the OP's requirements: lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']] costs = {} # nearly identical to Achim's solution, but with a list comp. [costs.__setitem__(name, costs.get(name,0)+float(price)) for name, number, price in lines] print costs # outputs: {'sam': 1.0, 'fred': 0.60} From rajarshi at presidency.com Tue Jul 29 17:35:58 2003 From: rajarshi at presidency.com (Rajarshi Guha) Date: Tue, 29 Jul 2003 17:35:58 -0400 Subject: searching for matches within a word list Message-ID: Hi, I have a large list of words (each on its own line) and I would like to find words that contain a specific string. I have been trying to use a regexp but I cant see how I can find the word that contained the regex pattern - all I get is the pattern itself if I use match or findall. I know that I could just go through the list line by line and see if the regex matches or not - but that method seems horifically inefficient. Does anybody have any suggestions as to how I could solve this efficiently? Thanks, Rajarshi From guido at python.org Wed Jul 2 12:57:03 2003 From: guido at python.org (Guido van Rossum) Date: Wed, 02 Jul 2003 12:57:03 -0400 Subject: OSCON lightning talks -- submit yours now! Message-ID: <200307021657.h62Gv3J17192@pcp02138704pcs.reston01.va.comcast.net> We still have a few lightning talk slots open for the Python conference at OSCON (the O'Reilly Open Source Conference, July 7-11 in Portland, Oregon -- http://conferences.oreillynet.com/os2003/ ). A lightning talk is a presentation of no more than 5 minutes (we'll have a gong!) on any subject that you think might interest Python users or developers. The Python lightning talks session is Thursday afternoon (July 10) from 4:30 till 6 pm. To submit your proposal, send email to David Ascher with "lightning" in the subject. He'll be accepting proposals until late in the game (even in person at the conference), but slots will be assigned first-come first-serve, so don't wait too long! If you've never heard of lightning talks, you can find out more information at: http://perl.plover.com/lt/osc2003/lightning-talks.html But ignore the submission informations on that site, just send email to David as explained above. See you in Portland, Guido and David --Guido van Rossum (home page: http://www.python.org/~guido/) From mwh at python.net Tue Jul 29 07:59:47 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 29 Jul 2003 11:59:47 GMT Subject: metaclasses References: Message-ID: <7h37k61k0h2.fsf@pc150.maths.bris.ac.uk> Simon Burton writes: > It seems this is a more general way to build classes than inheritance. > Is this a reasonable viewpoint? Yes, in a sense a class statement is just syntactic sugar for what you wrote. Class statements are a bit more readable, though :-) Cheers, mwh -- As it seems to me, in Perl you have to be an expert to correctly make a nested data structure like, say, a list of hashes of instances. In Python, you have to be an idiot not to be able to do it, because you just write it down. -- Peter Norvig, comp.lang.functional From gh at ghaering.de Fri Jul 18 05:41:23 2003 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Fri, 18 Jul 2003 11:41:23 +0200 Subject: Unicode question In-Reply-To: References: <65m1yubd.fsf@python.net> Message-ID: <3F17C0C3.6040309@ghaering.de> Ricardo Bugalho wrote: > On Fri, 18 Jul 2003 02:07:13 +0200, Gerhard H?ring wrote: >>>Gerhard H?ring writes: >>>>>>>u"???" >>>>u'\x84\x94\x81' >>>> [this works, but IMO shouldn't] > > You can use string literals in any encoding like this: > 'string in my favorite encoding'.decode('my favorite encoding'). > Note that the lack of the u prefix. Not very confortable though.. > u'string' ends up doing the same as 'string'.decode('latin1'). Yep. It's the latin1 default that I'm critizizing. > It doesn't work for docstrings though.. > > I'm not sure for what you mean about encoding cookie, See PEP 263 @ http://www.python.org/peps/pep-0263.html > but I like the idea > of each source file having some element that defines the encoding used to > process string literals. Then you'll like that exactly this is implemented in Python 2.3: #!/usr/bin/python # -*- coding: latin1 -*- ... > Either that or we define the Python code must be written in UTF-8. You can do that in Python 2.3 as well. Just save your source file with a UTF-8 BOM and you don't even have to explicitly define an encoding using an encoding cookie. > But that would break lots of code.. :D You'll get warnings if you don't define an encoding (either encoding cookie or BOM) and use 8-Bit characters in your source files. These warnings will becomome errors in later Python versions. It's all in the PEP :) -- Gerhard From scpusenet at werbung.schabi.de Tue Jul 8 03:30:08 2003 From: scpusenet at werbung.schabi.de (Markus Schaber) Date: Tue, 8 Jul 2003 09:30:08 +0200 Subject: Apache mod_python and Sessions References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> <20030707091923.1f12f872.scpusenet@werbung.schabi.de> <3f09b2cf$0$49098$e4fe514c@news.xs4all.nl> Message-ID: <20030708093008.651035f7.scpusenet@werbung.schabi.de> Hello, On Mon, 07 Jul 2003 19:50:11 +0200 Irmen de Jong wrote: > Markus Schaber wrote: > > python_weblib that does what I need (Additionally, my boss suggested > > that we should not use mod_python but CGI instead.) > > What!? Why!? > Any sane explanation why you should go with slow, outdated CGI scripts > instead of the nice, fast web server integration of mod_python? The script will have a very low usage (maybe about ten sessions a month). And it spends lots of time doing ldap database queries, so the starting overhead doesn't hurt so much. Additionally, the webserver currently doesn't have mod_python installed, and there is the fear that every additional module has disadvantages (bigger startup/fork time, potential bugs, memory footprint). I hope that these two argumens are "sane" in your world, at least they are sane enough for my boss. Greets, Markus From michaeljmoore at comcast.net Mon Jul 21 00:23:28 2003 From: michaeljmoore at comcast.net (Michael J. Moore) Date: Mon, 21 Jul 2003 04:23:28 GMT Subject: ODBC to Oracle (data source name not found) Message-ID: <4VJSa.97003$GL4.26848@rwcrnsc53> I have set up an ODBC connection to an oracle database named MIKE on my local machine. I have tested this ODBC connection using EXCEL and it works fine. The same data source results in ... ----------------- Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import dbi >>> import odbc >>> d=odbc.odbc('mike/mike/guess') Traceback (most recent call last): File "", line 1, in ? dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in LOGIN >>> What am I not doing correctly? TIA Mike From danbmil99 at yahoo.com Thu Jul 24 22:15:35 2003 From: danbmil99 at yahoo.com (dan) Date: 24 Jul 2003 19:15:35 -0700 Subject: python assignment References: Message-ID: "Tim Peters" wrote in message news:... > [Tim] ... > Bjorn added more appropriate words -- it would be bad design for the > __iadd__ method of a mutable type to return a pre-existing object other than > self. > > >>> a = [1, 2] > >>> b = [1] > >>> b += [2] > > While "a == b" must be true at this point, it would be a nightmare if "a is > b" could be true at this point. For immutable types it doesn't matter: > > >>> a = (1, 2) > >>> b = (1,) > >>> b += (2,) > > It so happens that "a is b" is not true at this point under any Python > released so far, but it could be true someday without causing harm. > > Sorry for the confusion! Ok, that makes sense to me. I still think it would be a good idea to put a section in the Tutorial -- perhaps under "for computer scientists and those who want to learn more" -- describing how Python binds names to objects. In particular, the fact that a list is a list of pointers, not the objects themselves, seems like an important point to make, even for relative newcomers. Here's the thing that tripped me up, and the solution I came up with, which I am now unsure of: #original code -- v[] is a list for x in range(n): temp = [x+y for y in range(3)] #or whatever v[x] = temp so I was quite surprised to find all members of v[] were in fact pointers to one object, temp[]. My solution, which I'm worried about, was this: for x in range(n): temp = [x+y for y in range(3)] #or whatever v[x] = temp + [] #'assignment by copy'??? So I'm still unclear as to whether an expression like temp+[] is defined as returning a new list or not. Seems like it might be undefined, since either way is arguably 'correct'. From trentm at ActiveState.com Tue Jul 22 17:46:33 2003 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 22 Jul 2003 14:46:33 -0700 Subject: python22_d.lib? In-Reply-To: ; from tim.one@comcast.net on Tue, Jul 22, 2003 at 02:21:53PM -0400 References: Message-ID: <20030722144632.D3074@ActiveState.com> [Tim Peters wrote] > > I have 2.2.3, but nowhere is there such a library. Must I get the source > > and build it myself? > > Yes. Or ActiveState may still have one available for download. Yes, but note that the current "debug libs" package is for Python 2.2.2 rather than Python 2.2.3: http://ftp.activestate.com/ActivePython/etc/ActivePython-2.2.2-224-win32-ix86.debug.zip Cheers, Trent -- Trent Mick TrentM at ActiveState.com From paul_rudin at scientia.com Tue Jul 22 11:33:51 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 22 Jul 2003 16:33:51 +0100 Subject: How to save web pages for offline reading? References: Message-ID: >>>>> "Will" == Will Stuyvesant writes: > There is no "man wget" on Windows :-) And unfortunately the GNU > Windows port of wget I have (version 1-5-3-1) does not have that > --page-requisites parameter. You need cygwin . That way you get "man wget" and a wget that has a --page-requisites option on your windows box. From BartolomeSintes at ono.com Thu Jul 10 12:28:32 2003 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Thu, 10 Jul 2003 16:28:32 GMT Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> Message-ID: I have a program that unzip some zip files. After unzipping them, I want to delete the zip files with os.remove, but I get this error: OSError: [Errno 13] Permission denied: .... What can I do? Thanks, From mis6 at pitt.edu Wed Jul 30 08:19:07 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 30 Jul 2003 05:19:07 -0700 Subject: while (assignment): References: <840592e1.0307291501.42b1156e@posting.google.com> Message-ID: <2259b0e2.0307300419.124c040b@posting.google.com> Sybren Stuvel wrote in message news:... > Hannu Kankaanp?? enlightened us with: > > Typically this is done by breaking out of the loop: > > > > while True: > > info = mydbcursor.fetchone() > > if not info: > > break > > print "Information: "+str(info) > > This was my first solution as well. Kinda ugly, though. > > Sybren When I started using Python I though the "while 1" idiom was horrible. Now I think it is quite Pythonic. Few months can change your mind! ;) You may also use this form, which you may find more readable: while 'info': info = mydbcursor.fetchone() if not info: break print "Information: "+str(info) Remember, 'info' is another spelling of True! This is a trick anyway, and I always use "while 1" in my code, it is the idiomatic way at the end. Michele From jepler at unpythonic.net Sun Jul 27 22:26:22 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 27 Jul 2003 21:26:22 -0500 Subject: file.close() In-Reply-To: <3F2460C7.44B8B046@alcyone.com> References: <2inav-q64.ln1@beastie.ix.netcom.com> <3F2460C7.44B8B046@alcyone.com> Message-ID: <20030728022622.GB7068@unpythonic.net> On Sun, Jul 27, 2003 at 04:31:19PM -0700, Erik Max Francis wrote: > You haven't > demonstrated a case where there actually is an I/O error that occurs > when .close gets called. What makes you believe that a Python file object's "close" can never error? "close" corresponds to the fclose() function of the C standard library, and the manpages have plenty to say on the subject (see below). I just created a small filesystem (1000 1k blocks, over half of which was used by filesystem overhead) and got Python to do this: >>> f = open("/mnt/tmp/x", "w") >>> f.write("x" * (453*1024+511)) >>> f.close() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 28] No space left on device Curiously enough, this doesn't even print the 'Exception in __del__ ignored' message: >>> f = open("/mnt/tmp/x", "w") >>> f.write("x" * (453*1024+511)) >>> del f even though the failed stdio fclose must still have been called. stdio buffering kept the last few bytes of the f.write() from actually being sent to the disk, but the f.close() call must dump them to the disk, at which time the "disk full" condition is actually seen. While I had to contrive this situation for this message, it's exactly the kind of thing that will to happen to you when your software is at the customer's site and you've left for a month in rural Honduras where there aren't any easily-accessible phones, let alone easy internet access. Jeff [from `man fclose'] RETURN VALUE Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case any further access (including another call to fclose()) to the stream results in undefined behaviour. [...] The fclose function may also fail and set errno for any of the errors specified for the routines close(2), write(2) or fflush(3). [from `man close'] ERRORS EBADF fd isn?t a valid open file descriptor. EINTR The close() call was interrupted by a signal. EIO An I/O error occurred. [from `man write'] ERRORS EBADF fd is not a valid file descriptor or is not open for writing. EINVAL fd is attached to an object which is unsuitable for writing. EFAULT buf is outside your accessible address space. EFBIG An attempt was made to write a file that exceeds the implementa- tion-defined maximum file size or the process? file size limit, or to write at a position past than the maximum allowed offset. EPIPE fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIG- PIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.) EAGAIN Non-blocking I/O has been selected using O_NONBLOCK and the write would block. EINTR The call was interrupted by a signal before any data was writ- ten. ENOSPC The device containing the file referred to by fd has no room for the data. EIO A low-level I/O error occurred while modifying the inode. Other errors may occur, depending on the object connected to fd. [from `man fflush'] ERRORS EBADF Stream is not an open stream, or is not open for writing. The function fflush may also fail and set errno for any of the errors specified for the routine write(2). From donn at drizzle.com Thu Jul 10 01:26:14 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 10 Jul 2003 05:26:14 -0000 Subject: Embedding Python, threading and scalability References: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> Message-ID: <1057814773.188737@yasure> Quoth Jeff Epler : | On Thu, Jul 10, 2003 at 11:14:47AM +0800, Simon Wittber (Maptek) wrote: |> Seriously though, this is an issue, which is a major hurdle Python *has* |> to cross if it is ever going to be seriously considered for use on large |> projects, on large SMP hardware. | | Has anybody proposed "how to get there from here" for this problem | (useful multithreading of non-blocking pure Python code)? I'm not | bright enough to see how, that's for sure. Especially if you are | talking about an incremental approach, not the mythical "Python 3000". | What I mean is that you have to work this magic *and* somehow let | existing modules written in C work, with at worst a recompile. (as | someone who doesn't *need* threads, but works on a project with piles of | Python modules written in C, that's my bias anyway) Ha - I knew I'd find an answer for this if I searched for "free threading" - and among other hits, I found this very thread! So in Andrew Dalke's words: > Ahh, the Global Interpreter Lock (GIL). > > Years ago, Greg Stein had a version of Python 1.4 running with no GIL. > > http://www.python.org/ftp/python/contrib-09-Dec-1999/System/threading.README > > Search for "free threading" to get more hits on this topic. At any rate, it sure isn't because Guido can't scare up an SMP machine. | I've written Python programs that use threads in a way that was expedient | to get a user interface running without long seizures, while I've never | written a thread in tcl or perl. OTOH if I'd had to treat everything | as explicit message passing (a la tcl threading), I'd have just found | another way (like "after idle" and "update" in tcl) Hm, not sure what you're alluding to here. I actually kind of like an I/O thread dispatch model myself, but I don't think Python cares either way nor would it if the GIL were abolished. | Jython will give you Java's thread model today, for Python code, won't | it? Back when I benchmarked it, Jython code and Python code ran at | fairly similar speeds (in pybench), if only you had a machine that could | keep the Jython interpreter from swapping... Don't know, but I noticed in another thread among the hits that Ype Kingma asserts that Jython does indeed support fine grained multithreading. Donn Cave, donn at drizzle.com From shane at zope.com Mon Jul 28 11:57:40 2003 From: shane at zope.com (Shane Hathaway) Date: Mon, 28 Jul 2003 11:57:40 -0400 Subject: Debugging Python ? In-Reply-To: <16165.13944.763754.224629@montanaro.dyndns.org> References: <008a01c354ad$5a52d840$6400a8c0@EVOD31> <16165.13944.763754.224629@montanaro.dyndns.org> Message-ID: <3F2547F4.4020601@zope.com> Skip Montanaro wrote: > Bill> I'd be happy to hear your techniques to debug python programs. > > Crude though it may seem, I find print statements quite effective. Works in > all environments as well. ;-) As a bonus, I find that print statements do not rightfully belong in most of the software I write. Therefore I can happily add print statements anywhere for debugging purposes, knowing that removing them later is perfectly safe. Shane From dan at osheim.org Mon Jul 14 22:37:00 2003 From: dan at osheim.org (Dan Williams) Date: Mon, 14 Jul 2003 21:37:00 -0500 Subject: itertools.take? Message-ID: Is there any interest in adding a "Haskellish" take function to itertools? I know its easy enough to roll my own, I've been using: take = lambda iter, n: [x for x in itertools.islice(iter, 0, n)] which works, but I was wondering if it was common enough to get into itertools? -Dan From nospam at here.com Fri Jul 4 13:21:39 2003 From: nospam at here.com (Richard Townsend) Date: Fri, 4 Jul 2003 18:21:39 +0100 Subject: bug in Tkinter? invalid literal for int() line 1035 References: Message-ID: <1057339224.48048.0@damia.uk.clara.net> "Fredrik Lundh" wrote in message news:mailman.1057326192.22017.python-list at python.org... > Ton K. wrote: > > > I get subject when binding to a listbox. > > The value for h is '??' which triggers the error. > > I'm running Python 2.2.2 from SuSE. > > you're using a version of Tk that's newer than your Tkinter; that "??" > you're seeing how really recent versions of Tk represent an "undefined > integer value"... > > this has been fixed in Python 2.3, so you can either upgrade Python > or link against an older Tk. > > (or modify Tkinter.py slightly, adding try/except clauses around the > problem spots in Tkinter.py) > > > > If you are running SuSE 8.2 there is a fix on http://www.suse.de/en/private/download/updates/82_i386.html for this problem. Look for the python-tk 2.2.2 link, dated 18 April 2003. RT From exarkun at twistedmatrix.com Tue Jul 8 06:17:44 2003 From: exarkun at twistedmatrix.com (Jp Calderone) Date: Tue, 8 Jul 2003 06:17:44 -0400 Subject: Python vs PHP In-Reply-To: References: Message-ID: <20030708101736.GA3899@intarweb.us> On Tue, Jul 08, 2003 at 11:14:10AM +0200, Jaroslaw Zabiello wrote: > On Mon, 07 Jul 2003 13:47:00 +0300, Catalin > wrote: > > >Can Python replace PHP? > > Sure. Look at http://spyce.sourceforge.net > Lest the OP think Spyce is the only or even the preferred solution for web programming with Python: http://cherrypy.org/ http://www.twistedmatrix.com/ http://skunkweb.sf.net http://webware.sf.net http://zope.org http://www.mems-exchange.org/software/quixote/ http://www.object-craft.com.au/projects/albatross http://jonpy.sf.net http://jotweb.tummy.com/ And let's not forget plain old CGI and mod_python. Jp -- "There is no reason for any individual to have a computer in their home." -- Ken Olson, President of DEC, World Future Society Convention, 1977 From domma at procoders.net Thu Jul 31 05:24:39 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 31 Jul 2003 11:24:39 +0200 Subject: Python speed vs csharp References: Message-ID: "Martin v. L?wis" wrote in message news:m3smonmcop.fsf at mira.informatik.hu-berlin.de... > Mike writes: > I recommend that you try out Python 2.3. It has significantly improved > memory allocation mechanisms, so you should see some speed-up. > > You could also try Psyco, which is a just-in-time compiler for > Python. It should give very good results in this case, also. Another option would be to implement the critical function in C++ and make it available to python. This could be done for example via boost.python. See this link for details: http://www.boost.org/libs/python/doc/tutorial/index.html It's much easier than you would expect. Achim From fperez528 at yahoo.com Wed Jul 9 13:39:14 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 09 Jul 2003 11:39:14 -0600 Subject: Image Streaming References: <381a2b17.0307072326.211c21b5@posting.google.com> Message-ID: JanC wrote: > Fernando Perez schreef: > >> or even gif (the patents expired recently). > > Only in the US, not in (some countries in) Europe & Japan. Ah, you're right. But I think they also expire soon, don't they? Well, anyway, png is better :) Best, f. From nicola-mingotti_NO_spam at libero.it Wed Jul 30 03:50:42 2003 From: nicola-mingotti_NO_spam at libero.it (Nicola Mingotti) Date: Wed, 30 Jul 2003 09:50:42 +0200 Subject: Thank you developers for 2.3 References: Message-ID: On Wed, 30 Jul 2003 08:21:09 +0200, Tino Lange wrote: > On Wed, 30 Jul 2003 05:35:02 GMT, David Lees > wrote: > >> .... >>2.3 5.04 sec >>version 2.2.3 9.77 sec > ... > By the way: What was/is the speed with 2.1.x on the same system? > On 2.1.3 speedTest doesn't work . It gives OverflowError: integer addition . It 's because in that version integer aren't converted into Long Int when necessary . ... t1 = time.time() k = 0L ... for j in xrange(n): for i in xrange(n): k += i + j t1 = time.time() return t1 - t0 From mis6 at pitt.edu Sat Jul 19 10:40:52 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 19 Jul 2003 07:40:52 -0700 Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: <2259b0e2.0307190640.56266017@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > Not sure exactly what you are doing, but what does > > object.__setattr__(client, self.name, value) > > do in your context in place of > > client.__dict__[ self.name ] = value > > ? > > Regards, > Bengt Richter I agree with Bengt, from your traceback it seems you are assigning directly to client.__dict__, but you cannot do that (I think because client.__dict__ is a dictproxy object and not a real dictionary). The right way to go is via object.__setattr__ , or type.__setattr__ in the case of metaclasses. I guess you are aware of the metaclass+properties recipes in the on-line cookbook, but just in case ... HTH, Michele From op73418 at mail.telepac.pt Mon Jul 28 07:18:33 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 28 Jul 2003 12:18:33 +0100 Subject: List Question References: Message-ID: On Mon, 28 Jul 2003 00:23:46 +0200, "Bill Loren" wrote: >Hello, > >Forgive my python newbieness. >Assume I have a list named heck_of_a_list. >how would I extract the number of elements out of it ? >(I'm looking for something like perl's $#heck_of_a_list operand) > >thanks >B Firing the interpreter: >>> heck_of_a_list = [] >>> len(heck_of_a_list) 0 >>> Maybe you would like to peruse the tutorial that comes with Python. It's a very nice intro and it may answer some (a lot?) of your newbie questions. With my best regards, G. Rodrigues From gumuz at looze.net Thu Jul 17 04:57:04 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 17 Jul 2003 10:57:04 +0200 Subject: IMAP examples References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: <3f166418$0$13804$4d4ebb8e@news.nl.uu.net> wow, that's cool, not sure if it is what I was looking, but this book seems pretty invaluable already :) thanx "Van Gale" wrote in message news:UWsRa.82$O94.42 at newssvr24.news.prodigy.com... > Will Stuyvesant wrote: > >>[Guyon Mor?e] > >>I can't seem to find any decent examples on how to use the IMPALIB module. > >>the docs aren't that sophisticated unfortunately.... the cookbook entry > >>comes close, but i'd like to know if someone knows some nice examples > >>somewhere. > > > > > > I did not use it myself but there is an example in the book "Python > > Standard Library" by Fredrik Lundh. The example file is called > > imaplib-example-1.py, maybe you can find it somewhere on the internet. > > Fredrik has graciously made the book available online. > > See: http://effbot.org/zone/librarybook-index.htm > From thomas.buschhardt at iac-leipzig.de Tue Jul 15 04:48:27 2003 From: thomas.buschhardt at iac-leipzig.de (Thomas Buschhardt) Date: Tue, 15 Jul 2003 10:48:27 +0200 Subject: Need help: Compiling Python-Code Message-ID: <004801c34aad$dbb5aca0$9108000a@iacleipzig.de> import py_compile pycompile.compile(Python-file) Bye Thomas From danb_83 at yahoo.com Sat Jul 5 18:51:20 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jul 2003 15:51:20 -0700 Subject: Calculating Year, Month and Day of Life References: Message-ID: hokiegal99 wrote in message news:... > Hello, > > I am a funeral director trying to write a small program that calculates > the number of years, months and days a person has lived by entering the > year, month and day of their birth. This is what I have so far: How do you calculate the years, months, and days? For your example (born: 1934-02-07, died: 2003-07-05), I can think of at least 3 plausible results. Method 1 (counting forward): * This person was 69 years old on their last birthday. * 4 months after their last birthday, it was June 7. * There were 23 days left in June, * and 5 days in July until the date of death. * So this person lived for 69 years, 4 months, and 28 days. Method 2 (counting backward): * 69 years before death was 1934-07-05. * 4 months earlier was March 5. * 5 days earlier was February 28, * when the person was 21 days old. * This person lived for 69 years, 4 months, and 26 days. Method 3 (day counts): * date of birth = R.D. 706051 * date of death = R.D. 731401 * This person lived for 25350 days. * There are an average of 30.436875 days in a month. * So 25350 days = 832 months + 26.52 days * 832 months = 69 years + 4 months * 26.52 days rounds to 27 * This person lived for 69 years, 4 months, and 27 days. From maxm at mxm.dk Tue Jul 1 04:03:11 2003 From: maxm at mxm.dk (Max M) Date: Tue, 01 Jul 2003 10:03:11 +0200 Subject: Howto: extract a 'column' from a list of lists into a new list? In-Reply-To: References: Message-ID: <3f013fb1$0$97259$edfadb0f@dread12.news.tele.dk> Greg Brunet wrote: > but I'm not sure about how to do that. I can do this: > >>>>for g in tbl.Fields(): print g[0] > > ... > STOCKNO > DACC > DEALERACCE > D-ACCRTL > D-ACCCST > > but I expect that one of those fancy map/lamda/list comprehension > functions can turn this into a list for me, but, to be honest, they > still make my head spin trying to figure them out. Any ideas on how to > do this simply? fields = [ ('STOCKNO', 'C', 8, 0), ('DACC', 'C', 5, 0), ('DEALERACCE', 'C', 30, 0), ('D-ACCRTL', 'C', 9, 0), ('D-ACCCST', 'C', 9, 0) ] # The "old" way to do it would be: NAME_COLUMN = 0 results = [] for field in fields: results.append(field[NAME_COLUMN]) print results # But list comprehensions are made for exactly this purpose NAME_COLUMN = 0 results = [field[NAME_COLUMN] for field in fields] print results regards Max M From martin at v.loewis.de Wed Jul 30 03:42:23 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2003 09:42:23 +0200 Subject: -shared option in distutils References: Message-ID: Dave Harrison writes: > Where can I find it ? It is extracted from the installed Makefile. In theory, if you build Python with the Sun compiler, it should automatically decide to use -G, and so should then distutils use -G as well, without manual intervention. Regards, Martin From alanmk at hotmail.com Tue Jul 22 15:01:31 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 22 Jul 2003 20:01:31 +0100 Subject: SAX questions... References: Message-ID: <3F1D8A0B.4AA19491@hotmail.com> Timothy Grant wrote: > I've worked with DOM before, but never SAX, I have a script that > seems to work quite well, but every time I look at it I think it's > amazingly unweildly and that I must be doing something wrong. > > def startElement(self, name, attr): > if name == "foo": > do_foo_stuff() > elif name == "bar": > do_bar_stuff() > elif name == "baz": > do_baz_stuff() > > There's similar code in endElement() and characters() and of course, > the more tags that need processing the more unweildly each method > becomes. > > I could create a dictionary and dispatch to the correct method based on a > dictionary key. But it seems to me there must be a better way. Tim, No, you're not doing anything wrong in your above code. But, yes, code like that can get pretty unwieldy when you've got deeply nested structures. A couple of suggested alternative approaches: 1. As you already suggested, build up a dictionary mapping tag names to functions. But that still means that you have to maintain state information between your function calls. 2. Represent each new element that comes in as a python object (object()), i.e. construct a "Python Object Model" or POM. All xml attributes on the element become python attributes of the python object. That object then goes onto a simple stack. Each object() also has a list of children. When a new xml child element is passed, through a nested startElement call, it too gets turned into a python object, and made a child of the python object on the top of the stack. Pop objects off the stack as you receive endElement events. This paradigm is described here, with working code http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 3. Have a specialised python class for each element type (i.e. tag name), that implements the "business logic" you want associated with the element type. Write descriptors or properties for each specialised class that, for example, only allow child python objects of a certain type. Create a dictionary mapping tag names to your classes, and instantiate a new python object of that class everytime you receive the relevant tag name through a startElement call. Put it onto a stack, as above, store nested xml elements as children of the top-of-stack, and pop the stack when you receive endElement calls. That's just a couple of approaches. There might be other, perhaps more appropriate, methods, if you could describe what you're trying to achieve. Are you extracting data from the documents? Or are you checking that the documents comply with some form of hierarchical structure? Or something else entirely? HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From maxm at mxm.dk Sat Jul 12 06:22:41 2003 From: maxm at mxm.dk (Max M) Date: Sat, 12 Jul 2003 12:22:41 +0200 Subject: Help Support Python In-Reply-To: References: Message-ID: <3F0FE171.1090102@mxm.dk> Guido van Rossum wrote: > I'm pleased to announce that the Python Software Foundation (PSF) is now > accepting donations from individuals and companies interested in > supporting our mission to improve the Python programming language. It would be nice if there was some suggested amounts. Like: $x.xx for a "one year Student Python subscription" $xx.xx for a "one year private Python subscription" $xxx.xx for a "one year company Python subscription" Etc. That could make it easier to decide what amount to donate. To me at least. Anyhoo, I plunked in some $ and hope others will too. It's a great language that has made my workday a lot more fun. regards Max M From ebolonev at rol.ru Tue Jul 8 06:52:45 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Tue, 8 Jul 2003 21:52:45 +1100 Subject: start script automatically References: Message-ID: Hello, Tom! You wrote on Tue, 08 Jul 2003 11:17:37 +0200: T> Hi, T> I have a problem because I don't know how to start my script T> automatically after a special event happens. T> In detail: I store data from a PLC. Every 30 seconds the data is stored T> in a new file. After the file is stored I would like to start my script T> that analyzes the data right away. Any help how to do this is deeply T> appreciated. T> Thank you very much in advance. T> Regards, Tom Your script have to work like a demon or the 'storer' have to run your script. With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From rtomes at ihug.co.nz Tue Jul 1 18:17:17 2003 From: rtomes at ihug.co.nz (Ray Tomes) Date: Wed, 02 Jul 2003 10:17:17 +1200 Subject: whitespace and ?asc()? Message-ID: <3F02086D.9010300@ihug.co.nz> Hi all I am totally new to python. On the whole I really like the design of the language and after just one day may be considered a convert. I was trying to find out the exact definition of whitespace so I went to look at strings.whitespace to find out which chars were whitespace, and found 9, 10, 11, 12, 13, 32 which according to my ancient ascii chart are TAB, LF, VT, NP, CR, SPACE. Anyone know what NP = 12 is? Also, in trying to find the ASCII (or is it ANSI) values for characters I could not find the reverse function for chr() [in BASIC it is asc()]- can someone please tell me what reverses chr()? I had to do this yucky thing to decode whitespace ... import string x=string.whitespace for b in x: for i in range(256): if chr(i) == b: print i Ray Tomes From stuart at bmsi.com Wed Jul 16 22:35:38 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Wed, 16 Jul 2003 22:35:38 -0400 Subject: Installing milter-0.5.4 (Python) on Mandrake 9.x with updates. References: <2a897f11.0307161631.7f41db19@posting.google.com> Message-ID: On Wed, 16 Jul 2003 20:31:59 -0400, Wayne Pierce wrote: > python setup.py build > > I get the following error (last 4 lines of output): ... > distutils.errors.DistutilsPlatformError: invalid Python installation: > unable to open /usr/lib/python2.2/config/Makefile (No such file or > directory) You need to install the python-devel RPM (or python2-devel). -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From shalehperry at comcast.net Wed Jul 30 21:20:51 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Wed, 30 Jul 2003 18:20:51 -0700 Subject: Misuse of In-Reply-To: <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> References: <3f27f0e3$1@news.broadpark.no> <3f28287e$0$103$8f4e7992@newsreader.goldengate.net> Message-ID: <200307301820.51591.shalehperry@comcast.net> On Wednesday 30 July 2003 13:20, Michael Sampson wrote: > How does the IDLE that comes with the latest release of python handle this? > When it automaticly indents does it do it with spaces or tabs? If you hit > tab in the IDLE will it just put 5 spaces in for you? > thou shalt always use even numbered indents. Or to paraphrase Monty Python: Thou shalt count to 4, 4 being the sacred number. Thou shalt not count 3 and 5 is right out. From tjland at iserv.net Sat Jul 26 18:08:39 2003 From: tjland at iserv.net (tjland at iserv.net) Date: Sat, 26 Jul 2003 18:08:39 -0400 (EDT) Subject: Beginners help with password program! Message-ID: <1214.68.73.64.62.1059257319.squirrel@webmail.iserv.net> This is my first version of this program, im kinda new to python and i was wondering if someone could help me with this. Their are some errors that i just cant find, and i want some advice on how to do some of these things easier. Thanx for the help! ---------------------------------------------------------------------------- from time import sleep def Sendfile(password, username): outfile = file(username, "w") outfile.write(password) outfile.close() print "Your are now registered" def Getfile(username): infile = file(username, "r") content = infile.readline(1) global content infile.close() login = input("Are u registered? ") if login == no: new_username = input("What do you want for a username, please letters only: ") new_password = input("What do you wish for a password: ") Sendfile(new_password, new_username) else: print "Please Login, Enter username, then wait for prompt!" username = input("Username: ") sleep(5) password = input("Password: ") Getfile(username) if password != content: print """Im sorry but you are not a registered user, If you would like to become a user contact the server admin for user privelges""" else: print "Welcome" ---------------------------------------------------------------------------- When you see the net take the shot When you miss your shot shoot again When you make your shot you win! Just remember Offense sells tickets But defense wins championships! From woooee at yahoo.com Wed Jul 2 22:27:16 2003 From: woooee at yahoo.com (Curly Joe) Date: Wed, 2 Jul 2003 19:27:16 -0700 (PDT) Subject: Clever One Liners Message-ID: <20030703022716.62264.qmail@web20514.mail.yahoo.com> I agree with you, especially since the compiler, in most cases, must break everything down into single steps anyway. Take for instance a very simple example: x = a + b/c The compiler would execute this as: x = b/c x += a While most people would no do this, we do have a problem with "line bloat" software. It would likely take someone who is debugging the program for the first time longer to figure out one of these twisted contortions than it took the original programmer to create it in the first place (and perhaps that's the point). If someone asks how to do something on one line or in the shortest amount of space, that's another situation, but for many of the questions it is obvious that the person is new to Python and sometimes to programming, which means their response would be "Huh? I don't have a clue as to what that means." Michael Chermside wrote: I'm not picking on you in particular, there have been several people doing this lately, but I'd like to ask folks to please lay off the quest for one-liners. __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From ta-meyer at ihug.co.nz Tue Jul 15 19:40:14 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 16 Jul 2003 11:40:14 +1200 Subject: FCNTL module deprecation warning In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130256632B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1318CF26@its-xchg4.massey.ac.nz> [Tony Meyer] > My question is then why the 2.3b2 Windows binary bothers installing > the FCNTL.py file. [Tim Peters] > Because it would be enormously more bother to special-case > it. If I could get the behaviour that you get, I wouldn't care if it installed it... [Tony Meyer] > Shouldn't the correct behaviour be to raise an ImportError if a > windows user tries to import fcntl or FCNTL? [Tim Peters] > It does for me: > > >>> import fcntl > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named fcntl > >>> import FCNTL > C:\CODE\PYTHON\lib\FCNTL.py:7: DeprecationWarning: the FCNTL > module is deprecated; please use fcntl > DeprecationWarning) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\CODE\PYTHON\lib\FCNTL.py", line 11, in ? > from fcntl import * > ImportError: No module named fcntl > >>> > > I get that under Python 2.2.3 and 2.3b2. Strange. I get the warning on 2.2.3 and 2.3b2, except in 2.3b2 IDLE, which successfully imports fcntl (odd). (long cut'n'pastes below). Do you have the PYTHONCASEOK envar set? (This doesn't seem to make any difference to me, but from the explanation I didn't think it would). I presume this means something is screwy with my Python setup? (or yours, but mine seems the more likely :). Any suggestions about what I might be able to change to get the import error that you do? =Tony Meyer Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import fcntl c:\progra~1\python22\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> import FCNTL c:\progra~1\python22\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import fcntl >>> import FCNTL c:\progra~1\python23\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl c:\progra~1\python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is dep recated; please use fcntl DeprecationWarning) >>> import FCNTL c:\progra~1\python23\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is dep recated; please use fcntl DeprecationWarning) >>> Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl c:\progra~1\python22\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is dep recated; please use fcntl DeprecationWarning) >>> import FCNTL c:\progra~1\python22\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is dep recated; please use fcntl DeprecationWarning) >>> PythonWin 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import fcntl C:\Program Files\Python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> import FCNTL C:\Program Files\Python23\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> PythonWin 2.2.3 (#42, May 30 2003, 18:12:08) [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 fcntl C:\Program Files\Python22\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> import FCNTL C:\Program Files\Python22\lib\FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> From marcstober at yahoo.com Wed Jul 2 12:11:09 2003 From: marcstober at yahoo.com (Marc) Date: 2 Jul 2003 09:11:09 -0700 Subject: Encoding questions Message-ID: Hi, Is there any way to see what encodings are installed on my computer, or a reference of the encodings distributed with Python and what each of them is for? I've looked at the reference for the codec module and imagine there's a folder full of Codec classes somewhere; is this how it works? The specific problem I have is a Unicode file that contains a bullet character (Unicode BULLET, 2022). Ultimately, it's going to be written into a PDF file (via ReportLab). The default ASCII encoding doesn't work, which is OK; suprisingly neither does 'latin-1', yet 'cp1252' does work. These are just encodings I've seen somewhere. Basically, I'd like to know how to go about choosing the best/most appropriate encoding for a given application. Thanks, Marc Stober From lists at gregfortune.com Tue Jul 22 16:26:55 2003 From: lists at gregfortune.com (Greg Fortune) Date: Tue, 22 Jul 2003 13:26:55 -0700 Subject: Installing lots of packages References: Message-ID: ack, sorry about that. Knode lied to me when it said the message didn't go through ;o) Greg Greg Fortune wrote: > I've got a whole bunch of package dependencies in the programs I develop. > Mainly, they are generic libraries/utilities I've written that are needed > by most of the programs I write. The biggest problem I've had with > python's packaging system is that I end up needing to install every > library > package on each machine I install my programs on. It's even worse when I > go through an upgrade... > > Is there any way to create something like a "meta-package"? ie, can > bundle > a whole bunch of packages together under a single installer? I'm working > on both Windows and Mac so the tools need to support both platforms. Does > anything exist for this purpose? > > Thanks, > > Greg Fortune > Fortune Solutions From ben at dadsetan.com Sun Jul 6 18:31:58 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Mon, 07 Jul 2003 00:31:58 +0200 Subject: Using Loops to track user input In-Reply-To: <3F089D60.4030203@dadsetan.com> References: <3F089D60.4030203@dadsetan.com> Message-ID: Behrang Dadsetan wrote: > hokiegal99 wrote: > >> I don't understand how to use a loop to keep track of user input. >> Could someone show me how to do what the program below does with a loop? >> > > # If you are want to loop a fixed amount of time, as I understand a way > # would be: > sum = 0 > for i in xrange(10): > sum += input("Enter a number: ") > average = sum/10 > print average > Ok, I just looked up the Reference documentation and int(raw_input("prompt text")) would be probably better than my suggested input() - like in the other anwsers you received. One should maybe note that if the end average calculated should be a float, then you need to use sum = 0.0 and should the user entering the data be allowed to use float values you will probably want to use float(raw_input("prompt text")) Regards, Ben. From cybersamurai at mac.com Thu Jul 17 11:24:57 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Thu, 17 Jul 2003 12:24:57 -0300 Subject: what u'=' mean??? Message-ID: <200307171224.57003.cybersamurai@mac.com> What ---- u'=' ---- mean?? Ex: args = [u'='.join(k,safe_eval(v) for k, v in attrs.items()] From mwh at python.net Tue Jul 15 11:52:11 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 15 Jul 2003 15:52:11 GMT Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: <7h3n0ffn69m.fsf@pc150.maths.bris.ac.uk> Francois Pinard writes: > [John J. Lee] > > > Alan Kennedy writes: > > > > I'd love to hear of other similar phrases. And somehow I intuit > > > there's people in this ng who know lots of them :-) > > > There are so many... > > Automated translators which ignore punctuation are pretty fragile, too. Oh, if we're allowed to play punctuation games, I like: I travelled on[,] my face towards home. Cheers, mwh -- Like most people, I don't always agree with the BDFL (especially when he wants to change things I've just written about in very large books), ... -- Mark Lutz, http://python.oreilly.com/news/python_0501.html From edavid at intnet.mu Wed Jul 23 11:14:53 2003 From: edavid at intnet.mu (David Hitillambeau) Date: Wed, 23 Jul 2003 19:14:53 +0400 Subject: The global statement References: Message-ID: On Wed, 23 Jul 2003 16:56:08 +0200, Thomas G?ttler wrote: > If foo and bar are in the same file, > you don't need the "global". Then when is "global" required? What is it's role? Thanks for your reply. -- David.H From jim_938 at hotmail.com Fri Jul 4 13:41:56 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Fri, 04 Jul 2003 23:11:56 +0530 Subject: strings problem Message-ID: Hello *.* Can you please tell me how can i have the output in no's, instead of string from this program: #/usr/bin/python import re import string def csNumEncode(num): if(num>=-107 and num<=107): return chr(num+139) elif(num>=108 and num<=1131): return chr(((num-108)/256)+247) + chr((num-108)%256) else: print 'do nothing' re_num = re.compile("\-?[0-9]+(\.[0-9]+)?") def CompileCS(source): result='' for tkn in re.split('[ \n\t]+', source): print "Token: %s"%tkn if re_num.match(tkn): result = result + csNumEncode(string.atoi(tkn)) else: raise SyntaxError, "%s is invalid operator"%tkn return result src1 = '50 800' t = CompileCS(src1) print t The output is Token: 50 Token: 800 \275\371\264 Instead of this i want the output should be in no's like this: bdF9B4 Your suggestions will be welcomed. Thanks a lot. Regards, Jim _________________________________________________________________ Looking for love? Yearning for friendship? http://www.msn.co.in/Romance/ You're in the right place. From adeutsch at kaval.com Mon Jul 28 17:01:55 2003 From: adeutsch at kaval.com (Adam Deutsch) Date: Mon, 28 Jul 2003 17:01:55 -0400 Subject: memory leak troubleshooting techniques Message-ID: <3601F5E21CA5D711965000508B4A8BD11922C0@MARKHAM2> I would like to ask some advice about tracking down memory leaks in Python code. We have a python application running on Python 2.0.1 in an embedded Linux environment (kernel version 2.4.7). We have recently detected a memory leak that we can see from "ps aux" is attributable to the Python processes. Running Sam Rushing's (http://www.nightmare.com/medusa/memory-leaks.html) get_refcounts() function does not yield any smoking guns: the reference counts for all classes remain stable even as memory use climbs. Is there any systematic method of determining how Python is using its allocated memory? Thanks. From noah at noah.org Fri Jul 11 17:25:26 2003 From: noah at noah.org (Noah) Date: 11 Jul 2003 14:25:26 -0700 Subject: Convert between Windows style paths and POSIX style paths References: <3F0DE565.1CEA39C6@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3F0DE565.1CEA39C6 at engcorp.com>... > You can use forward slashes in paths under Win32, except at the > command prompt. > > Even if you switch to use all forward slashes, however, what do > you plan to do about drive letters? There is no obvious mapping > to anything under POSIX, I think. Are you planning on disallowing > paths that go anywhere but the current drive under NT? > -Peter I had forgotten that NT supports forward slashes. My only concern is that some of the config file values are set programatically and I use os.path.join everywhere, so if the config file is modified when running under Windows then the paths will get \ separators and that will confuse the UNIX side. I think I will still need something to ensure that the paths are consistent... Hmmm... I wonder how evil it would be to simply set os.sep = '/' when I initialize my application. I wonder if I will be angering the dark lords of Microsoft by doing this. I was going to simply remove the drive letter, so, yes, that would disallow paths other than the curent drive. I might also map the drive letters to a point on the POSIX path or I might do it Cygwin style where C: becomes /cygdrive/c/. From anthony_barker at hotmail.com Thu Jul 31 09:55:52 2003 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 31 Jul 2003 06:55:52 -0700 Subject: Python's biggest compromises Message-ID: <899f842.0307310555.56134f71@posting.google.com> I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the language's 30+ year evolution. What to you think python largest compromises are? The three that come to my mind are significant whitespace, dynamic typing, and that it is interpreted - not compiled. These three put python under fire and cause some large projects to move off python or relegate it to prototyping. Whitespace is an esthetic preference that make Andrew Hunt and David Thomas (of Pragmatic Programmer fame) prefer Ruby. Personally, I love it - but I can see why some people might not like it (30 years of braces). Dynamic typing causes the most fuss. I like Guido's answer to the question - > "Doesn't dynamic typing cause more errors to creep into the code because you catch them later than compile time?". > "No, we use Unit Testing in Zope". That said, obvious Basic compromised by using things such as "Option Explicit", thereby allowing both dynamic and more static style variables. Yahoo groups moved from python to C due to dynamic typing. Non-compiled - obviously there are times when performance matters more than other things. Google I believe uses python to prototype (or used) and then turns to c++ for heavy lifting. What about immutable strings? I'm not sure I understand Guido's preference for them. Anthony http://xminc.com/anthony From trentm at ActiveState.com Fri Jul 18 15:55:10 2003 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 18 Jul 2003 12:55:10 -0700 Subject: Perl -> Python hopeless? In-Reply-To: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be>; from jarausch@skynet.be on Fri, Jul 18, 2003 at 07:21:28PM +0200 References: <3f182c9a$0$276$ba620e4c@reader0.news.skynet.be> Message-ID: <20030718125510.A8491@ActiveState.com> [Helmut Jarausch wrote] > Hi, > having been a Perl fan for years I have nearly converted to Python. > Still, there are LOTS and very good modules written in Perl. > > Is there a tool to lesson the burdon of translation of Perl to Python? > I am completely aware of the fact that a fully automatic translation > to readable Python source is hard if not impossible. > But such a tool could lots of the tedious work like replacing > braces by proper indentation and and similar things. > > Thanks for a pointer (if there is one) There is a project called PyPerl that was developed here at ActiveState to help integrate Perl support into Zope. Here is a wiki for PyPerl: http://www.python.org/cgi-bin/moinmoin/PyPerl Try this (YMMV): - install ActivePython 2.2 - install ActivePerl 5.6 - install PyPerl into your Perl and Python installations: pyppm install PyPerl - startup python and try to use the 'perl' module: python >>> import perl >>> print perl.eval("3+3") - read some docs on how to use it: http://aspn.activestate.com/ASPN/CodeDoc/pyperl/perlmodule.html I can't test this on my machine right now so I can't be sure that the above works smoothly. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From mlh at furu.idi.ntnu.no Mon Jul 28 20:24:20 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 29 Jul 2003 00:24:20 +0000 (UTC) Subject: Floyd-Warshall Algorithem in Python References: Message-ID: In article , Dave wrote: >Hello, > >I'm looking for a Floyd-Warshall Python implementation. The only >implementation I have seen (searching this newsgroup) used a Python >library called "Numeric". This implementation doesn't work anymore. >I was wondering whether anyone knew of any FW implementations >elsewhere, or knew how I could convert the old example to Python code >that would run on Python 2.2? This is really so simple that it's almost a bit redundant to have a separate library for it... Here is a sample implementation: def floyd_warshall(w, n): d = {0: w} for k in range(1,n+1): d[k] = {} for i in range(1,n+1): for j in range(1,n+1): d[k][i,j] = min(d[k-1][i,j], d[k-1][i,k] + d[k-1][k,j]) return d[n] This is basically directly translated from the standard pseudocode. A graph is represented by its weight matrix, in the form of a dictionary with tuple keys. For example: w = {} w[1,2] = 3 w[1,3] = 8 w[1,5] = -4 w[2,4] = 1 ... and so forth. You could add a loop like this to fill out the edges that aren't specified explicitly: for i in range(1,n+1): w[i,i] = 0 for j in range(1,n+1): w.setdefault((i,j), INF) Here, n is the number of nodes in the graph and INF may be set to something like sys.maxint. The algorithm above stores all steps of the algorithm, with d[k] being the distance matrix after step k -- a bit redundant, but useful if you want to display the steps. You might also want to keep a parent matrix (or, rather, a dictionary) where pi[k][i,j] is the parent to node j in the shortest path from i to j after step k (set this when selecting the minimum; you'd have to replace the call to min() with an if statement). Again, keeping the results from all steps is highly redundant, but easily simplified; you only need the previous and the current. >Thanks, >Dave. -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From paul_rudin at scientia.com Thu Jul 10 11:29:29 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 10 Jul 2003 16:29:29 +0100 Subject: Deleting specific characters from a string References: Message-ID: >>>>> "Michael" == Michael Chermside writes: > Paul Rudin writes: >> I'd expect it to be faster than your solution - particularly on >> large input (although I haven't actually tried). > Hmm... I doubt it. I'd expect the translate() version to be the > fastest, with multiple string.remove()'s being competative when > the number of different characters to be removed is small. RE's > are NOT renown for their speed when doing simple character > replacement, deletion or insertion on strings. My comparison was with one particular solution, not all solutions mentioned. Still I was previosuly unaware of the existence of translate... so thanks for mentioning it. > But _I_ haven't timed it either, so I'm going to shut up now. Me too :-) From newsgroups at jhrothjr.com Wed Jul 30 13:16:58 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 30 Jul 2003 13:16:58 -0400 Subject: Misuse of References: <3f27f0e3$1@news.broadpark.no> Message-ID: "Gisle Vanem" wrote in message news:3f27f0e3$1 at news.broadpark.no... > I'm a .py newbie and fascinated by the simplicity of formatting. > No need for {} as in Perl etc. But the misuse of that many > .py writers do makes it hard to understand how a script operates. > > E.g. > > def main(): > terminate = 0 > def foo(): > line = sys.stdin.readline() > try: > bar() > except: > terminate = 1 > > main() > > Now, with an editor with different tab-settings it's difficult to see where > the try statement belongs. In 'def main()' or in 'def foo()' ? > I'm confused, please enlighten me. You're quite right - mixing spaces and tabs when indenting is not the thing to do. In fact, it's warned against in a number of places. The recommended practice is to use spaces, and avoid tabs completely. I think you'll find that all the modules in the standard library use spaces exclusively. John Roth > > --gv > > From ulope at gmx.de Wed Jul 9 08:51:02 2003 From: ulope at gmx.de (Ulrich Petri) Date: Wed, 9 Jul 2003 14:51:02 +0200 Subject: Python Global Constant References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: "Peter Hansen" schrieb im Newsbeitrag news:3F0BE68B.893EB7E5 at engcorp.com... > Krisztian Kepes wrote: > > > *** module any *** > > import dirs; > > def CheckDir(Dir): > > if Dir=dirs.Const_Up: xxx > > This code should work fine, although you might want to follow > the Python conventions for capitalization and formatting of > your code, to make it more readable for others. For example, > variables and functions are generally mixed case, as in checkdir > or dir, while constants are usually ALLCAPS as in CONST_UP. No it wont. "if Dir = dirs.Const_Up:" is invalid syntax (Note the = instead of ==) Ciao Ulrich From mis6 at pitt.edu Thu Jul 17 08:55:22 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 17 Jul 2003 05:55:22 -0700 Subject: Documentation examples needed References: Message-ID: <2259b0e2.0307170455.31ae2e11@posting.google.com> "Stuart D. Gathman" wrote in message news:... > I am still wanting to produce Python standard format documentation for > Python extensions I have written. I have looked at the docs that come > with Python itself, but I am new to Latex, and don't know how to add the > document classes and styles from texinput for a new project. > > Is there a small project with documentation in the Python standard that I > can use as an example? Dave Kuhlman reported on the docutils mailing list that it was working on a docutils writer to produce standard Python documentation. http://www.rexx.com/~dkuhlman/#docutilsdocpy Michele From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jul 17 18:47:50 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 18 Jul 2003 00:47:50 +0200 Subject: A challenge to the ASCII proponents. In-Reply-To: <3F172442.2040907@v.loewis.de> References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> Message-ID: <3f172794$0$49102$e4fe514c@news.xs4all.nl> Martin v. Loewis wrote: > ???????? > > Look Ma, no markup. And not every character uses two bytes, either. > And I can use Umlauts (???) and Arabic (???.????) if I want to. > > I don't know for whom this renders well, but I guess MSIE5+, NS6+ > and Mozilla 1+ are good candidates - without the need for saving > things into files. Exactly, it renders perfectly okay for me (mozilla 1.4). I wonder one thing: how did you type it in? --Irmen From eniac at sdf-eu.org Thu Jul 10 07:05:07 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Thu, 10 Jul 2003 13:05:07 +0200 Subject: How does python work Message-ID: I'm asking myself how Python code get's executed ... What happens first etc ... First read the file and then .. How python handle's variable internally ... also could someone point me to the build in functions in the python source code ? From jjl at pobox.com Sat Jul 26 21:37:18 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Jul 2003 02:37:18 +0100 Subject: Tokenize References: <8%VTa.133$313.72262@news.uswest.net> Message-ID: <87he58rbqp.fsf@pobox.com> "Ken Fettig" writes: > Does Python have an equivelent to the Java StringTokenizer? If so, > what is it and how do you implement it? I don't mean to be grumpy, but why do people seem to have suddenly started saying 'implement' where they used to say 'use'? They mean (or used to mean!) quite different things! I can understand marketroids using the word like that, and non-native English speakers picking it up from them, but I really don't understand how native English speakers who are also programmers end up using this confusing way of talking. I suppose I now have to say "how to I write the body of that function" instead of "how do I implement that function", or Ken & co. will get confused... and I guess I now have to write a sentence or two where I used to use the general "how do I implement that?". Grumph. don't-get-me-started-on-imply-vs-infer-ly y'rs, John From op73418 at mail.telepac.pt Tue Jul 29 09:30:20 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 29 Jul 2003 14:30:20 +0100 Subject: metaclasses References: Message-ID: On Tue, 29 Jul 2003 08:25:26 +1000, Simon Burton wrote: > >It seems this is a more general way to build classes than inheritance. >Is this a reasonable viewpoint? > Yes, it's reasonable. A class statement is syntactic sugar for a call to the type constructor. As for the usefullness of the POV that's a whole different matter: "Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why)." -- Tim Peters Mr. Tim Peters is always right. With my best regards, G. Rodrigues From dion_mart at hotmail.com Thu Jul 24 01:16:10 2003 From: dion_mart at hotmail.com (Martin Dion) Date: Thu, 24 Jul 2003 05:16:10 GMT Subject: Needing help with sockets References: <3f1c4378$0$49110$e4fe514c@news.xs4all.nl> Message-ID: Thank you for your reply, but I have not been able to find good information about the select module for a client. Do you know a good place to find tutorials about select module for clients ? From manish.j at gmx.net Fri Jul 25 09:03:51 2003 From: manish.j at gmx.net (Manish Jethani) Date: Fri, 25 Jul 2003 18:33:51 +0530 Subject: data conversion question (binary string to 'real string') In-Reply-To: References: Message-ID: Alexander Eisenhuth wrote: > maby I don't see the forest because of all that trees, but : Maybe I don't understand your question... > from struct import * > > > # how can I convert > f = float(0.5) > > # with > bin_str = pack('!f', 0.5) > > # now bin_str is '?\x00\x00\x00' > > > # to "3F000000" ????? ??????????????? What is your question? -Manish -- Manish Jethani (manish.j at gmx.net) phone (work) +91-80-51073488 From roy at panix.com Mon Jul 7 14:41:32 2003 From: roy at panix.com (Roy Smith) Date: 7 Jul 2003 14:41:32 -0400 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: Dave Brueck wrote: > True, although rather than let the frame rate continue up the game designers > will simply add more polygons, more actors, more textures, greater viewable > distance, etc. so they won't ever reach the "fast enough" point either. On the other hand, much of that low-level rendering stuff is done in hardware (and more and more every day). The application running on the main CPU is less and less of a factor. To a certain extent, the question is not Python vs. C++, but ATI vs. Nvidia, and how well the app takes advantage of the underlying hardware. The same is true in a lot of domains. Modern network switches implement all of the critical-path logic in hardware, and (for the most part) all the software does is provide a management/configuration interface. It's not unusual for a switch to be running at or near capacity, and the CPU usage to be 10% or less. In a situation like that, it just doesn't matter how fast the software is. Time to market and robustness are much more important. From timr at probo.com Sat Jul 19 19:22:49 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 19 Jul 2003 16:22:49 -0700 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> <747bhv8r2h398bv121seft4spukd6bcsug@4ax.com> Message-ID: <28kjhvc7kcuf5uo96teg012rc6gqsnl10u@4ax.com> "Terry Reedy" wrote: > >"Stephen Horne" wrote in message >> Anyway, Algol and Fortran apparently (I didn't know this until >> today) *always* used call-by-reference. > >Not true (about Fortran). I vaguely remember (about 1980) when IBM >Fortran switched from one calling convention to another. No, you don't. A simple variable name is required to be passed by reference (or at least passed so it SIMULATES pass-by-reference), at least until Fortran90. Expressions in a parameter list are passed by value, of course, and you could force the compiler to use call-by-value by using trickery like: CALL FUNC1( PARAM1, (PARAM2), 1*PARAM3 ) PARAM2 and PARAM3 would usually by passed by value. I absolutely refuse to believe that IBM would have arbitrarily changed their Fortran compiler's default calling convention in 1980. The F77 standard simply would not allow it, if you were even using F77; much Fortran code was still F66 until well into the 1980s. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ray at rays-web.com Thu Jul 10 19:21:59 2003 From: ray at rays-web.com (Ray Smith) Date: 10 Jul 2003 16:21:59 -0700 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> Message-ID: <5654fff9.0307101521.5a3fec41@posting.google.com> graham__fawcett at hotmail.com (Graham Fawcett) wrote in message news:... > Without regard to the specifics of your question: if you haven't done > so already, I'd recommend reading Eric Raymond's essay "The Magic > Cauldron." > > Summary: "This paper analyzes the economics of open-source software. > It includes some explosion of common myths about software production > economics, a game-theoretical account of why open-source cooperation > is stable, and a taxonomy of open-source business models." > > http://www.catb.org/~esr/writings/magic-cauldron/ and also "Open Sources: Voices from the Open Source Revolution" in particular the "Cygnus" and "Open Source as a Business Strategy" chapters. Online at http://www.oreilly.com/catalog/opensources/book/toc.html Ray Smith From jdhunter at ace.bsd.uchicago.edu Wed Jul 9 10:37:24 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 09 Jul 2003 09:37:24 -0500 Subject: Application Development in Python In-Reply-To: <200307091017.49419.drlinux@columbus.rr.com> (Dave Reed's message of "Wed, 9 Jul 2003 10:17:49 -0400") References: <3089454.1057738936@dbforums.com> <200307091017.49419.drlinux@columbus.rr.com> Message-ID: >>>>> "Dave" == Dave Reed writes: Dave> Also note that using the database for manipulating the data Dave> makes the speed very acceptable. I'm almost certain that Dave> manipulating the data in Python would be way too slow to Dave> make it usable (e.g., generating a balance sheet that looks Dave> through all the transactions and groups them by account in Dave> Python would be much slower than using sql commands to do Dave> that). I'm not arguing that the dbase isn't the way to go, but if you wanted to do the manipulations in python, the Numeric package certainly provides the speed you need to manipulate large quantities of data rapidly. I sometimes use a C extension to put data from an SQL database directly into Numeric arrays and then manipulate the data in python. John Hunter From newsgroups at jhrothjr.com Thu Jul 31 17:27:46 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 17:27:46 -0400 Subject: Python's biggest compromises References: <899f842.0307310555.56134f71@posting.google.com> Message-ID: "Robin Becker" wrote in message news:TBO13LAmBVK$Ewml at jessikat.fsnet.co.uk... > In article , John Roth > writes > > > ..... > >High performance isn't Python's target. If PyPy ever gets their act > >off the ground, then we will have a shot at a good quality JIT > >interpreter. Then watch it fly. > > > .... doesn't psyco already attempt to do JIT? It certainly doesn't > speed things up that much. If all the variables are known to be of a > specific type then you could expect C like speeds from a good JIT, but > without global analysis it's hard to see how we infer/guarantee python > types. Well, that's certainly a problem, but Bicycle Repair Man seems to do a pretty good job of type inference, at least for refactoring. One of the things to consider here is that a decent JIT interpreter would automatically change the playing field for what is good practice and what isn't, at least if you expect performance. John Roth > -- > Robin Becker From adechert at earthlink.net Mon Jul 21 17:55:59 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 21:55:59 GMT Subject: Voting Project Needs Python People References: <3F1C31B1.B44774BA@engcorp.com> <2oWSa.113024$Io.9679242@newsread2.prod.itd.earthlink.net> <3F1C51BB.AC355795@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3F1C51BB.AC355795 at engcorp.com... > Alan Dechert wrote: > > > > "Peter Hansen" wrote in message > > news:3F1C31B1.B44774BA at engcorp.com... > > > Alan Dechert wrote: > > > > > > > > We are pulling together a great voting modernization projects. [snip] > > > > > > Is there a word missing in the above? I can't parse it as-is, but it > > > looks like it wants the word "many" after the word "great"... > > > > > Editing error. I started to say, "the mother of all voting modernization > > projects." > > > > You get the idea. > > I do now. Thanks. "The mother of all" has a distinctly different > character than "pulling together a great many". One hopes there will > not also be dozens of other such projects going on in parallel, wasting > resources. > There are various public and private voting machine development efforts going on, but nothing like ours. I'm the guy when it comes to PC based open source voting machine with a printer. The reason I'm still at it is that when people get the idea they'd like to work on such a thing and start making inquiries, they wind up getting referred to me. When it comes to the top experts in this area, there really aren't very many -- and we tend to know each other. Some of the very top voting technology experts (e.g., Roy Saltman and Doug Jones) are closely associated with this project. Several key people on our project were referrals from Stanford computer scientist David Dill. http://www.verifiedvoting.org/index.asp Alan Dechert From kamikaze at kuoi.asui.uidaho.edu Tue Jul 1 03:34:44 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 1 Jul 2003 07:34:44 GMT Subject: Python executables? References: Message-ID: Thu, 26 Jun 2003 12:37:23 +0300, Catalin : > How can I make executables with python? > I found some utilities that claim they can do something like that like > Installer and py2exe but they actualy pack the code in a huge arhive! > This solves the problem of giving python programs to users who don't > have python but doesn't solve the problem of the source "secrecy" > (copyright). You can use python -OO to produce .pyo "optimized" files, and then just ship those. .pyo isn't truly optimized or completely binary, but it's about as secure as Python normally gets. .pyo classes are tied to specific versions of Python, but if you're using py2exe, that's not a problem. Anyone with a decompiler will still be able to get at them, and there are AFAIK no obfuscators for Python, but at least it closes the door, even if it doesn't lock it. Ultimately, the only way to have full secrecy is to keep all your code on a trusted server (and hope nobody ever breaks in), and only give the users a minimal dumb client. -- Mark Hughes "We remain convinced that this is the best defensive posture to adopt in order to minimize casualties when the Great Old Ones return from beyond the stars to eat our brains." -Charlie Stross, _The Concrete Jungle_ From dave at pythonapocrypha.com Fri Jul 11 16:03:01 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 11 Jul 2003 14:03:01 -0600 Subject: Small Python, Java comparison Message-ID: <200307111403.01028.dave@pythonapocrypha.com> Below is some information I collected from a *small* project in which I wrote a Python version of a Java application. I share this info only as a data point (rather than trying to say this data "proves" something) to consider the next time the "Python makes developers more productive" thread starts up again. Background ========== An employee who left our company had written a log processor we use to read records from text files (1 record per line), do a bunch of computations on them, and load them into various tables in our database. Typically each day there are 1000 to 2000 files with a total number of records being around 100 million. The nature of the work the processor's work (some of it is summarizing data) results in about 1 database insert or update for about every 20 "raw" log records. After this employee left I inherited this chunk of code and the first thing I did was create a fairly comprehensive test suite for it (in Python) because there was no test suite and in the past we had had many problems with bugs and flakiness in the code. As I did this I got pretty familiar with how the code worked and noticed lots of places where the language seemed to "get in the way" of what needed to be done. During this time I also began hearing rumblings about how this processor would need to be extended to add more functionality, so I thought I'd start rewriting it in Python on the side just to see how it would turn out (the idea being that if I got it done and it was good enough then I could simply implement the new functionality in the Python version :) ). Data ==== The Java version is for the Java 1.4 platform (uses the Sun JVM), and it connects to an Oracle 9 database on our LAN via the thin JDBC driver provided by Oracle. As far as complexity goes, I'd rate the problem itself as non-trivial but not rocket science. :) Implementing it in Java turned out to be fairly involved; a lot of the complexity there revolved around efficiently maintaining data structures in memory that didn't get committed to the database until the end of each separate file. The developer for the Java version has about as much experience as a developer as I do, and he has about as much experience with Java as I do with Python (IOW, I don't consider that to be much of a differentiating factor - although the Java developer has *way* more database experience than I do). From the start of the design to the end of the implementation and initial round of bug fixing took 3 weeks. An additional 2-3 weeks were spent optimizing the code and fixing more bugs. The source code had 4700 lines in 9 files. When running, it would process an average of 1050 records per second (where process = time to parse the file, do calculations, and insert them into the database). The Python version is for Python 2.1.3 and it connects to the same Oracle database using DCOracle2. The implementation is very straightforward, nothing fancy. It's also still pretty "pristine" as I haven't had any time to try and optimize it yet. :) One of the biggest simplifying factors in the code was how easy it was to have dictionaries map dynamically-defined and arbitrarily-complex keys (made up of object tuples) to other objects. For whatever reason this seemed to be a huge factor in making data management go from a difficult problem to almost a no-brainer. If the Python version had come first and the Java one second, then some of that approach could have made it into the Java version, but in Java I don't find myself thinking about problems quite the same way - IOW the Python version's approach wouldn't be as obvious in Java or would seem to be too much up-front work (whereas the approach that was used was easier up front but in the end became quite complex and a limiting factor to adding new functionality IMO). Because I wasn't working on this full-time, the development was spread out over the course of two weeks (10 working days) at an average of just over 2 hours per day (for a total of not quite 3 full days of work). The source code was less than 700 lines in 4 files. Most surprising to me was that it processes an average of 1200 records per second! I had assumed that after I got it working I'd need to spend time optimizing things to make up for Java having a JIT compiler to speed things up, but for now I won't bother. Both versions could be improved by splitting the log parsing/summarizing and database work into two separate threads (watching the processes I see periods of high CPU usage followed by near-idle time while the database churns away). Currently the Java version averages 47% CPU utilization and the Python version averages 51%. Caveats ======= There are a million reasons why this isn't an apple-to-apple comparison or why somebody might read this and cry "foul!"; here's a few off the top of my head: - The second time you write something you can do it better - since development is often part exploratory, once you're done you usually have a good idea of how to do it better were you to do it again. I didn't write the first version, but writing the test suite (and fixing the bugs it uncovered) made me familiar with the weaknesses in the initial version. - It's proprietary code; nobody else can see the two versions of source - Too bad. ;-) - I haven't bothered to do a "true" LOC count for both versions - I just did "wc -l *.py" and "wc -l *.java" to get line counts - so comments and other junk is included in the line totals. - My development time didn't include much design time because my design was mostly a reaction to the Java implementation. - I used the thin Java driver (written in pure Java) and DCOracle 2 (uses native driver on Linux) - this may affect performance some. Conclusion ========== Like I said before, I'd hesitate to read *too* much into this experience, although I will say it's a more concrete and confirming example of what I (and many others) have experienced before - that there are some big productivity gains by using Python over some other languages. It's generally hard to measure this sort of thing because it's rare to do a rewrite without adding functionality, and the larger the project the more rare this becomes, so even though this is a very small example it's still useful. I certainly wouldn't have gotten "approval" to do the simple rewrite, but doing it in my spare time and having a comprehensive test suite made it possible. Anyway, for a very small development cost I ended up with a codebase 15% of the size of the original, and an implementation that will be far easier to extend (and easier to pass off to somebody else!). In order to get smaller and cleaner code I had been willing to take a modest performance hit, but in the end the new version was slightly faster too - icing on the cake! -Dave From kericks272 at earthlink.net Sun Jul 13 21:33:07 2003 From: kericks272 at earthlink.net (ken) Date: Mon, 14 Jul 2003 01:33:07 GMT Subject: Using PMW? Message-ID: Please pardon my ignorance regarding this question, I'm new to Python. I'm running Python 2.2.3 (win32) with the latest download of Python MegaWidgets 1.1. I'm attempting to run the demos but get the following: C:\Python22\Pmw\demos>python all.py Traceback (most recent call last): File "all.py", line 84, in ? DemoVersion.setPmwVersion() File "DemoVersion.py", line 32, in setPmwVersion if version in Pmw.installedversions(): AttributeError: 'module' object has no attribute 'installedversions' C:\Python22\Pmw\demos>python colors.py Traceback (most recent call last): File "colors.py", line 44, in ? Pmw.initialise(root, fontScheme = 'pmw1') AttributeError: 'module' object has no attribute 'initialise' Is this a problem with the libray not being found? I've read the docs with the widgets and it seems to be straight forward. I'm hoping someone has the answer. TIA From guettler at thomas-guettler.de Thu Jul 17 07:40:00 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Thu, 17 Jul 2003 13:40:00 +0200 Subject: tkinter: Better Traceback References: Message-ID: Fredrik Lundh wrote: > Thomas G?ttler wrote: > >> Is there a way to get a better traceback in tkinter? >> It would be nice to see the line number of the last line >> of "my" code. >> >> Exception in Tkinter callback >> Traceback (most recent call last): >> File >> "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", >> line 1299, in __call__ >> args = apply(self.subst, args) >> File >> "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", >> line 1035, in _substitute >> e.height = getint(h) >> ValueError: invalid literal for int(): ?? > > it's not a bug in your code, it's an incompatible change in Tk 8.4.2, > which uses "??" to represent an "undefined integer". > > either upgrade your Tkinter (Python 2.3 contains a workaround), or down- > grade your Tk to 8.4.1 or earlier (or link Tkinter against Tk 8.3.x). Hi Fredrik, Both solutions are need to change this which only root can do. The application will be installed on several workstations running Suse Linux8.2. Is there a workaround? Would be good if I could use the default python (2.2.2) and TK version (8.4.2). thomas From christian.knoblauch at icn.siemens.de Mon Jul 21 10:13:52 2003 From: christian.knoblauch at icn.siemens.de (Christian Knoblauch) Date: Mon, 21 Jul 2003 16:13:52 +0200 Subject: COM interface to the Python interpreter Message-ID: Hello all, under Win32 it is possible to use Python as a scripting language inside ASP pages (win32lib package), so there must be a COM interface to the Python interpreter. I like to use this interface instead of writing my own COM server to invoke Python scripts from COM aware languages, unfortunately i can not find the type-library for this interface. Can one provide this information (perhaps with an litle example) ? Thanks in advance ! By, Christian From peter at engcorp.com Mon Jul 14 00:09:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 00:09:59 -0400 Subject: new in town References: Message-ID: <3F122D17.A306A02D@engcorp.com> (Top-posting fixed. Elaine, please don't top-post. Thank you.) Elaine Jackson wrote: > Gerhard H?ring wrote in message > news:mailman.1058024839.27499.python-list at python.org... > | This and many more of your questions to come will be answered by the > | Python FAQ, btw: http://www.python.org/cgi-bin/faqw.py > > As comforting as it is to know that there are "several ways of doing this", I'd > be even happier if I knew the name of just one of those ways. The FAQ searcher > doesn't seem to understand lengthy explanations and hand-waving. The best way to use the FAQ is to read or at least skim through the *whole* thing from top to bottom. Unwillingness to do so indicates you don't value the time of those of us who try to help others in this newsgroup, and you may encounter some reluctance from us to help those who won't help themselves. Please read the FAQ before posting questions. That's good advice for anyone who is new to this group. It doesn't take long and the information will go a long way towards helping you understand the language and community. Cheers, -Peter From newsgroups at jhrothjr.com Thu Jul 31 11:02:30 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 31 Jul 2003 11:02:30 -0400 Subject: time, calendar, datetime, etc References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: "Skip Montanaro" wrote in message news:mailman.1059656902.23276.python-list at python.org... > > > I couldn't pick an asctime()-generated date out of a lineup. For most > logging I think it makes sense to use sortable numeric dates (ISO-8601). > Besides sortability, they are indifferent to language and unambiguous. > There are many little variations in "human readable" dates, even those which > are so-called standards. Someone always gets things "wrong". Quick, what's > the format of an RFC-822 date? Is it the same as an RFC-2822 date? What > about RFC-1036? RFC-850? > > Not that I have any claim to have been complaining loud and clear about this > problem back in 1982 and 1983 when these RFC were written (or earlier, when > the systems they codified were first developed), but I don't think there's > any use in further propagating arcane date formats. Amen, brother! John Roth > > Skip > > From exarkun at intarweb.us Tue Jul 22 10:28:42 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 22 Jul 2003 10:28:42 -0400 Subject: Memory errors when using imaplib with large email attachments In-Reply-To: <2144d9df.0307220353.a958f84@posting.google.com> References: <2144d9df.0307220353.a958f84@posting.google.com> Message-ID: <20030722142842.GA17435@intarweb.us> On Tue, Jul 22, 2003 at 04:53:36AM -0700, Richard Walkington wrote: > Hello, > > I'm using python to connect to an IMAP server and download mail. When > downloading messages with large attachements (> 10MB) Python socket > module crashes with a memory error. Is there anything I can do about > this? Short of hacking on imaplib.py yourself (and then using this modified version), I don't believe so. I would recommend using Twisted's IMAP support, which uses temporary files (among other strategies) to keep memory usage within reason. http://www.twistedmatrix.com/ The IMAP API is still in a very minor state of flux, but there should be no futher changes that seriously break application code using it. Jp -- A sad spectacle. If they be inhabited, what a scope for misery and folly. If they be not inhabited, what a waste of space. -- Thomas Carlyle, looking at the stars From sorry_i_am_tired_of_spam at refuse.com Wed Jul 16 19:32:16 2003 From: sorry_i_am_tired_of_spam at refuse.com (David McNab) Date: Thu, 17 Jul 2003 11:32:16 +1200 Subject: Choosing the right framework References: Message-ID: On Wed, 16 Jul 2003 14:54:16 +0200, Carsten Gehling paused, took a deep breath, then came out with: > Oh how often this subject may come up... > > The thing is, I've come to the decision of abandoning PHP as much as > possible (old projects still remain...), and use Python for all purposes. > Reason: One language to fit it all (instead of having one language for > webprogramming, one for batches, etc...) > > I stand now at the point where I must choose a framework for my web > application development. I've skimmed a few: mod_python, pso and Zope. > However, I cannot decide on which to choose. I've been working on an HTML generation framework called 'pyWeb'. Just posted to this ng yesterday, calling for testers. You might like to visit http://www.freenet.org.nz/python/pyweb and have a look. Cheers David From http Tue Jul 22 13:01:10 2003 From: http (Paul Rubin) Date: 22 Jul 2003 10:01:10 -0700 Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xbrvnmqzp.fsf@ruckus.brouhaha.com> Message-ID: <7x4r1exzqh.fsf@ruckus.brouhaha.com> Marc Wilson writes: > Ah. That's a whole load of trouble we don't have. To stand for election, > here, you have to pony up a deposit, which you lose if you don't get a > certain percentage of the vote. It's to discourage "frivolous" campaigns, > supposedly. IIRC, it's around GBP 1000; about USD 1500. Here, you have to get a certain number of voter signatures on petitions, plus pay a bunch of fees, to get your name actually printed on the ballot. But when voting, you can write in the name of anyone you want. Senator Strom Thurmond, who died recently at age 100, was originally elected to the US Senate through a write-in campaign in 1954. He went on to serve in the Senate for longer than anyone in history. Today, of course, someone winning a major office like a US Senate seat by write-in would be practically unthinkable. But occasionally a write-in candidate wins a local office, or affects the outcome of a local election. Tom Ammiano ran for mayor of San Francisco as a write-in candidate a couple of years ago and got 25 percent of the vote (apparently getting over 70% in his core neighborhoods), coming in second in a race with three non-write-in candidates listed on the ballot. That was enough to get Ammiano into a run-off election (which he lost with about 40%, but he was considered to have serious chances of winning). Ammiano spent about $25K on his write-in campaign while the guy who came in first spent over $3 million. So write-in campaigns are not necessarily "frivolous". From skip at pobox.com Sat Jul 12 11:37:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 12 Jul 2003 10:37:13 -0500 Subject: Problem with MySQLdb on Mac OS X... In-Reply-To: <110720032317344670%candiazoo@mac.com> References: <110720032317344670%candiazoo@mac.com> Message-ID: <16144.11049.435354.511911@montanaro.dyndns.org> Mike> I made modifications to setup.py to set safe threading to NO and Mike> also to point to the "real" location of the mysql libraries and Mike> stuff like that. To test it I wrote a simple script that just Mike> tries to connect to the database. It fails. It also fails Mike> interactively. Here is what I am getting... Your script worked fine for me (Mac OS X 10.2.6, Python 2.3b1+), though I didn't modify setup.py (at least not that I recall - it's been awhile). Mike> The download, build and install went fine. This same code works Mike> (well, different database name, user and password) on a different Mike> machine. The database, username and password are all correct. The only change I made was that the database is remote, so I set the host as well. Skip From kaericksonsprint at earthlink.net Sun Jul 13 17:01:18 2003 From: kaericksonsprint at earthlink.net (Ken Erickson) Date: Sun, 13 Jul 2003 21:01:18 GMT Subject: sample code from John Grayson's "Python and Tkinter Programning" book Message-ID: <3f11c0d5.19274484@news.earthlink.net> Does anyone know if the example code in John Grayson's book is available online? He has some interesting examples and I really don't want to spend hours re-typing his work (too many typo's late at night). I rather spend time walking through the code via the debugger. TIA. From vivek at cs.unipune.ernet.in Tue Jul 29 04:29:39 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Tue, 29 Jul 2003 13:59:39 +0530 Subject: How to get success/failure in case of thread In-Reply-To: <16165.10847.483917.787182@montanaro.dyndns.org>; from skip@pobox.com on Mon, Jul 28, 2003 at 08:51:27AM -0500 References: <20030728175542.A23857@cs.unipune.ernet.in> <16165.10847.483917.787182@montanaro.dyndns.org> Message-ID: <20030729135939.A11825@cs.unipune.ernet.in> On Mon, Jul 28, 2003 at 08:51:27AM -0500, Skip Montanaro wrote: > > vivek> import thread > vivek> thread.start_new_thread(my_func,(args,)) > > vivek> here my_func will return true/1 on success and false/0 on > vivek> failure. How can I check whether the function failed/succeeded > vivek> ??? > > Have the function (or a wrapper function) put() the return value on a Queue > object, then get() it from there. > THX a lot.. But I think it will not work in case if I want to return some value from the function. Like currently I am trying to implement three tier application using python. I mean a web server that will serve the http request, depending on the request it will create an XML string and will pass it to another tier running XMLRPCServer. On this tier the XML string will be parsed and will take actions accordingly ( like insertion in database etc.) Now I want the SimpleXMLRPCServer to create a new thread for the request that will process the particular request and will return the success/failure message. How can I do that with the help of queue object?? TIA and kind Regards Vivek Kumar From kern at taliesen.caltech.edu Fri Jul 11 17:02:45 2003 From: kern at taliesen.caltech.edu (Robert Kern) Date: Fri, 11 Jul 2003 21:02:45 +0000 (UTC) Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <87k7apyuor.fsf@pobox.com> Message-ID: In article , Ian Bicking writes: > I should have said "securing cookies isn't hard", so that's not the > reason not to use them (though you shouldn't just use plain-vanilla > cookies). Right. Chocolate-chip at minimum. What? Oh. *Those* cookies. -- Robert Kern kern at caltech.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From intentionally at blank.co.uk Mon Jul 14 19:08:58 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 00:08:58 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> Message-ID: On 14 Jul 2003 10:30:22 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv at 4ax.com>, >Stephen Horne wrote: >> >>C++ has precisely one type of variable. That variable is a placeholder >>for a value of a datatype which is specified in the declaration. The >>datatype may be a pointer datatype, but so what? Pointer datatypes are >>not treated any differently than other datatype except that they, like >>all datatypes, they have their own set of functionality. > >Really? I would argue that the differing syntaxes is an argument >against a single type of variable. What happens with this: > >char a; >a->b; To answer this, I simply have to restore the quote you deleted... : On 13 Jul 2003 21:03:59 -0700, owski at hotmail.com (Adam Ruth) wrote: : : >I don't see the arbitrary change. Python has one type of variable: A : >pointer that cannot itself be dereferenced. It's much more consistent : >then having 3 types of variables (in C++). This is not referring to data types - there are far more than three data types in C++. It is referring to whether something is a pointer or a reference or not. The mistake in Adams post simply being that these are simply datatypes. You will note that even in my words, I tried to keep the distinction clear by using the word 'datatypes' when I was referring to datatypes. In fact, lets look back at my first two scentences in your quote of my reply. >>C++ has precisely one type of variable. That variable is a placeholder >>for a value of a datatype which is specified in the declaration. One *type* of variable, which is associated with its own *datatype*. I find it hard to see how you could confuse this, but given my own mistakes - well, we're all human I suppose. From hokiegal99 at hotmail.com Wed Jul 16 08:56:03 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 16 Jul 2003 08:56:03 -0400 Subject: <> and != Message-ID: <3F154B63.3060503@hotmail.com> What is the difference between these two statements? if newfile <> oldfile if newfile != olfile Thanks guys!!! From dave at nullcube.com Tue Jul 15 20:34:54 2003 From: dave at nullcube.com (Dave Harrison) Date: Wed, 16 Jul 2003 10:34:54 +1000 Subject: Solaris 9, problem building Python 2.1.1 Message-ID: <20030716003454.GA2860@dave@alana.ucc.usyd.edu.au> Ok before I start, please dont mail me telling me to use a more recent version of Python, I _would_ use 2.2.x but due to an existing framework all based on using 2.1.1 I have been specifically told to use 2.1.1 to avoid any crossover issues/problems. Thanks ;-) So ... Using gcc Im compiling Python2.1.1, and it configures quite reasonably, the ./configure is trascribed at the bottom of this email. now once I have done that I compile it using make and it compiles just fine. But once I start up the interpreter and 'import socket' I get the following error : Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.1/socket.py", line 41, in ? from _socket import * ImportError: ld.so.1: python2.1: fatal: libssl.so.0.9.6: open failed: No such file or directory Now Ive looked through comp.lang.python for anything matching this, or solaris, etc but have come up pretty blank. Has anyone got any good news or ideas for me on this ? Cheers Dave Transcription of ./configure ***************************************** creating cache ./config.cache checking MACHDEP... sunos5 checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking whether the C++ compiler (c++ ) works... yes checking whether the C++ compiler (c++ ) is a cross-compiler... no checking for gcc... gcc checking whether the C compiler (gcc ) works... yes checking whether the C compiler (gcc ) is a cross-compiler... no checking whether we are using GNU C... yes checking whether gcc accepts -g... yes checking for Cygwin environment... no checking for mingw32 environment... no checking for executable suffix... no checking for --with-suffix... checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(PURIFY) $(CC) checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... ranlib checking for ar... ar checking for a BSD compatible install... /usr/local/bin/install -c checking how to run the C preprocessor... gcc -E checking for AIX... no checking for minix/config.h... no checking whether gcc accepts -OPT:Olimit=0... no checking whether gcc accepts -Olimit 1500... no checking for ANSI C header files... yes checking for dlfcn.h... yes checking for fcntl.h... yes checking for limits.h... yes checking for locale.h... yes checking for ncurses.h... yes checking for poll.h... yes checking for pthread.h... yes checking for signal.h... yes checking for stdarg.h... yes checking for stddef.h... yes checking for stdlib.h... yes checking for thread.h... yes checking for unistd.h... yes checking for utime.h... yes checking for termios.h... yes checking for sys/audioio.h... yes checking for sys/file.h... yes checking for sys/lock.h... yes checking for sys/modem.h... no checking for db_185.h... no checking for db.h... no checking for sys/param.h... yes checking for sys/poll.h... yes checking for sys/select.h... yes checking for sys/socket.h... yes checking for sys/time.h... yes checking for sys/times.h... yes checking for sys/un.h... yes checking for sys/utsname.h... yes checking for sys/wait.h... yes checking for pty.h... no checking for libutil.h... no checking for ndbm.h... yes checking for db1/ndbm.h... no checking for gdbm/ndbm.h... no checking for sys/resource.h... yes checking for dirent.h that defines DIR... yes checking for opendir in -ldir... no checking for clock_t in time.h... yes checking for mode_t... yes checking for off_t... yes checking for pid_t... yes checking return type of signal handlers... void checking for size_t... yes checking for uid_t in sys/types.h... yes checking size of int... 4 checking size of long... 4 checking size of void *... 4 checking size of char... 1 checking size of short... 2 checking size of float... 4 checking size of double... 8 checking size of fpos_t... 4 checking for long long support... yes checking size of long long... 8 checking for uintptr_t support... no checking size of off_t... 4 checking whether to enable large file support... no checking size of time_t... 4 checking for pthread_t... yes checking size of pthread_t... 4 checking for --with-next-framework... no checking for --with-dyld... no checking SO... .so checking LDSHARED... $(CC) -shared checking CCSHARED... -fPIC checking LINKFORSHARED... checking CFLAGSFORSHARED... checking for dlopen in -ldl... yes checking for shl_load in -ldld... no checking for --with-pydebug... no checking for t_open in -lnsl... yes checking for socket in -lsocket... yes checking for --with-libs... no checking for --with-signal-module... yes checking for --with-dec-threads... no checking for --with-threads... yes checking for mach/cthreads.h... no checking for --with-pth... no checking for pthread_create in -lpthread... yes checking for usconfig in -lmpc... no checking for thr_create in -lthread... yes checking for --with-cycle-gc... yes checking for --with-pymalloc... no checking for --with-wctype-functions... no checking for --with-sgi-dl... no checking for --with-dl-dld... no checking for dlopen... yes checking DYNLOADFILE... dynload_shlib.o checking for alarm... yes checking for chown... yes checking for clock... yes checking for confstr... yes checking for ctermid... yes checking for ctermid_r... yes checking for execv... yes checking for flock... no checking for fork... yes checking for fsync... yes checking for fdatasync... no checking for fpathconf... yes checking for ftime... yes checking for ftruncate... yes checking for getgroups... yes checking for getlogin... yes checking for getpeername... yes checking for getpid... yes checking for getpwent... yes checking for getwd... yes checking for kill... yes checking for link... yes checking for lstat... yes checking for mkfifo... yes checking for mktime... yes checking for mremap... no checking for nice... yes checking for pathconf... yes checking for pause... yes checking for plock... yes checking for poll... yes checking for pthread_init... no checking for putenv... yes checking for readlink... yes checking for select... yes checking for setegid... yes checking for seteuid... yes checking for setgid... yes checking for setlocale... yes checking for setregid... yes checking for setreuid... yes checking for setsid... yes checking for setpgid... yes checking for setuid... yes checking for setvbuf... yes checking for sigaction... yes checking for siginterrupt... yes checking for sigrelse... yes checking for strftime... yes checking for strptime... yes checking for symlink... yes checking for sysconf... yes checking for tcgetpgrp... yes checking for tcsetpgrp... yes checking for tempnam... yes checking for timegm... no checking for times... yes checking for tmpfile... yes checking for tmpnam... yes checking for tmpnam_r... yes checking for truncate... yes checking for uname... yes checking for waitpid... yes checking for _getpty... no checking for getpriority... yes checking for openpty... no checking for openpty in -lutil... no checking for forkpty... no checking for forkpty in -lutil... no checking for fseek64... no checking for fseeko... yes checking for fstatvfs... yes checking for ftell64... no checking for ftello... yes checking for statvfs... yes checking for dup2... yes checking for getcwd... yes checking for strdup... yes checking for strerror... yes checking for memmove... yes checking for getpgrp... yes checking for setpgrp... yes checking for gettimeofday... yes checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for tm_zone in struct tm... no checking for tzname... yes checking for time.h that defines altzone... yes checking whether sys/select.h and sys/time.h may both be included... yes checking whether char is unsigned... no checking for working const... yes checking for working volatile... yes checking for working signed char... yes checking for prototypes... yes checking for variable length prototypes and stdarg.h... yes checking for bad exec* prototypes... no checking for bad static forward... no checking whether va_list is an array... no checking for gethostbyname_r... yes checking gethostbyname_r with 6 args... no checking gethostbyname_r with 5 args... yes checking for __fpu_control... no checking for __fpu_control in -lieee... no checking for --with-fpectl... no checking for --with-libm=STRING... default LIBM="-lm" checking for --with-libc=STRING... default LIBC="" checking for hypot... yes checking what malloc(0) returns... null checking for wchar.h... yes checking for usable wchar_t... no checking whether byte ordering is bigendian... yes checking whether right shift extends the sign bit... yes checking for getc_unlocked() and friends... yes checking for rl_completion_matches in -lreadline... no checking for broken nice()... no checking for socklen_t... yes checking for build directories... done updating cache ./config.cache creating ./config.status creating Makefile.pre creating Modules/Setup.config creating config.h creating Setup creating Setup.local creating Makefile ***************************************** From davidcfox at post.harvard.edu Tue Jul 22 17:27:19 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 22 Jul 2003 21:27:19 GMT Subject: wxpython display jpg in a frame In-Reply-To: References: Message-ID: max4 wrote: > hello > i would like to know if there is a good tutorial about how to do this > or if someone could explain > > thank you > > [ i want to add a jpg to an existing about dialog] Create a wxImage from the jpg file, and then a wxBitmap from the image, then a wxStaticBitmap control from the bitmap. for example, i = wxImage("about.jpg", wxBITMAP_TYPE_JPEG) b = wxBitmapFromImage(i) sb = wxStaticBitmap(dialog, b, pos, size) As usual, see the wxPython demo for more details. David From Aaron.Buhr at campuscommgroup.com Wed Jul 30 14:02:38 2003 From: Aaron.Buhr at campuscommgroup.com (Aaron Buhr) Date: Wed, 30 Jul 2003 18:02:38 GMT Subject: Webware application question Message-ID: <2LTVa.13085$Oz4.4738@rwcrnsc54> Hello all. I am looking to rebuild our corporate website from Cold Fusion to Python/WebWare/Cheetah. I am new to all three, so I apologize in advance if my questions are ignorant. I do not understand how one would cache database connections using WebWare. At this point I do not want to use Middlekit, but I would like to compartmentalize all my database connection code and cache it for performance. The intent would be to have a shared connection pool that my pages would request an open connection from, utilize for SQL code, then give back to the db caching system. Specifically I do not understand where I would put the code to do this. Would I subclass the Application class and put my db caching code in there? If not, how would I make the db caching code consistent to all my pages? I could make a db cache class that would then be available to all my pages, but I am not sure how to make the same instance of that class (which is where all the cached connections would live) available to all pages. Thanks! Aaron Buhr Campus Communications Group, Inc. From g2h5dqi002 at sneakemail.com Mon Jul 28 00:05:58 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 28 Jul 2003 16:05:58 +1200 Subject: How to link a C extension module on Mac OS X? In-Reply-To: <7h31xwgthve.fsf@pc150.maths.bris.ac.uk> References: <7h31xwgthve.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > It works. Don't know why, mind -- the files end .so when shared > libraries usually end .dylib on OS X -- but it does. I think Darwin is using something like the original BSD model for shared libraries, in which the .so was really just a naming convention, and any object file could be loaded at run time (albeit with a possible performance penalty if it wasn't designed for it). Although Darwin seems to have a couple of different flavours of dynamic linking. When the OS X docs talk about a "dynamically linked" library, they seem to be referring to a mechanism which defers resolving references to functions until the first time they're called. It appears that it's possible for code to be loaded at run time without being "dynamically linked" in that sense. It probably helps that Python is explicitly loading the code, in which case it probably doesn't matter what the filename is. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Mon Jul 14 11:36:12 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2003 15:36:12 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> Message-ID: On 13 Jul 2003 22:46:41 GMT, bokr at oz.net (Bengt Richter) wrote: [...] Re-reading, I see that I should probably fill in some details (still subject to disclaimer ;-) > >Python name assignment does not do anything to an object. It just creates >an alias name for an object. It may reuse an existing name, but that only >changes the meaning of that name as an alias, it does not affect the object >that the name was previously an alias for. > >You can of course have other assignment targets than plain names. In fact, >a "plain name" is just the simplest expression for an assignment target. >But whatever the target expression evaluates to, what gets put "there" is >a reference to an object, not an object itself. > >The confusion, ISTM, is in what to think of as "there." "There" is definitely >not a memory space for a Python object representation or "value". > >The most accurate (UIAM) C concept would be a "there" of type PyObject* -- i.e., >a pointer variable that points to the representation of some kind of Python object. > I should have mentioned that there are various access mechanisms for storing the "pointer". I.e., the left hand side doesn't evaluate to a raw address until you are in the machine language of the implementation. When storage is actually happening, of course byte codes are being interpreted by the virtual machine of the current Python version. The byte codes will differ according to the translation of the target expression, and even for byte codes that looks the same, the implementation may involve complex dynamic behavior, e.g., in searches through an inheritance graph for an appropriate method that will accept the rh object reference and do the ultimate implementation-pointer storage. The byte codes with STORE in their names, and some typical source statements that generate them, are (2.2.3 windows): STORE_SLICE: x[a:b]=y # four byte codes numbered as STORE_SLICE+(1 if a is present)+(2 if b is present) STORE_SUBSCR: x[a]=y STORE_NAME: x=y #in global scope STORE_ATTR: x.a=y STORE_GLOBAL: def foo(): global x; x=y STORE_FAST: def foo(): x=y STORE_DEREF: def foo(): x=y # the STORE_DEREF def bar():return x return bar Note that, e.g., STORE_SUBSCR looks the same for lists and dictionaries, or even something undetermined that will give a run time error because the type of x doesn't support that operation. Storage is often mediated by various methods, e.g., __setitem__ but finding the ultimate method may be the result of a search through an inheritance graph, and/or it could find the setter function of a named property, and that function in turn may do much work that is not visible in the assignment statement source, or the immediate level of corresponding byte codes. >We don't have to know the implementation details to use the idea that the left hand >side of a Python assignment is an *expression* (even if a single name) that yields >a place to put a reference (effectively a pointer) to the object created by evaluating >the expression on the right hand side. Again, I should have been clearer. It *ultimately* yields a place, but potentially deep in the bytecode and ultimately machine code of some chain of method invocations and implementations. > >A C programmer will tend to think that a symbol on the left is a static expression >indicating a specific fixed memory space (static address or stack frame offset). But in Python >it is first of all a dynamic expression (though an unqualified target name can only have its "there" >be in the local or global namespace, and the choice between those is made statically Hm. There is a third choice. When variables of the local namespace are destined to be captured in a closure, the "there" is in the closure, stored by way of STORE_DEREF. >(at least w.r.t. a given level of compiling/exec-ing). > >In C terms, the Python assignment target expression always evaluates to a place to put a pointer, I elided a fair abount of implementation detail in saying that, but I think the effective semantics are ok. >never a place to put object representation bits. Of course, "a place to put a pointer" >may be *inside* an object. And such inside places are identified by target expressions >such as x[2] or x.a or x[2]().b[3] etc. Even a bare name really does identify a place inside >an object -- i.e., inside the local or global dict associated with the context. > >The "place" identified by x= after a global x declaration (or just in global scope) will be the >same place as globals()['x']= unless someone has subverted something. Either way, the binding >of the name to the object happens by evaluating to a "there" within the global dict object, >uniquely associated with the name ('x' here). Evaluated on the right hand side, that name will >produce the reference/pointer again for use in accessing the object or copying to another "there" >associated with perhaps some other name or a target within a composite object like a list or tuple, >or other namespace dict. > >> >>The wart remains, even if my description was wrong. And even that is a >>dubious claim. >> >Every assignment is effectively stores a referential alias for an object, >whether associated with a name or not. This is by design, not a wart. > The details of *how* an assignment "effectively stores" is a longer story though ;-) >>A Python user is interested in how an object behaves - not how it is >>internally implemented in the interpreter. Immutable objects don't >when you say "immutable objects," are you really speaking of names >bound to immutable objects? I.e., the integer 123 is an immutable object >represented by the literal 123. You get an immutable object of the same value >from the expression int('123'). These are the int *objects* -- how does >"behave as references" apply to these actual "immutable objects"? >I.e., could you rewrite your sentence (that this is breaking in two) >to make it perhaps more understandable for me ?;-) > >Names are not objects. Nor are left-hand-side assignment target expressions >in general, whether bare names or complicated. > >ISTM what you are discussing is not about objects but about the way names work, >and ISTM you are thinking of names as if they were C++ variable references, >which they are not, and they couldn't be. For one thing, a C++ reference type >has to be initialized once to refer to a specific object. It can't be made to >refer to something else during the life of that scope. Pointers are a better >model, since you have to distinguish by expression syntax whether you mean >to assign a new pointer value or modify the thing pointed to. In python you >can only assign pointers, if you want to think in those terms. When you >modify a mutable, you are still assigning pointers into some part of the >mutable object representation. When you assign to a bare name, you are still assigning >a pointer into a place in some dictionary object (or workalike). If you >want to modify an object in the usual C sense, you can code it in C and provide a >python interface to your C-implemented object. When you pass arguments >to the various methods of your mutable, you will get pointers that you >can dereference and you can do what you want to your mutable's C data representation. >But when you pass the result back to the python world, it will have to be >as a standard object reference/pointer, and if you assign that, you will be >storing a pointer somewhere. > >>behave as references - the internal use of references for immutable >>objects is basically a lazy copying optimisation and, apart from >>performace and a couple of other technicalities (e.g. the 'is' >>operator), has no relevance. Certainly it has no relevance to the >>point I was making. >> >The way it works is part of the semantics of the language, not just >an optimization issue. > >Names aren't variables. > >HTH ;-) > >I sometimes get things wrong. Corrections welcome. > Regards, Bengt Richter From bgailer at alum.rpi.edu Fri Jul 25 14:20:57 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 25 Jul 2003 12:20:57 -0600 Subject: How to detect typos in Python programs In-Reply-To: Message-ID: <5.2.1.1.0.20030725115739.03ae9638@66.28.54.253> At 07:26 PM 7/25/2003 +0530, Manish Jethani wrote: >Hi all, > >Is there a way to detect typos in a Python program, before >actually having to run it. Let's say I have a function like this: > > def server_closed_connection(): > session.abost() > >Here, abort() is actually misspelt. The only time my program >follows this path is when the server disconnects from its >end--and that's like once in 100 sessions. So sometimes I >release the program, people start using it, and then someone >reports this typo after 4-5 days of the release (though it's >trivial to fix manually at the user's end, or I can give a patch). > >How can we detect these kinds of errors at development time? >It's not practical for me to have a test script that can make >the program go through all (most) the possible code paths. consider: use a regular expression to get a list of all the identifiers in the program count occurrence of each by adding to/updating a dictionary sort and display the result program_text = """ def server_closed_connection(): session.abost()""" import re words = re.findall(r'([A-Za-z_]\w*)\W*', program_text) # list of all identifiers wordDict = {} for word in words: wordDict[word] = wordDict.setdefault(word,0)+1 # dict of identifiers w/ occurrence count wordList = wordDict.items() wordList.sort() for wordCount in wordList: print '%-25s %3s' % wordCount output (approximate, as I used tabs): abost 1 def 1 server_closed_connection 1 session 1 You can then examine this list for suspect names, especially those that occur once. We could apply some filtering to remove keywords and builtin names. We could add a comment at the start of the program containing all the valid names, and extend this process to report just the ones that are not in the valid list. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From maoy_REMOVE_IF_NOT_SPAM at cis.upenn.edu Fri Jul 11 14:50:00 2003 From: maoy_REMOVE_IF_NOT_SPAM at cis.upenn.edu (Yun Mao) Date: Fri, 11 Jul 2003 14:50:00 -0400 Subject: How to get all IP addresses in python? References: <6cd58b6.0307110715.1bb9bc23@posting.google.com> Message-ID: Sorry, this still doesn't work very well on my machine. >>> print socket.getaddrinfo(socket.gethostname(), None) [(2, 1, 6, '', ('127.0.0.1', 0)), (2, 2, 17, '', ('127.0.0.1', 0)), (2, 3, 0, '', ('127.0.0.1', 0))] >>> Any ideas? Thanks! Yun "Steve Pinard" wrote in message news:6cd58b6.0307110715.1bb9bc23 at posting.google.com... > Try socket.getaddrinfo rather than socket.gethostbyname. It returns a > list of tuples. tuple[4][0] of each list element is the IP address. > > addrs = socket.getaddrinfo(socket.gethostname(), None) > for addr in addrs: > print addr[4][0] > > The above worked on my machine but I only have one NIC card. > > - Steve From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 30 08:35:46 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 30 Jul 2003 14:35:46 +0200 Subject: Is there a standard module library function to access /etc/passwd or /etc/group In-Reply-To: <16469f07.0307300416.351ba776@posting.google.com> References: <16469f07.0307300416.351ba776@posting.google.com> Message-ID: <3f27bba2$0$49113$e4fe514c@news.xs4all.nl> Robin Cull wrote: > Hi all, > > I'm writing a script that needs to do lookups on the UNIX passwd and > groups file on textual usernames/group names and return numeric > UID/GID. Would the pwd and grp modules do the trick? http://www.python.org/doc/current/lib/module-pwd.html http://www.python.org/doc/current/lib/module-grp.html --Irmen From intentionally at blank.co.uk Tue Jul 15 04:18:59 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 09:18:59 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> Message-ID: On 15 Jul 2003 07:17:52 GMT, bokr at oz.net (Bengt Richter) wrote: >The syntax is like an optical illusion that can be seen more than one way, >and you are projecting a non-python view onto the syntax, which is interfering >with seeing the other view ;-) I *do* see the other view, honest! (though I admit to mistakes earlier on) I just don't agree with it. >Why don't you respect the possibility of a language that is *designed* to deal >with entities and relationships in ways you are not used to? ;-) Basically, because I've seen too many threads started by confused people who've made a mistake because of this, and because I've made the mistake an annoying number of times myself. It's not just about theory - it's about peoples intuitions about how things should work. >>This is not difficult to achieve. The implementations of the C++ >The difficulty is not really relevant. It's not a goal for this language ;-) A goal of Python is to be a 'very high level language'. Another is to 'do the right thing'. In my view, the current implementation of Python with respect to variable binding is against those goals. Especially in those cases where mutability is abused to fake pointers, but in general too. Am I seriously proposing a change? No. The scope of change needed would be too great - too many knock on effects (such as the pointer stuff), so it wouldn't be Python any more. I don't need to claim that Python is perfect - I've never seen a perfect language - but Python is pretty close. I can live with a couple of warts - even warts that others don't see as warts. >Why assume because some notion isn't used that it means disrespect? I didn't mean 'respect' to be taken that way. The idea of respecting a convention is a common English idiom. It simply means that you do what the convention says. > If you >read "variable" where you should be reading "alias" If I should be reading "alias", then how come the Python manuals say "variable"? >Expand your set of views. I think you will find one where you will see Python >as doing the right thing, for the most part. ;-) Always did, for the most part. I've been using Python since about '96 or '97. There must be some reason why! As it happens, I'm a bit of a programming language obsessive. Mostly, I've only played with languages though - it's just that I've played with a lot of them. A number have fundamental and important ideas that have stuck in my mind. Prolog and SQL for instance - I read somewhere that Prolog is the bit of relational database management that got missed out, and I kind of agree. Icon for generators and backtracking. Miranda for my first taste of functional programming, and Haskell even more so. A few others. Python isn't really a member of that list. OK, there are a couple of things that Python does differently, but nothing really profound that I haven't seen elsewhere. Yet Python *is* my first choice programming language for almost everything where I get a choice - for the prototype if not always for the final code. I would say Python provides a set of tools which are known to be useful from experience. It isn't an experimental language. It doesn't obsess on one particular concept. It is a language for getting things done with very little fuss. When people say I'm wrong and I see that I am wrong, I can admit it and shut up. When people say I'm wrong and I still disagree, even over a technicality, it tends to be a bit like a red rag to a bull - but it's still a philosophical point, really. From peter at engcorp.com Mon Jul 7 07:57:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Jul 2003 07:57:26 -0400 Subject: Python Gurus; "Legend in their own Lunchtime"? References: <3F0927C2.4000604@netspace.net.au> Message-ID: <3F096026.91F89383@engcorp.com> gmduncan wrote: > > But am I the only one to feel discomforted by the many Olympian > (questionable) judgements he scatters through the code, about > every aspect of software development ? A better editor needed ... If they're so questionable, why not question them? About which ones, specifically, do you have a beef? Maybe we can discuss them here, and all agree that the author missed the boat big time one pronouncement X or Y... ;-) -Peter From aahz at pythoncraft.com Sun Jul 13 21:40:32 2003 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2003 21:40:32 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> <3F11C42F.5030406@alcyone.com> Message-ID: In article , David Abrahams wrote: >Erik Max Francis writes: >> >> This is completely incorrect. On the contrary, builtin types are >> handled exactly uniformly in Python. The only difference here is that >> the builtin types that you've listed, along with some others, are >> immutable, so you cannot change them if you have a reference to them. > >All you guys must be forgetting: > > >>> a = [1] > >>> b = a > >>> a += b > >>> assert id(a) == id(b) > >>> a = 1 > >>> b = a > >>> a += b > >>> assert id(a) == id(b) > Traceback... I'm not forgetting that. It's an unfortunate and tricky part of Python semantics in some respects, but it's easily explained and understood if you focus on the objects rather than the operation: a = foo b = a a = a.__iadd__(b) Where id(a)==id(b) depends solely on the behavior of __iadd__(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From pecora at anvil.nrl.navy.mil Wed Jul 2 14:59:05 2003 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 02 Jul 2003 14:59:05 -0400 Subject: (Numeric) should -7 % 5 = -2 ? References: <87k7b6cf3d.fsf_-_@schedar.com> <290620030817191641%pecora@anvil.nrl.navy.mil> <3g32gvcolis4485956egtc35akm6lh3uq5@4ax.com> Message-ID: <020720031459050258%pecora@anvil.nrl.navy.mil> In article , Bob Gailer wrote: > "When an integer a is divided by another m, one has > a = km + r > where the remainder is some positive integer less than m. Maybe I'm misunderstanding this, but what about -7 divided by 5? We get k=-1 and r=-2. m can be negative. Maybe your quote was for the positive integers only. -- Lou Pecora - My views are my own. From staschuk at telusplanet.net Wed Jul 16 04:49:25 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Jul 2003 02:49:25 -0600 Subject: Securing the Pyton Interpreter? In-Reply-To: ; from mwilson@the-wire.com on Tue, Jul 15, 2003 at 11:59:05AM -0400 References: Message-ID: <20030716024925.A3824@tibia.amotlpaa.bogus> Quoth Mel Wilson: > seem to recall there are complications with suid on scripts > .. though I don't recall what they are. A simple example: Let the file insecure_script contain #!/bin/sh grep 'f.*bar' $* This script must not be made setuid-root. Consider: $ cat >grep #!/bin/sh cp /etc/shadow . && chmod 0666 ./shadow ^D $ chmod +x ./grep $ export PATH=.:$PATH $ insecure_script You could deal with this particular problem by using absolute path names for everything in the script, and/or by setting $PATH in the script itself. But there are other holes of this type, and, since shells are complicated beasts, it is very hard to be certain that a script has no exploitable dependencies on matters which are under the user's control. -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From sismex01 at hebmex.com Wed Jul 2 10:22:49 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 2 Jul 2003 09:22:49 -0500 Subject: Suggesting for overloading the assign operator Message-ID: > From: bokr at oz.net [mailto:bokr at oz.net] > Sent: Martes, 01 de Julio de 2003 09:07 p.m. > > [...snippage...] > > I'm not sure what that would mean. > > OTOH, a:=b might lead to analogies with a+=b and other a=b > and then where would we be ;-) > > Let's see... > > a+:=b => a.__update__(a.__add__(b)) > And people say Forth is unreadable. Yeesh. > > ?? ;-) > > Regards, > Bengt Richter > -gustavo -- Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From paul at boddie.net Thu Jul 10 07:15:27 2003 From: paul at boddie.net (Paul Boddie) Date: 10 Jul 2003 04:15:27 -0700 Subject: Python vs PHP References: Message-ID: <23891c90.0307100315.6b901978@posting.google.com> Afanasiy wrote in message news:... > > It would be nice to have a Python equivalent. Unfortunately, for now I > need to just get started on some things myself rather than convince a > bunch of other people to do the same. I suppose this could be the best > way to show so many of the factors I've been listing for months which > are apparently invisible. I'm sure people agree with me, but they do > not participate in Usenet, and are very busy being important. Important or not, the reason for your problems not being addressed is clearly that most associated with certain open source development processes: if the developers don't have the same needs as you have, and if they don't have any incentive to meet those needs, then they won't do the work if they have other things to be getting on with. I seem to remember that you wanted support for per-user isolation within Apache, for example, and I can only imagine that those people developing Web frameworks just don't have the same hosting limitations as you have; therefore, the need remains unsatisfied. > I can also imagine any sort of attempt at comparison, like a benchmark, > or the infamous language shootout, would be absolutely ridiculed. You mean like the "Web Framework Shootout"? http://colorstudy.com/docs/shootout.html Or do you share the views of certain other people on this? http://twistedmatrix.com/users/radix/musings-on-twisted/msg00000.html (Some interesting views on Woven, but a lot of seemingly elitist framework bashing, too.) > I personally consider them fairly useful, but most do not and I am > wary of spending so much time on something which would eventually, or > perhaps not so eventually, devolve into personal attacks. There are and were lots of different comparison charts, documents and resources. Perhaps you could use those as a starting point - I know I wouldn't mind if you adapted my old documents on the subject, and I can imagine that people would welcome contributions to the PythonInfo Wiki as well. Paul From tim at remove_if_not_spam.digitig.co.uk Wed Jul 16 06:12:15 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Wed, 16 Jul 2003 11:12:15 +0100 Subject: Python Quiz References: <84fc4588.0307152253.20858619@posting.google.com> Message-ID: On 15 Jul 2003 23:53:56 -0700, pythonguy at Hotpop.com (Anand Pillai) wrote: >Please try it out if you like quizzing. >Let me know if there are any factual errors. Q7: I think you mean "Modula", not "Module". Actually, I think that all of Q7 is arguable, as /all/ of the languages mentioned are promoted by /some/ of the opensource community, so the answer is pretty much your personal view. From zathras at thwackety.com Tue Jul 8 20:39:31 2003 From: zathras at thwackety.com (Michael Sparks) Date: Wed, 9 Jul 2003 01:39:31 +0100 Subject: Memoizing Generators In-Reply-To: References: Message-ID: <200307090139.32257.zathras@thwackety.com> > Now, the two remaining issues are 1) can we "unify" the generator > memoization with the "standard" memoization and 2) can we deal with lists > as well (i.e. my generator was returning tuples ... since I'm scared of > lists in recursive generator contexts *wink*). > One other memoization issues: what if the args (which will become > keys) are mutables ... in particular, lists. I suppose we could just > tuple() them up? How would you deal with the following generator? (On the assumption you want a a general purpose memoisation mechanism :) def retrieveData(source=None, command=True,blocksize=1024): if source: if not command: fh = open(source, "rb",0) else: fh = os.popen(self.command) else: fh = sys.stdin try: try: while 1: data = fh.read(blocksize) if data: yield data else: raise Finality except Exception, e: if source: fh.close() raise e except Finality: pass If your source is a network connection, or a real user this becomes further indeterminate... Not a suggestion to not try, just worth considering :) The other problem as I see it with your implementation is it expects the generator to terminate. This is far from guaranteed - generators are useful for dealing with infinite sequences/lists and working with functions that might not halt. (eg calculate the best approximation of pi that you can based on time available, not based on number of iterations/memory available) eg def runGenerator(fn,args,timeAlloted): tstart = time.time() gen = fn(args).next r = gen() while 1: if time.time()-tstart >=timeAlloted: break r = gen() return r Consider the possibility that the function is a "next move" in chess and the time is set by the first player to "hard" - ie lots of time. The next time a player comes along with the time set to "easy", the memoised version won't be aware of this in this scenario and returns the hard result (but very quickly...), or worse hits stop iteration - which the original version wouldn't. Or even worse - occasionally hits the StopIteration and normally returns the "hard" result aroung 80-90% of the time. That said memoising _good_ chess results from certain positions _might_ be considered a good thing. It's still an issue though. Regards, Michael. From tjreedy at udel.edu Fri Jul 25 14:11:28 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2003 14:11:28 -0400 Subject: Static typing References: Message-ID: "Michael Muller" wrote in message news:LvdUa.905$DU.696 at fe12.atl2.webusenet.com... > Is there currently any plan to introduce static typing in any future > version of Python? (I'm not entirely sure that "static typing" is the right > term: what I'm talking about is the declaration of types for variables, > parameters and function return values). > > I know there was a "types SIG" which introduced several proposals, but it > expired quite a while ago, and I was wondering whether whether some > consensus has been reached on the subject or if it has just been shelved > indefinitely. AFAIK, There is no consensus and no concrete plans for Python itself. However, there are various third party efforts. Pyrex is, in part, Python + type declarations for C compilation. Weave implicitly types vars as ints or floats. Psyco make declaration unnecessary. Terry J. Reedy From isaac at blueapples.org Thu Jul 24 16:04:15 2003 From: isaac at blueapples.org (Isaac Raway) Date: Thu, 24 Jul 2003 15:04:15 -0500 Subject: easy way to remove nonprintable chars from string In-Reply-To: <2b012c5e.0307241138.177e5c8c@posting.google.com> References: <2b012c5e.0307241138.177e5c8c@posting.google.com> Message-ID: <3F203BBF.2060408@blueapples.org> This seems to work. Not sure how fast it'd be, though. def stripNoPrint(str): results = "" for char in str: if string.printable.find(char): results += char return results Don Hiatt wrote: >Greetings, > >Is there an easy way to remove multiple non-printable >(e.g. "not strings.printable") from a string? Perhaps >something like foo.replace(list_of_nonprintables, '') >if it only existed? :-) > >Cheers, > >don > > From pahan at gmx.net Sun Jul 13 09:26:35 2003 From: pahan at gmx.net (PenguinOfDoom) Date: 13 Jul 2003 06:26:35 -0700 Subject: Reading packets from a tun device. References: Message-ID: <76590c5.0307121834.612633ca@posting.google.com> Andre wrote in message news:... > I'm trying to read packets from a tun device in Python, the code I used > for this is the following: > > f = file( '/dev/tun0', 'r+' ) You appear to be using the ethertap driver. That is obsolete. You want the new tuntap driver (module tun). Also, Twisted (www.twistedmatrix.com) can conveniently handle tuntap devices. You'll have to get the CVS version. The code is in twisted.pair.tuntap. This is not terribly tested or stable. Low-level functionality (opening the tuntap device) is provided by the Eunuchs project. I can't seem to find a website for it, but the module is available in Debian as python2.2-eunuchs. You could poke Tommi Virtanen for more details. He's Tv on irc.freenode.net From jorgenhansen at hotmail.com Tue Jul 22 14:40:16 2003 From: jorgenhansen at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Hansen?=) Date: 22 Jul 2003 11:40:16 -0700 Subject: Tkinter Listbox looses selection on Tab Message-ID: <117880a1.0307221040.60a27c0d@posting.google.com> Hi I have a problem with a Listbox in Tkinter. When I tab through several widgets with the tab-key, the listbox looses its selection, even though it has been selected with .selection_set. The example below demonstrates this. Can anyone provide me with some help on this? Regards Jorgen Ps. I'm on a W2K machine with Python 2.2.2 ---- from Tkinter import * root = Tk() colors = ['Yellow', 'Black', 'White', 'Green'] lb = Listbox(root) for color in colors: lb.insert(END, color) lb.selection_set(0) lb.pack() Entry(root).pack() root.mainloop() ---- From hannibal1812 at canada.com Fri Jul 4 21:48:15 2003 From: hannibal1812 at canada.com (hannibal) Date: Sat, 05 Jul 2003 02:48:15 +0100 Subject: Python in Excel In-Reply-To: <873chm9w7o.fsf@pobox.com> References: <1u3Na.12730$U23.8210@nwrdny01.gnilink.net> <873chm9w7o.fsf@pobox.com> Message-ID: You can use Microsoft Script Control. If you have the win32 extensions of python, you can use python in place of vb in this control -open the VBA script editor - In menus/Tools/References add Microsoft Script Control -Make a new module and declare a new MsScriptControl.ScriptControl Global sc as new MsScriptControl.ScriptControl -Initialize the language attibute with python - Note that you and users of your document must have python and its win32 extensions installed. Activestate python distribustion include it. You can put sc.language="python" in the routine Workbook_Open() Now you can import python modules using ExecuteStatement method of the control in vba and have results from python functions with eval method. One interesting thing is that you can pass an object to the control with AddObject method and have python manipulate it. And so on.. John J. Lee a ?crit : > "Tom Locke" writes: > > >>>>Can I write Excel macros/scripts using Python? >>>> >>>>I mean to actually put Python into an Excel document, not using >>>>Python to access data, for example, from some Excel document. >> >>These days you can script office with any .NET language, and that includes >>Python: > > [...] > > Or use good old COM. There's an example of controlling Excel (the > version from Office 2000) in the Python for Windows Extensions (aka > win32all) COM test code. IIRC, it'll be somewhere like > C:\Python\win32com\tests\. > > > John --- Posted via news://freenews.netfront.net Complaints to news at netfront.net From grante at visi.com Mon Jul 7 13:31:29 2003 From: grante at visi.com (Grant Edwards) Date: 07 Jul 2003 17:31:29 GMT Subject: anything new on the ternary operator? References: Message-ID: <3f09ae71$0$638$a1866201@newsreader.visi.com> In article , John Hunter wrote: >>>>>> "Tim" == Tim Peters writes: > > Tim> There were many creative interpretations of the vote counts, > Tim> but none of them showed the consensus Guido said at the start > Tim> would be needed for adoption. > > Perhaps there is a lesson for the next time a vote count comes around. > Although there wasn't a consensus on the syntactical form of a ternary > operator, there may be a consensus for the existence of one. This > suggests a runoff step is needed Holy cow, didn't you notice the endless threads on voting methods? There were two votes, both of which had various "instant runoff" sort of features. -- Grant Edwards grante Yow! Catsup and Mustard at all over the place! It's visi.com the Human Hamburger! From ____indru_june at yahoo.com____ Wed Jul 9 04:22:16 2003 From: ____indru_june at yahoo.com____ (indru) Date: Wed, 09 Jul 2003 08:22:16 +0000 Subject: Application Development in Python Message-ID: <3089454.1057738936@dbforums.com> Hi all, I am new to Python programming. I am from C,C++,Perl background. I am quite convinced by the possibilities python as a very high level language is offering. I am seriously thinking of using python in my project which is to create a accounting software. First thing came to my mind was C++ but the time required could be enormous and my people are not ready to wait that long. The project is a medium sized one but bigger than something like gnucash and KMyMoney2. Do any body have experience with application development using python and their experiences ?. Also please advice me whether Python can be used for such purposes. Thanks in advance Indru -- Posted via http://dbforums.com From ben at dadsetan.com Thu Jul 10 02:56:14 2003 From: ben at dadsetan.com (Behrang Dadsetan) Date: Thu, 10 Jul 2003 08:56:14 +0200 Subject: Deleting specific characters from a string In-Reply-To: References: <3F0C851C.4000500@livinglogic.de> <3F0C8AC3.5010304@dadsetan.com> Message-ID: Bengt Richter wrote: > On Wed, 09 Jul 2003 23:36:03 +0200, Behrang Dadsetan wrote: > ====< removechars.py >======================================================== > def removeChars(s, remove=''): > return s.translate( > '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' > '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' > ' !"#$%&\'()*+,-./' > '0123456789:;<=>?' > '@ABCDEFGHIJKLMNO' > 'PQRSTUVWXYZ[\\]^_' > '`abcdefghijklmno' > 'pqrstuvwxyz{|}~\x7f' > '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f' > '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f' > '\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf' > '\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf' > '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf' > '\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf' > '\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef' > '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' > , remove) It looks to me like serious overkill. If I would put in a method like that somewhere in my code, my colleagues would never talk to me again ;) Ben. From pxtl at hotmail.com Wed Jul 30 11:25:15 2003 From: pxtl at hotmail.com (martin z) Date: Wed, 30 Jul 2003 15:25:15 GMT Subject: Controlling what built-in modules Python compiles with? Message-ID: I'm having a lot of trouble figuring out the details of controlling Python compiling. I can compile and embed just fine, but I want some finer granularity on what gets compiled into Python. I can find little to no documentation of the compiler flags besides the ones essential to operating system compatibility. How does one choose what built-in modules are compiled into Python? I ask because newer versions are accumulating more and more unneeded features for my embedded app. For example, it seems unnecessary bloat to compile with zipimport if all the modules I plan to use are being loaded in directly by the embedding app. From fw at deneb.enyo.de Thu Jul 24 16:00:22 2003 From: fw at deneb.enyo.de (Florian Weimer) Date: Thu, 24 Jul 2003 22:00:22 +0200 Subject: Regex: Limiting Scope without capturing results References: <173ef463.0307240355.cf896bb@posting.google.com> Message-ID: <87oezjsnjd.fsf@deneb.enyo.de> megalith at btinternet.com (Gordon Chapman) writes: > Or a way of telling them to limit the scope of the match without > capturing the result ? You are looking for (?:foo|bar). From aahz at pythoncraft.com Tue Jul 22 23:58:16 2003 From: aahz at pythoncraft.com (Aahz) Date: 22 Jul 2003 23:58:16 -0400 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: In article , Marc Wilson wrote: > >Groovy. I may become a Python convert. *sigh* I've not finished learning >perl yet, and now I've got a new shiny toy. :) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From perrego at mail.buffnet.net Thu Jul 17 00:24:38 2003 From: perrego at mail.buffnet.net (Mark Perrego) Date: Thu, 17 Jul 2003 00:24:38 EDT Subject: anything like C++ references? Message-ID: <200307170424.h6H4Os3R002263@buffnet4.buffnet.net> I've been trying to follow this thread, mainly to make sure that how I think python works is how it actually does work. I was confused by (paraphrasing) "in math, variables are bound to values, and values don't change, and python doesn't work that way." I was saying to myself, "yes it does." And now I think I know why: >Stephen Horne wrote: >If I type... > > >>> a = [1, 2, 3] > >>> b = a > >Then in my mind, the point is that both variables get bound to the >value '[1, 2, 3]'. I don't believe this is the case. At least not for your concepts of "variable", "bound" and "value." To say it in (what I think are) your definitions of those terms... >>> a = [1, 2, 3] At this point, a is bound to a value which is a reference that refers to the list '[1, 2, 3]'. The list referred to by the value bound to a contains 3 references, which refer to the integers 1, 2 and 3. >>> b = a At this point, b is bound to a value which is another reference to the same list. >If I now type... > >>>> b[2] = 4 > >Then the variable b should now be bound to the value '[1, 2, 4]'. Why? You didn't change the binding of b. You changed the binding of the third spot in the list referred to by b. Or to be more explicit "... referred to by the value bound by b". >That is the whole point of what I've done. However, the fact that it was >achieved by modifying a part of an object is an implementation detail. But in reality, modifying an object is what you told python to do. You asked to modify the list to throw away the previous reference it was holding in the third spot and to put another one in its place. >It should not affect the *value* bound to the variable a. In other It doesn't affect the value bound to the variable a. The variable a is still bound to the same value. That value is a reference to a particular list. That list was modified. >words, a new object should be created at that point - a copy of the >original - which would then be modified. That way, the mathematical >concept of variables being bound to values would be respected. A copy of the original reference to the integer 3 is created, and modified to refer to the integer 4, then bound to the third spot in the list, replacing the original. But this would violate the "values are immutable" concept so how about the new reference refers to the integer 4 when it is created. I don't know which is correct, and I don't know how you could tell. Others, I believe, have used the term "bound" to mean what I am calling "referred to" which may be part of my confusion as I tried to pick which meaing of "bound" to take. Take all this with a grain of salt. Its me trying to explain how I think python works in what I think are your terms. And then there are the problems between my brain and my fingers. Am I missing your point? I know you don't _like_ that python binds variables to values that are references, but do I have straight what you mean by variable, bound and value? Thanks, - Mark From madsurfer2000 at hotmail.com Sun Jul 20 04:27:24 2003 From: madsurfer2000 at hotmail.com (-) Date: 20 Jul 2003 01:27:24 -0700 Subject: Strings and Unicode Message-ID: I have a function that takes a string as an input parameter. This function then urlencodes the string and sends it to a server with telnetlib.Telnet The problem is that the string gets converted into what seems to be Unicode. How can I check to see if the input-string is Unicode and convert it to a different character set (in this case ISO-Latin1). From paulpaterson at users.sourceforge.net Sat Jul 12 19:57:39 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sat, 12 Jul 2003 23:57:39 GMT Subject: ANN: vb2py-0.1 released Message-ID: Version 0.1 of vb2py has been released. What is vb2py? ============== vb2py is a toolkit to aid in the conversion of Visual Basic projects to Python (using PythonCard). The conversion will eventually include both forms and code (modules and classes). Version 0.1 is mainly a form layout converter to PythonCard with a very simplistic code translation. The project roadmap (http://vb2py.sourceforge.net/roadmap.htm) shows the project's development timeline. Converting VB to Python turns your VB projects into cross platform developments and allows full access to all Python's extensive library of modules. Getting the Software ==================== * The main website: http://vb2py.sourceforge.net * Download this version: http://vb2py.sourceforge.net/downloads.htm * Documentation: http://vb2py.sourceforge.net/documentation.htm Requirements ============ * Python 2.1 or greater * PythonCard * simpleparse (not used in the 0.1 code but required to use the experimental VB parser) * Visual Basic is *not* required (although it would help if you had some VB code ...) Licence ======= vb2py is released under the BSD licence. Release History =============== This is the first public release from the project. Contributors Welcome ==================== In a project like this one there are many ways people can contribute. Coding, testing, advice, etc are all valuable and much appreciated. ---- Paul Paterson (paulpaterson at users.sourceforge.net) vb2py :: A Visual Basic to Python Conversion Toolkit http://vb2py.sourceforge.net From ianb at colorstudy.com Wed Jul 30 12:58:00 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2003 11:58:00 -0500 Subject: Web tool kit : pro - cons ? In-Reply-To: References: Message-ID: <1059584280.12753.159.camel@lothlorien> On Wed, 2003-07-30 at 11:00, Jeffrey P Shell wrote: > >> Other tools try the O-R > >> mapping route for abstraction with varying degrees of success. > >> SkunkWeb has PyDO, Webware has one (I can't remember its name right > >> now). Zope's model is nice because it's not intrinsic to Zope that > >> you use SQL - it's just a nice model to plug into if you need it, when > >> you need it. I don't know how other toolkits stack up here. Some may > >> just say "go find a Python adapter that works for you and do what you > >> want with it", which seems to be as good of a way to go as any. > > > > PyDO and MiddleKit (Webware's) are both independent of their frameworks > > (it's kind of unfortunate that they appear to be tied, though), as are > > the other ORMs (like my SQLObject). All three provide something > > approximating business objects built around database rows. > > They all put the model too close to the Python code for my personal > comfort. Sometimes that's good. Other times, not so much. > > A couple of more interesting systems are Modeling ( > http://modeling.sf.net/ ) and Ape ( > http://hathaway.freezope.org/Software/Ape ). I don't really see the advantage of Modeling -- it seems terribly verbose to me, though I suppose that's because of its origins in Objective C. I don't see any advantage to separating the mapping from the class -- it's all code, it's all written by the same people, and if you need separate people to handle the pieces and you can't let them both work with the same class, either you don't have enough communication between people or you are making the whole thing a lot more difficult than it should be. Modeling feels too formal to me -- more like Java than Python. A Python ORM doesn't have to be hard. APE seems like the other side of formal, where it tries too hard to seamlessly support every Python object and in the process is just another object database (ala ZODB) that happens to be able to use a relational database as a backend. A relational database cannot hold arbitrary Python objects unless you want to ruin everything that's good about a relational database. What notions of inheritance that can be implemented have significantly different semantics than Python inheritance (and composition is usually better than inheritance anyway, and that is well supported by relational databases). Attributes aren't columns, Python types aren't database types. Relations are a different environment all around. I personally can't see the use case where you'll want to radically change storage mechanisms while leaving a business class alone. Yes, you may want to radically change the storage -- but it only matters that the *interface* to that class can stay the same, not that the entire class implementation is storage-neutral. That it requires some effort and thought to move from an RDBMS to a flat file (for instance) is not a big problem in my mind. Moving from, say, Postgres to MySQL without effort *is* nice, and achievable without having separate mapping objects. I think if APE is going to be relational, it has to be more like an ORM. And, for what it's worth, SQLObject does have a DBM-based backend (which is largely equivalent to a flat file backend), that is fully functional, including selects and joins. It's not that efficient -- but it could be. But having written that storage mechanism, I still think it's little more than a parlor trick, a clever abstraction that appeals to a programmer but offers little real benefit. The DBM backend is just an embedded relational database, and SQLite is a much better embedded relational database, so you might as well use that. If it shows anything, it is that the queries that SQLObject uses are portable beyond SQL, should you ever need to do that. Ian From cpl.19.ghum at spamgourmet.com Thu Jul 17 13:39:26 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 17 Jul 2003 19:39:26 +0200 Subject: html tags and webpages References: Message-ID: gret, google for dive into python. Exactly your job is described there in great detail, with examples. Best wishes, harald From skip at pobox.com Thu Jul 31 09:06:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Jul 2003 08:06:29 -0500 Subject: time, calendar, datetime, etc In-Reply-To: References: <153fa67.0307300326.45a29380@posting.google.com> Message-ID: <16169.5205.337041.191993@montanaro.dyndns.org> >> Maybe. Perhaps you would like to write a PEP? Ben> I would think that is best left up to those who know what they're Ben> doing... I'm just a newbie who's found date and time handling in Ben> Python to be confusing, and thought I'd mention it. (And I am the Ben> original poster, btw.) If nobody else agrees, maybe it's not Ben> really a problem. Yeah, but you spoke up. ;-) There are probably lots of people willing to throw stones at^H^H^H^H^H^H^H^H^H^H^H^H^H^H^Hcomment on your work, and since this would largely be a reorganization of existing modules, there wouldn't be all that much Python knowledge required (except that backwards compatibility is a requirement for 2.4). In any case, if you have concrete ideas about how the three should be merged into two, a PEP's the best place to document it. Your ideas will largely be lost if the python-list archive is the only place they are recorded. Ben> Well, one could say that its very existence makes it special. Ben> Technically asctime() is redundant as you can achieve the same Ben> effect with time.strftime(). I believe asctime() predates strftime() as a C library function by quite a bit. Ben> Yet it's in the library. Since time.asctime() exists as a special Ben> case, we're assuming that the use of that particular string format Ben> has some intrinsic merit. In particular, a lot of programs written Ben> in C may use it for logfiles. Therefore it makes sense (to me) to Ben> implement the inverse ("timeasc"?). I couldn't pick an asctime()-generated date out of a lineup. For most logging I think it makes sense to use sortable numeric dates (ISO-8601). Besides sortability, they are indifferent to language and unambiguous. There are many little variations in "human readable" dates, even those which are so-called standards. Someone always gets things "wrong". Quick, what's the format of an RFC-822 date? Is it the same as an RFC-2822 date? What about RFC-1036? RFC-850? Not that I have any claim to have been complaining loud and clear about this problem back in 1982 and 1983 when these RFC were written (or earlier, when the systems they codified were first developed), but I don't think there's any use in further propagating arcane date formats. Skip From frobozz_electric at hotmail.com Wed Jul 2 11:21:14 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 2 Jul 2003 15:21:14 GMT Subject: Newbie advice for string fromatting References: Message-ID: I don't know whether this is efficient, but its an example of your code in a form that actually works: words = {"adverb":None, "noun":None, "verb":None, "tool":None} keyorder = ["adverb", "noun", "verb", "tool"] # modify dictionary in this order for word in keyorder: print "\nEnter a(n)", word, ": ", words[word] = raw_input() print "\nThe %(adverb)s %(noun)s %(verb)s with a %(tool)s." % words "gt" wrote in message > libs = ["adverb", "noun", "verb", "tool"] > words = {a:j, n:j, v:j, t:j} For the code above to work as-is, all of a, n, v, t, and j would have to be variables (which is not the case). In my version, I've used your libs words as keys to the dictionary, and I've given each dictionary item a value of None to start with. Also, since dictionaries do not maintain items in the order that they are added, and because you appear to want to ask for words in a particular order, I've used the list 'keyorder'. If order was unimportant, you could get rid of keyorder altogether and just use: ... for word in words: ... ... But then you get things like "Enter a(n) tool: ", "Enter a(n) noun: ", etc... [snip] > print "The %s %s %s with a %s." % (a, n, v, t) Instead of using the "string" % tuple, you can also use "string with keywords" % dict, which allows you to re-use your 'words' dictionary (no need to create variables a, n, v, t). HTH Sean From bignose-hates-spam at and-zip-does-too.com.au Thu Jul 17 22:03:23 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 18 Jul 2003 11:53:23 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: On Thu, 17 Jul 2003 11:53:05 +0100, Alan Kennedy wrote: > JanC wrote: >> The verb "gignooskoo" (trying to write it with Latin letters ;) > Why limit yourself to that nasty little us-ascii alphabet? >;-) Because it will display reliably on any computer. > Here it is in a format where almost everybody will be able to see the > original greek verb on their screen. > [instructions to cut and paste to a file, then open in a limited range > of programs, on computers possessing the appropriate font] > > So, the challenge to the ASCII proponents is: put the greek word > "gignooskoo" on everybody's screen, originating from a usenet message, > in the original greek, where "oo" -> greek letter omega. Challenge accepted: Open any drawing program. Draw, in order from left to right, the Greek characters gamma, ipsilon, gamma, nu, omega, sigma, kappa, omega. Done. The desired word now appears on the screen. Oh, what's that -- you say that's cheating because the user has to use particular programs? Perform manual steps? Have some existing knowledge about the process? That the process may fail for any of these reasons? Those are attributes of the "simple" process of manually manipulating XML content you gave. Not every computer is capable of automatically displaying Greek characters. Even for those which can, there's not yet a universal way to instruct them to do so. Hence, it is not possible to have any computer automatically display a word with Greek characters. But you already knew that, so why the silly challenge? -- \ "Behind every successful man is a woman, behind her is his | `\ wife." -- Groucho Marx | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From Kyler at news.Lairds.org Thu Jul 31 20:18:36 2003 From: Kyler at news.Lairds.org (Kyler Laird) Date: Fri, 01 Aug 2003 00:18:36 GMT Subject: Secure FTP in Python? References: Message-ID: "d z e k y l" writes: >Or is there some other >(noncomplicated) way how secure uploading can be implemented in Python? About anything is less needlessly complicated than FTP. SSH is often the obvious choice, but WebDAV can also run over SSL. --kyler From Kepes.Krisztian at peto.hu Thu Jul 3 03:35:50 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Thu, 03 Jul 2003 09:35:50 +0200 Subject: Py + CGI or other ? Message-ID: Hi ! I want to substitute/replace my php site to python, 'cause I fall in love with Python, and not want to continue the work with php. A question: - how to I make the change ? So, I take an interest in Python+Web. Where I starting this learning ? 1. I use php used in module, not in cgi ? The python can load to apache in module ? 2. Or I must create an CGI library ? 3. The BaseHTTPServer is good for starting an cgi development ? 4. Can the python handle the session of web browsers ? 5. Can the python access other db servers (not mysql) ? Thx: KK From max at alcyone.com Sat Jul 5 02:01:25 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 04 Jul 2003 23:01:25 -0700 Subject: print attitude References: Message-ID: <3F0669B5.679FB505@alcyone.com> "Batista, Facundo" wrote: > Is this OK? > > Why this different behaviour? It's str vs. repr, and unfortunately it generates no end of confusion. Let's make a simple object so we can clearly see the difference: >>> class Display: ... def __str__(self): return '(str)' ... def __repr__(self): return '(repr)' ... >>> d = Display() >>> str(d) '(str)' >>> repr(d) '(repr)' So whether the str or repr of the object is called, we can tell the difference. Now, consider: >>> print d (str) >>> d (repr) >>> [d] [(repr)] >>> print [d] [(repr)] Printing an object prints its str, but simply specifying it as the value of an expression in the interactive interpreter prints the repr. What you're seeing is that both the str _and_ the repr of builtin container types print the _repr_ of their elements. I consider this something of a wart, but the rationalization is that it might be confusing if the str were used when using (say) list.__str__ since it might contain spaces or commas itself. >>> [' ', 'a, b', 'c', ' '] [' ', 'a, b', 'c', ' '] If that were the str of the elements, it might be confusing: >>> '[%s]' % ', '.join(map(str, [' ', 'a, b', 'c', ' '])) '[ , a, b, c, ]' I see the reasoning, but I'm not sure the benefit of the decision outweighs the confusion it constantly calls. (This, along with standard floating point equality questions, are probably the most frequently asked questions about Python.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ But since when can wounded eyes see / If we weren't who we were \__/ Joi From paul.m at speakeasy.net Sat Jul 26 17:28:41 2003 From: paul.m at speakeasy.net (Paul M) Date: Sat, 26 Jul 2003 17:28:41 -0400 Subject: Pythoness In-Reply-To: <3rnav-q64.ln1@beastie.ix.netcom.com> References: <3f2115e6$1@news.012.net.il> <3rnav-q64.ln1@beastie.ix.netcom.com> Message-ID: <3F22F289.9080906@speakeasy.net> Dennis Lee Bieber wrote: > Avner Ben fed this fish to the penguins on Friday 25 July 2003 05:34 am: > > >>The following is from the "A Word A Day" newsletter >>(http://www.wordsmith.org/awad/subscribe.html) of 22 July 2003. I >>thought you'd find it amusing... >> >> >>>pythoness (PIE-thuh-nis) noun >>> >>> 1. A woman with the power of divination. >>> >>> 2. The priestess of Apollo at Delphi in Greek mythology. >>> > > Hmmm, I'd always seen the priestess referred to as "the Pythia" (or > something similar). > For more on Pythia and Delphi see a recent Scientific American article: http://www.sciam.com/article.cfm?articleID=0009BD34-398C-1F0A-97AE80A84189EEDF&pageNumber=1&catID=2 If that URL get's munged, just go the the Scientific American homepage and search on "Delphi" --Paul From aahz at pythoncraft.com Thu Jul 10 15:54:14 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2003 15:54:14 -0400 Subject: Embedding Python, threading and scalability References: Message-ID: In article , Wenning Qiu wrote: > >My project will be running on an SMP box and requires scalability. >However, my test shows that Python threading has very poor performance >in terms of scaling. In fact it doesn't scale at all. That's true for pure Python code. >The fundamental reason for lacking scalability is that Python uses a >global interpreter lock for thread safety. That global lock must be >held by a thread before it can safely access Python objects. Correct. The problem is that the GIL makes Python more efficient in many ways, because there's no need for fine-grained locking. You're using Python inside-out for this purpose -- the way to scale Python in a threaded environment is to call out to a C extension that releases the GIL. >Has anyone on this list run into the same problem that I have, or does >anyone know of any plan of totally insulating multiple embedded Python >interpreters? Sure! Use multiple processes. Other people have mentioned Perl and Tcl in this thread. I wonder how they deal with the problem of loading DLLs with static data. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From galen at grex_nospam_.org Tue Jul 8 17:08:43 2003 From: galen at grex_nospam_.org (trewornan) Date: Tue, 08 Jul 2003 22:08:43 +0100 Subject: mx odbc References: <3f0accb5$0$13191$edfadb0f@dread15.news.tele.dk> Message-ID: On Tue, 08 Jul 2003 18:04:11 +0200, M.-A. Lemburg wrote: > Having a maintained and actively supported ODBC interface which > works on all major platforms, not just Windows ?! Agreed that this must be a lot of work but most of us use open source software for a reason. Certainly the licensing of mxODBC was the main reason I choose to use the mySQL module directly instead. Trewornan From tim.one at comcast.net Fri Jul 11 22:47:21 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 11 Jul 2003 22:47:21 -0400 Subject: The "intellectual property" misnomer In-Reply-To: Message-ID: [Guido] >> The PSF holds the intellectual property rights for Python [Ben Finney] > Ugh. Please don't propagate this ridiculous, meaningless term. It's > used to refer to a wide range of greatly disparate legal concepts; to > use it as a single term implies that there's some unifying > "intellectual property" principle joining them together, which is a > falsehood. Guido isn't writing a treatise on the law, he's briefly explaining (part of) what the PSF does. I doubt many are confused by what he said, and you proved you're not: > If the PSF holds the copyright to Python, please say that. > > If the PSF holds patents which cover Python, please say that. > > If the PSF owns the trademark for Python, please say that. > > If the PSF has trade secrets in Python, please say that. So you somehow managed to divine Guido's intent from that "ridiculous, meaningless term" <0.5 wink> -- part of the PSF's business is indeed dealing with all legalities affecting the use of Python. I don't think pedantic verbosity makes it any clearer, but may mislead due to omission. > But please *don't* muddy the water by saying the PSF holds "the > intellectual property rights" for Python. That says nothing useful -- > it doesn't help determine which of the above fields of law are > applicable -- and only promotes the idea that all these different > fields of law are part of a whole, which they are definitely not. A goole search just now got close to 30,000 hits on "IP law", with a striking similarity of meaning across the dozen I browsed. The idea that what Guido meant by the above is obscure defies common sense, and I know for a fact that he didn't author at least 25,000 of those web pages . From srijit at yahoo.com Fri Jul 11 06:52:46 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 11 Jul 2003 03:52:46 -0700 Subject: Python Documentation Message-ID: <221d8dbe.0307110252.7d44b63a@posting.google.com> Hello, I do not see any discussion of new style classes in tutorial section of Python 2.3b1 core documentation. I hope that I have not missed any section. Though there are many separate documents on this topic, I thought that it was good idea to have them all included in core documentation. Is there any plan to improve the tutorial section fo Python core documentation? Otherwise Python documentation is quite good. Regards, Srijit From vze4rx4y at verizon.net Tue Jul 15 03:09:01 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 15 Jul 2003 07:09:01 GMT Subject: Mix lambda and list comprehension? References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> Message-ID: Try this: >>> [lambda x, y=y:x+y for y in range(10)][4](2) 6 It is important to bind y in a closure at the time the lambda is defined. Otherwise, y remains unbound until you invoke the function call. At that time, the most recent value of y is the last value in the range loop (namely, 9). Raymond Hettinger "Peter Barth" wrote in message news:6f5b3f88.0307142302.1a1531f3 at posting.google.com... > Hi, > trying to mix lambda expresions and list comprehension > doesn't seem to work. > --- > >>> [lambda x:x+y for y in range(10)][9](2) > 11 > >>> [lambda x:x+y for y in range(10)][4](2) > 11 > --- > I expected the second expression to return 6. > What did I do wrong? Any hints? > Thanks > - Peter From lorenb2 at bezeqint.net Sun Jul 27 22:10:01 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Mon, 28 Jul 2003 04:10:01 +0200 Subject: Debugging Python ? Message-ID: <008a01c354ad$5a52d840$6400a8c0@EVOD31> Hi'ya ppl, I'd be happy to hear your techniques to debug python programs. Is there any interactive debugging environment by any chance ? thanks in advance, B From adechert at earthlink.net Sun Jul 20 22:42:18 2003 From: adechert at earthlink.net (Alan Dechert) Date: Mon, 21 Jul 2003 02:42:18 GMT Subject: Possible use of Python for a voting machine demo project -- your feedback requested References: <7xk7acai97.fsf@ruckus.brouhaha.com> <7x8yqstzf3.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x8yqstzf3.fsf at ruckus.brouhaha.com... > "Alan Dechert" writes: > > You make a lot of good points. As I understand it, Canada administers > > national, province, and local elections separately. They happen at > > different times and are conducted by different entities. The U.S. is one of > > very few where you see federal, state, and local contests on the same > > ballot. > > The US does not have federal contests. All elections for federal > office are actually state contests. That includes Presidential > elections, which are a bunch of state contests for slates of electors > from the individual states. That all the elections are state contests > and not federal ones is one of the reasons it's hard to impose uniform > national standards on how the elections are run. > I think you have a point but there is a symantics problem. It's true that the U.S. Constitution gives most (almost all) of the authority for conducting elections to the states. You're correct to say that this makes the establishment of "uniform national standards" highly problematic. Nonetheless, we plan to address this. This is a *very* involved subject. Have a look at our proposed Election Rules Database http://home.earthlink.net/~adechert/ucvs-proposal.rtf Some other details can be found here: http://home.earthlink.net/~adechert/votingstudydialog.txt Then there's the concept of "Regulatory Capture." We intend to drive the discussion of how to resolve contradictions in the current voting system. However, to say that "The US does not have federal contests" leaves me nonplussed. Federal elections involve the election of federal officials -- e.g., Congress, President, Vice President. We have the Federal Election Commission, which looks like it's being replaced by a host of commissions. You'll find the phrase "federal election" quite a few times on this page: http://www.fec.gov/hava/eac.htm --Alan Dechert From delphiro at zonnet.nl Thu Jul 3 10:27:39 2003 From: delphiro at zonnet.nl (delphiro) Date: Thu, 3 Jul 2003 16:27:39 +0200 Subject: Python is a gem, you need to keep pushing it .... In-Reply-To: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: <20030703162739.6e4e4023.delphiro@zonnet.nl> Same story here, My company primarily uses Delphi (Object Pascal) which is actualy a nice development language / IDE but with linux as a rising star and Kylix as a nasty and not-so-friendly-and-platform-indepandent Delphi-clone we have decided to use Python for a number of small projects. As a python addict I really hope this works out! No offence, but I'd rather be using Emacs and Python than the Delphi IDE. It is so much more fun and it runs on Linux *and* Windows (ok and more.. but those are our target OS'es). We now have a team of 4 Python addicts trying to convince our bosses and the 30+ Delphi developers. I realy hope this works out :-) Regards, Rob -- [-------------delphiro-------------] [-- http://pyciv.sourceforge.net --] [----------------------------------] From cookedm+news at physics.mcmaster.ca Thu Jul 3 21:44:27 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 03 Jul 2003 21:44:27 -0400 Subject: Auto free Buffer objects in C API? References: Message-ID: At some point, "Stuart D. Gathman" wrote: > I have a Python C module (dspam.c - http://bmsi.com/python/milter.html). > It needs to return some large buffers allocated by the library I am > wrapping. The buffers must be freed by the caller when finished. At > present, I do the following to copy, then free the buffer: > > PyObject * > toBuffer(char *buf;int len) { > PyObject *sig = PyBuffer_New(len); > if (sig) { > void *data; > int dlen; > if (!PyObject_AsWriteBuffer(sig,&data,&dlen)) > memcpy(data,buf,dlen); > else { > Py_DECREF(sig); > sig = 0; > } > } > free(buf); > return sig; > } > > Now, I would like to use PyBuffer_FromMemory(buf,len), but then I have no > way of knowing when to free(buf). Or do I? Am I missing something? Is > there a way for me to know when the Buffer object is being deleted so > that I can free the underlying C data? Staring at the definition of PyBufferObject in bufferobject.c, I see it has a member 'b_base' of type PyObject *, which is DECREF'd when the buffer is destroyed (by the buffer dealloc function). Looks to me like you could do something using a CObject with a passed destructor: /**********/ /* WARNING: UNTESTED CODE */ /* the contents of PyBufferObject are supposed to be private, so you need to include this */ typedef struct { PyObject_HEAD PyObject *b_base; void *b_ptr; int b_size; int b_readonly; long b_hash; } PyBufferObject; PyObject * toBuffer(char *buf, int len) { PyObject *sig = PyBuffer_FromMemory(buf, len); if (sig) { /* pass 'free' as the destructor for the passed memory */ (PyBufferObject *)sig->b_base = PyCObject_FromVoidPtr(buf, free); } return sig; } /**********/ Now, when the buffer is deallocated, the CObject at b_base will be DECREF'd, which will free your memory. This is a bit ugly, as it depends on internal details. Another, cleaner, method is to define an object which obeys the buffer protocol, and handles destruction like you want. (This is annoying, as you'll end up copying all the code in bufferobject.c). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From LogiplexSoftware at earthlink.net Tue Jul 1 17:53:20 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 01 Jul 2003 14:53:20 -0700 Subject: Suggesting for overloading the assign operator In-Reply-To: <3F01CC7B.F71C4C0B@hotmail.com> References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <2259b0e2.0307010328.1e1b4a04@posting.google.com> <6f03c4a5.0307010910.35ca3158@posting.google.com> <3F01CC7B.F71C4C0B@hotmail.com> Message-ID: <1057096400.1457.20.camel@software1.logiplex.internal> On Tue, 2003-07-01 at 11:01, Alan Kennedy wrote: > Not that I'm proposing that the OPs solution be adopted. Just that I think he is > addressing a valid concern. I agree that it is a valid concern. I think, however, that other valid concerns outweigh this one. I suspect you think so as well, otherwise you would have omitted the first sentence. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From skip at pobox.com Wed Jul 9 11:55:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 9 Jul 2003 10:55:11 -0500 Subject: QUESTION In-Reply-To: References: Message-ID: <16140.15071.44316.897109@montanaro.dyndns.org> >> I do not ever recall seeing "python" in the programs. gustavo> Compaq didn't bundle Python with it's computers, if that's what gustavo> you're asking. >> I have been having alot of problems with my computer lately and I am >> removing unecessary "junk". gustavo> Then, by all means, enter the control panel, select "Add or gustavo> Remove Programs", look for Python's entry and double-click on gustavo> it to remove it. I think you might want to be careful about deleting Python from your COMPAQ. It appears that COMPAQ did actually deliver Python on some of their systems: http://wingide.com/pipermail/marketing-python/2003-February/001050.html Deleting Python from the computer may make future upgrades difficult. Skip From missive at frontiernet.net Sun Jul 20 18:36:41 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 20 Jul 2003 22:36:41 GMT Subject: python tags on websites timeout problem References: Message-ID: In article , jeff wrote: > Hiya > > im trying to pull tags off a website using python ive got a few things > running that have the potential to work its just i cant get them to > becuase of certain errors? > > basically i dont what to download the images and all the stuff just > the html and then work from there, i think its timing out because its > trying to downlaod the images as well which i dont what to do as this > would decrease the speed of what im trying to achieve, the URL used is > only that for an example > A web page is made up of many separate components. When you "download a webpage" you generally are fetching the HTML code, and you will not get any images unless you specifically download those by their own URLs. > this is my source > > -------------------------------------------------------------------------------- > > #!/usr/bin/env python > import re > import urllib > > file = urllib.urlretrieve("http://images.google.com/images?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=rabbit" > , "temp1.tmp") > Two things: Don't use the name "file" as the name of your variable, as that is now the standard way to access a file (used instead of open) Why save the file and then read it back in? I might do something like... text = urllib.urlopen('http://www.example.org') for line in text.readlines(): print line > # searching the file content line by line: > keyword = re.compile(r"") > > for line in text: > result = keyword.search (line) > if result: > print result.group(1), ":", line, There are no parentheses in your regex, so I do not think you will ever have a group(1) >>> import re >>> keyword = re.compile(r"") >>> x = 'abc def' >>> z = keyword.search(x) >>> z.groups() () >>> z.group(0) '' >>> z.group(1) Traceback (most recent call last): File "", line 1, in ? IndexError: no such group >>> keyword = re.compile(r"()") >>> z=keyword.search(x) >>> z.group(0) '' >>> z.group(1) '' > -------------------------------------------------------------------------------- > and these are the errors im getting > > C:\Python22>python tagyourit.py > Traceback (most recent call last): > File "tagyourit.py", line 5, in ? > file = urllib.urlretrieve("http://images.google.com/image > 8&oe=UTF-8&q=rabbit" , "temp1.tmp") Is this newline (between image and 8 really there? Maybe there is a problem with the URL... > File "C:\PYTHON22\lib\urllib.py", line 80, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook, dat > File "C:\PYTHON22\lib\urllib.py", line 210, in retrieve > fp = self.open(url, data) > File "C:\PYTHON22\lib\urllib.py", line 178, in open > return getattr(self, name)(url) > File "C:\PYTHON22\lib\urllib.py", line 292, in open_http > h.endheaders() > File "C:\PYTHON22\lib\httplib.py", line 695, in endheaders > self._send_output() > File "C:\PYTHON22\lib\httplib.py", line 581, in _send_outpu > self.send(msg) > File "C:\PYTHON22\lib\httplib.py", line 548, in send > self.connect() > File "C:\PYTHON22\lib\httplib.py", line 532, in connect > raise socket.error, msg > -------------------------------------------------------------------------------- I think maybe you just are not getting any response at all from your try to fetch. Can you get any other URL ? Maybe google is watching user-agent strings to try to keep spiders out of their pages? From udo.gleich at web.de Tue Jul 29 04:11:09 2003 From: udo.gleich at web.de (Udo Gleich) Date: Tue, 29 Jul 2003 10:11:09 +0200 Subject: mixin class References: <3F24F8D2.E1ADFB08@web.de> <2259b0e2.0307281355.34725f83@posting.google.com> Message-ID: <3F262C1D.605117F2@web.de> > > mixed = new.classobj("K1_K2", (K1, K1), {}) There is an error in the code. Obviously it should read mixed = new.classobj("K1_K2", (K1, K2), {}) -- From ajw126 at york.ac.uk Wed Jul 9 14:49:35 2003 From: ajw126 at york.ac.uk (Andrew Wilkinson) Date: Wed, 09 Jul 2003 18:49:35 +0000 Subject: QUESTION References: Message-ID: <3f0c5593$0$45179$65c69314@mercury.nildram.net> Simon Bayling wrote: > I suggest you go to a tutorial and start learning Python :) > If that doesn't interest you, try renaming the folder and using your PC > for a while... if nothing you want to keep suddenly breaks then you can > most likely safely remove it. If your pc does still work ok having renamed it, I would rename it back to Python, and then try and run the uninstaller. This will remove any registry entries and file type associations. HTH, Andrew Wilkinson -- Quiet! You'll miss the humorous conclusion From usenet at soraia.com Mon Jul 28 12:37:14 2003 From: usenet at soraia.com (Joe Francia) Date: Mon, 28 Jul 2003 16:37:14 GMT Subject: Any Software can Python <-> Delphi ? In-Reply-To: References: Message-ID: <_icVa.1123902$ZC.164425@news.easynews.com> PythonMan wrote: > Any Software can change Python source code to Delphi ? > thx > You might find an easier time of it to embed your Python in Delphi, or, even better, write a Python extension with Delphi: http://www.atug.com/andypatterns/pythonDelphiTalk.htm http://membres.lycos.fr/marat/delphi/python.htm jf From python-url at phaseit.net Mon Jul 28 05:19:45 2003 From: python-url at phaseit.net (Irmen de Jong) Date: Mon, 28 Jul 2003 09:19:45 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 28) Message-ID: QOTW: "What's the reason for having two symbols [!= and <>] mean the same thing? Hysterical raisins. Python originally used only '<>'. C programmers whined about that, so Python added '!=' too. But Python code already used '<>', so it was too late to get rid of that one. '<>' was deprecated instead. That's a computer science term usually meaning it's like a mentally disturbed uncle: we won't kill it, but we won't talk about it either . The good news is that Guido has become more hardened to whining over the centures since then." -- Tim Peters "As they say, science advances, funeral by funeral." -- Marc Wilson Discussion ---------- Raymond Hettinger intrigues with the third episode of a series of mysterious Python puzzles. Paul Rubin proposes a language extension to deal with closing files in a nice way. While the original question was about scripting Paint Shop Pro Duncan Booth shows how easy it is to write text in an image by using PIL. Steven Taschuk discusses several ways to implement Singletons in Python. Raymond St. Marie writes something that I'm not sure of what it is, but it is funny nonetheless. Chris Perkins wrote a checkable iterator, for when you need to know when an iterator is exhausted. Raymond Hettinger argues that a new syntax to create Sets is not needed. Bengt Richter gives a detailed analysis and example code for a genric 'namespace' type to store variables in. A possible way to help you finding errors in your Python programs is by listing all identifiers that are used. Bengt Richter wrote a little program that does just this (mind the correction in the follow-up message). Announcements ------------- It was a busy week, last week! Guido van Rossum is interviewed in the Wall Street Journal. Bruce Eckel talks with Bill Venners about how Python's minimal finger typing allows programmers to focus on the task, not the tool, generating a productivity that makes more projects feasible. Python 2.3 release candidate 2, the second and last release candidate for Python 2.3 This will become Python 2.3 final if no new major bugs are found this week. A binary installer for MacPython-2.3rc2 for Mac OS X 10.2: PythonD 2.2.1 Release 2.0, a 32-bit, multi-threaded, networking- and OpenGL-enabled Python interpreter for DOS and Windows KirbyBase is a simple, pure-python, flat-file database management system ... Epydoc 2.0, a tool for generating API documentation for Python modules, based on their docstrings. Aap's 1.0 release is not only "the first stable version of this powerful build tool", but offers the potential of real money for interested developers. py2exe 0.4.1, is a distutils extension to convert python scripts into windows exe-files (plus a few dlls), able to run on computers without requiring a python installation. The SciPy '03 Workshop on Scientific Computing with Python is being held at Cal Tech again this year. It is a two day workshop held September 11-12 in Pasadena, CA. WebTK 0.alpha3, a Python framework using Twisted as its underlying Web server, allowing webmasters to develop websites like any classic GUI software. Leo 3.12, an outlining editor/browser/organizer for programmers. numarray 0.6, an array processing extension supporting records, memory mapping, and computational capabilities. CUTE 0.1.6, a Qt and Scintilla based text editor which can be easily extended using python. SciParam 1.0.0 is a Python package to easily add additional quality control for entering scientific parameters in wxPython-based user interfaces. WordUtils 0.7.0, pure-Python objects related to word searching and matching. Fnorb 1.3, a pure-Python CORBA implementation. cx_Freeze 2.1, a set of utilities for freezing Python scripts into executables. cx_OracleDBATools 1.2 and cx_OracleTools 7.1, a set of Python scripts that handle Oracle tasks in a cross platform manner. imgv 2.8.6, a cross-platform image viewer written entirely in Python, using Pygame. pynum2word-0.1, translate numbers into words in different languages. ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From leo.broska at NOSPAM.isys.com.au Wed Jul 2 22:09:38 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Thu, 3 Jul 2003 12:09:38 +1000 Subject: arbitrary long integer aritmetics References: Message-ID: thanks guys i just should've read the doc. ;-) leo "Leo" wrote in message news:bdtv1s$22dm$1 at otis.netspace.net.au... > hi all > > is there a python module around allow using arbitrary long integers? > > i.e. the result of an integer operation is as long as necessary, so that a*b > never produces an overflow error. (but rather an out of memory error ;-) ) > > thanks, leo From peter at engcorp.com Mon Jul 14 17:30:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Jul 2003 17:30:43 -0400 Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: Message-ID: <3F132103.4D18759F@engcorp.com> Tim Gerla wrote: > > Very fun stuff. Someday I hope to have a Zaurus or similar device to > toy with. Anyway, to actually be on topic, "proper" HTML (XHTML 1.0, > and maybe HTML 4.0? I don't recall...) requires double-quotes to be > used. Single quotes are illegal. Are you certain about that? It seems very unlikely that it would outlaw use of single quotes when it is supposed to be XML-compatible, and XML explicitly allows either single or double quotes around attributes. I checked a page or two at W3C and couldn't find an obvious way to prove that you are wrong, but I think the onus is on you to prove that you are right here. -Peter From theller at python.net Thu Jul 24 02:39:40 2003 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2003 08:39:40 +0200 Subject: Newbie question regarding py2exe. References: Message-ID: Marco.LaRosa at csiro.au writes: > Hi all, > > This is a dumb question and I apologise. > > I have just started using py2exe and no matter what I try, I can't get it to > work. > The only thing (IMO) you can do severely wrong is to create your scripts and your setup.py file in the lib/site-packages/py2exe directory. Use a different directory for that. > Sometimes modulefinder.py complains, other times its VersionInfo.py. If you only get warnings, that's ok. They are warnings;-) Look in the dist/... directory for an exe file (and the additional dlls/pyds). Thomas From peter at engcorp.com Tue Jul 15 17:30:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Jul 2003 17:30:15 -0400 Subject: [OT] sentances with two meanings References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> <4701fb.8co.ln@195.171.216.1> <87smp7biet.fsf@pobox.com> Message-ID: <3F147267.3C3CE115@engcorp.com> "John J. Lee" wrote: > > bhahn at spam-spam.g0-away.com (Brendan Hahn) writes: > > > duncan at rcp.co.uk wrote: > > >"Colin S. Miller" wrote: > > >To "take someone in" means to trick or deceive them. > > > > "take in" can also mean to observe. > > But "take someone in" never means that. It really is a wonder that we > manage to communicate this way... Never say never. I could picture a writer better than I, carefully crafting a sentence in a book involving a very, very large women (or man, let's not be sexist here), saying something to the effect of "She was so large, I couldn't take her all in." But you're write (sic) about it being hard to communicate sometimes. (Did I mean "sometimes you're right", or did I mean "sometimes it's hard to communicate"? ;-) -Peter From sschwarzer at sschwarzer.net Sat Jul 26 20:00:46 2003 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 27 Jul 2003 02:00:46 +0200 Subject: Standard behaviour of a getSomething method In-Reply-To: References: Message-ID: John Roth wrote: > "Stefan Schwarzer" wrote in message > news:bfulr8$5mi$1 at online.de... >> Somewhat, I dislike the sometimes recommended __getattr__/__setattr__ >> approach. I wouldn't like to have something like > > That sounds more than a bit heavyhanded to me. The more > general practice is simply to name private attributes with a > leading underscore. Then you can verify that there aren't any > improper references by scanning the source for references to > underscored variables that don't start with "self._". I refered to public attributes here. For private (i. e. implementation- specific) attributes I would just use the leading-underscore convention, like you. Stefan From robin at jessikat.fsnet.co.uk Thu Jul 31 07:09:09 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 31 Jul 2003 12:09:09 +0100 Subject: RELEASED Python 2.3 (final) References: <3f27bacd$0$49113$e4fe514c@news.xs4all.nl> <38ec68a6.0307301828.7310e01b@posting.google.com> <3F28EA71.6A863E7@hotmail.com> Message-ID: I've been testing reportlab with 2.3 and although it's a lot faster I get some ominous warnings and complaints from the future. 1) SyntaxWarning: assignment to None eg for None, name in colorNamePairs: what is the preferred way to do this nowadays? It's fairly trivial to go through and change these to for notUsed, x in .... but is there a nicer way. 2) FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up eg self.assertEquals(ttf.read_ulong(), 0x81020304) # big-endian Is there no way to preserve the clarity of the above in future? We have quite a lot of code that deals with low level binary formatted stuff. Changing will move it further away from the original C definitions. The same applies to FutureWarning: x< <1058329089.889337@yasure> Message-ID: "Donn Cave" schreef: > You can also SSL-ize a protocol in Python. AFAIK the libraries that come with the binary installer for Windows aren't compiled with SSL support in versions prior to 2.3, and I'm using Windows here... But that shouldn't be a problem for the OP though (as he seems to be using Linux). -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From adalke at mindspring.com Wed Jul 2 15:19:46 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 2 Jul 2003 13:19:46 -0600 Subject: splitting a string into 2 new strings References: Message-ID: Anton Vredegoor: > The issue seems to be resolved already, but I haven't seen the split > and strip combination: > > from string import letters,digits Use "ascii_letters" instead of "letters". The latter is based on the locale so might not work on some machines where "C" (or rather, byte 67) isn't a letter in the local alphabet. Andrew dalke at dalkescientific.com From staschuk at telusplanet.net Wed Jul 30 15:05:02 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 30 Jul 2003 13:05:02 -0600 Subject: special case loading modules with imp In-Reply-To: <18a.1d812bef.2c595809@aol.com>; from Erendil@aol.com on Wed, Jul 30, 2003 at 01:19:05PM -0400 References: <18a.1d812bef.2c595809@aol.com> Message-ID: <20030730130502.A1069@tibia.amotlpaa.bogus> Quoth Erendil at aol.com: > Thanks! There's just one part I don't get... (I like to fully understand it > before I use it) > > >>>exec sourcecode in mod.__dict__ > > What exactly does that do? It executes the source code in the given string, using the module's dict as the namespace. Details: All assignment operations bind a name to an object. This includes simple assignment statements such as x = 3 but also statements such as def foo(): # ... (which binds the name 'foo' to a certain function object). The mapping from name to object is maintained using a dict, one dict for each namespace of relevance. The globals of a given module, in particular, are stored in a dict known as moduleobj.__dict__. (The local namespace of a function -- the namespace in which its local variables are bound -- actually has a different implementation, I think, for performance. But ignore that.) 'exec ... in ...' specifies which dict to use as the namespace for the executed code. Example: >>> d = {} >>> exec 't = 3' in d >>> d['t'] 3 >>> exec 'def foo(x): return 11*x' in d >>> d['foo'] Of course, name lookup uses the given namespace as well: >>> exec 'print foo(t)' in d 33 Thus my suggested "import by hand" code does what importing a module usually does -- it executes the code in the module, thereby usually populating the module dict with functions, classes, etc.. For more, see the Language Reference section on the exec statement, and maybe the section on Python's data model too. -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From bgailer at alum.rpi.edu Wed Jul 16 18:52:29 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 16 Jul 2003 16:52:29 -0600 Subject: Augmented Assignment question In-Reply-To: <215bhv0bnkn13eivh0s64ic5ml8obpgfg7@4ax.com> Message-ID: <5.2.1.1.0.20030716164227.027c9d50@66.28.54.253> At 06:13 PM 7/16/2003 +0000, Doug Tolton wrote: >I have a function that returns a tuple: > > def checkdoc(self, document): > blen = document['length'] > bates = document['obates'] > > normal, truncated, semicolon = 0,0,0 > for bat in bates: > if len(bat) == 2 * blen: > semicolon += 1 > if len(bat) == blen - 1: > truncated += 1 > if len(bat) == blen: > normal += 1 > > return normal, truncated, semicolon > >on the other side I have 3 variables: >normal, truncated and semicolon > >I would like to be able to do an augmented assignment such as: > >normal, truncated, semicol += self.checkdoc(mydoc) > >however this returns the following error: >SyntaxError: augmented assign to tuple not possible > >I did some reading and it seems that an augmented assignment is >specifically verboten on tuples and lists. Is there a clean way to >accomplish this? I dislike in the extreme what I've resorted to: > >fnormal, ftruncated, fsemicolon = 0,0,0 > >// loop through a file and process all documents: > normal, truncated, semicolon = self.checkdoc(curdoc) > fnormal += normal > ftruncated += truncated > fsemicolon += semicolon > >This solution strikes me as inelegant and ugly. Is there a cleaner >way of accomplishing this? I suggest: use a list instead of separate counter variables, and update the list within the function. counters = [0]*4 # initialize list def checkdoc(self, document, counters): blen = document['length'] bates = document['obates'] for bat in bates: if len(bat) == 2 * blen: x = 0 if len(bat) == blen - 1: x = 1 if len(bat) == blen: x = 2 else: x = 3 # counters[x] += 1 Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From missive at frontiernet.net Wed Jul 23 17:13:48 2003 From: missive at frontiernet.net (Lee Harr) Date: Wed, 23 Jul 2003 21:13:48 GMT Subject: Standard behaviour of a getSomething method References: Message-ID: In article , Batista, Facundo: > This message is in MIME format. Since your mail reader does not understand > this format, some or all of this message may not be legible. > > When I want to know about a attribute (e.g.: myAttrib) of an object, I > should use the specific method (e.g.: getMyAttrib). > > Considering that this attribute is always another object (everything is = > an > object in Python), what should getMyAttrib do? > > 1) Return the object > 2) Return a copy of the object > I do not think there is a definite rule regarding this. However, whichever one it does, you should probably document it :o) > How do I return a copy of the object? > You can use the copy module to create either a shallow or deep copy. From postmaster at cpress.cz Thu Jul 3 10:02:41 2003 From: postmaster at cpress.cz (System Administrator) Date: Thu, 3 Jul 2003 16:02:41 +0200 Subject: Undeliverable: Re: Movie Message-ID: Your message To: snajdr at cpress.cz Subject: Re: Movie Sent: Thu, 3 Jul 2003 15:56:57 +0200 did not reach the following recipient(s): SNAJDR at CPRESS.CZ on Thu, 3 Jul 2003 16:02:39 +0200 The recipient name is not recognized The MTS-ID of the original message is: c=cz;a= ;p=computer press;l=MAIL050307031402NXMVAZKM MSEXCH:IMS:Computer Press:CPBRNO:MAIL05 0 (000C05A6) Unknown Recipient -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Re: Movie Date: Thu, 3 Jul 2003 15:56:57 +0200 Size: 1055 URL: From MatthewS at HeyAnita.com Wed Jul 9 21:09:05 2003 From: MatthewS at HeyAnita.com (Matt Shomphe) Date: 9 Jul 2003 18:09:05 -0700 Subject: Odd scrollbar behavior in IDLE v1.0b2 (Bug?) Message-ID: <5ab0af73.0307091709.2baeca43@posting.google.com> My setup: Win2K Python 2.3b2 IDLE 1.0b2 If I use IDLE and have a block of "wraparound" text (text that runs on to the next line without having an explicit line break) then use the scrollbar on the right-hand side to navigate (either by dragging on the bar,using the scroll-wheel on the mouse, or clicking on the directional arrows), the grey, moveable part of the scrollbar changes size. For example: >>> 'a'*6000 will yield a large block of text that should demonstrate this problem. There are two conditions: (1) The scroll bar is active (2) There is a block of wraparound text To reproduce this, just move the scroll bar around. Is this a bug that should be reported? From lorenb2 at bezeqint.net Sun Jul 20 20:51:24 2003 From: lorenb2 at bezeqint.net (Bobbie) Date: Mon, 21 Jul 2003 02:51:24 +0200 Subject: Overriding Libraries Problem Message-ID: <00d701c34f22$35b320c0$6700a8c0@inet43> Hello, I'm doing my first python steps so forgive my Newbies' questions. Prob is that while using urllib2 I've found out there's a default User-agent HTTP attribute that is being added automatically. How can I override this behaviour (preferrable from within my code) ? I even tried to remove the relevant code directly from my library but alas the unsolicited attribute kept showing up. Here's the relevant code: class OpenerDirector: def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] I tried to comment out the last code line but in vain... any suggestions ? thx B. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave at boost-consulting.com Fri Jul 25 19:03:19 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 25 Jul 2003 19:03:19 -0400 Subject: Problem build Boost.Python References: Message-ID: Bren writes: > Hi, > > Pardon my stupid, but I'm having a problem building Boost.Python as > per the instructions at > http://www.boost.org/libs/python/doc/building.html > > I got boost-build-2.0-m6.zip from sourceforge and build bjam.exe. It is possible to build Boost.Python under Boost.Build-2.0, but not using those instructions. Boost.Build v1 is still the official build system of Boost for the time being. [Boost.Build guys, do we need to rename the BBv2 prerelease so this confusion doesn't recur?] It looks like you're on windows, so you should either get the precompiled executable in bjam-3.1.4-2-ntx86.zip, or visit the tools/build/jam_src subdirectory of your Boost installation and invoke build.bat as per http://www.boost.org/tools/build/jam_src/index.html#installing > I've tried several ways: > > bjam -a > bjam -sTOOLS="msvc" > bjam -sTOOLS=msvc > > I tried with and without the using msvc ; in user-config.jam. > > In every case I get: > > C:/Project/boost/tools\boostbook.jam:86: in boostbook.init > *** argument error > * rule path.make ( native ) > * called with: ( ) > * missing argument native > C:/Project/boost/new\path.jam:42:see definition of rule 'path.make' > being called > > C:/Project/boost/new\toolset.jam:22: in using > C:\Project\boost\new\../new\user-config.jam:58: in modules.load > C:/Project/boost\build-system.jam:55: in load > C:\Project\boost\new\..\kernel\modules.jam:296: in import > C:\Project\boost\new\..\kernel\bootstrap.jam:122: in boost-build > C:\Project\boost\new\boost-build.jam:2: in module scope > > > Can anyone help? > HTH, -- Dave Abrahams Boost Consulting www.boost-consulting.com From null-spam at tfh.ca Mon Jul 7 14:20:59 2003 From: null-spam at tfh.ca (Sean) Date: Mon, 7 Jul 2003 13:20:59 -0500 Subject: Executing a remote process via WMI in Win32. Message-ID: I can connect to a machine remotely with no problems but I'm having trouble trying to create a process remotely. Initially this was a perl and VB script which I'm converting to python. Its entire purpose is to start a process remotely. The problem initially was that the perl script could not 'see' any mapped drives as it would alway return 'access denied' so I'm trying to not only rewrite the script but fix this problem and my idea was to connect with the Administrator account. Now the following script sort of works. I can get the set of running processes but it dies out when I try to create one. ## being ## import win32com.client wmi = win32com.client.Dispatch('wbemscripting.swbemlocator') remote_machine = wmi.ConnectServer('','root\\cimv2',Administrator','') process = remote_machine.InstancesOf("Win32_Process") for proc in process: size = int(proc.WorkingSetSize)/1024 print proc.Caption, size,"kb" # test to see if we can 'see' what's on a mapped drive. # doesn't seem to go. process.Create("cmd.exe /K dir w:\\") ## END ## The script will print out all the processes fine but once it get's to 'Create' it dies out with and error message I don't understand. NOTEPAD.EXE 80 kb Traceback (most recent call last): File "C:\Documents and Settings\scody\test.py", line 14, in ? process.Create("cmd.exe /K dir w:\\") File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: InstancesOf.Create The process method should only have the one parameter as defined at: http://userpages.umbc.edu/~kbradl1/wsz/ref/WMIref.html#process I just tried using the 'Terminate' process but that didn't work either.... So I'm going to assume that the WMI objects are not instantiated as python classes (hence why the methods are not working). Am I completely off base here (meaning it is a syntax problem)? Any suggestions or pointers to the right direction would be creately appriciated... -- Sean (ps. remove -spam to email me). From heafnerj at spam.vnet.net Tue Jul 15 18:32:42 2003 From: heafnerj at spam.vnet.net (Joe Heafner) Date: Tue, 15 Jul 2003 17:32:42 -0500 Subject: Mac OS X, Fink, Python, and web browser References: <2b012c5e.0307151342.e5db114@posting.google.com> Message-ID: Don Hiatt wrote: > You can change your default web browser to Safari using the preferences > pane (under internet, I believe). If IDLE_fork uses the default browser > property then Safari should launch. > Hi. I just double checked and Safari is indeed my system default under System Preferences -> Internet -> Web. There's no mention of Safari in webbrowser.py though. JH From http Fri Jul 11 12:30:01 2003 From: http (Paul Rubin) Date: 11 Jul 2003 09:30:01 -0700 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <7xk7ap3j6z.fsf@ruckus.brouhaha.com> <3F0EE2E1.1C30CEA4@hotmail.com> Message-ID: <7xvfu9kovq.fsf@ruckus.brouhaha.com> Alan Kennedy writes: > Do you mean transmit the checksum to the client with the cookie? And > check that they match when the cookie and checksum come back? Yes. See other posts in the thread for sample code. > Or is the checksum stored on the server, in some form of lookup > dictionary keyed by some user session identifier? If you have a convenient way to do that, it's best to just send a session number in the cookie, and keep all the session data on the server. Then you don't ever have to unpickle anything. From bokr at oz.net Tue Jul 1 19:48:15 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2003 23:48:15 GMT Subject: I have a list... References: <20030701113915.226ae9bd.agg@astranet.ru> Message-ID: On Tue, 1 Jul 2003 11:39:15 +0400, "Damir Hakimov" wrote: >Hi, All! > >say, i have a function: > >def f(*b): > print b > return > >then i do: >f(3,4,5) >(3, 4, 5) > >but i have list f=(3,4,5) >f(l) >((3, 4, 5),) > >how can i call f function to result >f(???(b)) >(3, 4, 5) > Is this what you are looking for? : >>> def f(*b): ... print b ... >>> tup = (1,2,3) >>> f(tup) ((1, 2, 3),) tup was single arg, but: >>> f(*tup) (1, 2, 3) tup got unpacked to make args >>> L = [4,5,6] >>> f(L) ([4, 5, 6],) L was single arg, but: >>> f(*L) (4, 5, 6) L got unpacked similarly, but note that args become tuple b, not a list. Regards, Bengt Richter From jan at jandecaluwe.com Sun Jul 27 17:22:58 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Sun, 27 Jul 2003 23:22:58 +0200 Subject: Checking whether bool is a type Message-ID: <3F2442B2.E660E97@jandecaluwe.com> In my application I need to know whether bool is available as a type (in Python2.3) or not. I just realized I can use the following: jand> python Python 2.3c1 (#1, Jul 21 2003, 12:40:39) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> type(bool) is type True jand> python2.2 Python 2.2.2 (#1, Oct 16 2002, 19:59:11) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> type(bool) is type 0 Great isn't it ?! Not sure whether I should consider this to be completely obvious or very deep ... Regards, Jan -- Jan Decaluwe - Resources bvba Losbergenlaan 16, B-3010 Leuven, Belgium mailto:jan at jandecaluwe.com http://jandecaluwe.com From missive at frontiernet.net Fri Jul 11 02:20:58 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 11 Jul 2003 06:20:58 GMT Subject: Zope problem: objectValues('Folder') References: <3F0D11C7.4010805@gmx.de> <3F0D21D4.3040902@mxm.dk> <3F0D2405.1070606@gmx.de> <3F0D2EAC.2010605@mxm.dk> <3F0D4C74.5040304@gmx.de> Message-ID: In article <3F0D4C74.5040304 at gmx.de>, Jens Riedel wrote: > The problem seems to be somewhere else: > > I used the objectValues('Folder')-method in a DTML-method named > 'navigation'. I include in a > 'standard_html_header' DTML method, and this standard_html_header is > used in the index_html document. > All three are in the same folder which contains 3 Subfolders. If I view > 'navigation' or 'standard_html_header' in the management area, I see the > 3 folders, but in the index_html they don't appear. Everything else in > the standard_html_header, like stylesheets etc. are correctly shown so > I'm sure that the correct standard_html_header is included. > > Jens > Is index_html a DTML_Document, maybe? In that case, I think objectValues() would look in the index_html for its objects, instead of the containing folder. Try creating a new DTML_Method and putting your code in there. From hab at polbox.com Fri Jul 4 08:04:57 2003 From: hab at polbox.com (hab) Date: Fri, 04 Jul 2003 14:04:57 +0200 Subject: AIX + GCC 2.95.3 - Python (2.1 or 2.2) - building the shared library (.so) for python - HOW TO?!? Message-ID: <3F056D69.1090705@polbox.com> Hi all, (If I use standard -shared linking, during the _import python is crashing.) As seen in in AIX-NOTES there should be used ld_so_aix. But I suspect that it was prepared for standard xlC (CC) compiler. How to make it running for GCC compiler? Now I receive following error: gcc -Wl,-einitlib.a -Wl,-bE:lib.a.exp -Wl,-bI:./python.exp -Wl,-bhalt:4 -Wl,-bM: SRE -Wl,-T512 -Wl,-H512 -lm -o lib.a. -shared -Wl,-bbigtoc -L../../../../lib/pow erpc_aix_4.3_gcc -L/users/tbech/ND/Python/usr/local/lib/python2.1/config python. exp y.tab.o lex.yy.o idlerr.o idlutil.o idltype.o idlrepoId.o idlscope.o idlexpr .o idlast.o idlvalidate.o idldump.o idlconfig.o idlfixed.o idlpython.o ld: 0711-418 ERROR: Import or export file lib.a.exp at line 10: A symbol name may only be followed by an export attribute or an address. The line is being ignored. When I remove this line 10 from lib.a.exp it is telling that several Py* functions are not exported and that entry point initlib.a not found. Additional questions: 1. Why is such nonuderstandable-ultimate-tricky solution prepared for AIX? 2. Does it work only for xlC (CC) or also for GCC? If, how to do it? 3. What is the entry point function? How I can find it in the sources? 4. Seems that makexp_aix wrongly makes exports :( Thanks in advance, Tom From gh at ghaering.de Sun Jul 6 18:22:44 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Jul 2003 00:22:44 +0200 Subject: Using Loops to track user input In-Reply-To: References: Message-ID: <3F08A134.9040009@ghaering.de> Hi hokiegal99 if that's what you want me to call you, hokiegal99 wrote: > I don't understand how to use a loop to keep track of user input. Could > someone show me how to do what the program below does with a loop? Your text book or tutorial should show that quite well, but here we go: > > Thnaks! > > ---------------------------- > #Write a program that reads 10 numbers from the user and prints out the > sum of those numbers. > > num0 = input("Enter a number: ") > num1 = input("Enter a number: ") > num2 = input("Enter a number: ") > num3 = input("Enter a number: ") > num4 = input("Enter a number: ") > num5 = input("Enter a number: ") > num6 = input("Enter a number: ") > num7 = input("Enter a number: ") > num8 = input("Enter a number: ") > num9 = input("Enter a number: ") > > num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9 > > print num > ---------------------------------- #v+ sum = 0.0 for i in range(10): sum += int(raw_input("Enter a number: ")) print sum #v- If your prof is any good, (s)he reads this newsgroup as well ;-) -- Gerhard From alan.gauld at btinternet.com Thu Jul 24 18:31:11 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jul 2003 22:31:11 GMT Subject: very Very VERY dumb Question About The new Set( ) 's References: <20030723144732.13232.00000523@mb-m10.aol.com> Message-ID: <3f205d3c.745868662@news.blueyonder.co.uk> On 23 Jul 2003 18:47:32 GMT, rastm2 at aol.commorespam (Raymond Arthur St. Marie II of III ) wrote: > Doc\ref 2.6 Delimiters show's three unused characters "@ $ ?". > @ sort of looks like and sort of sounds like a set an > $ well sort of obvious. > I can imagine that the $ would be confused for money and @ is ugly. Since I detest any thought of prefix symbols to indicate type(as per Perl etc) but have no visibility of these debates, I'll throw in my suggestion and done a flameproof suit! Since both dictionaries and Sets require unique members/keys, why not use the dictionary braces but without the key/value syntax. So: mySet = {1,2,3,4} Which is illegal for a dictionary but would be OK for a Set. It also just happens to be the same delimiters used in math for sets... Just a thought before I go to bed! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From ta-meyer at ihug.co.nz Wed Jul 16 21:11:48 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 17 Jul 2003 13:11:48 +1200 Subject: IMAP examples In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13026F805B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AB34@its-xchg4.massey.ac.nz> > I can't seem to find any decent examples on how to use the > IMAPLIB module. the docs aren't that sophisticated > unfortunately.... the cookbook entry comes close, but i'd > like to know if someone knows some nice examples somewhere. What do you mean by decent? Spambayes (http://spambayes.org) has an IMAP filter, which is an example of using imaplib. Whether it's decent or not, well... ;) =Tony Meyer From gsmatthew at ozemail.com.au Mon Jul 14 08:26:07 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Mon, 14 Jul 2003 22:26:07 +1000 Subject: How to give a custom object instance a type name ? References: Message-ID: Hi Ulrich Sorry only read some high level java stuff but have not really coded in it thanks ill give it a try Graeme "Ulrich Petri" wrote in message news:beu76g$8t8vu$1 at ID-67890.news.uni-berlin.de... > "Graeme Matthew" schrieb im Newsbeitrag > news:DAwQa.168$O05.9536 at nnrp1.ozemail.com.au... > > > > Here is a custom Dispatcher class that I have written > > > > >>> from BI.System.Controller.Dispatcher import Dispatcher > > >>> x = Dispatcher() > > >>> type(x) > > > > You did Java before ;)? > > > How do I get the same as with instance 'm' above where the type displays > the > > actual object instance name, however my > > custom dispatcher instance is just a generic 'instance', is there some > > builtin where this is set ? > > > > how about > >>> x.__class__.__name__ > > HTH > Ciao Ulrich > > From http Sun Jul 20 14:42:11 2003 From: http (Paul Rubin) Date: 20 Jul 2003 11:42:11 -0700 Subject: "Pure Python" MySQL module like Net::MySQL References: Message-ID: <7xk7advy4c.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > This has benefits and disadvantages. As the author points out, this lets > you connect to MySQL databases from systems to which the MySQL client > libraries haven't been ported. On the other hand, the MySQL wire protocol > is probably not part of the official external interface, so the author has > to track changes to the protocol. What the heck? If the wire protocol isn't part of the official external interface, then how on earth are external applications supposed to talk to the database? They certainly can't expect you to use black-box client libraries if they're at all serious about being in the same league with Oracle. From bignose-hates-spam at and-zip-does-too.com.au Sat Jul 12 19:45:27 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 13 Jul 2003 09:35:27 +0950 Subject: [OFF TOPIC] Re: The "intellectual property" misnomer References: <3f103fa7_6@corp.newsgroups.com> Message-ID: On Sat, 12 Jul 2003 13:04:03 -0400, Steve Pinard wrote: > This newsgroup is for postings related to the computer language > Python. The thread was in direct response to, and kept to the context of, a post made to this group by Guido about the Python Software Foundation. I'm not in the habit of starting off-topic threads, and started this one because it was of concern to the Python community specifically. > (In other words, you all should know better. Take it outside.) I've stated my position several times, and don't see the need to do so again in this thread. I'm done. -- \ "War is God's way of teaching geography to Americans." -- | `\ Ambrose Bierce | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From Scott.Daniels at Acm.Org Fri Jul 25 21:38:54 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 25 Jul 2003 18:38:54 -0700 Subject: Static typing In-Reply-To: <3f218ef1$0$27926$626a54ce@news.free.fr> References: <3f218ef1$0$27926$626a54ce@news.free.fr> Message-ID: <3f219c8d$1@nntp0.pdx.net> Bruno Desthuilliers wrote: > Michael Muller wrote: >> Is there currently any plan to introduce static typing in any future >> version of Python? > Seriously, why would you do that ? You _might_ want some static typing information as program documentation or to enable efficient program translation. The types sig was interested in allowing type annotation where possible. Remember, the type you might want may be more like "what protocol must these objects (the ones passing through this variable) follow" than "what are the construction details of these objects". I would like to see interface descriptions describing what kinds of parameters are required and results produced for packages that I am considering using. If there were a single central-python-endorsed form for those descriptions even better. If the descriptions can be mechanically read, and at least sometimes mechincally checked (possibly slowly, possibly only for slow execution), I might use such a system to check a module before announcing it to the world. A very old Sun study determined that most variables in a dynamically typed system (smalltalk, IIRC) are almost always of the same type. David Ungar got a fair amount of mileage out of optimizing for a guessed common case in a protype-driven language where you couldn't even name types in the language (you make objects "just like that one except..."). I had a sketch of how to optimize for OODBs using behavior-based typing. The big trick was to use the DB's knowledge of the classes in the DB (provided for each instance in the DB) to determine when there was, at least currently, only one method for the given function. An environment like that might be able to do much better at query optimization than any OODB that allows you to store arbitrary objects and retrieve them based on message calls. -Scott David Daniels Scott.Daniels at Acm.Org From peter at engcorp.com Wed Jul 9 05:55:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Jul 2003 05:55:23 -0400 Subject: Python Global Constant References: Message-ID: <3F0BE68B.893EB7E5@engcorp.com> Krisztian Kepes wrote: > > I want to create an module and I want to use some Global Constant in it. > How to I create an global constant in module what is accessable in from other modules ? > > like this example: > > *** module dirs *** > const Const_Up=1 > const Const_Down=1 Just do what you did above, without the "const" modifier, which doesn't exist and is not really needed in Python. > *** module any *** > import dirs; > def CheckDir(Dir): > if Dir=dirs.Const_Up: xxx This code should work fine, although you might want to follow the Python conventions for capitalization and formatting of your code, to make it more readable for others. For example, variables and functions are generally mixed case, as in checkdir or dir, while constants are usually ALLCAPS as in CONST_UP. -Peter From staschuk at telusplanet.net Tue Jul 8 17:57:50 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 8 Jul 2003 15:57:50 -0600 Subject: print attitude In-Reply-To: ; from donn@u.washington.edu on Mon, Jul 07, 2003 at 09:53:22AM -0700 References: <3F0669B5.679FB505@alcyone.com> Message-ID: <20030708155750.A1044@tibia.amotlpaa.bogus> Quoth Donn Cave: [...] > I think some time back, Steven Taschuk proposed to submit a rewrite > of the str & repr documentation, [...] I did. See I am not entirely satisfied with the text (suggestions welcomed); I haven't taken the time to look at the matter again. -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From m at moshez.org Tue Jul 8 01:39:36 2003 From: m at moshez.org (Moshe Zadka) Date: 8 Jul 2003 05:39:36 -0000 Subject: anything new on the ternary operator? In-Reply-To: <3F09E4B4.FED89C06@alcyone.com> References: <3F09E4B4.FED89C06@alcyone.com>, <3F09252F.9B0F52BD@alcyone.com>, Message-ID: <20030708053936.25443.qmail@green.zadka.com> On Mon, 07 Jul 2003, Erik Max Francis wrote: > (And, to trump your next response, yes, I know you do not > hail from Europe.) Ah? Of course I'm from Europe. [The consensus in EP was that Israel was in Europe] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From op73418 at mail.telepac.pt Wed Jul 16 09:44:21 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 16 Jul 2003 14:44:21 +0100 Subject: <> and != References: <3F154B63.3060503@hotmail.com> <3F154BBD.2060304@hotmail.com> Message-ID: <3jlahv8o1fcu2j0oij2p31c32nftnb3er8@4ax.com> On Wed, 16 Jul 2003 08:57:33 -0400, hokiegal99 wrote: >that sould be: > >if newfile <> oldfile >if newfile != oldfile No difference whatsoever. I believe != is prefered (style guide?) though -- and that's the one I always use. With my best regards, G. Rodrigues From abbeflabbe at InospamIhotmail.com Fri Jul 18 13:44:01 2003 From: abbeflabbe at InospamIhotmail.com (Linkages) Date: Fri, 18 Jul 2003 17:44:01 GMT Subject: gui References: Message-ID: Il Fri, 18 Jul 2003 07:04:01 +0000, David M. Cook ha scritto: > In article , Linkages > wrote: > >> a good GUI for linux ? > > I like pygtk together with glade for doing layout: > > FAQ: http://www.async.com.br/faq/pygtk/index.py?req=all > Tutorial: http://www.moeraki.com/pygtktutorial/pygtk2tutorial/index.html > Reference: http://www.moeraki.com/pygtkreference/pygtk2reference/ > > There are also wxpython, pyqt, foxpy, and good old tkinter > (which is what comes with the standard library.) > > Dave Cook tx a lot im going to try it... bye linka From gregbrunet at NOSPAMsempersoft.com Thu Jul 31 23:25:55 2003 From: gregbrunet at NOSPAMsempersoft.com (Greg Brunet) Date: Thu, 31 Jul 2003 22:25:55 -0500 Subject: Python speed vs csharp References: Message-ID: "Mike" wrote in message news:rkdc7poiachh.1x4jtxjzaf3zo.dlg at 40tude.net... > Bear with me: this post is moderately long, but I hope it is relatively > succinct. > ... > This is an error function approximation, which gets called around 1.5 > billion times during the simulation, and takes around 3500 seconds (just > under an hour) to complete. While trying to speed things up, I created a > simple test case with the code above and a main function to call it 10 > million times. The code takes roughly 210 seconds to run. > > The current execution time is acceptable, but I need to increase the > complexity of the simulation, and will need to increase the number of data > points by around 20X, to roughly 30 billion. This will increase the > simulation time to over a day. Since the test case code was fairly small, I > translated it to C and ran it. The C code runs in approximately 7.5 > seconds. That's compelling, but C isn't: part of my simulation includes a > parser to read an input file. I put that together in a few minutes in > Python, but there are no corresponding string or regex libraries with my C > compiler, so converting my Python code would take far more time than I'd > save during the resulting simulations. > ... > Surprisingly (to me, at least), this code executed 10 million iterations in > 8.5 seconds - only slightly slower than the compiled C code. > > My first question is, why is the Python code, at 210 seconds, so much > slower? > I'm just a little curious how test code runs 10 million cycles in 210 seconds, while production code with runs 1.5 billion cycles in 3500 seconds. That makes your production code more efficient by roughly a factor of 10. If so, even though folks are only quoting an improvement factor of about 3x for Pysco and 5-6x with Pyrex, that may be sufficient enough for your needs. -- Greg From hwlgw at hotmail.com Tue Jul 8 16:42:24 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 8 Jul 2003 13:42:24 -0700 Subject: urllib2 for HTTPS/SSL References: <153fa67.0307080233.2f7abdf5@posting.google.com> Message-ID: > [Kylotan] > ........................Is there any chance of the official > documentation on this useful-looking module being improved? It is one of the biggest problems with Python that not enough people like to write good documentation about how to use the Python Standard Library. I think the best documentation for you is the book "Python Standard Library" (PSL) by Fredrik Lundh with its nice examples (could use even more!); but some bonehead at O'Reilly made the decision to publish "Python in a Nutshell" and "Python Cookbook" instead of the 2nd edition of PSL. But these have bad example code and the English feels bad, not as bad as my written English perhaps but not a pleasure to read either. Many Python modules have a class based design and class based frameworks need a detailed description and especially examples how to use those classes. That will also force the designers to give a *motivation* for the class-based design. Answer questions like "Why do I want users of this module to subclass my Application class? Would it not be easier for them to supply just a list of functions with a clear description of input and output?". To my opinion there are just too much class based designs, like for example that Twisted thing: too much use of OO and inheritance makes it hard to understand and often leaves the user with the question "But why...". It would take a *LOT* of documentation to make up for the design decisions there. I am not against OO, it has its virtues; I am against overusing OO. And especially against class-based designs with poor documentation lacking motivation. -- Python is an excellent language for learning object orientation. (It also happens to be my favorite OO scripting language.) -- Sriram Srinivasan, _Advanced Perl Programming_ From alanmk at hotmail.com Tue Jul 1 14:01:31 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 01 Jul 2003 19:01:31 +0100 Subject: Suggesting for overloading the assign operator References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <2259b0e2.0307010328.1e1b4a04@posting.google.com> <6f03c4a5.0307010910.35ca3158@posting.google.com> Message-ID: <3F01CC7B.F71C4C0B@hotmail.com> Rim wrote: > What do you think about providing a statement to assign values > without assigning type? > > '=' statement assigns value and type > ':=' statement assigns value ony I think the concept has some merit. I think that sometimes it useful to ensure that the target of a rebind operation have the same type as the object which was bound before the rebind. I know that the same effect can be achieved by descriptors or overriding "setattr" et al. Or something like this a = 9 b = 42 if isinstance(b, type(a)): a = b else: raise TypeError("Incompatible types.") However, these options, i.e. putting type checking logic in "setattr" et al, do not make it explicit in the code that type enforcement is in place. Expressing the enforcement syntactically, as Rim suggests, would make it more explicit for the programmer, as well as providing some extremely useful optimisation hints, especially for products such as psyco. Psyco, if I understand it correctly, generates machine code for all paths through a suite, depending on the types of the objects manipulated in the suite. Such explicitly stated type enforcement would provide valuable information to optimisers. Not that I'm proposing that the OPs solution be adopted. Just that I think he is addressing a valid concern. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From staschuk at telusplanet.net Thu Jul 31 21:06:32 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 31 Jul 2003 19:06:32 -0600 Subject: .setdefault() In-Reply-To: <3cjiivs4ippc6v7qjllfhi3knvthrfnj2g@4ax.com>; from tl_news@nexgo.de on Thu, Jul 31, 2003 at 07:13:56PM +0200 References: <87ispid400.fsf@pobox.com> <3cjiivs4ippc6v7qjllfhi3knvthrfnj2g@4ax.com> Message-ID: <20030731190632.C22513@tibia.amotlpaa.bogus> Quoth Tino Lange: > On 31 Jul 2003 18:01:51 +0100, jjl at pobox.com (John J. Lee) wrote: [...] > >Don't, then. :-) Use key in dict, or dict.has_key(key). > > or the C-like style: > >>> a[3] = a.get(1) or b.setdefault(4,1) Be careful doing that -- it relies on all possible values for a[1] being true. Consider: >>> a = {1: 0} >>> b = {} >>> a[3] = a.get(1) or b.setdefault(4, 1) >>> a {1: 0, 3: 1} >>> b {4: 1} -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From mesteve_b at hotmail.com Sat Jul 5 12:10:32 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 05 Jul 2003 16:10:32 GMT Subject: trying to connect to Amazon web services References: Message-ID: I think I'm going to use their XML method, and just use python to parse the resulting xml download into a csv file, much better. "python newbie" wrote in message news:u0MMa.1116$ez7.28745829 at newssvr15.news.prodigy.com... > Hey Py fans, > I have two basic motivations that I'm going for. > > One, to learn Python. > > Another, to download the list of 92 books I have added to my Amazon wishlist > up to now, so that I could write a clean csv file of these books to my hard > drive. > > I downloaded the pyAmazon web services package, and read the code examples, > however ( and you probably don't even have to know about pyAmazon to be able > to offer a suggestion ) I'm not sure how to connect to the Internet. > > My script is so far, this: > ------------------- > import amazon > amazon.setLicense('< i put my number here >') > mywishlist = amazon.searchByWishlist(' < i put my number here >'); > ------------ > > .. I'm going to figure out how to get the book info from the 'mywishlist' > object later, but if I run this script like this, this doesn't connect to > the Internet or to Amazon. > > How would I do that, I'm wondering? > > Thanks > > From candiazoo at mac.com Sat Jul 12 23:21:29 2003 From: candiazoo at mac.com (Michael S. Jessop) Date: Sun, 13 Jul 2003 03:21:29 GMT Subject: Problem with MySQLdb on Mac OS X... References: <110720032317344670%candiazoo@mac.com> Message-ID: <120720032321075007%candiazoo@mac.com> [[ This message was both posted and mailed: see the "To," "Cc," and "Newsgroups" headers for details. ]] I tried supplying host as well, same error. :/ Something is hosed. I guess I could try reinstalling. I really want to get this to work. I am trying to write a maintenance program for my wife, so she can remotely modify the database containing information about her artwork, distribution lists, etc. Mike J. In article , Skip Montanaro wrote: > Mike> I made modifications to setup.py to set safe threading to NO and > Mike> also to point to the "real" location of the mysql libraries and > Mike> stuff like that. To test it I wrote a simple script that just > Mike> tries to connect to the database. It fails. It also fails > Mike> interactively. Here is what I am getting... > > Your script worked fine for me (Mac OS X 10.2.6, Python 2.3b1+), though I > didn't modify setup.py (at least not that I recall - it's been awhile). > > Mike> The download, build and install went fine. This same code works > Mike> (well, different database name, user and password) on a different > Mike> machine. The database, username and password are all correct. > > The only change I made was that the database is remote, so I set the host as > well. > > Skip > From h.b.furuseth at usit.uio.no Wed Jul 9 09:57:01 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 09 Jul 2003 15:57:01 +0200 Subject: M2Crypto: How to check server certificate? References: Message-ID: Ng Pheng Siong wrote: >According to Hallvard B Furuseth : >> Does anyone know how I check the server certificate with M2Crypto? >> Currently a program I have inherited does this: > > Specify an SSL context: Thank you. > from M2Crypto import SSL > from M2Crypto.m2xmlrpclib import Server, SSL_Transport > > # Server is Zope-2.6.1 on ZServerSSL/0.12. > ctx = SSL.Context('sslv3') > ctx.load_cert_chain('client.pem') I think I can drop that when I have ca.pem... > ctx.load_verify_locations('ca.pem') Should be load_verify_location. Heh. That failed - correctly - because our test CA certificate is expired. > ctx.set_verify(SSL.verify_peer, 10) What does 10 mean? I can see from the function declaration that it is depth, but I don't know what depth is. -- Hallvard From exarkun at intarweb.us Tue Jul 8 13:39:37 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 8 Jul 2003 13:39:37 -0400 Subject: Embedding as scripting engine In-Reply-To: References: Message-ID: <20030708173928.GA4404@intarweb.us> On Tue, Jul 08, 2003 at 03:50:55AM -0700, ?lfur Kristj?nsson wrote: > Python... a great language, no doubt. And the abillity to be able to > extend it with C/C++ code, fantastic. But has anybody been able to > successfully embed Python in their application to use it as a > scripting language of sorts? Surprisingly, yes. > > I am in the process of writing a game and from the documentation and > word of mouth gathered that Python would be just the thing for the > scripting part. And sure enough it is easy enough to run Python code > from C/C++. However, in order to be make it do something actually > useful for my game it would be handy to be able to pass in anything > besides the basic data types (strings, numerics) such as either an > instance of or a pointer to a gameobject. What I want to be able to do > is something like this: > > GameObject go; > > Py_Initialize() > ... > PyObject* po = GameObject2PyObject(go); > ... > result = PyObject_CallObject(func, "O", po ); > ... > go = PyObject2GameObject(result); > > Theres alot of documentation and discussion out there that suggests > that this should be possible but noone seems to tell you how it's > actually done. Am I just missing something blatantly obvious? Your question is to vague and short on details to be answered usefully. What specific problems have you run into? Jp -- No, `Eureka' is Greek for `This bath is too hot.' -- Dr. Who From skip at pobox.com Fri Jul 18 09:23:31 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 18 Jul 2003 08:23:31 -0500 Subject: feature request: a better str.endswith In-Reply-To: <2259b0e2.0307180401.5dae02f2@posting.google.com> References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <16151.62675.386894.638631@montanaro.dyndns.org> Michele> I often feel the need to extend the string method ".endswith" Michele> to tuple arguments, in such a way to automatically check for Michele> multiple endings. For instance, here is a typical use case: Michele> if filename.endswith(('.jpg','.jpeg','.gif','.png')): Michele> print "This is a valid image file" This is analogous to how isinstance works, where its second arg can be a class or type or a tuple containing classes and types. I suggest you submit a feature request to SF. A patch to stringobject.c and unicodeobject.c would help improve chances of acceptance, and for symmetry you should probably also modify the startswith methods of both types. Skip From adonisv at earthlink.net Mon Jul 28 00:05:27 2003 From: adonisv at earthlink.net (Adonis) Date: Mon, 28 Jul 2003 04:05:27 GMT Subject: Question regarding HTMLParser module. Message-ID: When parsing my html files, I use handle_pi to capture some embedded python code, but I have noticed that in the embedded python code if it contains html, HTMLParser will parse it as well, and thus causes an error when I exec the code, raises an EOL error. I have a work around for this as I use different set of characters rather that use something like (tag) then revert it back to via another function, I was wondering if there is a way to tell HTMLParser to ignore the embedded tags or another alternative? Any help would be greatly appreciated. And another note, I am well aware of Zope, Webware, CherryPy, etc... for py/html embedding options, but I want this to be a learning experience. HTML processing instruction: testing!()') > error: Traceback (most recent call last): File "C:\home\Adonis\python\t.py", line 40, in -toplevel- x.feed(z) File "C:\Python23\lib\HTMLParser.py", line 108, in feed self.goahead(0) File "C:\Python23\lib\HTMLParser.py", line 154, in goahead k = self.parse_pi(i) File "C:\Python23\lib\HTMLParser.py", line 232, in parse_pi self.handle_pi(rawdata[i+2: j]) File "C:\home\Adonis\python\t.py", line 33, in handle_pi exec(data) File "", line 4 print ' hi all i use python-mode in emacs and want to start a script which gets data from the standard input via "input". this script works fine from the command line but in emacs via py-execute-buffer i get always an python execution error. additionally i want to start the script with input redirection from a file which as well works fine via command line,but i have no idea how to tell emacs to execute the file with input redirection. thanks for any help, leo From LogiplexSoftware at earthlink.net Thu Jul 10 14:01:21 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 10 Jul 2003 11:01:21 -0700 Subject: replace value of a specific position In-Reply-To: References: Message-ID: <1057860081.15508.157.camel@software1.logiplex.internal> On Thu, 2003-07-10 at 10:36, Tom wrote: > Hi, > > I want to replace a specific part of a string. I tried replace but this > doesn't work the way I want it, because it checks and replaces all > values and not the position (index). > > t = '010010101001001110100101010111' > t = t.replace(t[5], '2') > > This is just a bad example of what I tried. It produces this output: > > 212212121221221112122121212111 > > But I wanted: > > 010012101001001110100101010111 >>> def strrep(s, i, c): ... return s[:i] + c + s[i + 1:] ... >>> t = '010010101001001110100101010111' >>> strrep(t, 5, '2') '010012101001001110100101010111' -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From LISTSERV at LISTSERV.DFN.DE Sun Jul 13 20:06:08 2003 From: LISTSERV at LISTSERV.DFN.DE (L-Soft list server at Fraunhofer IMK for DFNList (1.8e)) Date: Mon, 14 Jul 2003 02:06:08 +0200 Subject: Rejected posting to NAMESPACES@LISTSERV.DFN.DE Message-ID: You are not authorized to send mail to the NAMESPACES list from your python-list at PYTHON.ORG account. You might be authorized to send to the list from another of your accounts, or perhaps when using another mail program which generates slightly different addresses, but LISTSERV has no way to associate this other account or address with yours. If you need assistance or if you have any question regarding the policy of the NAMESPACES list, please contact the list owners: NAMESPACES-request at LISTSERV.DFN.DE. -------------- next part -------------- An embedded message was scrubbed... From: Subject: Re: Movie Date: Sun, 13 Jul 2003 19:06:06 --0500 Size: 1122 URL: From janeaustine50 at hotmail.com Wed Jul 2 02:11:23 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 1 Jul 2003 23:11:23 -0700 Subject: __del__ not working with cyclic reference? (and memory-leaked?) References: Message-ID: > Jane Austine wrote: > > > I read the gc module reference thoroughly and > > thanks to your short comment, I could understand it. > > (I should not use __del__ for singleton patterns, but > > any other alternatives?) > > I'm not sure why you'd want to use __del__ for a singleton pattern in > the first place, since singleton patterns are supposed to cushion the > creation and destruction of the singleton object away from the interface > user. What are you trying to do with singleton patterns as it relates > to __del__? For example, say the singleton has a database connection, in a cgi program. I want the singleton clear itself(and close the connection) before the whole process exits. It seems to be more convenient and object-oriented. [snip] > > However, Python doesn't make any guarantees about how timely __del__ > will be called, or indeed even if it will be (in the case of circular > references). If you're finding yourself needing to rely on using Then "destructor" has less use than in other environments. Maybe I should avoid destructors in python as well as I can. > __del__ to get rid of important objects (such as those that are attached > to significant resources), a far better solution would be to use try: > ... finally: clauses surrounding the usage of such objects: > > resource = Resource() > try: > ... use resource ... > finally: > resource.close() > It is neat and reliable. Thanks. > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > / \ Men and women, women and men. It will never work. > \__/ Erica Jong From bokr at oz.net Wed Jul 23 22:47:02 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2003 02:47:02 GMT Subject: How does Mr. Martelli's Borg recipe work ? References: <764b8294.0307221520.18017b09@posting.google.com> Message-ID: On Wed, 23 Jul 2003 16:40:00 -0600, Steven Taschuk wrote: >Quoth Bengt Richter: > [borg vs singleton] >> How about just >> >> import zerolengthfile as borginstancename >> >> and using it? E.g., [...] > >That would be fine in many cases, I'm sure. > >Modules don't do properties (or other descriptor magic), though. > Not insurmountable ;-) ====< propmod.py >========================================== class PropModNames(object): def __get__(self, ob, cls=None): if ob is None: return self return 'Shared names of propmod: %r' % vars(ob).keys() def __set__(self, ob, val): raise AttributeError, 'names property is read-only' def __delete__(self, ob, val): raise AttributeError, 'names property is read-only' class SetPropModProp(object): def __init__(self): self.name2use = None def __get__(self, ob, cls=None): if ob is None: return self if not self.name2use: props = [k for k,v in vars(ob.__class__).items() if not k.startswith('_') and ( hasattr(v, '__get__') or hasattr(v, '__set__'))] props.sort() return 'Properties of propmod: %r' % props else: return getattr(ob.__class__, self.name2use) def __set__(self, ob, nameNprop): if isinstance(nameNprop,str): self.name2use = nameNprop elif len(nameNprop)==1: delattr(ob.__class__, nameNprop[0]) # (name,) means delete else: name, prop = nameNprop; setattr(ob.__class__, name, prop) class PropMod(object): names = PropModNames() properties = SetPropModProp() # expects propmod.setprop = name, property or name2use def __init__(self): __import__('sys').modules['propmod'] = self ============================================================ ===< apm.py >============ import propmod as zz ========================= The first lines below binds the real propmod module temporarily. The second line binds the magic propmod locally and makes it available (by PropMod.__init__ side effect ) for import by anyone else as an ordinary (looking) "import propmod." (Note what apm.py does). I thought it cute to make a property that is a kind of gateway to the class attribute space, so that one can use the .properties attribute of the propmod module to list, store, retrieve, and delete properties -- as well as arbitrary class variables... >>> import propmod >>> propmod = propmod.PropMod() >>> propmod.properties "Properties of propmod: ['names', 'properties']" >>> propmod.names 'Shared names of propmod: []' >>> propmod.x = 123 >>> propmod.y = 456 >>> propmod.names "Shared names of propmod: ['y', 'x']" >>> propmod.properties "Properties of propmod: ['names', 'properties']" >>> propmod.properties = ('hello', property(lambda self:'Hello properties!')) >>> propmod.properties "Properties of propmod: ['hello', 'names', 'properties']" >>> propmod.hello 'Hello properties!' >>> import apm >>> apm.zz.properties "Properties of propmod: ['hello', 'names', 'properties']" >>> apm.zz.hello 'Hello properties!' >>> apm.zz.z = 'z via apm.zz.z' >>> propmod.z 'z via apm.zz.z' >>> apm.zz.names "Shared names of propmod: ['y', 'x', 'z']" Not to go on and on, but ... >>> apm.zz.properties = ('hello',) >>> propmod.properties "Properties of propmod: ['names', 'properties']" >>> propmod.properties = 'names' >>> propmod.properties >>> propmod.properties = '' >>> propmod.properties "Properties of propmod: ['names', 'properties']" >>> propmod.properties = ('classvar', 'classvar value') >>> apm.zz.properties "Properties of propmod: ['names', 'properties']" >>> apm.zz.classvar 'classvar value' >>> apm.zz.__class__ >>> apm.zz.__class__.__dict__.keys() ['__module__', 'names', '__dict__', 'classvar', '__weakref__', 'properties', '__init__', '__doc__'] >>> apm.zz.__class__.__dict__['classvar'] 'classvar value' >>> apm.zz.classvar = 'obj attr' >>> propmod.names "Shared names of propmod: ['y', 'x', 'z', 'classvar']" >>> propmod.classvar 'obj attr' >>> del propmod.classvar >>> propmod.classvar 'classvar value' Regards, Bengt Richter From grobinson at transpose.com Sun Jul 27 10:22:24 2003 From: grobinson at transpose.com (Gary Robinson) Date: Sun, 27 Jul 2003 10:22:24 -0400 Subject: multiple file objects for some file? Message-ID: For some code I'm writing, it's convenient for me to have multiple file objects (say, 2 or 3) open on the same file in the same process for reading different locations. As far as I can tell, there is no problem with that but I thought it might be a good idea to ask here just in case I'm wrong. Thanks in advance for any feedback... --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From petrk at pochtamt.ru Mon Jul 21 09:46:52 2003 From: petrk at pochtamt.ru (Peter Klyushkin) Date: Mon, 21 Jul 2003 17:46:52 +0400 Subject: [OT] Re: How to save web pages for offline reading? References: Message-ID: Hello, hwlgw at hotmail.com! >>>>> "WS" == Will Stuyvesant writes: WS> I am trying to download pages from Python, for offline reading. WS> This to save telephone costs :-) WS> If a page contains something like href='../pythonware.css' type='text/css' /> and I use WS> fp=urllib.urlopen(...) and then fp.read(), I get the HTML but not WS> the CSS. As a result the page looks bad when reading offline. WS> How to solve this? Also the .GIF's in a page would be nice, but WS> this is less important and also would take more time to download. Try installing caching web-proxy. If squid or oops is to heavy and complex for you, try wwwoffle. Anyway, this has nothing common with Python. -- C'ya, Peter. --=[petrk at pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From peter at engcorp.com Sun Jul 6 23:03:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Jul 2003 23:03:05 -0400 Subject: Collective memory (was: Good code patterns in Python) References: Message-ID: <3F08E2E9.8014B9A9@engcorp.com> Michael Sparks wrote: > > > One really funny problem was when I guy reformatted his Python code, > > around 15K lines of it, and basically unindented *ALL* of the code to > > column 1. It was the only recoverable copy of the code too. > > > > He had to read the entire program line by line to recreate the logic. > > I changed all the permissions in /etc once by accident as well. (to 777 > IIRC) This quite spectacularly busted my system, and that took a long > while to sort out. At the time that was probably a similar number of lines > affected by a pretty stupid simple action. > > What's the moral? Backup regularly and often and especially before doing > something that touches a significant amount of stuff. Actually, the moral is "use a revision control system". Anyone not doing so should not be programming professionally.(*) -Peter *) I speak as someone who programmed professionally without using a good revision control system, for a while, and made some serious mistakes as a result. Backups are *not* sufficient, but merely a slight step up from doing nothing at all. From P.Schnizer at nospam.gsi.de Thu Jul 3 03:42:10 2003 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 03 Jul 2003 09:42:10 +0200 Subject: how to pass a file descriptor in a swig module References: Message-ID: <871xx82h0t.fsf@smtp.gsi.de> "kj.kjn" writes: > My function func(File * des) is embedded in a module swig. > > I would to know how to call this function from python script and if it's > necessay > > to declare a typemaps ? > > Thank you How to wrap call backs is explained here: http://www.swig.org/Doc1.3/SWIG.html#n30 So basically you just need to wrap the C function to an pointer, and pass that pointer to swig. A simple example is given here: http://www.itp.tu-graz.ac.at/~pierre/swig_example.tar.gz Pierre From kp at kyborg.dk Mon Jul 14 08:42:17 2003 From: kp at kyborg.dk (Kim Petersen) Date: Mon, 14 Jul 2003 14:42:17 +0200 Subject: How to give a custom object instance a type name ? In-Reply-To: References: Message-ID: <3f12a529$0$13261$edfadb0f@dread15.news.tele.dk> Graeme Matthew wrote: > Hi all, quick one, > > I hope I am explaining this properly, I am wanting to do some introspection > on custom object instances, for example: > > import md5 > >>>>m = md5.new() >>>>type(m) > > > > I can at least test here by doing something like if type(m) == 'md5.md5': how about doing this instead: isinstance(m,md5.md5) > > > Here is a custom Dispatcher class that I have written > > >>>>from BI.System.Controller.Dispatcher import Dispatcher >>>>x = Dispatcher() >>>>type(x) > > > > How do I get the same as with instance 'm' above where the type displays the > actual object instance name, however my > custom dispatcher instance is just a generic 'instance', is there some > builtin where this is set ? isinstance(x,Dispatcher) otherwise if you _really_ need the name - just do as some others indicated. -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S (Udvikling) IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From bgailer at alum.rpi.edu Thu Jul 3 20:57:01 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 03 Jul 2003 18:57:01 -0600 Subject: pipeline In-Reply-To: <200307031208.27973.dave@pythonapocrypha.com> References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <5.2.1.1.0.20030703184133.024aac98@66.28.54.253> When I worked at IBM I came across a great mainframe utility called Pipeline. It was driven by a specification that described data sources, various stages thru which the data was to be sent, various pipes that connected the stages, and various destinations for the data. The specification was not procedural. Each line of input was treated as a unit of data. Stages did things like replace, filter, sort, rearrange, conditional route to different pipes, split line, merge lines, translate, .... I keep looking for something like this to arise for the PC. Have you seen anything like this? If not I'm inclined to write one, and Python seems a likely candidate for implementing such a program. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 From klappnase at web.de Tue Jul 29 08:03:02 2003 From: klappnase at web.de (klappnase) Date: 29 Jul 2003 05:03:02 -0700 Subject: How to stop screensaver from starting up References: <9a410299.0307280614.444cc2b2@posting.google.com> Message-ID: Jeff Epler wrote in message news:... Thanks for the feedback, > For systems using xscreensaver, see xscreensaver-command(1). > > You could use > xscreensaver-command -throttle > to force screen blanking (not screensaver) when the system is idle > or > xscreensaver-command -exit > to force the screensaver process to exit. In the former case, you would > use > xscreensaver-command -unthrottle > to restart the screensaver, and in the latter case > xscreensaver -nosplash > in the latter. > > This is not robust if multiple processes all try to manipulate the > screensaver without some additional kind of locking. > > Jeff I know this, but what I had in mind was, if there is a way to disable the screensaver directly from within python/tkinter while a certain process inside my application is running (it is the recording issue I have posted here a while ago, where it seems like memory leaks occur while recording when a screensaver starts up). The basic problem with the xscreensaver command is of course that it will not work if kde-screensavers are used. I am sorry if this is a silly question, I just thought it might be easier to disable the screensaver while recording than to try a workaround for the snack recording function; maybe what I want is simply not possible. Best regards Michael From jjl at pobox.com Wed Jul 23 12:28:14 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Jul 2003 17:28:14 +0100 Subject: htaccess & urllib References: <52yTa.21249$On.2682411@twister.nyc.rr.com> Message-ID: <878yqpb42p.fsf@pobox.com> "Max Khesin" writes: > Is there a way to access an htaccess-protected directory with urllib, > password being known? urllib2 is better than urllib. >From the urllib2 module docstring, cut down a bit (and assuming you mean basic HTTP authentication -- HTTPDigestAuthHandler might also be of use to you): import urllib2 authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password('realm', 'host', 'username', 'password') opener = urllib2.build_opener(authinfo) f = opener.open('http://www.python.org/') print f.info() # response headers print f.read() # response body John From fortepianissimo at yahoo.com.tw Wed Jul 23 09:28:22 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 23 Jul 2003 06:28:22 -0700 Subject: How to link a C extension module on Mac OS X? Message-ID: Just started learning how to write a C extension module on Mac OS X. Here is a simple module taken from Programming Python: --- #include #include /* module functions */ static PyObject * /* returns object */ message(PyObject *self, PyObject *args) /* self unused in modules */ { /* args from python call */ char *fromPython, result[64]; if (! PyArg_Parse(args, "(s)", &fromPython)) /* convert Python -> C */ return NULL; /* null=raise exception */ else { strcpy(result, "Hello, "); /* build up C string */ strcat(result, fromPython); /* add passed Python string */ return Py_BuildValue("s", result); /* convert C -> Python */ } } /* registration table */ static struct PyMethodDef hello_methods[] = { {"message", message, 1}, /* method name, C func ptr, always-tuple */ {NULL, NULL} /* end of table marker */ }; , /* module initializer */ void inithello( ) /* called on first import */ { /* name matters if loaded dynamically */ (void) Py_InitModule("hello", hello_methods); /* mod name, table ptr */ } --- Then I did this g++ -I/sw/include/python2.3 -dynamiclib -o hello.dylib hello.c and got this error message: In file included from /sw/include/python2.3/Python.h:70, from hello.c:6: /sw/include/python2.3/objimpl.h:255: warning: use of `long double' type; its size may change in a future release /sw/include/python2.3/objimpl.h:255: warning: (Long double usage is reported only once for each file. /sw/include/python2.3/objimpl.h:255: warning: To disable this warning, use -Wno-long-double.) ld: Undefined symbols: _PyArg_Parse _Py_BuildValue _Py_InitModule4 /usr/bin/libtool: internal link edit command failed This is Mac OS X 10.2.6 with latest Fink installed. I guess the fetal one is the ld reporting undefined symbols. Any tip? Thx. From max at alcyone.com Wed Jul 30 22:05:13 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2003 19:05:13 -0700 Subject: reading in lines from a file -FAST! References: <300720031742549961%mday@apple.com> Message-ID: <3F287959.C83CA1EA@alcyone.com> Mark Day wrote: > How about: > s = f.read() > (assuming f is a file object) Or, if he wants to do it 1.7 MB at a time, something like: while True: chunk = f.read(1700000) if not chunk: break # handle chunk here -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Life is a zoo in a jungle. \__/ Peter de Vries From news at exultants.org Thu Jul 17 04:15:48 2003 From: news at exultants.org (Van Gale) Date: Thu, 17 Jul 2003 08:15:48 GMT Subject: IMAP examples In-Reply-To: References: <3f15cf46$0$45389$1b62eedf@news.wanadoo.nl> Message-ID: Will Stuyvesant wrote: >>[Guyon Mor?e] >>I can't seem to find any decent examples on how to use the IMPALIB module. >>the docs aren't that sophisticated unfortunately.... the cookbook entry >>comes close, but i'd like to know if someone knows some nice examples >>somewhere. > > > I did not use it myself but there is an example in the book "Python > Standard Library" by Fredrik Lundh. The example file is called > imaplib-example-1.py, maybe you can find it somewhere on the internet. Fredrik has graciously made the book available online. See: http://effbot.org/zone/librarybook-index.htm From toc-01-nospam at blikroer.dk Sat Jul 5 18:18:39 2003 From: toc-01-nospam at blikroer.dk (Tomas Christiansen) Date: Sun, 6 Jul 2003 00:18:39 +0200 Subject: win32service problems References: Message-ID: Justin Johnson wrote: > I created an NT service using win32service. This service runs as a > particular user on the domain and accepts connections to run commands on > the server. The service is working great on most of the servers I have, > but on one server it fails to start What OS'es are on the servers? ------- Tomas From steve at ferg.org Wed Jul 16 09:36:54 2003 From: steve at ferg.org (Stephen Ferg) Date: 16 Jul 2003 06:36:54 -0700 Subject: How about using python to write a CMS? References: Message-ID: Why not simply use Zope? From PoulsenL at capanalysis.com Fri Jul 18 10:47:59 2003 From: PoulsenL at capanalysis.com (PoulsenL at capanalysis.com) Date: Fri, 18 Jul 2003 10:47:59 -0400 Subject: reading Netscape mail folders Message-ID: <72F73B808A78D511A73600034771D9FF7185BE@dc_exchange2.howrey.com> I am attempting to process a number of email files that were copied from Netscape mail users. I am using the email module, but it doesn't seem to adequately determine when an email is multipart. In several instances it refuesed to parse a multi-gig text file as multiple emails. Has anyone tackled this issue before with success? Just point in the right direction and I can read on from there. Thanks in advance, Loren J. Loren Poulsen CapAnalysis Sr. Economist (202) 383-7141 This communication is for the named recipient only and may contain information that is privileged, confidential and exempt from disclosure under applicable law. If you are not the intended recipient or the employee or agent responsible for delivering this communication to the intended recipient, you are hereby notified that any unauthorized use, dissemination, distribution or copying of this communication is strictly prohibited. If you are not the intended recipient, please delete the document without opening any attachments, destroy any hard copies you may have printed and immediately notify Howrey Simon Arnold & White that you received this e-mail in error. From andrew-pythonlist at puzzling.org Sun Jul 6 00:44:06 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 6 Jul 2003 14:44:06 +1000 Subject: Collective memory (was: Good code patterns in Python) In-Reply-To: References: Message-ID: <20030706044406.GB11835@frobozz> On Fri, Jul 04, 2003 at 11:08:33PM -0400, Charles Shannon Hendrix wrote: > > Python uses it for actually determining the logic in your program, which > IMHO is dangerous. > > if > > > > > Is part of the if statement, or did someone with different > tab settings from the author make a mistake and align it accidentally? C code is indented to reflect its structure, but uses braces to reflect that structure. This is IMHO worse. if (something) work(); more_work(); add_numbers(); Is add_numbers() part of the if statement? No. Did the author intend it to be? Maybe. You can't tell. They've indented it to imply one way, but it actually works another way. Given that you should indent your code to reflect the structure anyway, Python simply discards the redundant punctuation, and avoids this sort of ambiguity. "There should be one-- and preferably only one --obvious way to do it." > One really funny problem was when I guy reformatted his Python code, > around 15K lines of it, and basically unindented *ALL* of the code to > column 1. It was the only recoverable copy of the code too. > > He had to read the entire program line by line to recreate the logic. "Doctor, when I randomly corrupt my source, it doesn't work anymore!" "So don't do that then." As another poster pointed out, deleting e.g. all the asterisks from C code would be equally painful. It's not Python's fault that guy wasn't using a version control system. -Andrew. From maxm at mxm.dk Thu Jul 10 04:47:35 2003 From: maxm at mxm.dk (Max M) Date: Thu, 10 Jul 2003 10:47:35 +0200 Subject: Python vs PHP In-Reply-To: References: Message-ID: <3F0D2827.4070501@mxm.dk> Afanasiy wrote: > Python web development is fragmented. Ahem ... How os Python web development fragmented? Most of it probably takes place in the Zope world. But mod_python is an official Apache module. Wich sets it about on par with PHP. It has a standard library that beats the socks of PHP's builtin functions. On top on this there are severeal modules for templating etc. PHP does not have these modules, so everybody has to do it in PHP's own faulty way. Python is not fragmented, but there are more high level modules for doing things. There are more PHP developers, that's right, but they are all starting from scratch, with a poor language. So it's their loss. regards Max M From zneptune321 at zexcite.zcom Mon Jul 14 17:38:57 2003 From: zneptune321 at zexcite.zcom (Conrad) Date: Mon, 14 Jul 2003 21:38:57 GMT Subject: Sio serial module install problem with ActiveState Message-ID: Greetings, I have a need to print from Win98SE to a little serial label printer provided by United Parcel, so based on Mark Hammond's recommendation in 'Programming on Win32' I decided to try the Sio module at http://starship.python.net/crew/roger/ My problem: The Sio installer dies looking for: HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.2\InstallPath I am using ActiveStates Python 2.2.2 build 224 on Win98SE. ActiveState apparently does do registry setup, for example, the HKEY_USERS\.DEFAULT\SOFTWARE tree contains the \Python\PythonCore\2.2\InstallPath keys. I re-installed Python, thinking I had blown the registry, but the keys that Sio wants are never set. FWIW, PyPGSQL, wxPython, and the egenix MxBase packages all find Python on machines with ActiveState and install OK. I don't know what they are checking on install. Can anyone suggest a fix/workaround for someone who is just a bit befuddled by registries, or did I perhaps grab the wrong Sio? ( I got SioModule22.EXE at 171184 bytes from: http://starship.python.net/crew/roger/ ) BTW, this serial printer is apparently pretty much a 'dump and go' type device - the only thing the printer seems to be capable of returning is a 4-byte error code after a special error report command is sent to the printer - other than that, all of the data and commands seem to move downstream only, with no return from the printer expected. Is Sio overkill for this, i.e. is there some incredibly simple "open a serial port under Win32 for write only" command I'm missing in the basic Python stuff? Many thanks, Conrad From mcfletch at rogers.com Tue Jul 29 01:27:25 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 29 Jul 2003 01:27:25 -0400 Subject: octet string conversion In-Reply-To: References: Message-ID: <3F2605BD.8040805@rogers.com> Bengt Richter wrote: >On 28 Jul 2003 13:14:50 -0700, ruach at chpc.utah.edu (Matthew) wrote: > > > >>I am working on some software that uses SNMP to get information from >>routers and switches. I am using the pysnmp module (v2.0.8) to do the >>snmp part. The problem that I am having is that when I query a router >>for mac addresses pysnmp returns octetstrings like this: >> >>\000\002\263\254\264\351 >>\010\000 \301F\021 >>\010\000 \300\303[ >>\000\002\263\254\264\241 >> >>what I need though is hex strings like this: >> >>0:e0:7d:de:5:48 >>0:e0:7d:c8:dc:9f >>8:0:36:4:3b:de >>0:80:ad:3a:9e:2b >> >>Can anyone tell me how to convert the octet strings to hex strings? >> >> >Assuming that your data is really octal character representations like \nnn, >and the spaces, F, and [ in the middle lines are typos, and that your need example >has nothing to do with the example data, > (I'll go from the other assumption, that he has simple strings of octets, that is, binary data) >>> def hexify( octets ): ... return ":".join( [ '%x'%(ord(c)) for c in octets ] ) ... >>> hexify ( '\010\000 \301F\021' ) '8:0:20:c1:46:11' >>> hexify ( '\000\002\263\254\264\351' ) '0:2:b3:ac:b4:e9' HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From aahz at pythoncraft.com Mon Jul 28 14:49:03 2003 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2003 14:49:03 -0400 Subject: How to get success/failure in case of thread References: Message-ID: In article , wrote: > > I am trying to learn using threads in python. But the main problem I am >facing is how to check whether the function called using a thread succeeded or >failed. like when I call: > import thread > thread.start_new_thread(my_func,(args,)) > >here my_func will return true/1 on success and false/0 on failure. How can I >check whether the function failed/succeeded ??? While Queue is probably the best way, you could also subclass from threading.Thread, call your function from the run() method, then set an instance attribute. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From srijit at yahoo.com Wed Jul 16 10:19:49 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 16 Jul 2003 07:19:49 -0700 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <221d8dbe.0307160619.2c2943c3@posting.google.com> Hi, I am working on Python-Excel interface based on the excellent library win32com. I was planning to put it up as a Python recipe in Activestate. Anyway before that I shall personally send you the code after some cleanup. It will be good to get an early feedback before I upload it in Activestate. Regards, Srijit "Allison Bailey" wrote in message news:... > Hi Folks, > > I'm a brand new Python programmer, so please point me in the right > direction if this is not the best forum for this question.... > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. > > I'm not really sure how to get started with this process. > I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), > using Microsoft Excel 10.0 Object Library, then > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") > > Then, I get errors when I try the following: > sh = wb.worksheets(1) > > > I think I'm missing something fairly fundamental, but I've googled all > over the place and can't seem to find anything very introductory about > opening and using data from MS Excel using Python. Any suggestions, > including places to get more information are welcome. > > Also, do I need to run the makepy utility every time I run my script? > If so, how would I do it from within my Python program, rather than with > the GUI in the IDE? > > Thanks for your help, > > Allison > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Allison Bailey > TerraLogic GIS, Inc. > allisonb at terralogicgis.com > 425-673-4495 > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From grante at visi.com Wed Jul 23 09:50:52 2003 From: grante at visi.com (Grant Edwards) Date: 23 Jul 2003 13:50:52 GMT Subject: python assignment References: Message-ID: <3f1e92bc$0$161$a1866201@newsreader.visi.com> In article , Ben Finney wrote: >> What I need is an exact and unambiguous algorithm for determining when >> an assignment will change the id of the variable > > As I understand it, this is specific to the implementation of each type. > The only sensible way to code is as if the identity of an object, on > assignment, were completely unpredictable. > > The examples you gave showed that integers share identity with other > integers of the same value, while floats do not. I believe that's only true for small integers, isn't it? -- Grant Edwards grante Yow! I want to TAKE IT at HOME and DRESS IT UP in visi.com HOT PANTS!! From heikowu at ceosg.de Tue Jul 29 15:56:47 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 29 Jul 2003 21:56:47 +0200 Subject: Itertools In-Reply-To: References: Message-ID: <1059508607.816.69.camel@d168.stw.stud.uni-saarland.de> Just tested the code, amend as stated (remove the - lines, and add the + lines): --- START OF CODE --- import copy class IDup(object): def __init__(self,iterin): self.__iter = iterin self.__iterno = 0 self.__iteritems = [] self.__hasstopped = None - def registerIter(): + def registerIter(self): iterno = self.__iterno self.__iterno += 1 self.__iteritems.append([]) + return iterno def getNext(self,iterno): if self.__iteritems[iterno]: iteritem = self.__iteritems[iterno].pop(0) elif self.__hasstopped is not None: raise self.__hasstopped else: try: iteritem = self.__iter.next() except StopIteration, e: self.__hasstopped = e raise for id, i in enumerate(self.__iteritems): if id <> iterno: i.append(copy.deepcopy(iteritem)) return iteritem class IDupped(object): def __init__(self,idup): self.__idup = idup self.__iterno = idup.registerIter() def next(self): return self.__idup.getNext(self.__iterno) + def __iter__(self): + return self def isplit(iterin,splitno=2): idup = IDup(iterin) iduppeds = [] for i in range(splitno): iduppeds.append(IDupped(idup)) return tuple(iduppeds) test = ["hello","how","are","you?"] x, y = isplit(iter(test)) for i in x: print i for i in y: print i --- END OF CODE --- This works as stated. Heiko. From bokr at oz.net Thu Jul 17 01:56:29 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2003 05:56:29 GMT Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? References: <3f15ca92@shknews01> Message-ID: On Wed, 16 Jul 2003 22:57:16 +0100, "Rogue9" wrote: >Hi, >I?m trying to retrieve an item from a list using a reference called >?draw?' (which is an integer from 1 to 792 in a while loop) using:- > >draw = 1 >while 1: > if draw == 792: > break > b1 = someOtherList[draw-1] > r1 = b1[draw] > draw = draw+1 > >However,the item I expect is not being retrieved i.e. a zero is the result >of the retrieval rather than the integer in the list I was expecting. >Furthermore,when I substitute an integer for draw e.g. r1 = b1[12],I >do get the expected result. >Can anyone enlighten me as to why and how to get over this please? Assuming all the lists are big enough, why is not the end result of the above loop just b1 = someOtherList[790] r1 = b1[791] draw = 792 In other words, you are not showing how your code showed you what was "being retrieved." Put in some prints to show us. Unless there are some sneaky side effects, you could as well start draw off at e.g. 789 so there won't be too much printing ;-) Is someOtherList a big list of lists or is it some strange indexable producing another strange indexable when indexed? Regards, Bengt Richter From adam6No_Spam_Please at speedy.co.il Fri Jul 25 18:20:55 2003 From: adam6No_Spam_Please at speedy.co.il (Adam) Date: Sat, 26 Jul 2003 00:20:55 +0200 Subject: Downloading Python files In-Reply-To: References: Message-ID: Luke StClair wrote: > Only marginally belonging in this newsgroup... but oh well. > > I've just started writing in python, and I want to make the files > available on the web. So I did the standard href="mypath/myfile.py"> and not surprisingly, it displays like a > webpage, but just the code. If I gzip it, and then link to the new > file, it will download, but its so small I don't want it zipped. > How can I make this into a downloadable > file SIMPLY? The other thread seems a bit complicated... > > Thanks > > > In order to assure that the file is downloaded and not displayed, you need a certain amount of control either at the client agent or the server: 1. Server: you need to be able to send the client a header which is intended for download rather than display (content-type not set to text/html) 2. Client: you need to be able to tell the client agent to download the data and save it as file on the disk ("Save targer as...") rather than display it. Adam From abelikov72 at hotmail.com Thu Jul 3 15:37:07 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 03 Jul 2003 19:37:07 GMT Subject: Python in Excel Message-ID: Can I write Excel macros/scripts using Python? I mean to actually put Python into an Excel document, not using Python to access data, for example, from some Excel document. -AB From fgeiger at datec.at Thu Jul 3 14:16:32 2003 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 3 Jul 2003 20:16:32 +0200 Subject: A story about Python... sort of References: <3f03f430$0$97222$edfadb0f@dread12.news.tele.dk> Message-ID: <3f04727e@news.swissonline.ch> > (who can't learn it) involved on your project? It also (by design) makes > previous C programmers productive very fast. Empirically - just look at all [OT] That's not a pro, that's a con on the C++ side. And actually that's the reason why there's so much bad C++ software. A C programmer first has to forget C to be able to program in C++ - well, to be able to program OO in C++. Best regards Franz GEIGER "Max Khesin" schrieb im Newsbeitrag news:KwWMa.3332$Aw.3042 at twister.nyc.rr.com... > import flame.* > import sorry.* > Ok, with all my respect to python, the stuff about C++ is a bunch of hooey. > Compilation time is the problem? Give me a break. > 1) separate compilation? > 2) precompiled headers? > 3) tools that allow cluster compilation? > 4) ever read 'large-scale c++ development' by Lacos? a must for large c++ > project. letter-envelope idiom to help compilation...etc. > Anyway, if you are coding so fast that compilation time becomes a serious > problem you are either > a) the smartest and fastest programmer on earth > b) are not thinking enough > > c++ is great when execution speed and memory efficiency is a must. It is > hard to learn, but there are great benefits, and do you really want halfwits > (who can't learn it) involved on your project? It also (by design) makes > previous C programmers productive very fast. Empirically - just look at all > the C++ projects on SF! > > max. > > > -- > ======================================== > Max Khesin, software developer - > max at cNvOiSsPiAoMntech.com > [check out our image compression software at www.cvisiontech.com, JBIG2-PDF > compression @ > www.cvisiontech.com/cvistapdf.html] > > > "Max M" wrote in message > news:3f03f430$0$97222$edfadb0f at dread12.news.tele.dk... > > There is a story today on Slashdot > > > > > > Open Source Project Management Lessons > > ====================================== > > > http://developers.slashdot.org/article.pl?sid=03/07/02/1817220&mode=flat&tid > =185 > > > > "Paul Baranowski takes a moment to reflect on Open Source Project > > Management in his blog. His reflections are based on the first two years > > of the Peek-a-booty project." Interesting comments on media coverage, > > choice of programming language, when to release a project, and more. > > > > > > In that article Paul Baranowski has a list of lessons. One being > > > > Engineering Lessons > > ------------------- > > 1. C/C++ is no longer a viable development language > > > > > > He doesn't really say in the article what language should be used > > instead. But there is a link to another page: > > > > Which Language Do You Recommend? > > ================================ > > http://peek-a-booty.org/Docs/WhichLanguageDoYouRecommend.htm > > > > > > And guess which language it is? > > > > > > regards Max M > > > > From eltronic at juno.com Thu Jul 17 17:30:18 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Thu, 17 Jul 2003 17:30:18 -0400 Subject: [OT] Re: Problems retrieving items from a list {lottery numbers} Message-ID: <20030717.173024.-176465.0.eltronic@juno.com> > >At 04:05 PM 7/17/2003 +0100, Rogue9 wrote: > >to illustrate the problem I'm having.Therefore I have > >printed the listing below which is quite short > >and hopefully won't annoy too many people > >about the length of my post. > >To reiterate: > >The masterList holds the results for the UK lottery >[snip] On Thu, 17 Jul 2003 10:51:41 -0600 Bob Gailer writes: > I sure hope you are not writing "yet another winning lottery number > predictor". It is a sad commentary on mathematics education when > individuals belive that one can predict the outcome of a truly > random > process based on any history. there are only few things more important than understanding just how random a list of numbers are. although, I agree the properly conducted lottery is random enough, therefore, we agree, don't quit your day job. in NY's pic3, randomness is ensured by randomly substituting each component of the draw, number balls, machines, air pressurem weather, who knows what else. and one can assume, sophisticated PHD's whose job depends on ensuring randomness are working on the list and sharing info. in NY numbers pic3, 000 to 999 possible, 1 of 1000. presumably the easiest to guess. if you think its impossible to narrow down the numbers to a buyable amount, then you have either never tryed or failed or believe people who tell you that its impossible. if anyone tells you its possible to narrow down the list to a buyable amount day after day, or on any particular day, they haven't run enough simulations. IMO, independant of amount of data and assuming all data is accurate. we know there are winning tickets out there never cashed in because the newspapers or official websites published the wrong info, mixed up the days, transcription errors, random bit errors. letting history go beyond a few weeks is useless due to the changes in the picking operation itself. and a few weeks of data isn't enough to turn up miniscule variations assuming you could correct for the weather. you will stand to win more than you spend or lose more than you spend on tickets. no one can guess which it will be. faith to overcome the reality that you will lose more often than you will win is a personal, however flawed, decision. the falacy is that because position one number hasn't appeared for 28 days, it soon must. and it forces you to pick position two and position three ready or not. the simulation of possible numbers bought and outcomes is the more valuable program. randomly picking numbers from all possible numbers is often as good as culling a list of ready to hit numbers. a good source of random numbers is, you guessed it, lotteries. but in this case you really don't want random numbers you want a repeatable list that matches pervious picks extropolated into the future. I repeat, the numbers I'm familiar with are random. creating a system of narrowing down the numbers is probably a lost cause, possibly in violation of the rules. it really depends on how much you desire to get out of the exercise, so I cant really quibble with the futility point. with that disclaimer: write smaller bits of code which can be tested separately. docstring testing is great for this. it specifys how the function will be used and if the data changes you can more easily adapt. with out seeing more of the code itself, its hard to guess if the program is correct from unit test and data. to simplify the program you might try to pick just the first number of the day. as you know the numbers are often sorted for publication, if so, you begin with flawed data. e ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From mis6 at pitt.edu Sat Jul 12 15:14:21 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 12 Jul 2003 12:14:21 -0700 Subject: Accessing and updating global variables among several modules References: Message-ID: <2259b0e2.0307121114.5689529b@posting.google.com> fumingw at tom.com (Fuming Wang) wrote in message news:... > Hi, > > I have several modules that need to access global variables among > them. I can do that by import modules: > > module A: > gA = 'old' > > module B: > import A > print A.gA > >>> 'old' > > change gA in module A after some initialization: > def init_fuct(): > gA = 'new' Are you aware that in this way your creating a *local* variable gA (local to the function init_fuct) without touching the original gA variable? Try def init_fuct(): global gA gA = 'new' HTH, Michele From raims at dot.com Sun Jul 20 05:33:20 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 20 Jul 2003 11:33:20 +0200 Subject: object as a reserved keyword References: Message-ID: <7dokhvgv12fdbha8sun6c6q658cth5uq2c@4ax.com> On Sun, 20 Jul 2003 11:29:03 +0200, Lawrence Oluyede wrote: >I'd like to avoid oddities like this: I just noticed that it's the same thing with other builtin types such as list, dict and so on... Hope anyone exlpain me the reason to that. Maybe is beyond my views... Lawrence From grobinson at transpose.com Tue Jul 15 11:03:51 2003 From: grobinson at transpose.com (Gary Robinson) Date: Tue, 15 Jul 2003 11:03:51 -0400 Subject: md5 consistent across platforms/Python versions? Message-ID: Hi, I know that hash functions are often platform-dependent for efficiency reasons. From what I understand, this includes Python's hash(), which I have read is not guaranteed to return the same result across platforms or even across Python versions. Can someone tell me whether an MD5 hash using Python's MD5 library IS guaranteed to return the same results for the same input string, across platforms and Python versions? My limited understanding of how MD5 is normally used would seem to indicate that this must be the case, but it would be helpful for me to have confirmation, since my knowledge in this area is very limited. --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From none at n.com Mon Jul 21 20:27:32 2003 From: none at n.com (none) Date: Mon, 21 Jul 2003 20:27:32 -0400 Subject: Python bug with dictionary Message-ID: <3F1C84F4.3B1E4F9A@n.com> or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two distinct instances of Dict and 4 distinct instances of Item. By using the accessor method addItem() in Dict I add the instances of Item to Dict. In this case I add Item1 and Item2 to Dict1 and I add Item3 and Item4 to Dict2. When this is done I print out the instances of Dict and of Item. It appears that the dictionary items in each of the Dict instances is the exact same instance even though they were created as distinctly separate classes. The print out of the results shows them at the same memory address. The items dictionary inside of each Dict object have the same id when I do id(dict1.items) and id(dict2.items). This means that each of the items dictionary in the Dict instances has all four items in it, even though each should only have two. Apparently when I add the first to Item instances to dict1 and then the second two Item instances to dict2 they are being added to the same items dictionary. If I assign the Item instances to the items dictionary without using the accessor method this does not occur. I have also tried a test with lists with and without accessor method. This works fine also. The simple solution is not to use accessor method but shouldn't this work? Dale class Dict: items = {} name = "" def addItem(self,item,name): self.items[name] = item def setName(self,name): self.name = name def getName(self): return self.name def printItemKeys(self): print "Dictonary Keys: ",self.items.keys() class Item: name = "" def getName(self): return self.name def setName(self,name): self.name = name if __name__ == '__main__': dict1 = Dict() dict1.setName("dict1") dict2 = Dict() dict2.setName("dict2") item1 = Item() item1.setName("item1") item2 = Item() item2.setName("item2") item3 = Item() item3.setName("item3") item4 = Item() item4.setName("item4") print "Item 1: ",item1 print "Item 2: ",item2 print "Item 3: ",item3 print "Item 4: ",item4 print "\n" dict1.addItem(item1,item1.getName()) dict1.addItem(item2,item2.getName()) dict2.addItem(item3,item3.getName()) dict2.addItem(item4,item4.getName()) print "Dictionary Object: ",dict1 print "Dictionary Name: ",dict1.getName() dict1.printItemKeys() print "Dictionary Keys: ",dict1.items.keys() print "Dictionary Item Objects: ",dict1.items print "\n" print "Dictionary Object: ",dict2 print "Dictionary Name: ",dict2.getName() dict2.printItemKeys() print "Dictionary Keys: ",dict2.items.keys() print "Dictionary Item Objects: ",dict2.items print "\n" print "ID of items in dict1: " + str(id(dict1.items)) print "ID of itmes in dict2: " + str(id(dict2.items)) Item 1: <__main__.Item instance at 0x00778F20> Item 2: <__main__.Item instance at 0x00779240> Item 3: <__main__.Item instance at 0x00779518> Item 4: <__main__.Item instance at 0x00779820> Dictionary Object: <__main__.Dict instance at 0x00778BE8> Dictionary Name: dict1 Dictonary Keys: ['item2', 'item3', 'item1', 'item4'] Dictionary Keys: ['item2', 'item3', 'item1', 'item4'] Dictionary Item Objects: {'item2': <__main__.Item instance at 0x00779240>, 'i tem3': <__main__.Item instance at 0x00779518>, 'item1': <__main__.Item instance at 0x00778F20>, 'item4': <__main__.Item instance at 0x00779820>} Dictionary Object: <__main__.Dict instance at 0x00778BB0> Dictionary Name: dict2 Dictonary Keys: ['item2', 'item3', 'item1', 'item4'] Dictionary Keys: ['item2', 'item3', 'item1', 'item4'] Dictionary Item Objects: {'item2': <__main__.Item instance at 0x00779240>, 'i tem3': <__main__.Item instance at 0x00779518>, 'item1': <__main__.Item instance at 0x00778F20>, 'item4': <__main__.Item instance at 0x00779820>} ID of items in dict1: 8016928 ID of itmes in dict2: 8016928 From gregadelliot at hotmail.com Sat Jul 19 19:27:35 2003 From: gregadelliot at hotmail.com (jeff) Date: 19 Jul 2003 16:27:35 -0700 Subject: python tags on websites timeout problem Message-ID: Hiya im trying to pull tags off a website using python ive got a few things running that have the potential to work its just i cant get them to becuase of certain errors? basically i dont what to download the images and all the stuff just the html and then work from there, i think its timing out because its trying to downlaod the images as well which i dont what to do as this would decrease the speed of what im trying to achieve, the URL used is only that for an example ive included my source and the errors cheers greg this is my source -------------------------------------------------------------------------------- #!/usr/bin/env python import re import urllib file = urllib.urlretrieve("http://images.google.com/images?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=rabbit" , "temp1.tmp") # open a file file = open("temp1.tmp","r") text = file.readlines() file.close() # searching the file content line by line: keyword = re.compile(r"") for line in text: result = keyword.search (line) if result: print result.group(1), ":", line, -------------------------------------------------------------------------------- and these are the errors im getting C:\Python22>python tagyourit.py Traceback (most recent call last): File "tagyourit.py", line 5, in ? file = urllib.urlretrieve("http://images.google.com/image 8&oe=UTF-8&q=rabbit" , "temp1.tmp") File "C:\PYTHON22\lib\urllib.py", line 80, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, dat File "C:\PYTHON22\lib\urllib.py", line 210, in retrieve fp = self.open(url, data) File "C:\PYTHON22\lib\urllib.py", line 178, in open return getattr(self, name)(url) File "C:\PYTHON22\lib\urllib.py", line 292, in open_http h.endheaders() File "C:\PYTHON22\lib\httplib.py", line 695, in endheaders self._send_output() File "C:\PYTHON22\lib\httplib.py", line 581, in _send_outpu self.send(msg) File "C:\PYTHON22\lib\httplib.py", line 548, in send self.connect() File "C:\PYTHON22\lib\httplib.py", line 532, in connect raise socket.error, msg -------------------------------------------------------------------------------- From pythonguy at Hotpop.com Wed Jul 30 04:01:17 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 30 Jul 2003 01:01:17 -0700 Subject: Wrtiting AVI files with Python References: <3b24bbb8.0307290957.17a126b8@posting.google.com> Message-ID: <84fc4588.0307300001.70bf5edb@posting.google.com> AFAIK the only apis in python that come close to being called multimedia APIs are PIL and the ming library for reading SWF files. PIL has support for basic animation like Animated gifs and Autodesk flc/fli animations but not for the 'heavy' formats like AVI/MPEG/QT. Of course one cannot write a library for managing multimedia formats like AVI/MPEG in pure python. The best approach is to borrow some C++ library code and implement a python interface for it. Something similar to the spread toolkit for python. (http://www.python.org/other/spread/) I was interested in creating a multimedia library for python for handling AVI/MPEG files in this manner by using a widely available C++/C library and writing a python extension for it. I have not yet done anything for it. If you plan to write one, please post it here so that I can join in or help with the coding. Regards ~Anand touma at eglin.af.mil (JamesT) wrote in message news:<3b24bbb8.0307290957.17a126b8 at posting.google.com>... > Hi all, > > I looked around for information about how to write AVI files with > Python but I didn't find any. PIL does not have that feature > implemented. The closest thing I found what the source code for > avifile which is in C++. Does any one know if there is such a tool for > Python or some libraries that I could import and use in my code? > > Thanks, > JET From lamar_air at hotmail.com Fri Jul 11 10:34:51 2003 From: lamar_air at hotmail.com (lamar_air) Date: 11 Jul 2003 07:34:51 -0700 Subject: Enter parameters into Fortran executable from python cgi script Message-ID: <2c6431ab.0307110634.1bf59a6b@posting.google.com> I have a fortran executable which when run from cmd it asks for a series of parameters which you enter then hit enter. >From my python cgi script i want to be able to run the executable. Enter the 4 or 5 parameters needed then end the executable and redirect to another web page which will display some results given from an output file from the fortran executable. When the user clicks submit on the form it seems to hang up on the interaction between python cgi and fortran exe. In this example the fortran exe only accepts on variable then terminates. How do i do this correctly? testrun3 can be accesed from any dir because it's directory is set in the environment variables. import os os.system("testrun3") os.system("Y") os.system("exit") From just at xs4all.nl Tue Jul 8 09:51:03 2003 From: just at xs4all.nl (Just van Rossum) Date: Tue, 8 Jul 2003 15:51:03 +0200 Subject: path module In-Reply-To: <16138.51270.256713.554899@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Just> a.join(b, c, d) > > Just> which I don't think is all that bad. > > Yes, but > > a/b/c/d > > is nicely analogous to Unix pathname syntax. But when the items are variables, what you read is not what you get. Often you'll want (some) literals, and then you get path = basePath/"a"/"b"/"c" ...and _that_ I find quite horrible... (Did I mention that / usually means divide in Python? ;-) Just From scpusenet at werbung.schabi.de Mon Jul 7 03:19:23 2003 From: scpusenet at werbung.schabi.de (Markus Schaber) Date: Mon, 7 Jul 2003 09:19:23 +0200 Subject: Apache mod_python and Sessions References: <20030704131617.4b1a73ca.scpusenet@werbung.schabi.de> Message-ID: <20030707091923.1f12f872.scpusenet@werbung.schabi.de> Hi, On Fri, 4 Jul 2003 13:16:17 +0200 Markus Schaber wrote: > Does anybody know a module that works with Apache 1.3 mod_python and > provides session tracking? Thanks for all that answered, I now found the nice debian package python_weblib that does what I need (Additionally, my boss suggested that we should not use mod_python but CGI instead.) I just was too stupid by including "apache" in all my search requests on google and apt-cache - this filtered out lots of useful answers... Thanks, Markus From ianb at colorstudy.com Sun Jul 20 21:42:02 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jul 2003 20:42:02 -0500 Subject: Possible use of Python for a voting machine demo project -- your feedback requested In-Reply-To: References: <7xllus94t8.fsf@ruckus.brouhaha.com> Message-ID: <1058751722.28066.2514.camel@lothlorien> On Sun, 2003-07-20 at 19:12, A.M. Kuchling wrote: > On 20 Jul 2003 16:06:11 -0700, > Paul Rubin <> wrote: > > one another. Otherwise the ballot would be a voting receipt, > > something that a good voting system should not provide. Search for > > "receipt-free voting" in Google to see what a big problem this is for > > computerized systems. > > On the other hand, given the ready availability of cellphones with digital > cameras, even in a paper-based system you can now make your own voting > receipt while you're still in the voting booth. Not clear what can be done > about this... perhaps you'll have to hand in your cellphone when voting, and > go through an X-ray system to prove you don't have it. In this system you could prove that you filled out *one* ballot a certain way, but not that the ballot you took a picture of was the same ballot that you submitted, since you can throw ballots away and start over. Ian From jepler at unpythonic.net Fri Jul 11 12:44:27 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 11 Jul 2003 11:44:27 -0500 Subject: Embedding Python, threading and scalability In-Reply-To: References: Message-ID: <20030711164427.GB16513@unpythonic.net> On Thu, Jul 10, 2003 at 07:48:57PM -0400, Aahz wrote: > In article , > Jeff Epler wrote: > >On Thu, Jul 10, 2003 at 03:54:14PM -0400, Aahz wrote: > >> > >> Other people have mentioned Perl and Tcl in this thread. I wonder how > >> they deal with the problem of loading DLLs with static data. > > > >As far as I know, tcl enforces a one interpreter to one thread > >requirement. An extension should have only thread-local data, using a > >Tcl-supplied API. > > What happens when Tcl wants to interact with some 3rd-party DLL that is > *not* thread-safe? I guess you'd have to do your own locking. Tcl has standard C APIs for Conditions, Mutexes, and thread-specific data, see the Thread(3) manpage. You'd have to surround all non-reentrant calls with Tcl_MutexLock(m) ... Tcl_MutexUnlock(m). If two extensions wanted to use the same non-thread-safe library, they'd have to cooperate in some way to use the same 'm' to Tcl_Mutex*(). I don't know if there's a standard way to do this, but I think that having the mutex defined in a shared lib they both link might work. Jeff From owski at hotmail.com Wed Jul 16 18:00:22 2003 From: owski at hotmail.com (Adam Ruth) Date: Wed, 16 Jul 2003 22:00:22 +0000 (UTC) Subject: anything like C++ references? References: <20030716130631003-0600@news.xmission.com> <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed@4ax.com> Message-ID: <20030716160013839-0600@news.xmission.com> In <8sdbhvk5b5ia2onmbca4ajkaidpu3ht9ed at 4ax.com> Stephen Horne wrote: > On Wed, 16 Jul 2003 19:06:40 +0000 (UTC), Adam Ruth > wrote: > >>In Michael Chermside >>wrote: > >>> Look, first of all, let me say that I disagree with Stephen Horne in >>> this discussion. Or, to be more precise, I think that the approach >>> he is using is not one which is useful in describing Python. HOWEVER, >>> that doesn't mean that there's NOTHING to what he is saying, and >>> your claim that there is no situation requiring "pointers" in Python >>> seems wrong to me. > > Thankyou - nice to know I'm not *completely* insane ;-) > >>You are correct in that there are times when pointer semantics would >>be somewhat useful, but they're never necessary. His statement was >>that there are time that "you really can't avoid pointers". > > Hmmm - those words were in a context. I never claimed that "you really > can't avoid pointers" in *current* Python - that's obviously not true. > But if the copy-on-write stuff were implemented, the need would arise. > For example... It sure seemed that way to me: >>They're an unhappy necessity, akin to stop-lights. You need them >>because roads intersect, but if roads don't intersect, don't use them! > >Absolutely true. And the worst thing you can do when you really can't >avoid pointers is to obscure the issue even more by disguising them as >something else. We were talking about people who wrap things in lists to simulate pointers. It would seem, from your statement, you think there are situations where you really can't avoid pointers. If I misread that, I apologize. > >>>> class c : > .... x = 0 > .... >>>> k = c() >>>> def fn(a) : > .... a.x=1 > .... >>>> fn(k) >>>> k.x > > At the moment, the result is 1. With copy-on-write, object parameters > would behave exactly the same as integer or other immutable > parameters. The result would be 0. You'd need pointers or references > or call-by-reference to do a number of things. Something occurred to me earlier today. And that is that Python does use copy-on-write semantics for parameter calls, it's just that Python only has one data type. A reference. The reference is passed by value to the function, just as you describe it should. Python, however, has a futher layer of abstraction on top of its one data type, and that's objects. I would venture that it's the extra layer of abstraction that makes Python work in a more intuitive, proper way. This is, however, just my opinion. But it does seem that new programmers who learn this abstraction find it natural and simple. It's people coming from C, et al., that seem thrown off by it. > >>I definitely went a little overboard, and it sounds like I'm saying, >>"not only are pointers not necessary, they're never desirable". My >>tone was a bit more knee jerk than was prudent. > > Then I withdraw certain comments I've made. I really can't complain > about people going "a little overboard", can I ;-) It's much less overboard then I've been known to go. I must be making progress :) > >>This is just as clear as the C++ version, and more clear than the >>Python version that wraps with the list. This example, though, >>doesn't really show the difference, it's too trivial. All of the >>versions are clear enough, with the difference being academic. > > I agree with both of these comments. > >>I would be interested in seeing a more complex example where something >>would be substantially cleaner with pointers. I have to acknowledge >>the possibility that they exist, I don't know everything... yet :) > > I was told today that both Perl and ML have something equivalent to > pointers. I don't know either language, though. Given the current > audience, mentioning Perl may be a mistake - but we could look up the > rationale for including them in ML. > > That is something to do with caution, though. I imagine that ML is a > very different language to Python. I have used Haskell and Miranda, > which are at least broadly the same paradigm but may or may not be > quite a similar languages, but even those I never exactly knew well. > > The rationales might not be very portable. >From this discussion, there seem to be two points regarding pointers. 1) Whether or not pointers are necessary, or helpful in Python as it now stands. This is debatable. 2) Whether or not pointers would be necessary if Python used a form of parameter passing more like you prefer. I now see better that this is what you are talking about regarding pointers. That they *would* be necessary if copy-on-write were in use. That I can agree with, they would be necessary (or at least some of the semantics). I still can't see that copy-on-write is better than what we have now, but hey, I prefer Pepsi to Coke, so that tells you something! As a side note, based on your description of your eduction and studies in an earlier post, I realize now how different our backgrounds seem to be. I'm coming from a world where the focus is engineering (Ada is the only language purpose-built for engineering, AFAIK). You seem to come from a background more focused on science and theory. Perhaps this is the cause of our different world views (on this issue). Just a thought, though it is interesting we both chose Python. Adam Ruth From mike at nospam.com Thu Jul 31 02:09:22 2003 From: mike at nospam.com (Mike) Date: Wed, 30 Jul 2003 23:09:22 -0700 Subject: Python speed vs csharp Message-ID: Bear with me: this post is moderately long, but I hope it is relatively succinct. I've been using Python for several years as a behavioral modeling tool for the circuits I design. So far, it's been a good trade-off: compiled C++ would run faster, but the development time of Python is so much faster, and the resulting code is so much more reliable after the first pass, that I've never been tempted to return to C++. Every time I think stupid thoughts like, "I'll bet I could do this in C++," I get out my copy of Scott Meyers' "Effecive C++," and I'm quickly reminded why it's better to stick with Python (Meyers is a very good author, but points out lots of quirks and pitfalls with C++ that I keep thinking that I shouldn't have to worry about, much less try to remember). Even though Python is wonderful in that regard, there are problems. Here's the chunk of code that I'm spending most of my time executing: # Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. 7.1.26) # Fifth order approximation. |error| <= 1.5e-7 for all x # def erfc( x ): p = 0.3275911 a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 t = 1.0 / (1.0 + p*float(x)) erfcx = ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) return erfcx This is an error function approximation, which gets called around 1.5 billion times during the simulation, and takes around 3500 seconds (just under an hour) to complete. While trying to speed things up, I created a simple test case with the code above and a main function to call it 10 million times. The code takes roughly 210 seconds to run. The current execution time is acceptable, but I need to increase the complexity of the simulation, and will need to increase the number of data points by around 20X, to roughly 30 billion. This will increase the simulation time to over a day. Since the test case code was fairly small, I translated it to C and ran it. The C code runs in approximately 7.5 seconds. That's compelling, but C isn't: part of my simulation includes a parser to read an input file. I put that together in a few minutes in Python, but there are no corresponding string or regex libraries with my C compiler, so converting my Python code would take far more time than I'd save during the resulting simulations. On a lark, I grabbed the Mono C# compiler, and converted my test case to C#. Here's the corresponding erfc code: public static double erfc( double x ) { double p, a1, a2, a3, a4, a5; double t, erfcx; p = 0.3275911; a1 = 0.254829592; a2 = -0.284496736; a3 = 1.421413741; a4 = -1.453152027; a5 = 1.061405429; t = 1.0 / (1.0 + p*x); erfcx = ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * Math.Exp(-Math.Pow(x,2.0)); return erfcx; } Surprisingly (to me, at least), this code executed 10 million iterations in 8.5 seconds - only slightly slower than the compiled C code. My first question is, why is the Python code, at 210 seconds, so much slower? My second question is, is there anything that can be done to get Python's speed close to the speed of C#? -- Mike -- From mis6 at pitt.edu Wed Jul 2 12:55:11 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 2 Jul 2003 09:55:11 -0700 Subject: cooperation of buitlin methods usingtsuper References: Message-ID: <2259b0e2.0307020855.478300c2@posting.google.com> Matthias Oberlaender wrote in message news:...> I would like to adopt the cooperation paradigm in conjunction with builtin > methods and operators, such as len, iter, +, * etc. Fine. > But the direct approach does not work with the current implementation of > super. For example, 'len(super(Y, y)' will always result in 'len() of > unsized object'. Of course, it must give an error! I think you do not understand how super works. But don't worry, that's quite common ;) > As far as I understand, this is because builtins don't use a dynamic lookup > chain, but go directly to the slots for the builtins. However, super returns > an instance of class 'super'. Since all super objects share this class, its > slots will not be filled as one might hope. > My workaround is this: I create a subclass of 'super' on the fly each time I > call 'mysuper'. Look at the definition below. It seems to work. But maybe > I have overlooked something. Is my understanding correct? Is 'mysuper' a > good solution? Possible improvements? (e.g. caching of subclasses) > Thanks for comments! > import new > class X(object): > def __len__(self): return 2222 > class Y(X): > def __len__(self): return 1111 > def mysuper(cls, inst): > return new.classobj('mysuper', (super,) + cls.__bases__, {})(cls, inst) > y = Y() > try: > print len(super(Y, y)) > except Exception, msg: > print msg > try: > print len(mysuper(Y, y)) > except Exception, msg: > print msg >Output: > len() of unsized object > 2222 I think you should re-read the documentation and google on the newsgroup for 'super'. The use case for super is in multiple inheritance, as in this example: class B(object): def __len__(self): print 'called B.__len__' return 1111 class C(B): def __len__(self): print 'called C.__len__' return super(C,self).__len__() class D(B): def __len__(self): print 'called D.__len__' return super(D,self).__len__() class E(C,D): pass print len(E()) The output of this is called C.__len__ called D.__len__ called B.__len__ 1111 Do you see why? Feel free to ask if not. I do not understand what behavior you expect from 'super'. Can you give more details on your specific use case? P.S. BTW, in Python 2.2+ you can replace ``new.classobj(name,bases,dic)`` with the built-in ``type(name,bases,dic)``. -- ____ __ _/_/ . ( / / ( / / / / Michele From martin at v.loewis.de Wed Jul 16 00:15:54 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Jul 2003 06:15:54 +0200 Subject: Anyone noticed any new changes in tkinter References: Message-ID: sreekant writes: > Any ideas This was an incompatible change in Tk 8.4.2. Either install an older Tk version, or a new _tkinter version (e.g. Python 2.3). Regards, Martin From gh at ghaering.de Thu Jul 31 08:52:45 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 31 Jul 2003 14:52:45 +0200 Subject: SQL2000 database vs python In-Reply-To: <55939F05720D954E9602518B77F6127F02F465D5@FTWMLVEM01.e2k.ad.ge.com> References: <55939F05720D954E9602518B77F6127F02F465D5@FTWMLVEM01.e2k.ad.ge.com> Message-ID: <3F29111D.2080002@ghaering.de> Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Can someone tell me if there is a module out for using a sql2000 database within python? > My python application (runs on Linux) already uses mysql but now I need also to talk to a sql2000 database on another machine. > > Any suggestions? www.python.org, google couldn't help me. http://www.object-craft.com.au/projects/mssql/ -- Gerhard From klapotec at chello.at Fri Jul 25 17:11:33 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 25 Jul 2003 21:11:33 GMT Subject: decimal to binary References: <200307250653.18754.gherron@islandtraining.com> Message-ID: On Fri, 25 Jul 2003 18:52:00 GMT, "manuel" wrote: >I use ord() to convert the value of byte in >integer, if I don't make this, I've the ASCII >symbol... > >But, for listByte[17], I must read the sequence >of 0 and 1, because I must know the 4? and 5? bit: >this bits specify the image origin. > >How I can read the 4? and 5? bit from listByte[17]? You can use this function to generate a list of digits (least significant first!) from any integer, with the default being the 8 binary digits of one byte (and no checking for anything): def digitlist(value, numdigits=8, base=2): val = value digits = [0 for i in range(numdigits)] for i in range(numdigits): val, digits[i] = divmod(val, base) return digits >>> digitlist(234) # binary 11101010 [0, 1, 0, 1, 0, 1, 1, 1] >>> digitlist(39) # binary 00100111 [1, 1, 1, 0, 0, 1, 0, 0] Now you can easily access the 4th and 5th elements (which are probably reversed if you needed the 4th and 5th bit most significant first)... Hope this helps, Christopher -- Christopher From news at yebu.de Tue Jul 29 04:20:32 2003 From: news at yebu.de (Karl Scalet) Date: Tue, 29 Jul 2003 10:20:32 +0200 Subject: blanks embedded in python 2.3 optparse In-Reply-To: <3f2625b7$0$24594$626a54ce@news.free.fr> References: <3f2625b7$0$24594$626a54ce@news.free.fr> Message-ID: pascal barbedor schrieb: > Hi > > is there a way to pass a param with blank embedded with optparse ? > (C:\Python23\Doc\lib\module-optparse.html) > > > for instance > prog --name=mr jones > you need to quote the name like prog --name="mr jones" That should work Karl From eniac at sdf-eu.org Tue Jul 8 13:39:48 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Tue, 08 Jul 2003 19:39:48 +0200 Subject: anygui newbie question References: <54omgv8rb7p08uct892h6q1qck489gvoph@4ax.com> Message-ID: Op Tue, 08 Jul 2003 20:29:53 -0400, schreef Gerard C Blais: > > I'm trying to learn anygui, running on Win98. When I run backend(), I > get mswgui. > > I've typed in the first program from the manual (one button, random > sentence in text box on click). > > Window comes up fine. When I click the button, I get a run-time error > and the traceback says my handler function has received an unexpected > argument, "source". As far as I can tell, "source" should be > expected. > > I do have a link call (link (btn, handler). > > Any ideas? Any place to look besides the on-line manual ahd Hetland's > Practical Python? > > Thanks, > > Gerry This has nothig to do with your question but have you given www.wxpython.org a try it's a really great gui toolkit From akaihola at ambi-spam-me-not-tone.com Tue Jul 22 06:25:58 2003 From: akaihola at ambi-spam-me-not-tone.com (Antti Kaihola) Date: Tue, 22 Jul 2003 13:25:58 +0300 Subject: Pause in a loop In-Reply-To: <%W7Ta.10360$t92.299097@news1.tin.it> References: <%W7Ta.10360$t92.299097@news1.tin.it> Message-ID: > Eval.py is imported in main.py, but I've a loop > in eval.py that must call a function in main.py... The obvious solution is to move that function into another module, which you import in both main.py and eval.py. Not knowing the details, this might not suit to your case... From jjl at pobox.com Tue Jul 29 17:57:52 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Jul 2003 22:57:52 +0100 Subject: unittest problems References: Message-ID: <87el095733.fsf@pobox.com> Richard Wesley writes: > I am trying to retrofit some units test into our code using the unittest > module. I can get individual rewrites to work, but I am having trouble > writing the "one test to run them all and in the darkness bind them" > script. There are two main sources of trouble: > > - Test data that is stored next to the script that uses it; > - Several levels of scripts (top/utils/tests) with tests/data scattered > at all levels; > > Are there any good examples out there of a more complex set of tests in > a multilevel tree/package with attached test data? What about standard > conventions for hooking stuff together (suite(), etc.)? http://tinyurl.com/ig2q John From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 21 21:46:12 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 22 Jul 2003 11:36:12 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <3F172442.2040907@v.loewis.de> <3F195CC4.D426E416@hotmail.com> <3F1AA450.765D07FD@hotmail.com> <3F1BB7A3.D4223855@hotmail.com> Message-ID: On Mon, 21 Jul 2003 10:51:32 +0100, Alan Kennedy wrote: > Ben Finney wrote: > > Expecting people to use a news reader that attempts to parse markup > > and render the result, is like expecting people to use an email > > reader that attempts to parse markup and render ther result. Don't. > > Solely because of technical inertia, and unwillingness to address the > (perhaps excessive) complexity of our various communications layers, > i.e. our own "Tower of 7-bit Babel", we're suppressing cultural > diversity, for no technically valid reason. Yes. The solutions must involve a significant sociological element, since that is a large part of the current situation. > I personally don't have the slightest problem with reformulating NNTP > and POP to use XML instead: In a way, I think it's almost inevitable, > given how poor our existing "ascii" technologies are at dealing with > i18n and l10n issues. Emails and usenet posts are all just documents > after all. I've no idea, though, why you keep banging on about XML for simple, plain-text documents. Substitute XML with UTF-8 in the above, and I agree entirely. This is a problem of character encodings, yet you keep wanting to apply a heavy, structural markup solution. That way lies HTML/XML email, and it's totally unnecessary and unhelpful. Email and NNTP are lightweight, freeform, unstructured document formats, and they're good that way. Nothing you've said so far has offered even a pretence of a reason for abandoning freeform text formats for heavy, markup-oriented formats. Where character encoding is the problem, Unicode is the current best solution. But that in no way necessitates a markup format. -- \ "If you're not part of the solution, you're part of the | `\ precipitate." -- Steven Wright | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From gst at gmx.at Thu Jul 31 07:34:51 2003 From: gst at gmx.at (Guenther Starnberger) Date: 31 Jul 2003 04:34:51 -0700 Subject: Python speed vs csharp References: Message-ID: Mike wrote in message news:... > The current execution time is acceptable, but I need to increase the > complexity of the simulation, and will need to increase the number of data > points by around 20X, to roughly 30 billion. This will increase the > simulation time to over a day. Since the test case code was fairly small, I > translated it to C and ran it. The C code runs in approximately 7.5 > seconds. That's compelling, but C isn't: part of my simulation includes a > parser to read an input file. I put that together in a few minutes in > Python, but there are no corresponding string or regex libraries with my C > compiler, so converting my Python code would take far more time than I'd > save during the resulting simulations. just write the time critical code in C and use SWIG (http://www.swig.org/) to generate a wrapper which allows you to call your C function from your python code. /gst From sholden at holdenweb.com Tue Jul 1 23:56:26 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 02 Jul 2003 03:56:26 GMT Subject: Possible fix for Bug 494589 - os.path.expandvars bug References: <3F02015F.3000903@dadsetan.com> Message-ID: "Behrang Dadsetan" wrote ... [...] > For the second problem - as of now a real bug whatever we decide, I > wrote within this comment (hereafter) a new expandvars version which > fits the docstring documentation of dospath.py and the comments of > ntpath.py. Sorry you will be getting no patch from me at the moment > since sourceforge's anonymous CVS access does not like me. [...] If you can figure out everything you wrote about, it can't be *that* hard to create a sourceforge account ;-). regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From travis at enthought.com Sat Jul 26 18:15:17 2003 From: travis at enthought.com (Travis N. Vaught) Date: Sat, 26 Jul 2003 17:15:17 -0500 Subject: [ANN] SciPy 03 Workshop - Scientific Computing with Python Message-ID: <002701c353c3$6888f4c0$0200a8c0@tvlaptop> ------------------ SciPy '03 Workshop ------------------ The SciPy '03 Workshop on Scientific Computing with Python is being held at Cal Tech again this year. Online registration is now available. After last year's success, we expect another great turnout with compelling presentations/tutorials. It is a two day workshop held September 11-12 in Pasadena, CA. More information may be found at: http://www.scipy.org/site_content/scipy03 Online registration is available at: https://www.enthought.com/scipy03 Please register early. Last minute registrants will have to suffer the indignity of a handwritten name tag. It currently looks like breakfast (bagels, etc.), lunch and supper will be provided Thursday, and breakfast and lunch will be provided Friday. Discussion about the workshop may be directed to the SciPy-user mailing list (http://www.scipy.org/site_content/MailList) to which you may post messages at scipy-user at scipy.org. Presenters: If you would like to present at the workshop, there are two formats: - Lightning Talks: Short (5-15 minute) presentations of a particular scientific problem solved with Python. - Presentations: Traditional presentation format ~45 minute talks. If you would like to present, contact Eric Jones at eric at enthought.com. For any other questions, please feel free to call or email Travis Vaught: travis at enthought.com, (512)536-1057. You can call the same number to register via phone (Business Hours CST). Links: SciPy.org community site: http://www.scipy.org Workshop Home: http://www.scipy.org/site_content/scipy03 Summary of last year's workshop: http://www.scipy.org/site_content/scipy02/scipy02summary.htm From peter at engcorp.com Fri Jul 4 23:30:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 04 Jul 2003 23:30:41 -0400 Subject: RTS/CTS and DTR/DTS control References: <3F060F8D.94E47DCD@engcorp.com> Message-ID: <3F064661.33614890@engcorp.com> Mike wrote: > > On Fri, 04 Jul 2003 19:36:45 -0400, Peter Hansen wrote: > > > Mike wrote: > >> > Is there a library in Python that will give me control over the > >> > handshaking lines directly? > > I actually want to control my X10 firecracker device. I have done it in > Java (on Windows) already but now I want to do it in Python on Linux. You > control the device by wiggling the control lines with certain patterns. Okay, that helps. Are there any tight timing constraints with X10? It's been a while since I looked at the specs. Pretty low data rate, isn't it? Here's a few snippets/ideas that might help get you started, if there's nothing off the shelf: >From inside a "SerialPort" class we've built, which is lacking what you need but has some pieces that might be relevant: class SerialPort: def some method(): self.port = os.open(self.portName, os.O_RDWR | os.O_NOCTTY ) def CD(self): '''retrieve CD status''' status = fcntl.ioctl(self.port, TIOCMGET, TIOCM_zero_str) value = struct.unpack('I', status)[0] & TIOCM_CD if value > 0: return 1 else: return 0 At the top, we have some ugly constants defined, probably grabbed from various web pages/google searches on Linux serial ports: ------------- # The following may be Linux specific TIOCM_CD = 0x040 TIOCM_CAR = 0x040 TIOCMGET = 0x5415 TIOCMSET = 0x5418 # The following is used to convert between C's long to Python's int. TIOCM_zero_str = struct.pack('I', 0) ------------- A quick search again with Google using TIOCMSET and TIOCM_CTS and a bunch of others finally led to this, which might be the best yet, and includes some constant definitions that might let you get something working, if this doesn't directly solve your problem: http://sparc.dnsalias.net/Python_stuff/PosixSerial.py Good luck! -Peter From aahz at pythoncraft.com Sat Jul 19 20:18:07 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2003 20:18:07 -0400 Subject: Volunteers need more visibility (was Re: www.python.org hacked?) References: <5cf68ce0.0307141017.1f3fe18e@posting.google.com> <3F12FA18.B04B400E@engcorp.com> <3F131F69.8FD9B8DD@engcorp.com> Message-ID: In article <3F131F69.8FD9B8DD at engcorp.com>, Peter Hansen wrote: > >Thanks then to Aahz, Skip, Thomas, and anyone else involved. I think we >should find a place to give more visible credit to the many people >involved in handling with such things. I had no idea so many people >who regularly contribute here were also the ones who step in to resolve >such problems, or who manage the day-to-day updates and additions. >And obviously this is a very distributed effort, unless you all happen >to be roommates. ;-) Nope, we're even on separate continents. >To add to the workload then :-), but also perhaps to help inspire >additional people to volunteer and share the load, I suggest adding a >reasonably prominent page to www.python.org with a quick summary of who >helps run the site, or other community efforts, and perhaps something >like a one-sentence bio to give a bit more of a face to some of the >lesser known folks. Enh. Maybe, but I'm too tired/busy to think about it. What I suggest is that anyone who has an interest in how the web site is set up join the site design list at http://mail.python.org/mailman/listinfo/pydotorg-redesign (This is a discussion list, not a list for the people doing the maintenance work.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From sybrenUSE at YOURthirdtower.imagination.com Tue Jul 15 03:43:27 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 15 Jul 2003 07:43:27 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <3F132103.4D18759F@engcorp.com> Message-ID: Jeremy Bowers enlightened us with: > The confusion probably stems from the fact that as of the latest XHTML > specification at the time I read it, every single example XHTML > fragment used double quotes. At no point is it ever specified either > way in the XHTML specification, except by reference to the XML > specification. Got a point there. I use single quotes all the time thouhg, in HTML generated in PHP: $msg" ?> It's a lot better than something I otHften see in other people's code: echo "$msg" Doing it the other way around doesn't work, since PHP doesn't do variable substitution between single quotes. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From bdesth.nospam at removeme.free.fr Sat Jul 19 12:26:46 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sat, 19 Jul 2003 18:26:46 +0200 Subject: List of declared variables in interactive Python session? In-Reply-To: References: Message-ID: <3f196f8b$0$23859$626a54ce@news.free.fr> Fredrik Fornwall wrote: > Hello. > > Is there a way to list all the declared variables in an interactive > Python session? > I'm not sure this is exactly what you're looking for, but you could try with dir() or globals(). HTH Bruno From frank at chagford.com Mon Jul 14 15:13:38 2003 From: frank at chagford.com (Frank Millman) Date: 14 Jul 2003 12:13:38 -0700 Subject: Business model for Open Source - advice wanted References: <246a4e07.0307100613.fc2fc50@posting.google.com> <55EPa.8760$R92.7900@news2.central.cox.net> Message-ID: <246a4e07.0307132345.5b5f576@posting.google.com> "David M. Cook" wrote in message news:<55EPa.8760$R92.7900 at news2.central.cox.net>... > In article <246a4e07.0307100613.fc2fc50 at posting.google.com>, Frank Millman > wrote: > > > I would like some advice, and I hope that the good people on c.l.p > > will give me the benefit of their experience. > > I was going to point you to this talk on "partnership" billing: > > http://www.sdphp.net/node.php?id=10 > > but I'm having problems unzipping it under Linux, myself; maybe it's OK > under windows. > > Dave Cook Nope - it will not unzip under Windows either - it seems that it is not a valid zip file. Thanks anyway. Frank Millman From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jul 18 09:39:17 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 18 Jul 2003 15:39:17 +0200 Subject: feature request: a better str.endswith In-Reply-To: References: <2259b0e2.0307180401.5dae02f2@posting.google.com> Message-ID: <3f17f883$0$49107$e4fe514c@news.xs4all.nl> Jp Calderone wrote: > On Fri, Jul 18, 2003 at 05:01:47AM -0700, Michele Simionato wrote: > >>I often feel the need to extend the string method ".endswith" to tuple >>arguments, in such a way to automatically check for multiple endings. >>For instance, here is a typical use case: >> >>if filename.endswith(('.jpg','.jpeg','.gif','.png')): >> print "This is a valid image file" >> >>Currently this is not valid Python and I must use the ugly >> >>if filename.endswith('.jpg') or filename.endswith('.jpeg') \ >> or filename.endswith('.gif') or filename.endswith('.png'): >> print "This is a valid image file" > > > extensions = ('.jpg', '.jpeg', '.gif', '.png') > if filter(filename.endswith, extensions): > print "This is a valid image file > > Jp > Using filter Michele's original statement becomes: if filter(filename.endswith, ('.jpg','.jpeg','.gif','.png')): print "This is a valid image file" IMHO this is simple enough to not require a change to the .endswith method... --Irmen From rmunn at pobox.com Fri Jul 18 10:30:41 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 18 Jul 2003 14:30:41 GMT Subject: A few beginning questions References: <3f129a8a$1@mail.hmgcc.gov.uk> <2259b0e2.0307140930.4b3c43a5@posting.google.com> Message-ID: Thomas Heller wrote: > mis6 at pitt.edu (Michele Simionato) writes: > >> "richardc" wrote in message news:<3f129a8a$1 at mail.hmgcc.gov.uk>... >>> Ive just started playing with Python and have a couple of questions. >>> >>> Im looking for an agument parsing library (from the command line), Ive come >>> across optik and argtools. What other ones are there are any of them any >>> good, is there a 'standard' lib for doing this. >>> >> >> optparse (a.k.a. optik) is great, whereas I never made my mind up to >> getopt. To "cure" getopt, I needed to define my own routines for >> argument parsing; after I started using optparse I had the satisfaction >> of erasing all of them ;) > > I have not yet tried optparse. Is it able to parse Windows' style > command lines (use '/' instead of '-', ignore case of command line > options, use long options with a single '-' or '/')? > > Thomas No. From the optparse documentation: Some other option syntaxes that the world has seen include: + a hyphen followed by a few letters, e.g. -pf (this is not the same as multiple options merged into a single argument.) + a hyphen followed by a whole word, e.g. -file (this is technically equivalent to the previous syntax, but they aren't usually seen in the same program.) + a plus sign followed by a single letter, or a few letters, or a word, e.g. +f, +rgb. + a slash followed by a letter, or a few letters, or a word, e.g. /f, /file. optparse does not support these option syntaxes, and it never will. (If you really want to use one of those option syntaxes, you'll have to subclass OptionParser and override all the difficult bits. But please don't! optparse does things the traditional Unix/GNU way deliberately; the first three are non-standard anywhere, and the last one makes sense only if you're exclusively targeting MS-DOS/Windows and/or VMS.) (This is from http://www.python.org/doc/2.3b2/lib/optparse-terminology.html) Is Windows-style arguments (with slashes) *that* important to you? Because there's absolutely nothing wrong with following the standard that's been established for over twenty years... :-) -- Robin Munn | http://www.rmunn.com/ | PGP key 0x6AFB6838 -----------------------------+-----------------------+---------------------- "Remember, when it comes to commercial TV, the program is not the product. YOU are the product, and the advertiser is the customer." - Mark W. Schumann From hwlgw at hotmail.com Thu Jul 3 10:47:33 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 3 Jul 2003 07:47:33 -0700 Subject: XML Validation with Python References: Message-ID: I could not find a solution using the Python Standard Libraries to write a simple commandline utility to do XML validation. And I found the xml.sax documentation unclear, there are no good examples to look at. Also in the Python Cookbook and in the Python in a Nutshell book the XML examples are BAD. There is nowhere a motivation for the class library design, for example "why do you need a handler in a xml.sax.parse() and why is there no default handler", nor simple examples how to use it. I like the approach taken by the Python Standard Library book by Fredrik Lundh MUCH more: clear examples and explanations. A damn shame they do not want a new edition at O'Reilly, the poor guy is now putting a free version on his website. I have found a solution for XML validation using the 3rd party pyRXP library from http://www.reportlab.com/xml/pyrxp.html Their "download and install" info is a mess, I downloaded first a .ZIP with only .DLL and .PYD files and it turned out you had to plunk that into C:\Python22\DLL. This made me turn away from pyRXP initially because bad installation usually means bad software. But later on I found a bigger .ZIP with more stuff so maybe I should've used that one? At least it works now. I can do "import pyRXP". Make sure you also download pyRXP_Documentation.pdf. This is good documentation with examples. I notice the docs in the other big .ZIP are in .RML format...whatever that is! I can not believe the amount of bad documentation and bad install approaches I see with 3rd party software. That is why I normally stick to Python Standard Library only. Anyway, I can now do XML validation, below is "validate.py". But I am not solving my initial problem: if it validates, then validate.py prints nothing, if there is a mistake then it prints an error message. What I really wanted; giving more confidence that the validation is okay; is to print 1 or 0 depending on the result, but I have not figured out yet how to do that and now I am too tired of it all... # file: validate.py import sys if len(sys.argv)<2 or sys.argv[1] in ['-h','--help','/?']: print 'Usage: validate.py xmlfilename' sys.exit() import pyRXP p = pyRXP.Parser() fn=open(sys.argv[1], 'r').read() p.parse(fn) From max at alcyone.com Thu Jul 10 00:00:15 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Jul 2003 21:00:15 -0700 Subject: A story about Python... sort of References: Message-ID: <3F0CE4CF.2398AE8C@alcyone.com> "Greg Ewing (using news.cis.dfn.de)" wrote: > Hmmm. So, if the universe is open and contains an infinite > amount of matter, then we could solve chess eventually, > but we might have to wait a while for the limits of the > observable universe to expand sufficiently... The problem is the heat death ultimately puts a limit on how much computation you can do, at least per unit volume. Lightspeed delays might put some dampers on the amount of a single, coherent distributed computation you could possibly do, since you have a finite amount of computation per unit volume possible so you need to distribute, but you need to transmit and collect those results around at only lightspeed. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ There are countless planets, like many island Earths ... \__/ Konstantin Tsiolkovsky From pete at fenelon.com Thu Jul 3 14:28:17 2003 From: pete at fenelon.com (Pete Fenelon) Date: Thu, 03 Jul 2003 18:28:17 -0000 Subject: Collective memory References: <1057243309.793889@saucer.planet.gong> <1057251216.551262@saucer.planet.gong> Message-ID: In alt.folklore.computers Rupert Pigott wrote: > > I noticed that a few of the KDE 3.1 editors support folding... :) Hmmmm, editor and GUI are two concepts that I try to keep firmly separated ;) pete -- pete at fenelon.com "there's no room for enigmas in built-up areas" HMHB From skip at pobox.com Wed Jul 2 16:17:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 2 Jul 2003 15:17:02 -0500 Subject: Possible fix for Bug 494589 - os.path.expandvars bug In-Reply-To: <3F032161.7000108@dadsetan.com> References: <3F02015F.3000903@dadsetan.com> <3F032161.7000108@dadsetan.com> Message-ID: <16131.15806.215814.555138@montanaro.dyndns.org> Behrang> I there a way for me to get a SSH CVS access? Behrang> Or will someone make/submit the patch for me? Martin v. L?wis is making nightly snapshots of the CVS tree: http://mail.python.org/pipermail/python-dev/2003-June/036609.html With that, you could create a "good enough" context diff and submit a patch on Sourceforge. Skip From harry.g.george at boeing.com Wed Jul 23 15:09:47 2003 From: harry.g.george at boeing.com (Harry George) Date: Wed, 23 Jul 2003 19:09:47 GMT Subject: Design tool References: <3f1e985d$0$236@hades.is.co.za> Message-ID: Tertius writes: > Can anyone suggest a favorite, design/Case/UML Tool used by the open > source community? (in particular the Python community) > Personally, I use Dia: http://www.lysator.liu.se/~alla/dia/ Some people use argo (which I find slow). tcm is another candidate -- lots of capability but tiny fonts and hard to grab the label handles last time I tried it. > Thanks, > Tertius > -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From elainejackson7355 at home.com Sat Jul 12 14:39:25 2003 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 12 Jul 2003 18:39:25 GMT Subject: new in town References: Message-ID: As comforting as it is to know that there are "several ways of doing this", I'd be even happier if I knew the name of just one of those ways. The FAQ searcher doesn't seem to understand lengthy explanations and hand-waving. Gerhard H?ring wrote in message news:mailman.1058024839.27499.python-list at python.org... | Elaine Jackson wrote: | > Can Python be compiled? [...] | | That depends on your definition of "compiled". If you mean that machine | language can be constructed without any interpreter involved, then the | answer is no. | | If you want a way to make a Python application not depend on an | installed interpreter, then there are several ways to do this. | | This and many more of your questions to come will be answered by the | Python FAQ, btw: http://www.python.org/cgi-bin/faqw.py | | -- Gerhard | From aahz at pythoncraft.com Sun Jul 6 12:56:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2003 12:56:15 -0400 Subject: Threading issue: [Error 9]: bad file descriptor References: Message-ID: In article , Kevin wrote: > >Has anyone else run into random IOErrors ([Error 9] bad file >descriptor) in multi-threaded Python apps? > >The app I'm running into this with (once in a while... not really >repeatable predictably) is using 3 threads, and I'm using locks around >all shared objects. The error seems to be happening mostly when I'm >trying to delete a temporary file that was originally created by a >different thread. Sounds like the problem isn't locking per se, but lack of synchronization. The simple answer: never use an external object in multiple threads. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From bignose-hates-spam at and-zip-does-too.com.au Mon Jul 21 05:15:46 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 21 Jul 2003 19:05:46 +0950 Subject: A challenge to the ASCII proponents. References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> <60dfb6f6.0307201951.4eea1930@posting.google.com> Message-ID: On Mon, 21 Jul 2003 16:20:48 +1200, Mark Hadfield wrote: > I hope you won't think if I'm a spoilsport in pointing out that it > fails the "everybody" test, as many people use proportional fonts in > their news readers. *All* solutions fail the "everybody" test. Newsreaders use the NNTP protocol, which (IIRC) only requires 7-bit ASCII. (Regardless, most newsreaders only expect 7-bit ASCII, and sometimes implement 8-bit in inconsistent ways). "International characters" and "everybody" are, at present, incompatible criteria. -- \ "Quidquid latine dictum sit, altum viditur." ("Whatever is | `\ said in Latin, sounds profound.") -- Anonymous | _o__) | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From ianb at colorstudy.com Thu Jul 10 14:47:25 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Jul 2003 13:47:25 -0500 Subject: Sample Web application In-Reply-To: References: Message-ID: <1057862845.9505.1262.camel@lothlorien> On Thu, 2003-07-10 at 10:01, A.M. Kuchling wrote: > On 09 Jul 2003 20:53:17 -0500, > Ian Bicking wrote: > > But more generally, I can't stand writing about how to work around > > problems, when (as a programmer) it is within my power to fix those > > problems. It seems far better to spend time fixing problems than merely > > documenting them. > > I don't believe it's possible to fix the installation problems. Quixote > works with Apache, IIS, AOLserver, Medusa, and Twisted; there seems nothing > that can be done to simplify things across that entire range. Well, it wasn't Quixote I was talking about. It was more things like jonpy (with wt templates, specifically), or Spyce, and in general the frameworks that were more closely tied to Apache, and to non-standard configuration (Albatross, in contrast, uses plain CGI scripts, so configuration was easy). So of course installation can be improved. Quixote works with all those environments, Webware should do it exactly the same, JOTWeb should do it the same, etc. Some of these systems are (close to) as flexible as Quixote for deployment, most aren't anywhere close. Also, the work that goes into installing one system is usually not helpful when installing another. Not only should all the frameworks be similarly flexible, but they should *do it in the same way*. > It can be made easier in one particular case, of course. For example, > setting up an SCGI application with Apache requires three steps: > > 1) Compile mod_scgi and install it. (On Debian unstable, > you can install it with apt-get. > 2) Add a directive to httpd.conf and restart: > > SCGIServer 127.0.0.1 6500 > SCGIHandler On > > 3) Run the SCGI application so that it listens to port 6500. mod_skunkweb, for instance, has a few more features than mod_scgi or mod_webkit for failure conditions (if the backend application disappears), though both have more than mod_scgi, and mod_webkit has something for handling files by extension as well. These features do make it a little more complicated, but they solve particular problems, and reducing duplication would help us all. All three protocols (mod_scgi, mod_skunkweb, and mod_webkit) do almost exactly the same thing. And then there's FastCGI... > The Dulcinea package (http://www.mems-exchange.org/software/dulcinea/) > includes scripts for running multiple web sites on a machine and easily > configuring them, but that's a feature that isn't being pushed very > strongly, and we made little effort to make this feature usable by > outsiders. Which portions are you referring to? None of the modules you describe in the overview seem to apply. Ian From rdsteph at earthlink.net Sun Jul 6 21:37:15 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: Mon, 07 Jul 2003 01:37:15 GMT Subject: Merlin, a fun little program Message-ID: <3F08CFDF.6050603@earthlink.net> I posted to my web site a fun little program called merlin.py today. Please keep in mind that I am a hobbyist and this is just a little hack, if you look at the code you will see that it is still possible to write spaghetti code, even with Python. I apologize, and I do intend to clean up the code, but it may take awhile. For now it works, with some bugs. It is a composite of a few scripts. The first, based on a script Max M uploaded to this newsgroup a while ago (2 years?), is a web scraper based multiple choice guesser. I re-wrote the web scraper to use Yahoo rather than Google, as Google somehow recognizes it as a script now and so has disabled the ability to use Google, as they say it violates their terms of service. I certainly do not want to violate anyone's terms of service, this is a just a fun little script. I also used string functions instead of regexes and an algorithm of my own. Kudos to David Mertz' Text Processing in Python for helping me figure out how to do this, indirectly. (BTW, I also posted a review of his new book on my web site...and submitted it to Slashdot, but one never knows if they will run it). The stand alone version of the web scraper (askMerlin.py) uses NLQ, a natural query language class found on the web at http://gurno.com/adam/nlq/ to identify possible answers to a user's's questions, to then be submitted to the main algorithm to choose amongst the possible answers, which I call options. Of course, the program is much more likely to be accurate when you give it a correct "option" to be picked out from amongst several incorrect options that you also give it; and in fact a bug in the composite program I call Merlin ( merlin.py) crashes completely if you do not give it any options; but this can be fixed. askMerlin.py doesn't crash and uses NLQ, but gives poor answers. However, I have a much better algorithm in mind for this part of the program; instead of giving NLQ the main response page from a query, I will give it the first "link" page from a query, which I reckon to be much more likely to contain keywords that represent good possible answers. Alas, this may have to wait until the next long weekend, unless someone else takes up the task ;-))) In the long run, the program is much more interesting using NLQ to find answers to questions where the user offers no possible answers to choose amongst or other clues; I think this has potential. For now, please give Merlin options to choose amongst. Then, I include a slightly improved Decision Analysis script, and two fun variations or specific applications of it. This script has the virtue of being my own creation, although I did recieve help from Paul Winkler and others on this list. Then I also include a script shamelessly stolen off the web that will be instantly recognizable to most of you on this newsgroup, but perhaps not to some newbies. I have in mind more such fun stuff to be added. Also, I intend to do a full GUI version, with a much better user interface, and then to create executable installers for Windows, Linux, and Mac OS X. For now though, the command line interface has the advatage of working anywhere one can get a Python command prompt; I have tested it on Windows, Linux, Mac OS X and the Sharp Zaurus PDA. The additon of a GUI and creation of executable files should keep this hobbyist busy for a while ;-))) A GUI version of Decision Analysis, that I wrote using PythonCard, is available already. All of the above can wait until I add more fun stuff to it, make it better, fix bugs, move it from the deprecated regex to the re module, and clean up the code! OK, so this hack may not be worth all the words I've given it, but, in the spirit of computer programming for everybody, I am pleased that I am producing something. I think it might be something other newbies might be able to understand and hack on also, since it is so simple. If not, so be it. I am having fun. All of this is on my web site, right at the top, at http://www.awaretek.com/plf.html Ron Stephens From p at ulmcnett.com Fri Jul 4 13:38:56 2003 From: p at ulmcnett.com (Paul McNett) Date: Fri, 4 Jul 2003 10:38:56 -0700 Subject: pyBoards.com In-Reply-To: <840592e1.0307040900.14e3e668@posting.google.com> References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> <840592e1.0307040900.14e3e668@posting.google.com> Message-ID: <200307041038.56088.p@ulmcnett.com> Hannu Kankaanp?? writes: > Message boards are more user friendly, better organized (big > plus) and more interactive. At least when I post here from > Google Groups, it takes 3-6 hours for the message to arrive > :P. Many questions thus are answered 5 times by different > people. But I don't know if the messages would arrive quicker > if I used a mail program for posting. Yes, using a mail program, I see responses immediately (within a couple minutes usually). -- Paul McNett From aahz at pythoncraft.com Tue Jul 29 12:00:38 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2003 12:00:38 -0400 Subject: Casting stones (was Re: Debugging Python ?) References: <84fc4588.0307290453.52671e11@posting.google.com> <3F268802.BDB26B67@hotmail.com> Message-ID: In article <3F268802.BDB26B67 at hotmail.com>, Alan Kennedy wrote: >Aahz wrote: >> >> Top-posting is more annoying IMO. > >However, there is a down side: it makes it impossible to get >meaningful summaries of a posters posting history on Google Groups. To the extent that's an issue (and I don't necessarily agree that it is an issue), I consider that Google's fault for not writing software that accounts for quoting. If/when they fix their software, that solves the issue from your perspective; in the meantime, we get easier-to-read threads in realtime. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From daniel.nouri at con-fuse.org Fri Jul 4 12:19:29 2003 From: daniel.nouri at con-fuse.org (Daniel Nouri) Date: Fri, 04 Jul 2003 16:19:29 GMT Subject: 'self' disappearing Message-ID: The idea of my simple piece of code is to start from a given module and wrap all functions and methods in that module and submodules. FunWrapper is the class that I use for wrapping. The last two calls of main() in module bla are of interest. While the first 'foo.bar(c)' works as expected, i.e. prints 'Hello from foo.bar' and 'Calling bar', the second call bails out with: File "seque.py", line 9, in __call__ self.fun(*args, **kwds) TypeError: bar() takes exactly 1 argument (0 given) It appears that 'instance.method()' is not the same as 'klass.method(instance)' in this case. But why? And how do I deal with that? ---bla.py--- def a(): print 'Hello from A' def b(): print 'Hello from B' class foo: def bar(self): print 'Hello from foo.bar' def baz(self): print 'Hello from foo.baz' def main(): a() b() c = foo() foo.bar(c) #works c.bar() #raises TypeError (0 arguments given) ---seque.py--- import types class FunWrapper: def __init__(self, fun): self.fun = fun def __call__(self, *args, **kwds): print 'Calling', self.fun.__name__ self.fun(*args, **kwds) def _traverse(object): for (name, obj) in object.__dict__.items(): mytype = type(obj) if mytype in (types.FunctionType, types.UnboundMethodType): wrapper = FunWrapper(obj) object.__dict__[name] = wrapper elif mytype in (types.ModuleType, types.ClassType): _traverse(obj) def seque(module, fun): _traverse(module) module.__dict__[fun]() if __name__ == '__main__': import bla seque(bla, 'main') From donn at u.washington.edu Wed Jul 9 15:29:43 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 09 Jul 2003 12:29:43 -0700 Subject: Deleting specific characters from a string References: <5ab0af73.0307091044.254f5aab@posting.google.com> Message-ID: In article <5ab0af73.0307091044.254f5aab at posting.google.com>, MatthewS at HeyAnita.com (Matt Shomphe) wrote: > Maybe a new method should be added to the str class, called "remove". > It would take a list of characters and remove them from the string: Check out the translate function - that's what its optional deletions argument is for. Donn Cave, donn at u.washington.edu From fredrik at pythonware.com Thu Jul 10 18:18:44 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Jul 2003 00:18:44 +0200 Subject: Deleting specific characters from a string References: <1057847111.3f0d77471178b@mcherm.com> Message-ID: Fredrik Lundh wrote: > if you precompile the regexp, p.sub(text, "") is nearly as fast as the > translate method under 2.3. ymmv. mmmv, too. it's "p.sub("", text)", and it was a (different) flaw in my test script. if you want performance, use "translate". From cjw at sympatico.ca Wed Jul 30 15:30:12 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 30 Jul 2003 15:30:12 -0400 Subject: PEP 209 - Multi-dimensional Arrays Message-ID: <3F281CC4.70408@sympatico.ca> This PEP was written 30 or more months ago. It appears to set out design objectives for what is becoming numarray. The original ArrayType and Array seem to have become NDArray and NumArray/ComplexArray respectively. The use of __init__ seems to have been deprecated in favour of factory functions. The numarray pdf file gives a good picture of numarray, but it is difficult to link into the main Python documentation, which is HTML oriented. Is there any intention to update the roadmap for numaray in the light of later experience or is this still the design direction? Colin W. From tvassila at siac.com Thu Jul 17 15:31:00 2003 From: tvassila at siac.com (Thanos Vassilakis) Date: Thu, 17 Jul 2003 15:31:00 -0400 Subject: html tags and webpages Message-ID: The problem you will have is HTMLParser is not great at getting the CDATA or PCDATA - thats the stuff between the tags. Try pso http://sourceforge.net/projects/pso/ |---------+----------------------------------------------> | | Rene Pijlman | | | | | | Sent by: | | | python-list-admin at python.org | | | | | | | | | 07/17/2003 02:43 PM | | | | |---------+----------------------------------------------> >------------------------------------------------------------------------------------------------------------------------------| | | | To: python-list at python.org | | cc: (bcc: Thanos Vassilakis/SIAC) | | Subject: Re: html tags and webpages | >------------------------------------------------------------------------------------------------------------------------------| jeff: >Basically what i want to do is create a script in python that will >look at a website and pull off a certain type of html tag and anything >contained within them tags, This is what you need: http://www.python.org/doc/2.2.3/lib/module-urllib.html http://www.python.org/doc/2.2.3/lib/module-HTMLParser.html -- Ren? Pijlman -- http://mail.python.org/mailman/listinfo/python-list ----------------------------------------- This message and its attachments may contain privileged and confidential information. If you are not the intended recipient(s), you are prohibited from printing, forwarding, saving or copying this email. If you have received this e-mail in error, please immediately notify the sender and delete this e-mail and its attachments from your computer. From vegard at mail.com Mon Jul 7 07:18:59 2003 From: vegard at mail.com (Vegard Bakke) Date: 7 Jul 2003 04:18:59 -0700 Subject: Will Python exceptions be documented? Message-ID: <33a013af.0307070318.73013d4@posting.google.com> >From whet I can see, Python documentation is lacking a very important piece of information. Very few functions have documented what exceptions they raise, and under what cicumstances. Is this a task on the schedule? In my opinion, every function that might raise an exception should state so explicitly in the documentation, even uncaught exceptions from a subfunction. I have seen many different examples for catching exceptions from open(). Which is the right one? The error from function math.log(0) is a by unpredictable, but at least that is documentet. What about all the others? math.asin(2), shutil, os, sys? All know that asin(2) is wrong, but how do I know that ValueError is the exception I should catch, and how do I know that is the only one? (Sorry, try it is the wrong answere here.) My other issue with is concerning the documentation of the exceptions themselves. How can I find out that I can use 'filename', 'errno' and 'strerror' for the exception IOError without having to use dir(IOError())? And is it valid in all versions/platforms? Since I'm critisising the lack of work, I will voulunteer to help out with the process. But I will need some guidance and pointers in the beginning. Python is too good to have a B+ documentation. We can do better. Cheers, Vegard -- Vegard Bakke My spelling is wobbly. It's good spelling, but it wobbles, and the letters get it the wrong places. Winnie the Pooh :wq From hokiegal99 at hotmail.com Thu Jul 17 21:33:42 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Thu, 17 Jul 2003 21:33:42 -0400 Subject: using functions and file renaming problem Message-ID: <3F174E76.4000302@hotmail.com> A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad charcters in it, that the code needs to run until all bad characters are gone? For example, if a file has the name "/\|\\]') #search for these. print " " setpath = raw_input("Path to the dir that you would like to clean: ") print " " print "--- Remove Bad Charaters From Filenames ---" print " " for root, dirs, files in os.walk(setpath): for file in files: badchars = bad.findall(file) newfile = '' for badchar in badchars: newfile = file.replace(badchar,'-') #replace bad chars. if newfile: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) print oldpath print newpath print " " print "--- Done ---" print " " From max at alcyone.com Thu Jul 24 01:19:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 Jul 2003 22:19:07 -0700 Subject: file.close() References: <3F1F5297.15D768EF@alcyone.com> <3F1F5CB2.7FB4C205@alcyone.com> Message-ID: <3F1F6C4B.BE9CCA25@alcyone.com> Ben Finney wrote: > This doesn't match Bryan's nested structure above, which you blessed > as > not "overkill" (in his words). It was this that I considered a > poorly-scaling structure, or "overkill" since only one 'try' block is > required. Do you disagree? It uses try/finally to secure the closing of many files in a timely manner. In that sense, it certainly fits the pattern. It doesn't have the same nested pattern, but try/finally isn't at issue here. If you had code which opened 50 files and looked like: fileOne = file(...) fileTwo = file(...) fileThree = file(...) ... fileFortyNine = file(...) fileFifty = file(...) I would say you are doing something wrong. A more systematic handling of many, many files is indicated whether or not you're using the try/finally idiom to ensure files get closed in a timely manner. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Together we can take this one day at a time \__/ Sweetbox From mwh at python.net Mon Jul 14 06:38:21 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Jul 2003 10:38:21 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> Message-ID: <7h3n0fho0w1.fsf@pc150.maths.bris.ac.uk> Ian Bicking writes: > Is there someplace in particular to reference people who need to learn > about what Python variables are (that they are bindings, etc)? I like http://starship.python.net/crew/mwh/hacks/objectthink.html which has the advantage of doing things the pictorial (my) way, and the verbal (Alex Martelli's) way. Cheers, M. -- First time I've gotten a programming job that required a drug test. I was worried they were going to say "you don't have enough LSD in your system to do Unix programming". -- Paul Tomblin -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From kdahlhaus at yahoo.com Wed Jul 23 09:46:41 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 23 Jul 2003 06:46:41 -0700 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: <283adf56.0307230546.379d92c3@posting.google.com> "Greg Brunet" wrote in message news:... > Thanks for mentioning PSP 8's support of Python. I have an older copy > that I haven't updated for a while, and this scripting capability is an > update worthwhile making! > Greg, If you do upgrade, please let them know that the python scripting was a major factor in your decision to do so. From kamikaze at kuoi.asui.uidaho.edu Sat Jul 26 07:00:58 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 26 Jul 2003 11:00:58 GMT Subject: Get data from a Tkinter Text Object References: Message-ID: 25 Jul 2003 10:36:04 -0700, Mauro Baraldi : > Hello World... world.hello("Mauro") > Someone can help me with a Tkinter doubt. > I need to get some data, from a Tkinter text objetc and write to a variable. s = self.textarea.get(1, END) > And, sent to a text objetc some data from a var. self.textarea.insert(END, s) -- Mark Hughes "The computer is incredibly fast, accurate, and stupid. Man is unbelievably slow, inaccurate, and brilliant. The marriage of the two is a force beyond calculation." -Leo Cherne From klapotec at chello.at Mon Jul 28 14:03:38 2003 From: klapotec at chello.at (Christopher Koppler) Date: Mon, 28 Jul 2003 18:03:38 GMT Subject: Defining/declaring constants in Python References: Message-ID: On 28 Jul 2003 10:49:58 -0700, swenggsri at yahoo.com (Sriram Chadalavada) wrote: >Hello everyone, > I am a newbie to Python with experience in C programming. For my >project, I am re-writing C routines as Python functions. > I am currently using raw numerical values and was wondering if >there is an equivalent of #define in Python for declaring constants. Python doesn't need no steenkeeng conztantz! More seriously though, no, there's no equivalent for constants in Python, as the programmer is generally considered intelligent enough to leave a value he wants to stay constant alone. So just assign your raw numerical value to whatever name you think fits best, like any other variable, and then don't assign it any other value. Accepted usage is to write the name in ALL CAPS, though - ah, just like in good old C! > Is there an elegant way of defining constants in Python? Please let >me know. If you really, really, REALLY want a varia^Wconstant that cannot be changed, no matter how hard you try, in Python, have a look at this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 Christopher From bokr at oz.net Sat Jul 19 12:34:21 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 16:34:21 GMT Subject: How to identify the method that has called another method ? References: <764b8294.0307180620.37781a4@posting.google.com> Message-ID: On 18 Jul 2003 07:20:18 -0700, martin_a_clausen at hotmail.com (Mars) wrote: >Hi. > >I am using Python 2.2.3 and new-style classes. I want to implement a >static factory method to build objects for me. My plan is to have >__init__ check that it has been called from said factory method and >not directly. Is there a elegant way of achieving this ? (and is this >a silly idea in general ?) You don't say why __init__ should need to check. Are you re-using instances and only want to do part of the init job if the factory re-uses instances from a free list? Why not just leave __init__ out and give your class an ordinary method for initializing that won't be called except on purpose? And limit __init__ to normal on-creation initialization and don't call it directly. E.g. (untested!) class MyClass(object): def __init__(self): self.init_on_creation = 'whatever needs setting once on creation only' def myinit(self, whatever): self.whatever = whatever # or whatever ;-) def myfactory(something): if freelist: instance = freelist.pop() else: instance = MyClass() instance.myinit(something) return instance ... directly = MyClass() # no automatic call to directly.myinit factorymade = myfactory(123) I'm sure you can think of variations from there. HTH Regards, Bengt Richter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jul 21 15:40:09 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 21 Jul 2003 21:40:09 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 21) In-Reply-To: <7h3ispvzw4f.fsf@pc150.maths.bris.ac.uk> References: <7h3ispvzw4f.fsf@pc150.maths.bris.ac.uk> Message-ID: <3f1c4197$0$49109$e4fe514c@news.xs4all.nl> Michael Hudson wrote: > I think there's been some quoted-printable nagery happening. Exactly. Please accept my apologies for this! Thanks to Ian Bicking for posting the 'right' URLs. I'm not sure what caused the character conversion problem, but I'll do my best to avoid it in future editions. --Irmen de Jong From jordan at krushen.com Mon Jul 21 03:48:41 2003 From: jordan at krushen.com (Jordan Krushen) Date: Mon, 21 Jul 2003 07:48:41 GMT Subject: httplib\urllib attributes problem References: Message-ID: On Mon, 21 Jul 2003 07:45:19 GMT, Jordan Krushen wrote: > At least for this one, here's the relevant code from urllib2.py: > > class OpenerDirector: > def __init__(self): > server_version = "Python-urllib/%s" % __version__ > self.addheaders = [('User-agent', server_version)] > > You should be able to override your opener's addheaders attribute > (untested): > > opener.addheaders = None Actually, it's late. Use this instead: opener.addheaders = [] This won't break if something else tries to append to the list. J. From sjmachin at lexicon.net Wed Jul 16 07:59:45 2003 From: sjmachin at lexicon.net (John Machin) Date: 16 Jul 2003 04:59:45 -0700 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: Francois Pinard wrote in message news:... > ... Montcalm, a French Canadian military of > old times. The history reports that he said: > > "Messieurs les Anglais, tirez les premiers!" > > but Audouard wrote that he fears the correct writing should have been > something like: > > "Messieurs! Les Anglais... Tirez les premiers!" > There's a much wider disparity between reported versions of Cambronne's retort to the English offer that he chuck it in at the end at Waterloo :-) From amk at amk.ca Thu Jul 31 17:51:07 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 31 Jul 2003 16:51:07 -0500 Subject: curses and use_default_colors() References: <7652139e.0307291843.2ade58c6@posting.google.com> Message-ID: On Wed, 30 Jul 2003 17:34:29 GMT, Brian Victor wrote: > static PyObject * > pyuse_default_colors(PyObject *self, PyObject *args) > { > use_default_colors(); > Py_INCREF(Py_None); > return Py_None; > } > > static PyMethodDef SpamMethods[] = { > {"use_default_colors", pyuse_default_colors, METH_VARARGS, > "Use Default Colors."}, > {NULL, NULL, 0, NULL} /* Sentinel */ Use METH_NOARGS instead of METH_VARARGS; as written, this code will accept any number of arguments to the Python use_default_colors() method and not raise any error. An alternative would be to leave METH_VARARGS and put "if (!PyArg_NoArgs(args)) return NULL;" in pyuse_default_colors(); this would work with older versions of Python at the cost of being slightly slower. I'll add this function to the curses module, so at least it'll be in 2.4; thanks for writing it. Anyone know if it's possible to test it on MacOS X? Does the Terminal support transparency? --amk > }; > > /* PyMODINIT_FUNC */ > /* The docs say to use the above, but it doesn't exist in my copy of > * Python.h. */ > void initusedefault() > { > (void) Py_InitModule("usedefault", SpamMethods); > } > #v- > > setup.py > #v+ > from distutils.core import setup, Extension > > module1 = Extension('usedefault', > libraries = ["ncurses"], > sources = ['usedefault.c']) > > setup (name = 'usedefault', > version = '1.0', > description = 'Use default colors in curses', > ext_modules = [module1]) > #v- > From no at nospam.no Thu Jul 31 15:52:46 2003 From: no at nospam.no (d z e k y l) Date: Thu, 31 Jul 2003 21:52:46 +0200 Subject: Secure FTP in Python? Message-ID: Hello, I'd like to write a small backup utility in Python, which would take advantage of Secure FTP to upload backup archives. Is there a library implementing SFTP in Python (something like ftplib)? Or is there some other (noncomplicated) way how secure uploading can be implemented in Python? Thank you for advice, Michal From dan at osheim.org Wed Jul 23 19:19:52 2003 From: dan at osheim.org (Dan Williams) Date: Wed, 23 Jul 2003 18:19:52 -0500 Subject: Standard behaviour of a getSomething method In-Reply-To: References: Message-ID: Batista, Facundo wrote: > When I want to know about a attribute (e.g.: myAttrib) of an object, I > should use the specific method (e.g.: getMyAttrib). > Its not really considered "pythonic" to access attributes through getters and setters. Instead, you can access them directly: >>> class Foo: ... def __init__(self, val): ... self.a = val ... >>> foo = Foo(4) >>> print foo.a 4 >>> foo.a = 6 >>> print foo.a 6 >>> If you need to to other processing of the data for the data (ie, if you wanted to give a copy), you can use the __getattr__ and __setattr__ methods. > Considering that this attribute is always another object (everything is > an object in Python), what should getMyAttrib do? > > 1) Return the object > 2) Return a copy of the object > > How do I return a copy of the object? try looking at: >>> import copy >>> help(copy) HTH, -Dan > > Thanks for all. > > . Facundo > > [snip] From hancock at anansispaceworks.com Wed Jul 30 01:59:45 2003 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 29 Jul 2003 22:59:45 -0700 Subject: mime types and vector graphics Message-ID: I need to store some data with a content specification like "major-type"/"minor-type", where the major-type needs to specify roughly the following types of data: text, image, vector graphic, vector 3-D model, audio, etc., and each might be represented by a specific format as well, so I might have "image/gif" or "vector/dxf" etc. Well, that looks a lot like MIME content-types, but not quite. In particular, MIME seems to have nothing to say about vector graphics (I guess they must be in the "application" type?). But I'm not very well-informed about MIME, so I wonder if my information is up-to-date. How is SVG specified in MIME, for example? I've seen "image/svg" and "image/svg+xml" and so on in a Google search, but one thing the web does poorly is tell you what the date was on the page you're reading! :-O I think I would gain a lot by conforming to an internet standard like MIME, but I'm not sure how much effort it's going to cost me. ;-) But I am doing a rather similar thing -- I need to be able to edit the data, adapting to the format, so I need to register "editor"/"viewer"/"filter" tools (I just call them "editor" but it's a broad definition) by specifying that they know what to do with the various types of data and that they can be used to "create", "edit", "quote", "markup", "view", "convert/check". All of which is pretty much the same thing as what MIME is used for in email systems. The QUESTION is: When I want to add a vector type, such as DXF, for example, should I go with: x-vector/dxf (i.e. an extension spec inside my software) or application/dxf or image/dxf (or maybe something weird along the lines of the svg+xml stuff I saw above, that looks frighteningly like adding a third layer in the MIME hierarchy). Anyway, I'm reaching a point of indecision about this. ;-) I realize this isn't exactly a python-specific question, but I am actually doing this in Python (and Zope). Any thoughts appreciated, Terry -- Terry Hancock Anansi Spaceworks http://www.AnansiSpaceworks.com/ From ugly_411 at yahoo.com Wed Jul 30 22:34:58 2003 From: ugly_411 at yahoo.com (Wes Fraser) Date: Wed, 30 Jul 2003 19:34:58 -0700 (PDT) Subject: keystroke check Message-ID: <20030731023458.86658.qmail@web20710.mail.yahoo.com> Is there any way to check in a loop to see if at that given moment in the program, a key on the key board is being pressed without actually stopping like raw_ipnut does? Thanks! Wes __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From bokr at oz.net Sun Jul 13 19:08:28 2003 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2003 23:08:28 GMT Subject: removing spaces from front and end of filenames References: <3F10BABB.D548961B@alcyone.com> <93f5c5e9.0307130744.7e9d8377@posting.google.com> Message-ID: On 13 Jul 2003 08:44:05 -0700, hokiegal99 at hotmail.com (hokiegal99) wrote: >Erik Max Francis wrote in message news:<3F10BABB.D548961B at alcyone.com>... >> hokiegal99 wrote: >> >> > This script works as I expect, except for the last section. I want the >> > last section to actually remove all spaces from the front and/or end >> > of >> > filenames. For example, a file that was named " test " would be >> > renamed "test" (the 2 spaces before and after the filename removed). >> > Any >> > suggestions on how to do this? >> >> That's what the .strip method, which is what you're using, does. If >> it's not working for you you're doing something else wrong. > >for root, dirs, files in os.walk('/home/rbt/scripts'): > for file in files: > fname = (file) > fname = fname.strip( ) >print fname > >When I print fname, it prints the filenames w/o spaces (a file named " >test " looks like "test"), but when I ls the actual files in the >directory they still contain spaces at both ends. That's what I don't >understand. It seems that .strip is ready to remove the spaces, but >that it needs one more step to actually do so. Any ideas? I don't see where you rename " test " to "test" ;-) BTW, file is a builtin name for the file class, which creates open file objects, so it's best to use another name. Maybe change that last loop to (untested!) for root, dirs, files in os.walk('/home/rbt/scripts'): for fname in files: newfile = fname.strip( ) if newfile != fname: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,fname) os.rename(oldpath,newpath) print `oldpath` # back ticks to print repr to make sure you can see spaces print `newpath` Regards, Bengt Richter From wpeterson1 at socal.rr.com Tue Jul 15 16:48:01 2003 From: wpeterson1 at socal.rr.com (William Peterson) Date: 15 Jul 2003 13:48:01 -0700 Subject: Open MS Excel Spreadsheet with Python References: Message-ID: <3d0678bb.0307151248.1ebc62f6@posting.google.com> "Allison Bailey" wrote in message news:... > Hi Folks, > > I'm a brand new Python programmer, so please point me in the right > direction if this is not the best forum for this question.... > > I would like to open an existing MS Excel spreadsheet and extract > information from specific worksheets and cells. > > I'm not really sure how to get started with this process. > I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), > using Microsoft Excel 10.0 Object Library, then > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") > At this point, I don't believe you're doing Python any more, but Visual Basic for Applications > Then, I get errors when I try the following: > sh = wb.worksheets(1) > Is worksheets the proper term or should it be Sheets? Probably depends on the version of Excel/VBA Im looking at "Python Programming on Win32", an Oreilly book. If you really must work with Excel or Word you should get it. Bill From vze4rx4y at verizon.net Mon Jul 14 23:05:33 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 15 Jul 2003 03:05:33 GMT Subject: itertools.take? References: Message-ID: <1cKQa.367$5G6.52@nwrdny03.gnilink.net> "Dan Williams" wrote in message news:vh6q7cl5ifin20 at corp.supernews.com... > Is there any interest in adding a "Haskellish" take function to > itertools? I know its easy enough to roll my own, I've been using: > > take = lambda iter, n: [x for x in itertools.islice(iter, 0, n)] I use: >>> def take(n, seq): ... return list(islice(seq, n)) > which works, but I was wondering if it was common enough to get into > itertools? It made it to the lastest update of the examples in the docs for itertools. If there is enough demand, it could go into Py2.4 Raymond Hettinger From bignose-hates-spam at and-zip-does-too.com.au Tue Jul 1 20:00:29 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 02 Jul 2003 00:00:29 GMT Subject: Circular Inheritance References: Message-ID: On Tue, 01 Jul 2003 15:36:11 -0700, jinal jhaveri wrote: > B requires C > C requires A > A requires B > > and when I try to do this using > from ...import.... > it tells me that you cannot import this. Don't Do That Then. Re-design the modules so that inheritance is a hierarchy. A band-aid solution may be to create a new class that mediates between two others, breaking the circle. Much better is to figure out why the classes need to know so much about each other, and redesign them with smaller, simpler interfaces. Even if there were a way to do circular inheritance, it would be a nightmare to understand, so needs to be redesigned anyway. -- \ "I'm beginning to think that life is just one long Yoko Ono | `\ album; no rhyme or reason, just a lot of incoherent shrieks and | _o__) then it's over." -- Ian Wolff | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From mis6 at pitt.edu Tue Jul 15 08:41:02 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Jul 2003 05:41:02 -0700 Subject: Mix lambda and list comprehension? References: <6f5b3f88.0307142302.1a1531f3@posting.google.com> Message-ID: <2259b0e2.0307150441.22921165@posting.google.com> peter.barth at t-online.de (Peter Barth) wrote in message news:<6f5b3f88.0307142302.1a1531f3 at posting.google.com>... > Hi, > trying to mix lambda expresions and list comprehension > doesn't seem to work. > --- > >>> [lambda x:x+y for y in range(10)][9](2) > 11 > >>> [lambda x:x+y for y in range(10)][4](2) > 11 > --- > I expected the second expression to return 6. > What did I do wrong? Any hints? > Thanks > - Peter It is a scope issue. The last value for y is used for all the created lambdas. All lambdas users are bitten by that, soon or later. The solution is to make y local to the lambda function, with the optional argument trick: >>> [lambda x,y=y:x+y for y in range(10)][4](2) 6 Michele From michaelb_spam_this at yahoo.com Wed Jul 23 15:29:06 2003 From: michaelb_spam_this at yahoo.com (Michael Bendzick) Date: 23 Jul 2003 12:29:06 -0700 Subject: Reading Keyboard Scan Codes Message-ID: <23daa443.0307231129.12d7ccf5@posting.google.com> Is there a simple way in python to read a keyboard scan code? I'm working on a shell script that interfaces with a proprietary keyboard device (extra buttons) and need to be able to distinguish between those keys. Thank you From t.leeuwenburg at nothing.bom.gov.au Thu Jul 17 22:10:44 2003 From: t.leeuwenburg at nothing.bom.gov.au (Tennessee James Leeuwenburg) Date: Fri, 18 Jul 2003 12:10:44 +1000 Subject: Jython classpath question References: Message-ID: Never mind, It was barfing on a dependant class that wasn't in the classpath. I was just misreading the error message. Thanks guys, -T From max at nospam.com Wed Jul 23 17:20:52 2003 From: max at nospam.com (max) Date: Wed, 23 Jul 2003 21:20:52 GMT Subject: Design tool In-Reply-To: References: <3f1e985d$0$236@hades.is.co.za> Message-ID: <3F1EFDA6.2060808@nospam.com> > All work on Windows (ArgoUML is Java application). > I meant Argo does. dia does not, AFAIK From sfb at alysseum.com Thu Jul 10 16:04:27 2003 From: sfb at alysseum.com (Simon Bayling) Date: Thu, 10 Jul 2003 20:04:27 +0000 (UTC) Subject: Parsing References: Message-ID: whatsupg21 at hotmail.com (Michael) wrote in news:e5fb8973.0307100938.13fcea56 at posting.google.com: > I have been assigned a project to parse a webpage for data using > Python. I have finished only basic tutorials. Any suggestions as to > where I should go from here? Thanks in advance. > Parsing? What are you looking for? Do you have to download the page as well? If it's a fairly simple thing to find, you could use something like; >>> import urllib >>> source = urllib.urlopen("http://www.google.com").readlines() >>> for line in source: >>> if line.find("logo.gif") > -1: >>> print "Found google logo" If the data to find is more complicated, or you need to parse the HTML as well, you should look at more string methods, maybe regular expressions (import re)... Cheers, Simon. From cookedm+news at physics.mcmaster.ca Thu Jul 31 21:50:18 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 31 Jul 2003 21:50:18 -0400 Subject: Python speed vs csharp References: Message-ID: At some point, "Terry Reedy" wrote: > "David M. Cooke" wrote in message > news:qnkn0eutndk.fsf at arbutus.physics.mcmaster.ca... >> At some point, Mike wrote: >> > Here's the chunk of code that I'm spending most of my time > executing: >> > >> > # Rational approximation for erfc(x) (Abramowitz & Stegun, Sec. > 7.1.26) >> > # Fifth order approximation. |error| <= 1.5e-7 for all x >> > # >> > def erfc( x ): >> > p = 0.3275911 >> > a1 = 0.254829592 >> > a2 = -0.284496736 >> > a3 = 1.421413741 >> > a4 = -1.453152027 >> > a5 = 1.061405429 >> > >> > t = 1.0 / (1.0 + p*float(x)) >> > erfcx = ( (a1 + (a2 + (a3 + >> > (a4 + a5*t)*t)*t)*t)*t ) * math.exp(-(x**2)) >> > return erfcx > > Does inlining the constants give any speedup? or is local lookup so > fast that it does not matter? Should've thought of that too :-). It runs in 6.07 s now (my previous version was 6.45 s, and the unmodified version above was 8.23 s). Here's my best version: exp = math.exp def erfc( x ): t = 1.0 + 0.3275911*x return ( (0.254829592 + ( (1.421413741 + (-1.453152027 + 1.061405429/t)/t)/t - 0.284496736) /t)/t ) * exp(-(x**2)) The reversal of the order of the a2 evaluation is because looking at the bytecodes (using the dis module) it turns out that -0.284 was being stored as 0.284, then negated. However, -1.45 is stored as that. This runs in 5.77 s. You could speed that up a little if you're willing to manipulate the bytecode directly :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From theller at python.net Fri Jul 4 13:39:17 2003 From: theller at python.net (Thomas Heller) Date: Fri, 04 Jul 2003 19:39:17 +0200 Subject: [Dream] A meta-wrapper module to interface any C dynamic library References: <45e6545c.0307040656.4f273046@posting.google.com> Message-ID: <8yrefayi.fsf@python.net> hwlgw at hotmail.com (Will Stuyvesant) writes: >> [Seo Sanghyeon] >> To see is to believe. >> >>> import ctypes >> >>> loader = ctypes.cdll >> >>> dll = loader.msvcrt >> >>> sin = dll.sin >> >>> sin.argtypes = [ctypes.c_double] >> >>> sin.restype = ctypes.c_double >> >>> sin(3.14) >> 0.0015926529164868282 > > I love examples like this! And ctypes is very good, I downloaded the > .EXE installer and ran it and this example works "out of the box". > > How do you know what functions are available in "dll"? Any general > strategy? On windows, you use dependency walker, although it would also be possible to write something similar in ctypes ;-) http://www.dependencywalker.com/ On unix like systems, I don't know. Use nm(1) ? Thomas From fumingw at tom.com Fri Jul 11 23:38:48 2003 From: fumingw at tom.com (Fuming Wang) Date: 11 Jul 2003 20:38:48 -0700 Subject: Accessing and updating global variables among several modules Message-ID: Hi, I have several modules that need to access global variables among them. I can do that by import modules: module A: gA = 'old' module B: import A print A.gA >>> 'old' change gA in module A after some initialization: def init_fuct(): gA = 'new' no change in module B: print A.gA >>> 'old' However, when I modify these global variables in one module, the other modules would not see the changes. Any one has any suggestions? ( I don't want to use from A import *) Thanks, Fuming From max at alcyone.com Wed Jul 2 02:31:27 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Jul 2003 23:31:27 -0700 Subject: __del__ not working with cyclic reference? (and memory-leaked?) References: Message-ID: <3F027C3F.BE89AA99@alcyone.com> Jane Austine wrote: > For example, say the singleton has a database connection, in a cgi > program. > I want the singleton clear itself(and close the connection) before > the whole process exits. It seems to be more convenient and > object-oriented. Typically singleton patterns need an out-of-band signal to tell them to destroy and reclaim the (protected) singleton instance. Usually it's done with some kind of 'close' or 'finish' method. Note that there are other patterns that are useful for singleton-like behaviors in Python; say, for instance, the Borg pattern (where each "instance" really just has a reference to the original instance's __dict__ contents). > Then "destructor" has less use than in other environments. > Maybe I should avoid destructors in python as well as I can. Not really. In C++, destructors are only called when an object is properly deleted. In Java, finalize methods have the same guarantees as Python's __del__ method; they're not guaranteed to be called in a timely fashion or at all. > It is neat and reliable. Thanks. Sure thing. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ When the solution is simple, God is answering. \__/ Albert Einstein From Eric.Sosman at sun.com Tue Jul 29 12:50:20 2003 From: Eric.Sosman at sun.com (Eric Sosman) Date: Tue, 29 Jul 2003 12:50:20 -0400 Subject: Collective memory References: <3F082031.3010503@netscape.netNOTthisBIT> Message-ID: <3F26A5CC.439ADC59@sun.com> Nico de Jong wrote: > > > Among the latter were two posters printed on [now I have forgotten the > > English word for this type of paper, but it has tractor holes along > > both sides, and is flimsy, and has horizontal perforations every now > > and then] paper, with a silk-screeened slogan advocating recycling on > > the supposedly blank side. > > You are thinking of fanfold and/or leporello. > Leporello comes probably from the operette figure, who in a scene reads a > list of his masters "conquests", and as there are about 1000 names, he had > to fold it in some way. You're off by one order of (binary) magnitude: 640 In Italia sei cento e quaranta, 231 In Alemagna due cento e trent'una, 100 Cento in Francia, 91 in Turchia novent'una, 1003 Ma in Ispagna, son gi? mille e tre! ==== 2065 I once performed this "catalog aria" in an extrememly low-budget production. As a sight gag, I handed poor Donna Elvira the "non piccolo libro," turned a couple pages for her while she registered disbelief and horror, opened up a page as if to show her the Playboy centerfold, and then strolled clear across the stage from down left to down right -- still grasping the paper, with forty feet of fan-fold unfurling as I went ... Cheap productions, cheap gags. But, I think, a perfect justification for the term "leporello" applied to fan-fold paper! -- Eric.Sosman at sun.com From db3l at fitlinxx.com Tue Jul 15 18:40:06 2003 From: db3l at fitlinxx.com (David Bolen) Date: 15 Jul 2003 18:40:06 -0400 Subject: delete file References: <2c6431ab.0307100711.780a65ad@posting.google.com> <3F0D962E.23DA9F59@engcorp.com> <2c6431ab.0307110529.7a336f30@posting.google.com> <3F0EBFED.BB283660@engcorp.com> <2c6431ab.0307150743.7dd52f3f@posting.google.com> Message-ID: Gerhard H?ring writes: > if not os.path.exists("foo"): > os.remove("foo") Wouldn't you want this to be a positive check (e.g., without "not")? > or just catch the error, with something like: > > try: > os.remove("foo") > except OSError, detail: > if detail.errno != 2: > raise For the OP, the second option should in general be preferred, since even in the first case, the file might disappear between when the exists() call is made and when the remove() call is made. Or put another way, even if you do want to use os.path.exists() to conditionalize the execution of some code, you'll need to realize that the check won't guarantee that the file remains present for any specific length of time following the check. So for maximum robustness you'd need to protect the os.remove() call anyway, and might as well dispense with the initial check and just attempt the operation. -- David From gnosis at gnosis.cx Sat Jul 5 03:18:30 2003 From: gnosis at gnosis.cx (Dr. David Mertz) Date: Sat, 5 Jul 2003 02:18:30 -0500 (CDT) Subject: Least used builtins? In-Reply-To: <1057382150.516.63.camel@lothlorien> Message-ID: |just means that "core Python" (i.e., the subset of Python's |standard library used by 95% of significant code) Nah... I think the ratio is exactly the opposite. Putting all the things I mentioned before into outside modules would require no modification at all to 95% of my modules (well, excluding some unusual introspective code I've written). And the 5% that would be affected would need one extra import line at top (unless some mechanism like startup.py eliminated even that one line). |The premise of PyPy is that *everything* is a likely candidate for |reimplementation in Python. It shouldn't matter if it's a builtin. Well... yes and no. The project is necessarily incremental. Everything is a candidate for reimplementation, but one picks low hanging fruit first. |I disagree. There's nothing saying you have to describe |everything in __builtins__ -- using that module as a teaching |outline is surely a bad idea. As soon as a new programmer gets an interactive shell they run 'dir()'. And then they wonder what all those names are about. And a natural presentation puts everthing builtin together, for example in a reference text. |That describes most of my modules! I seldom import sys -- I probably |import os much more often, but certainly not half of the time. Really?! How do you get sys.argv then? Or sys.stdin? Admittedly, a simple 'print' usually gets you the sys.stdout you want, but what about sys.stderr? At very least, your style of programming is very different from mine, or from most of the modules I download. I do agree that a bit of stuff is lumped together inside sys. Perhaps a different factoring might have been good ten years ago... but that matters a lot less than does what is in __builtins__. From rxs141 at cwru.edu Mon Jul 21 19:08:14 2003 From: rxs141 at cwru.edu (Ravi) Date: Mon, 21 Jul 2003 19:08:14 -0400 Subject: Automatically filling in answers to interactive shell command questions In-Reply-To: References: Message-ID: Ted Weatherly wrote: > Is it possible to use python to automatically fill in the answers to > interactive shell command questions? For example, I am using a shell > command addperson that behaves as follows: > > > addperson > First Name: Ted > Birthday: 12/08/1977 > Height: 6'0" > Location: San Francisco, CA > > > > I am prompted for "First Name: " and I enter "Ted". I am prompted for > "Birthday: " and I enter "12/08/1977". Imagine doing this for 100 > people or more...it gets tiresome. > > Assuming I can't change the addperson command to read data from a > file, is there any way to use python to fill in the data for the > expected questions? Perhaps a different language would be better? > > -Ted As a last resort, you can always use PExpect. It pretends to be a user sitting at a terminal. http://pexpect.sf.net Ravi From donn at drizzle.com Thu Jul 3 02:43:41 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 03 Jul 2003 06:43:41 -0000 Subject: Signal-handling question References: Message-ID: <1057214619.556563@yasure> Quoth Gary Robinson : | In some code we're writing we're making an assumption, and I'd like to | confirm that the assumption is valid. | | Suppose a signal arrives while a file is being written, and the signal | handler explicitly raises a SystemExit exception. | | My understanding is that the C-level I/O code will continue and the signal | won't be processed until the end of the atomic python interpreter | instruction that invoked that C code. | | Then, the signal handler is executed, including the SystemExit. | | Are we guaranteed that there are no circumstances under which any more file | I/O will be carried out by the interrupted code after the signal handler is | invoked? That is, are we guaranteed that the SystemExit raised by the signal | handler will immediately terminate the interrupted call to write()? I can't say I really know the details for sure, but here are a couple of questions and observations. - What interrupted call to write()? I thought your C I/O call was going to complete. I believe that's correct, it will complete, if it's really to disk, or if you get BSD-style restartable I/O on your platform. If so, the output goes out, even if after the delivery of the signal and the execution of the Python-internal C signal handler. At the system call level, at any rate, there isn't anything to terminate by the time the Python code runs. - If writing to a pipe or something and I/O isn't restartable, write will raise an exception; don't know for sure when the signal handler's Python code will run in this case, presumably before the exception handlers but I'm just guessing. - But you're probably not really calling posix.write, are you? The Python file object uses C stdio functions like fwrite(3). In this case, the effect should be similar, but different in a way that you may care about, I can't tell. The thing is, C stdio output doesn't actually write all the data to disk. The rest typically is written on fclose(3), which is automatically done at process exit, whether Python closes the file objects or not. In this case, the data is still all from writes issued prior to the Python code signal handler, but some of it is written to disk afterwards. Donn Cave, donn at drizzle.com From runeb at [remove].eyeone.com Mon Jul 21 12:34:10 2003 From: runeb at [remove].eyeone.com (Rune Braathen) Date: Mon, 21 Jul 2003 18:34:10 +0200 Subject: Python scripting with Paint Shop Pro 8.0 In-Reply-To: References: Message-ID: Marc Wilson wrote: > It's a start- actually, we want to convert the file to JPEG (if not > already), sharpen it, fix the size and also derive a thumbnail from it. I don't know whether that is doable with the python scripting in PaintShop Pro as I haven't got round to upgrading yet, but I do know that Python+PIL can do that in very few lines of work. With some tweaking, you can use py2exe to make your script into an executable, thereby removing the need for every user to install python. ( ... ) > While I'm sure Python is a lovely language, the choice is due to PSP using > the scripting engine: if I have to write something from scratch (or even > from bits'n'bobs), I'll use a language I already know. That's a very sound argument. However, if you are planning on doing any image processing in the future, you will never regret the time spent learning Python and PIL. In fact, it is a fairly good possibility that you would look back and wonder how you ever survived without it. -- runeb From suresh_vsamy at rediffmail.com Thu Jul 3 00:53:45 2003 From: suresh_vsamy at rediffmail.com (Suresh Kumar) Date: 3 Jul 2003 04:53:45 -0000 Subject: Converting canvas coordinates to window coordinates....... Message-ID: <20030703045345.10507.qmail@webmail25.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From newgene at bigfoot.com Tue Jul 29 15:37:42 2003 From: newgene at bigfoot.com (newgene) Date: 29 Jul 2003 12:37:42 -0700 Subject: howto redirect stdout/stderr into a wxPython textctrl? References: Message-ID: It works. Thank you. From m at moshez.org Tue Jul 8 12:09:06 2003 From: m at moshez.org (Moshe Zadka) Date: 8 Jul 2003 16:09:06 -0000 Subject: anything new on the ternary operator? In-Reply-To: <16138.56413.684250.921762@montanaro.dyndns.org> References: <16138.56413.684250.921762@montanaro.dyndns.org>, <3F09E4B4.FED89C06@alcyone.com> <3F09252F.9B0F52BD@alcyone.com> <40a939c9.0307080622.3118cfd7@posting.google.com> Message-ID: <20030708160906.11325.qmail@green.zadka.com> On Tue, 8 Jul 2003, Skip Montanaro wrote: > Sure, but what continent is the the Middle East in, Europe, Asia or Africa? > I had to make the same decision in Musi-Cal. I decided that Israel was part > of Europe. The decision wasn't entirely arbitrary. Most concert dates we > list for Asia are in Japan, Korea or Hong Kong. There are almost never any > African concert dates listed. Israel was close enough to Europe that it > made sense to group it there. Of course, for a music thingy it makes double the sense -- we're on the Eurovision, which may effect concert dates. [Of course, some may think grouping the eurovision with music is worse than grouping Israel with Europe :)] -- Moshe Zadka -- http://moshez.org/ Buffy: I don't like you hanging out with someone that... short. Riley: Yeah, a lot of young people nowadays are experimenting with shortness. Agile Programming Language -- http://www.python.org/ From gsmatthew at ozemail.com.au Mon Jul 14 08:29:25 2003 From: gsmatthew at ozemail.com.au (Graeme Matthew) Date: Mon, 14 Jul 2003 22:29:25 +1000 Subject: How to give a custom object instance a type name ? References: Message-ID: works fine, ta x.__class__.__name__ 'Dispatcher' >>> "Ulrich Petri" wrote in message news:beu76g$8t8vu$1 at ID-67890.news.uni-berlin.de... > "Graeme Matthew" schrieb im Newsbeitrag > news:DAwQa.168$O05.9536 at nnrp1.ozemail.com.au... > > > > Here is a custom Dispatcher class that I have written > > > > >>> from BI.System.Controller.Dispatcher import Dispatcher > > >>> x = Dispatcher() > > >>> type(x) > > > > You did Java before ;)? > > > How do I get the same as with instance 'm' above where the type displays > the > > actual object instance name, however my > > custom dispatcher instance is just a generic 'instance', is there some > > builtin where this is set ? > > > > how about > >>> x.__class__.__name__ > > HTH > Ciao Ulrich > > From bokr at oz.net Sun Jul 20 18:52:09 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Jul 2003 22:52:09 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: On 20 Jul 2003 09:39:51 -0400, aahz at pythoncraft.com (Aahz) wrote: >In article , >Mike C. Fletcher wrote: >> >> * finally, stores the value >> o tries to do what would have been done if there were no >> descriptor (with the new, coerced value) >> o does *not* create new names in the object's namespace (all >> names are documented w/ descriptors, there's not a lot of >> '_' prefixed names cluttering the namespace) >> o does *not* require a new dictionary/storage-object attribute >> for the object (the descriptor works like any other >> descriptor, a *stand-alone* object that replaces a regular >> attribute) > >But this is a recipe for name clashes. If you follow the first bullet, >it's a normal attribute, but everything else says you want a property. >Properties are themselves objects that are attached to names in an >object. You can't have the same name bound to two different objects. I was wondering if Mike was wanting to have class C(...) with property p (meaning the property object is an attribute of class C or a base), and wanting also to have the instance dict contain the data as c.p rather than, say, c._p. IOW, does he want a sneaky way to avoid seeing the underscored or otherwise modified names in the object, so as to have a clean dir(c)? Other than the problem of getting the class defined in a dynamically configurable way via metaclasses or other machinery, c.__dict__['p'] = value_from_property_fset should work, IWT. The code below does that, though a little more parameterized ;-) What I'm not getting is why a dict proxy is getting in the way, unless there is an attempt to use the property mechanism to store properties-as-values in a class-as-instance. If so, does he (continuing 3rd person since I'm replying to AAhz. Hi Mike ;-) really want all that dynamic meta-stuff to happen every time a class is instatiated, or should the classes-to-use be created once at some configuration time (maybe system start or other special times), and thereafter appear to be equivalent to plain valnilla manually written classes with properties? If the latter, some kind of factory module that manufactures configured classes with configured properties and puts them in its global name space to be used in apparently normal "import m; inst=m.C()" fashion would seem better than metaclass inheritance magic behind C. If there are other configuration times than first-import, the module could have a special factory functions for that, IWT (as in cpc.py below). The properties of the final configured/manufactured classes could of course act with any degree of dynamism desired when accessed as attributes of the final class instances. BTW, do I recall somewhere seeing that defining __dict__ as a slot induces creation of a writable dict, and could that be used to get a dict in place of proxy for the trouble spot? For Mike: What does the following not address (I assume you can rearrange things to your taste ;-) that you want to do? (InfoSource is my placeholder as an example for whatever dynamic configuration of the ultimate class you want to do). ====< cpc.py >================================================================= def getCustPropClass(infoSource): class MC_CustPropBase(type): """Metaclass to provide basic customized property methods and data""" def __new__(cls, name, bases, cdict): if name == 'CustPropBase': return type.__new__(cls, name, bases, cdict) cdict['__name__'] = name cdict['__doc__'] = infoSource[name, '__doc__'] # was raw_input('Base Doc string for property %r: '%name) # let subclasses "underride" default and config if 'default' not in cdict: cdict['default'] = infoSource[name, 'default'] # was raw_input('Base Default for property %r: '%name) if 'config' not in cdict: cdict['config'] = infoSource[name, 'config'] # was raw_input('Base Config data for property %r: '%name) def __set__(self, client, val): client.__dict__[self.__name__] = val def __get__(self, client, ctype=None): if client is None: return self if self.__name__ not in client.__dict__: return self.default return client.__dict__[self.__name__] def __delete__(self, client): if self.__name__ not in client.__dict__: raise AttributeError, 'Property %r has no instance data to delete.' % self.__name__ del client.__dict__[self.__name__] for method in '__set__ __get__ __delete__'.split(): if method in cdict: continue # don't override cdict[method] = vars()[method] return type.__new__(cls, name, bases, cdict) class CustPropBase(object): __metaclass__ = MC_CustPropBase class MC_ConfProps(type): """ Configurable property definitions to be instantiated in the instances of (this meta) class. """ def __new__(cls, name, bases, cdict): docs = filter(None, [cdict.get('__doc__', '')]) for k,v in MC_ConfProps.__dict__.items(): #walk prop defs in this class if isinstance(v, type) and (hasattr(v,'__set__') or hasattr(v, '__get__')): cdict[k] = v() docs.append('\n see also %s.%s.__doc__ for property %r'%(name, k, k)) cdict['__doc__'] = ''.join(docs) return type.__new__(cls, name, bases, cdict) class p(CustPropBase): """property p direct doc string will be overwritten by CustPropBase""" default = infoSource['p','default'] # was raw_input('Property p: "Underride" of Base default value: ') conf = infoSource['p','conf'] # was raw_input('Property p: Special Config data: ') def __set__(self, client, val): # special set method differs from CustPropBase client.__dict__['p'] = ( '(%r) modified w/ overridden base default(%r) data plus\n' 'base config(%r) & special config(%r) data.' % ( val, self.default, self.config, self.conf)) class q(CustPropBase): pass # totally default class r(CustPropBase): # totally default except read-only def __set__(self, client, val): raise AttributeError, 'Property %r is read-only' % self.__name__ class ConfiguredProperties(object): __metaclass__ = MC_ConfProps class C(ConfiguredProperties): """Empty test class C inheriting from ConfiguredProperties""" return C class InteractiveInfo(object): def __getitem__(self, ixtup): # expect (propname, dataname) tuple as key return raw_input('Enter value for property %r attribute %r: '% ixtup) #(propname,dataname) testInfo = { ('p','__doc__'): '

', ('p','default'): '

', ('p','config'): '

', ('p','conf'): '

', ('q','__doc__'): '', ('q','default'): ('', (lambda x: 123456789),'(not just strings ;-)'), ('q','config'): '', ('r','__doc__'): '', ('r','default'): '', ('r','config'): '', } def test(): for info_source in (testInfo, InteractiveInfo()): C = getCustPropClass(info_source) c = C() print 'intitial p:', c.p print 'intitial q:', c.q print 'intitial r:', c.r print 'try to set them to 123 and retrieve' for prop in 'pqr': print 'setting %s to 123'%prop try: setattr(c, prop, 123) except Exception, e: print '%s: %s'% (e.__class__.__name__, e) print 'getting %s:\n----\n%s\n----' %(prop, getattr(c,prop,'???')) print 'try to delete them and retrieve' for prop in 'pqr': print 'deleting %s'%prop try: delattr(c, prop) except Exception, e: print '%s: %s'% (e.__class__.__name__, e) print 'after deleting %s:\n----\n%s\n----' %(prop, getattr(c,prop,'???')) print 'c.__doc__\n', c.__doc__ for prop in 'pqr': print getattr(C, prop).__doc__ if __name__ == '__main__': test() =============================================================================== An interactive run (with automatic test data first): [15:46] C:\pywk\clp\fletcher>cfc.py intitial p:

intitial q: ('', at 0x00800730>, '(not just strings ;-)') intitial r: try to set them to 123 and retrieve setting p to 123 getting p: ---- (123) modified w/ overridden base default('

') data plus base config('

') & special config('

') data. ---- setting q to 123 getting q: ---- 123 ---- setting r to 123 AttributeError: Property 'r' is read-only getting r: ---- ---- try to delete them and retrieve deleting p after deleting p: ----

---- deleting q after deleting q: ---- ('', at 0x00800730>, '(not just strings ;-)') ---- deleting r AttributeError: Property 'r' has no instance data to delete. after deleting r: ---- ---- c.__doc__ Empty test class C inheriting from ConfiguredProperties see also C.q.__doc__ for property 'q' see also C.p.__doc__ for property 'p' see also C.r.__doc__ for property 'r'

Enter value for property 'p' attribute 'default': [p default] Enter value for property 'p' attribute 'conf': [p conf] Enter value for property 'p' attribute '__doc__': [p doc] Enter value for property 'p' attribute 'config': [p config] Enter value for property 'q' attribute '__doc__': [q doc] Enter value for property 'q' attribute 'default': [q default] Enter value for property 'q' attribute 'config': [q config] Enter value for property 'r' attribute '__doc__': [r doc] Enter value for property 'r' attribute 'default': [r default] Enter value for property 'r' attribute 'config': [r config] intitial p: [p default] intitial q: [q default] intitial r: [r default] try to set them to 123 and retrieve setting p to 123 getting p: ---- (123) modified w/ overridden base default('[p default]') data plus base config('[p config]') & special config('[p conf]') data. ---- setting q to 123 getting q: ---- 123 ---- setting r to 123 AttributeError: Property 'r' is read-only getting r: ---- [r default] ---- try to delete them and retrieve deleting p after deleting p: ---- [p default] ---- deleting q after deleting q: ---- [q default] ---- deleting r AttributeError: Property 'r' has no instance data to delete. after deleting r: ---- [r default] ---- c.__doc__ Empty test class C inheriting from ConfiguredProperties see also C.q.__doc__ for property 'q' see also C.p.__doc__ for property 'p' see also C.r.__doc__ for property 'r' [p doc] [q doc] [r doc] Regards, Bengt Richter From intentionally at blank.co.uk Mon Jul 14 22:45:05 2003 From: intentionally at blank.co.uk (Stephen Horne) Date: Tue, 15 Jul 2003 03:45:05 +0100 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <78c6hvgu599ku5denkkl7pgmd4n13t460i@4ax.com> <3F1353ED.4111EC1D@alcyone.com> Message-ID: On Mon, 14 Jul 2003 18:07:57 -0700, Erik Max Francis wrote: >Stephen Horne wrote: > >> 99 out of 100 times, true. But not always - especially in discrete >> maths. >> >> For example, if I write... >> >> [forall] x . f(x) = y >> >> It's hard to interpret that '=' as an assertion. Similar applies to a >> range of maths operators. > >How is that not an assertion, anymore than > > [exists] x [~ (x = y)] The '=' isn't an assertion here. The '[exists]' is an assertion - it asserts that there exists an value x for which [~ (x = y)] evaluates to true. Note the use of the boolean 'not' operator (which you represented using '~'. The boolean 'not' operator returns a value - either 'true' or 'false'. It doesn't assert anything except in the context of the whole expression. If I wrote... z = [exists] x [~ (x = y)] Things become even more clear. The '[exists]' part is no longer an assertion any more than '1+2' is an assertion. It is an expression returning a boolean result. >I don't mean this as an insult, but it seems to me that much of your >comments on Python in these threads come down to, "The way this works is >not something I would have given this name to." While that's completely >legitimate, it's hard to see it as very compelling, since your >distinctions seem to me to be fairly arbitrary (x = y is assertion but >ALL x [f(x) = y] isn't?). Not at all. If I write... x = 1 ...that is an assertion. If I write... ALL x [f(x) = y] ...that is also an assertion - but the role of the '=' operator is simply to return a boolean result. It can't form an assertion on its own because it is only a part of the expression. There is no such thing as a 'subassertion' - an assertion is an indivisible thing. A subexpression from the overall assertion, out of context, does not usefully assert anything. The '=' operator plays the same role as the '+' operator in the following... ALL x [f(x) + g(x) = 0] The '=' operator contributes to the expression because it returns a value - exactly the same as the '+' operator. From belred1 at yahoo.com Mon Jul 14 22:26:58 2003 From: belred1 at yahoo.com (Bryan) Date: Tue, 15 Jul 2003 02:26:58 GMT Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <7dc4hvslh7a8fk9p6cvsfqa1c8d44rmmnv@4ax.com> <41e6hvcl2q5bdjqlp30t1gfq42j2tgo4u4@4ax.com> Message-ID: > > In maths, a variable binds to a value. In Python, a variable binds to > an object in a way that does no correctly implement binding to a value > unless the object happens to be immutable. > this sentence is completely FALSE because python does not have the concept of variables that bind to values. therefore it's impossible for python to incorrectly implement binding variables to values like in math. python does not have the concept of variables. instead, as has been pointed out several times, python has what you can call "names" that bind to objects. two completeley different concepts. i think a lot of this argument is based on this false premise that python has true "slot" variables and incorrect comparisons are being made. bryan From troy at gci.net Tue Jul 1 21:46:28 2003 From: troy at gci.net (Troy Melhase) Date: Tue, 01 Jul 2003 17:46:28 -0800 Subject: functors References: <3jc4gvgn5rb4c4008eedg958ee594lu8p2@4ax.com> Message-ID: Tom Plunket wrote: > What I want (being a C++ coder ), is to be able to create an > object that I is callable. Hi Tom: I'm not quite certain how you intend to use the classes you provided in your original post, but the answer to your question is to define a __call__ method in your class. Untested example: class SomeClass: def __init__(self, factor): self.factor = factor def __call__(self, value): return value * self.factor my_object = SomeClass(3) print my_object(4) You can learn more about __call__ and other special functions for classes in the Language Reference (section 3.3 for python2.2). Good luck, troy From ianb at colorstudy.com Fri Jul 25 15:17:48 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Jul 2003 14:17:48 -0500 Subject: path module In-Reply-To: <20030725203322.P6906@prim.han.de> References: <1057651068.5348.386.camel@lothlorien> <20030708113219.H6906@prim.han.de> <11234c14.0307211016.344d40bc@posting.google.com> <20030725184158.O6906@prim.han.de> <1059155133.24478.10738.camel@lothlorien> <20030725203322.P6906@prim.han.de> Message-ID: <1059160667.28096.10876.camel@lothlorien> On Fri, 2003-07-25 at 13:33, holger krekel wrote: > Ian Bicking wrote: > > Jason had walkers both for all files, just non-directory files, and > > directory files. This seems useful to me, and by making it explicit I > > might just start distinguishing text from binary (which I don't now > > because I am forgetful). And a globbing walker, though I don't know how > > much of an advantage that would be over list comprehension. Actually, > > all his walkers have a globbing option. > > We currently only have one 'visit' method that accepts a filter for returning > results and a filter for recursing into the tree. You can use and > combine multiple filters like so: > > root = Path('...) > for path in root.visit(AND(isdir, nolink)): > # iterates over all non-link dirs in the tree (breadth-first) > > or > > for path in root.visit(AND(isfile, endswith('.txt')), nodotfile): > # iterates over all '*.txt' files but not recursing into ".*" > > and so on. This proved to be flexible and convenient and mostly avoids > the need for multiple walk-methods. Yeah... but we know that's not going to get into the standard library. It requires a big namespace, logic functions (AND, OR, etc.), and it confuses functions with these filter objects, which are named the same (and even if the filter objects can be used as functions, it's still confusing). It's a style that doesn't exist in the standard library, and it seems unlikely that it would get in here. The multiple walk methods would only be a shortcut anyway. Again, they might be difficult in a situation like a URL where directory and file are intermingled (and maybe ReiserFS 4...?) -- which maybe is okay, a urlpath object simply wouldn't implement that walker. Ian From frobozz_electric at hotmail.com Thu Jul 17 11:11:25 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 17 Jul 2003 15:11:25 GMT Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: Actually, that last bit of code wasn't quite right, since it relied on the LockStepper's to control the alternating between each others statement execution. What is probably being asked for is something outside the LockStepper's that will manage the switching. class LockStepper: def __init__(self, id, nstmts): self.id = id self.stmt = 1 self.nstmts = nstmts def next(self): print "instruction %s-%s"%(self.id, self.stmt) self.stmt += 1 def hasnext(self): return self.stmt <= self.nstmts class Switcher: def __init__(self, *steppers): self.steppers = steppers def __call__(self): while True: for stepper in self.steppers: if stepper.hasnext(): stepper.next() if self._done(): break def _done(self): return not [f for f in (f1,f2) if f.hasnext()] f1 = LockStepper(1, 4) f2 = LockStepper(2, 7) switch = Switcher(f1,f2) switch() From scooterm at hotmail.com Tue Jul 1 22:06:33 2003 From: scooterm at hotmail.com (valued customer) Date: 1 Jul 2003 19:06:33 -0700 Subject: Any views on YAML? References: Message-ID: <1b347673.0307011806.15eeaf00@posting.google.com> Views On YAML: Benefits: - YAML is much better than XML if 'human readability' is truly a top priority for your particular application. - YAML can pass the 'grandma' test (so simple, your grandmother can understand it without having to know 'techie' stuff). - I use YAML for persisting metadata of all sorts. It is easy to generate template-based transformations of YAML (just like one would do with XML plus [*YUK*] XSLT). For this category, I use YAML plus TemplateToolkit. Hassles: - It is not as popular as XML and therefore may be unfairly disregarded or shunned by those who require buzzword compliance. - It is relatively new and has some of the standard newness annoyances (no built-in support in development tools, inconsistencies and quirks, sparse interest). cartermark46 at ukmail.com (Mark Carter) wrote in message news:... > Does anyone have any particular views on YAML, esp. wrt XML? > > I've been storing information in CSV format - but lately I've been > thinking that it might be nice to "beef it up a bit". So as well as > storing the data itself, I might want to store the field descriptions, > formatting style, and some other stuff. So a file would be processed > along the lines of: > repeat until eof: > read-chunk-header > read-chunk-data #dependent on the header you find > > ... a la IFF (Interleaved File Format); for those who can cast their > mind back to Amigas. From g2h5dqi002 at sneakemail.com Thu Jul 10 00:06:55 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 10 Jul 2003 16:06:55 +1200 Subject: Python Global Constant In-Reply-To: <3F0BE68B.893EB7E5@engcorp.com> References: <3F0BE68B.893EB7E5@engcorp.com> Message-ID: Peter Hansen wrote: > Just do what you did above, without the "const" modifier, which > doesn't exist and is not really needed in Python. If you *really* insist on preventing anyone from changing them, it is possible, with some hackery. Here's one way that works: ####################################################### # # MyModule.py # _constants = ['PI', 'FortyTwo'] PI = 3.1415 FortyTwo = 42 import types class _ConstModule(types.ModuleType): __slots__ = [] def __setattr__(self, name, value): if name in self.__dict__['_constants']: raise ValueError("%s is read-only" % name) self.__dict__[name] = value del types import MyModule MyModule.__class__ = _ConstModule ####################################################### Figuring out *how* it works is left as an exercise for the student. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From alanmk at hotmail.com Mon Jul 14 06:06:03 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 14 Jul 2003 11:06:03 +0100 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> Message-ID: <3F12808B.E53193B8@hotmail.com> Dan Bishop wrote: > The Babelfish translation is > > "People, you polskazhite plz where to reach progu to > frizer(kazhet'sya, shorter must be into yekhe-shnik outdistanced)." My favourite "phrase designed to mess up machine translation" (I'll bet there's one big long word for that in German) is "Time flies like an arrow, but fruit flies like a banana". :-D I'd love to hear of other similar phrases. And somehow I intuit there's people in this ng who know lots of them :-) If people think it's too much newsgroup abuse to discuss such a non-python subject, then email them to me privately, and I'll collect and list them. monday-morning-coffee-hasn't-kicked-in-yet-ly yrs. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From nagylzs at freemail.hu Fri Jul 11 11:58:07 2003 From: nagylzs at freemail.hu (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Fri, 11 Jul 2003 17:58:07 +0200 Subject: Securing 'pickle' References: <7x1xwxu98y.fsf@ruckus.brouhaha.com> <3F0E1875.574DC6D7@alcyone.com> <87k7apyuor.fsf@pobox.com> Message-ID: <3F0EDE8F.1050408@freemail.hu> > > >>Security isn't a big deal -- or rather, securing cookies isn't a big >>deal. >> >> > >I don't understand. The problem is that pickles can be constructed >that can damage systems when unpickled, is that right? If that's >true, then surely unpickling cookie data is unsafe, because stuff >coming in from the network has to be regarded as malevolent. Are you >saying that web server environments are sufficiently-well bolted down >that no pickle attack will work? But belt-and-braces is the best >policy, isn't it? > I'm sorry, I just caught this thread and I don't know your problem very well. I'm extensively using this (see below). It is unable to pickle class instances but you won't accidentally run constructors. I think it is safe for sending/receiving data. I did not try to publish this yet but it would be great to know if this is safe or not so please make comments. Laci 1.0 import cStringIO import cPickle def dumps(obj): f = cStringIO.StringIO() p = cPickle.Pickler(f,1) p.dump(obj) return f.getvalue() def loads(s): f = cStringIO.StringIO(s) p = cPickle.Unpickler(f) p.find_global = None return p.load() -------------- next part -------------- An HTML attachment was scrubbed... URL: From tzot at sil-tec.gr Tue Jul 22 13:28:14 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Jul 2003 20:28:14 +0300 Subject: Confusing automated translators. References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> <3F12808B.E53193B8@hotmail.com> <87brvw3ula.fsf@pobox.com> Message-ID: On 15 Jul 2003 10:24:17 -0400, rumours say that Francois Pinard might have written: >Automated translators which ignore punctuation are pretty fragile, too. There is also the old story of the Oracle at Delphi (and *that* is indeed related to Python, see http://www.tylwythteg.com/delphi/delphi.html :), which owed much of its success to the dubiousness of the predictions (nobody could prove the prediction wrong); a good example of needed punctuation was the one that meant either "you will go, you will come, you won't die at war" or "you will go, you won't come, you will die at war" In ancient Greek that was because of the negation "ou", which being between the second and third subsentence, could be attributed to either one; it was valid greek either way. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From mail at cheesch.de Tue Jul 15 18:10:09 2003 From: mail at cheesch.de (Carsten Heesch) Date: Wed, 16 Jul 2003 00:10:09 +0200 Subject: Need help: Compiling Python-Code References: Message-ID: > import py_compile > py_compile.compile(Python-file) That's it. Thx! Now I can compile my complex capisuite-incoming/idle-scripts. Carsten From vivek at cs.unipune.ernet.in Thu Jul 31 06:26:01 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Thu, 31 Jul 2003 15:56:01 +0530 Subject: Sol : MultiThreaded XMLRPCServer was (Re: How to get success/failure in case of thread) In-Reply-To: <84fc4588.0307300511.11b4db5b@posting.google.com>; from pythonguy@Hotpop.com on Wed, Jul 30, 2003 at 06:11:41AM -0700 References: <20030728175542.A23857@cs.unipune.ernet.in> <16165.10847.483917.787182@montanaro.dyndns.org> <84fc4588.0307290442.7c203e35@posting.google.com> <84fc4588.0307300511.11b4db5b@posting.google.com> Message-ID: <20030731155601.A32564@cs.unipune.ernet.in> > vivek at cs.unipune.ernet.in wrote in message news:... > > How can I use multiple threads in SimpleXMLRPCServer ??? > > > > TIA and Kind Regards > > Vivek Kumar OK, so I was looking in the wrong direction. But it is not entirely my fault. There is no mention of ThreadingTCPServer in the Standard Python Documentation. There is only one line in documentation of SocketServer module like : "The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour." But still there was no mention that some TCP or UDP server are already implemented there on these classes. Anyway, after reading the code in the SockerServer module and finding that there is already a ThreadingTCPServer available all other thing becomes very very easy. To implement the Threaded XMLRPCServer I just copied the code of SimpleXMLRPCServer into a new file and changed the SocketServer.TCPServer to SocketServer.ThreadingTCPServer. That is all I have done and now it is a multithreaded XMLRPCServer :-). But I think that the Python Documentation (Library reference) should contain the documentation for all the modules provided with the standard Python distribution. Again a BIG THX for all you people's support and help Kind Regards Vivek Kumar From donn at u.washington.edu Mon Jul 7 12:35:40 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Jul 2003 09:35:40 -0700 Subject: AIX + GCC 2.95.3 - Python (2.1 or 2.2) - building the shared library (.so) for python - HOW TO?!? References: <3F056D69.1090705@polbox.com> Message-ID: In article , martin at v.loewis.de (Martin v. Lowis) wrote: > hab writes: > > > (If I use standard -shared linking, during the _import python is crashing.) > > As seen in in AIX-NOTES there should be used ld_so_aix. But I suspect > > that it was prepared for standard xlC (CC) compiler. How to make it > > running for GCC compiler? > > Nobody knows anything about AIX in the Python world. You have to make > it work yourself. > > > 1. Why is such nonuderstandable-ultimate-tricky solution prepared for AIX? > > There are two possible reasons: > 1. AIX is such a strange system that you need to play dirty tricks to > make it load modules dynamically. > 2. Whoever ported shared loading to AIX didn't know anything about the > system, and tried random things until he got a working solution. > > I don't know which one it is, but I'm leaning towards 1) AIX is a classic example of underemployed engineers working in a vacuum. It's strange, sometimes arguably better but rarely worth the trouble. Linux strikes me a bit the same way, actually, and IBM's interest in Linux is no surprise. I doubt there are any really dirty tricks, but there is a point at which things like this are going to depend on the compiler software. ld_so_aix works fine with xlc, in my experience, and there's no reason to look for malfeasance on either side to explain why it stops there. If you want a normal UNIX platform with an open architecture, try one of the BSDs, or Linux if you're not that picky about the normal UNIX part. If you're obliged to work on AIX, then whoever's paying for AIX should happy to pay for the compiler too. Donn Cave, donn at u.washington.edu From bobsmith327 at hotmail.com Tue Jul 8 20:52:38 2003 From: bobsmith327 at hotmail.com (Bob Smith) Date: 8 Jul 2003 17:52:38 -0700 Subject: Possible to install from CD using distutils? Message-ID: Hi. I'm trying to distribute a Python package on a CD-ROM that gets installed using distutils. The problem is that distutils attempts to write a new 'build' folder on the CD during the installation and fails (it of course can't write the to CD). I know the user could copy my files onto his hard drive and then install the package, but I'm trying to make the installation as simple as possible. So... is there a way to tell distutils to use the hard drive when it's being run from a CD? Thanks. Bob From shane at ZOPE.COM Tue Jul 8 12:08:22 2003 From: shane at ZOPE.COM (Shane Hathaway) Date: Tue, 08 Jul 2003 12:08:22 -0400 Subject: __eq__ and __ne__ In-Reply-To: References: Message-ID: <3F0AEC76.8080304@zope.com> Tim Peters wrote: > Since the richcmp operators aren't constrained to return scalars, an attempt > to define one in terms of the others seemed futile. Instead they're 6 > independent methods. Ok. Thanks for finding the docs. I guess I'll stick to my boilerplate code. I think some guidance should be added to the Python docs, though, explaining that whenever you define __eq__, you very likely ought to define __ne__ also. Shane From creedy at mitretek.org Tue Jul 15 10:52:05 2003 From: creedy at mitretek.org (Chris Reedy) Date: Tue, 15 Jul 2003 10:52:05 -0400 Subject: =?ISO-8859-1?Q?Re=3A_Python_Mystery_Theatre_--_Episode?= =?ISO-8859-1?Q?_2=3A__As=ED__Fue?= In-Reply-To: References: <8f35dab2.0307141258.3da9b9d4@posting.google.com> <6qvfu4jgh1.fsf@salmakis.intevation.de> Message-ID: <3f141512_2@corp-news.newsgroups.com> John Machin wrote: > Robin Becker wrote in message news:... > >> [snip] >> >>I know that it's in microsoft >> >>the print width description contains >> >>[snip] > > > It's pretty much bog-standard C. E.g. K&R2, appendix B, section 1.2 > says: > [snip] Just for reference purposes: This behavior is part of the C-standard. See section 7.19.6.1, "The fprintf function", in ISO/IEC 9899:1999. From faizan at jaredweb.com Mon Jul 28 21:42:24 2003 From: faizan at jaredweb.com (Fazer) Date: 28 Jul 2003 18:42:24 -0700 Subject: Python vs. Perl vs. PHP? References: <7b454334.0307281002.41dae81b@posting.google.com> Message-ID: <7b454334.0307281742.10274598@posting.google.com> "Diez B. Roggisch" wrote in message news:... > Fazer wrote: > > > Hello, > > > > I am an avid user of PHP and I am just fooling around with Python for > > now. I originally wanted to know which one is faster. As in, works > > faster. So far, I think PHP is the fastest for dynamic web-content. > > Am I wrong? > > Definitely. See here: > > http://www.bagley.org/~doug/shootout/craps.shtml > > Python is place 13, with a speed index of 578. PHP is second last (before > bash) and has a speed index of 197. > > Besides that, PHP is a really ugly language - not only to the eye (which is > admittedly a matter of taste), but a friend of mine currently implements a > PHP->C-Compiler had delved deep into the language implementation - and it > _is_ ugly. > > I expirienced mayor flaws in PHP 4.0.x, where my declared functions in a > 6000 line include vanished from time to time - repeating the request > sometimes solved the problem. That was really nasty. > > Regards, > > Diez Wow, thanks for link! I will use it as hard proof to lure some of my friends in using Python! ;-) This is a little off-topic, but I wish to know how would you turn a string (or data from a text-file) into an array? For example, maybe turn each \n into an array. So a string like: "This is line 1 This is line 2 This is line 3" And so when you read that into a list called text text[0] would the "This is line 1". Thank you once again. From http Fri Jul 25 03:54:38 2003 From: http (Paul Rubin) Date: 25 Jul 2003 00:54:38 -0700 Subject: file.close() References: Message-ID: <7xhe5b82ip.fsf@ruckus.brouhaha.com> Francois Pinard writes: > For one, I systematically avoid cluttering my code with unneeded `close'. > The advantages are simplicity and legibility, both utterly important to me. > ... > The only reason to call `close' explicitly is when there is a need to close > prematurely. Absolutely no doubt that such needs exist at times. But > closing all the time "just in case" is symptomatic of unsure programming. > Or else, it is using Python while still thinking in other languages. Unfortunately Python doesn't guarantee that you won't leak file descriptors that way. CPython happens to gc them when the last reference disappears, and your willingness to patch the code if you move to a different implementation may be workable for you (that's something only you can decide). But if you want to write correct code in the current Python spec, you have to include those messy close's. I think a much better solution would involve a language extension, maybe a macro in some hypothetical macro extension for Python. E.g. with f = open(frob): [do stuff with f] could be equivalent to: f = open(frob) try: [do stuff with f] finally: f.done() # calls f.close() del f "done" here is a generic method that gets called on exiting a "with" block. From lol at lolmcNOSPAM.com Fri Jul 4 17:04:54 2003 From: lol at lolmcNOSPAM.com (Rogue 9) Date: Fri, 04 Jul 2003 22:04:54 +0100 Subject: Sorry about import problem multiple post Message-ID: <3f05ebe1@shknews01> I'm so sorry I'm using Pan v0.13.0 and it was doing screwy things when I tried to postfrom my sendlater folder.I re wrote the post but it went awry again and now I find multiple copies of my posts on the server. Please accept my apologies folks. Lol McBride -- Remove NOSPAM from my email address to use it,please. From fredrik at pythonware.com Tue Jul 1 18:28:23 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Jul 2003 00:28:23 +0200 Subject: Question regarding naming convention References: <1056988215.49928.0@iris.uk.clara.net> <1057062415.13616.0@doris.uk.clara.net> Message-ID: "michael" wrote: > Both of the above seem to overcomplicate the syntax. Of the two, > I prefer the second, but I'm sure I've read on c.l.py that the from. > import.. version is not a preferred way of doing things. "from ... import *" is usually a bad idea. "from SomeClass import SomeClass" is an excellent idea. more here: http://effbot.org/zone/import-confusion.htm From LogiplexSoftware at earthlink.net Thu Jul 10 16:45:52 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 10 Jul 2003 13:45:52 -0700 Subject: sort() doesn't work on dist.keys() ? In-Reply-To: <6cd58b6.0307101214.34e99f2a@posting.google.com> References: <6cd58b6.0307101214.34e99f2a@posting.google.com> Message-ID: <1057869952.16636.12.camel@software1.logiplex.internal> On Thu, 2003-07-10 at 13:14, Steve Pinard wrote: > (Got a comm error trying to post first time, sorry if this > is a duplicate) > > New to Python, so please bear with me. > > >>> import sys > >>> print sys.modules.keys() # works fine > ['code', ...snip... ] > >>> print sys.modules.keys().sort() # returns None, why? > None > > According to my reference (Nutshell), keys() returns a > "copy" of the dict keys as a list, so I would expect when > I aply sort() to that list, I would get an in-place sorted > version of that list. Why do I get None? Because sort() sorts the list in-place. It doesn't return anything (which in Python means it returns None). Try this instead: keys = sys.modules.keys() keys.sort() print keys -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From LogiplexSoftware at earthlink.net Mon Jul 7 14:41:19 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 07 Jul 2003 11:41:19 -0700 Subject: Threading issue: [Error 9]: bad file descriptor In-Reply-To: <1G7Oa.376746$ro6.9153831@news2.calgary.shaw.ca> References: <1G7Oa.376746$ro6.9153831@news2.calgary.shaw.ca> Message-ID: <1057603279.14514.4.camel@software1.logiplex.internal> On Sun, 2003-07-06 at 22:37, Kevin wrote: > My oversight, thanks! > > I'm testing on Windows 2000 Professional, but have had other users report > the same problem on other Windows flavours (NT, 98). I experienced a similar problem a few years ago (on Windows NT Server). A long-running threaded application would sporadically raise an exception when writing to a log file. Never figured out the cause, but "solved" it by catching the exception and reopening the file (IIRC). Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From loiosh13 at yahoo.com Mon Jul 7 00:04:32 2003 From: loiosh13 at yahoo.com (Tim Isakson) Date: Mon, 07 Jul 2003 04:04:32 GMT Subject: Newbie question: Strange TypeError Message-ID: Howdy, I'm a new python programmer - new to python, not so much to programming - my background was mainly C, with some C++, but it's rusty. I'm learning python to try and get back into some coding, and am running into a problem - I'm writing a calculator in python and wxPython as an exercise to learn both, and the following problem is leaving me baffled. I have an event handler, and it's getting called fine - but within the event handler, I'm calling a class method, HandleInput. The definition and call are shown below: def HandleInput(self, input): if self.results.GetValue() == "0": return input elif newVal == True: return input else: tmpVal = self.results.GetValue() + input return tmpVal def OnButton1(self,e): tmpVal = self.HandleInput(self, "1") self.results.SetValue(tmpVal) The call to HandleInput is made, but I get the following error: Calling HandleInput(self, '1') Traceback (most recent call last): File "pycalc.py", line 115, in OnButton1 tmpVal = self.HandleInput(self, "1") TypeError: HandleInput() takes exactly 2 arguments (3 given) So far as I can tell, the offending call *IS* calling HandleInput with 2 arguments, but the interpreter obviously thinks different, and I'm at a loss as to why that might be. I'm sure I'm doing something odd and not noticing, and I'd appreciate any help you can provide! Thanks in advance, Tim From owski at hotmail.com Tue Jul 15 13:33:17 2003 From: owski at hotmail.com (Adam Ruth) Date: 15 Jul 2003 10:33:17 -0700 Subject: anything like C++ references? References: <000301c348c7$3c501980$21795418@dell1700> <3F11106A.65FDA8F2@alcyone.com> <8vd6hv0sdvoitccmnj4pdj66ss2vg4ii3n@4ax.com> <5ir6hvof9m5rjh6i3u992l91un21qtmsh4@4ax.com> <9iu6hv4r968o9s1n5fh887u2j7an94de4e@4ax.com> Message-ID: Stephen Horne wrote in message news:... > On Mon, 14 Jul 2003 20:57:44 -0700, Tom Plunket > wrote: > > >Stephen Horne wrote: > > > >> >Are they really technicalities, though? I mean, a mutable object > >> >can be changed. It's the same object, just changed. Immutable > >> >objects, however, can't be changed. You can get something that > >> >appears like changing it, but it's actually building a new thing > >> >and binding the label to that new thing. > >> > >> Yes. But the thing being changed *is* an object, *not* a value. Values > >> are always immutable - basic fact of mathematics. > > > >Sure, but we're not modelling pure mathematics, we're modelling a > >level of abstraction that's appropriate for the problem that > >we're solving. > > If that were true, the abstraction would not regularly be causing > confusion and errors, and it would not be a recurring issue on this > newsgroup. There's two types of confustion: 1) Confusion about abstraction itself. It's complex for people to grasp, that's true of *any* language. Programming is hard, that's just a fact of life. 2) Cross language confusion. Anyone moving from one language to another will have confusion, depending on how different it is. People coming from Smalltalk or Ruby to Python don't get confused about this issue, they get confused about other things. This is a big confusion for C and C++ programmers, but other things make perfect sense. You're reading too much into this confusion, as though it means there's something wrong with the Python implementation. If we all jumped onto an analog computer, I'm sure we'd all be flustered because it's not like the digital computing we're used to. But some of us wouldn't cry foul at how the analogs are going about doing it all wrong. Adam Ruth From howard at eegsoftware.com Fri Jul 4 15:49:36 2003 From: howard at eegsoftware.com (Howard Lightstone) Date: Fri, 04 Jul 2003 19:49:36 GMT Subject: RTS/CTS and DTR/DTS control References: Message-ID: "Mike" wrote in news:pan.2003.07.04.19.37.02.310028 at kordik.net: > Is there a library in Python that will give me control over the > handshaking lines directly? > > Thanks > For Windoze, I heartily recommend siomodule. ( http://starship.python.net/crew/roger ) This is a wrapper around a well-designed professional serial I/O package. The Python version includes the dll for free (when used with Python). From tim.one at comcast.net Thu Jul 3 21:06:09 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 3 Jul 2003 21:06:09 -0400 Subject: A possible bug in python threading/time module? In-Reply-To: Message-ID: [Tim] >> If you run "enough" threads, chances are high you'll eventually run >> into a platform thread bug on any platform -- but into different >> platform bugs on different platforms. You didn't say which OS or >> platform thread library you were using, and those are probably the >> only things that matter. >> >> Here's a simplified and generalized minor rewrite of the above, with >> a comment about what happens under Win2K and 2.3b2. I've got no >> interest in chasing it down, since it's hung in the bowels of a >> Windows DLL and there's no evidence of a Python bug: >> >> """ >> import time >> import threading >> >> # One thread hung at the end on Win2K at N == 2011. # No problem if >> N < 2011. N = 2011 >> sem = threading.Semaphore(N) >> >> class MyThread(threading.Thread): >> def __init__(self): >> threading.Thread.__init__(self) >> sem.acquire() >> >> def run(self): >> time.sleep(5) >> sem.release() >> >> for i in range(2*N): >> MyThread().start() >> """ [vm_usenet] > I tried it on Windows 2000 and XP. "It" means the program above, or something else? What happened? > I guess it could be a platform-specific bug, but it still disturbs me > because I later programmed the same thing in C - and it worked > perfectly. Without seeing your C code I'm afraid this doesn't say anything -- "same thing" has got to be stretching the truth in ways that can't be guessed. > It's a long-shot, but I guess somewhere the bug is caused > due to a misuse by the python runtime (or perhaps an inefficient use) > of the platform-specific threading facilities... Dig into it, then. All Python's synch gimmicks are built on the Python lock, which is a cross-platform abstraction. On Windows, the implementation of the Python lock is in Python/thread_nt.h. No bugs have been reported against it, but that doesn't mean it doesn't have any. If you find one, that would be great. I expect there may be a bug *somewhere* in Python because a few thousand threads is really far fewer than I expect to create trouble on Windows. The evidence I saw suggested the program actually finished all its "useful" work, and got hung in threading.py's _MainThread.__exitfunc(), waiting to join one of the worker threads at Python shutdown time. From c-b-o-o-m-e-r at tiscali.co.uk Fri Jul 25 09:38:29 2003 From: c-b-o-o-m-e-r at tiscali.co.uk (Christopher Boomer (don't dash!)) Date: Fri, 25 Jul 2003 14:38:29 +0100 Subject: DOM as a flat dictionary Message-ID: <3f21335a_2@mk-nntp-2.news.uk.tiscali.com> Until now I have been using XSLT to translate from a known foreign XML format to a local XML format for import to Postgres. Now I need to be able to let others define the relationship from new foreign documents using a gui. My thought was to generate a flat dictionary representation of the foreign and local formats with the absolute Xpath expression as dictionary key. The user is presented with a list of elements&attributes in the local file and asked to select the foreign element|attribute fills that role. I could then use the keys from this mapping to generate XSLT which can be stored. Using dictionary keys means that duplicate elements will be lost, but this is not problematic since I am attempting to map the structure not the content. What are the other implications of this approach? Or is there an easier way to do what that I cannot find in Google? And has anyone written such a thing, even in part? Many thanks, Christopher Boomer Belfast. From chatralias at aol.com Sun Jul 20 12:20:18 2003 From: chatralias at aol.com (Chatralias) Date: 20 Jul 2003 16:20:18 GMT Subject: (mini-)ANN: Document for Python LaTeX setup References: Message-ID: <20030720122018.09823.00000328@mb-m11.aol.com> TYPOS I only found one. >From: Dave Kuhlman dkuhlman at rexx.com >I've written a document ... 2.1 Step 1 -- Install the Python Source You will the source distribution for Python... ^ need Thanks Dave, from your target audience (dare I speak for us all) for the Great job. This is just what I needed. Ray St.Marie RASTM2 at aol.com From max at alcyone.com Mon Jul 14 03:07:44 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Jul 2003 00:07:44 -0700 Subject: anything like C++ references? References: Message-ID: <3F1256C0.4BDC816F@alcyone.com> Stephen Horne wrote: > Imagine, for instance, changing all assignments and other 'copying' to > use a copy-on-write system. Then add a pointer type and a 'newcopyof' > operator. And nick the C-style prefix '*' for dereferencing and add > '&' as a 'make a pointer to this object' operator (absolutely NOT a > physical memory address). The problem is that this misses the point that Python is not C++. You shouldn't try grafting syntaxes and approaches that make Python look more like C++, you should be learning to use Python on its own merits. If what you want is a "pointer" -- something which encapsulates a reference to some other object which can be changed -- then you can do this very easily in Python through containment (either the single-element list, or a dedicated, and thus probably more clear, Container class like I gave at the outset of this thread). You're saying you want something which misses the point of Python's handling of variables: Variables are not slots where objects are placed, their Post-It notes you can paste onto objects. Post-It notes can be added and removed at will, and some names can be different in different scopes. Everything is handled the same way; it's just that some objects are mutable in Python and some are not. You can say that immutability is _equivalent_ to having those types of objects treated separately, but that's not the same thing as them _actually_ being treated differently, because as it's been made clear here they are not. You're drawing an arbitrary line in the sand, but the line you're drawing is in the wrong place (assignment doesn't work differently on mutable and immutable objects -- with the exception of the extended += operators mentioned earlier) and is not particularly arbitrary. Already examples of C code that will choke based on their implicit immutability, mentioned nowhere in the code by use of const, has been given; that makes C++'s mutability issues far more arbitrary than Python's! Or, to put it another way, if you want to program in C++, why not use C++? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ A life without festivity is a long road without an inn. \__/ Democritus From skip at pobox.com Tue Jul 8 10:03:15 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 8 Jul 2003 09:03:15 -0500 Subject: path module In-Reply-To: References: <16138.51270.256713.554899@montanaro.dyndns.org> Message-ID: <16138.53027.356511.290162@montanaro.dyndns.org> >> a/b/c/d >> >> is nicely analogous to Unix pathname syntax. Just> But when the items are variables, what you read is not what you Just> get. Often you'll want (some) literals, and then you get Just> path = basePath/"a"/"b"/"c" Just> ...and _that_ I find quite horrible... I don't know for sure, but I suspect the above could also be path = basePath/"a/b/c" Still not perfect, but in any case, the '/' is meant to be suggestive, not literal. Perhaps you would have preferred he use ':'? ;-) Just> (Did I mention that / usually means divide in Python? ;-) Sure, just like '%' means modulo in Python, but it seems to have found a home in printf-style string expansion. Skip From gherron at islandtraining.com Thu Jul 24 15:02:45 2003 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 24 Jul 2003 12:02:45 -0700 Subject: Mystery Theater New Style Classes In-Reply-To: <5.2.1.1.0.20030724100432.01d9d460@66.28.54.253> References: <5.2.1.1.0.20030724100432.01d9d460@66.28.54.253> Message-ID: <200307241202.45258.gherron@islandtraining.com> On Thursday 24 July 2003 09:05 am, Bob Gailer wrote: > Predict the output: > > class A(int): > classval = 99 > def __init__(self, val = 0): > if val: > self = val > else: > self = A.classval > a=A(3) > b=A() > print a,b > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 Since A this is a subclass of int, an immutable type, the asignment to 'self' is a red herring -- it has no affect. That's clearer here: >>> class A(int): ... def __init__(self, val): ... print 'Initial value of self:', self ... self = 'Huh?' ... print 'Final value of self:', self ... >>> a = A(123) Initial value of self: 123 Final value of self: Huh? >>> print a 123 For immutable types, you need to create the object with the proper value a little earlier in the creation process, and that's where the method __new__ comes in. This works as expected: >>> class A(int): ... classval = 99 ... def __new__(cls, val = 0): ... if val: ... return int.__new__(cls, val) ... else: ... return int.__new__(cls, A.classval) ... >>> a=A(3) >>> b=A() >>> print a,b 3 99 >>> See http://www.python.org/2.2/descrintro.html#__new__ for more details. Gary Herron From alanmk at hotmail.com Thu Jul 24 15:12:15 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 24 Jul 2003 20:12:15 +0100 Subject: running python References: Message-ID: <3F202F8F.6B00EC0C@hotmail.com> Iain Macalister wrote: > How do you run files written with python if you don't have the > compiler and stuff on your computer? Unfortunately, that's not possible. Although a compiler is not required to run python programs, some python stuff (namely a "python virtual machine") is required (the distinction between compiler and VM is possibly not important to you). Tangent: To give a comparison, trying to run a python program without a python VM is comparable to running Pentium programs without a Pentium CPU. It can be done (a man called Turing said so), but it's a lot of hard work that you probably wouldn't want to get into. However, I would strongly encourage you to install python on your system and run your software that way. It's really rather easy and painless. If your requirement is to install and run python programs on other peoples computers, then there are several ways to bundle your python programs and the virtual machine + support libraries into a single distributable file, such that the end user doesn't even know python is in use. If this is your intention, check on py2exe, the McMillan installer, freeze, squeeze, etc. I do believe the FAQ entry about distribution can be found here http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.028.htp HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ianb at colorstudy.com Fri Jul 18 02:39:39 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 18 Jul 2003 01:39:39 -0500 Subject: How do I get info on an exception ? In-Reply-To: References: Message-ID: <1058510379.11535.1525.camel@lothlorien> On Fri, 2003-07-18 at 01:33, Frank wrote: > Using Python 2.2.2, > I want to catch all exceptions from "socket.gethostbyaddr(ip)" > > >From IDLE, I can generate: > >>> socket.gethostbyaddr('1.2') > Traceback (most recent call last): > File "", line 1, in ? > socket.gethostbyaddr('1.2') > herror: (11004, 'host not found') <=== what I want when I catch > When I run this code: > try: > hostname, aliases, hostip = socket.gethostbyaddr(ip) > return (hostip, hostname) > except: > print sys.exc_info() > print sys.exc_type > return try: do exceptional stuff... except Exception, e: print e.args, dir(e) Probably that information is just in e.args, but you can add other attributes to exceptions, any of which should be revealed by dir(e). Exceptions are poorly documented, so I don't know where that might be noted. Ian From vincent_delft at yahoo.com Sat Jul 26 18:27:47 2003 From: vincent_delft at yahoo.com (vincent_delft) Date: Sun, 27 Jul 2003 00:27:47 +0200 Subject: Web tool kit : pro - cons ? Message-ID: <3f23003f$0$266$ba620e4c@reader0.news.skynet.be> I'm looking for a Web Tool kit to build web pages with the following criteria (in priority order) : - easy to use, develop (reuseability of code, ...) - flexible (ideally should run with Python CGIHTTPServer and/or with Apache (with or wihout mod_python) - possibility to have load balancing and/or caching (for very high loaded web pages) I've founded lot of tools ... I've read the doc of most of them, I've tested some of them. But, is there anyone "experienced user" who can give the pro-cons for each of those solutions ? (or propose an another) Is there a site who list the main charateristics of each of those Web tool kit ? Thanks Zope (www.zope.org), SkunkWeb (http://skunkweb.sourceforge.net/), Quixote (http://www.mems-exchange.org/software/quixote/), Twisted (http://www.twistedmatrix.com/) Albatross (http://www.object-craft.com.au/projects/albatross/) Cherrypy (...) pwo (...) ... From john_taylor_1973 at yahoo.com Sun Jul 6 21:37:53 2003 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 6 Jul 2003 18:37:53 -0700 Subject: Server Push References: <3f05b7ab$0$49103$e4fe514c@news.xs4all.nl> Message-ID: John, You could always write a Java applet. If the applet used something like a progress bar, the server-side program could notify the applet when to increase the progress bar percentage. Another way to do it, would be for the applet to poll the server every few seconds by having it make a http connection to a 'quick-running' cgi that would tell the applet the status. Based on this result, the progress bar would (or would not) be updated. You may also be able to write the applet in Jython, too. Good luck...let everyone know how you decide to implement your solution. John Taylor "John Bradbury" wrote in message news:... > I have used the Netscape examples and can not get them work. I am using > Windows and have tried Omnicron and XITAMI servers. What is frustraing me > is that I can achieve the desired result in Delphi by simply using : > response.sendresponse; > request.writestring('progress line'); > > I was hoping to find similar functionality in Python. > > John > > > "Irmen de Jong" wrote in message > news:3f05b7ab$0$49103$e4fe514c at news.xs4all.nl... > > John Bradbury wrote: > > > I want to send updates from a long running cgi. I have tried copying > perl > > > examples of server push and can not get them to work. > > > Does anyone have an idiot proof example of a working server push or > sending > > > output in chunks in Python? > > > > Check out: http://wp.netscape.com/assist/net_sites/pushpull.html > > > > There are basically two ways to do this. Either use the > > above mentioned "multipart response", which only seems to work on > > certain browsers (confirmed on netscape and mozilla, IE doesn't seem > > to work). The other method is just flushing your output and > > continue to write more data... but this won't allow you to > > 'clear the page' in the client's browser (multipart repsonses will). > > > > --Irmen > > From LogiplexSoftware at earthlink.net Tue Jul 8 15:55:16 2003 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 08 Jul 2003 12:55:16 -0700 Subject: id = -1 in wxpython In-Reply-To: <3F0B204A.20004@mac.com> References: <3F0B204A.20004@mac.com> Message-ID: <1057694115.5396.73.camel@software1.logiplex.internal> On Tue, 2003-07-08 at 12:49, Luiz Siqueira Neto wrote: > id -1 for some object mean that this object have a default id, but how I > can work with this kind of id? object.GetId() -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From tjreedy at udel.edu Sun Jul 13 17:16:08 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2003 17:16:08 -0400 Subject: anything like C++ references? References: <13t0hvsb7idh0g6ac3upe5k0qd6flc17ah@4ax.com> Message-ID: "Stephen Horne" wrote in message news:b8c3hvsesjoumiboobml3nsnajtha99mp1 at 4ax.com... > On Sun, 13 Jul 2003 15:07:23 -0400, "Terry Reedy" > wrote: > > >How a particular interpreter performs name binding is its own > >business, as long as the specified semantics are implemented. > > You could use the same argument to rationalise a language which used > the + operator to express subtraction. Bogus comparison with name binding. I am not aware that Python does anything quite so backwards. > The fact is that 'assignment' has a common meaning separate from the > choice of programming language, and that the way Python handles name > binding means that meaning is not respected by Python for mutable > objects. >From what others have posted, Python is not the only language in which 'name=object' means "assign 'name' to that object". This is much closer to the common idea of object having names than the idea that names can only name value holders (blocks of linear memory) and not values or objects themselves. Terry J. Reedy From someone at somewhere.com Sun Jul 27 13:54:15 2003 From: someone at somewhere.com (reh) Date: Sun, 27 Jul 2003 17:54:15 GMT Subject: eric3, pyqt, qscintilla - guru needed. References: Message-ID: Detlev Offenbach wrote: > reh wrote: > >> reh wrote: >> >>> Have installed on Redhat 9.0 in the following order; >>> >>> Qscintilla >>> sip >>> PyQt >>> >>> When I install eric3 (python install.py), I get this error; >>> Sorry, please install QScintilla and/or reinstall >>> PyQt with QScintilla support. >>> >>> It seems the errors occurs in the install.py file at: >>> from qtext import QextScintilla >>> >>> From qtext.py, I have typed in at the python prompt; >>> >>> import libsip # ok here >>> >>> from qt import QWidet # ok here >>> >>> from qt import QObject # ok here >>> >>> from qt import QPrinter # ok here >>> >>> import libqtextc # error here >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> ImportError: libqscintilla.so.2: cannot open shared object file: No >>> such >>> file or directory >>> >>> >>> >>> Been through all readme files, tried just about everything. >>> Anyone have an idea what's wrong. >>> >> Forgot to say that the libqscintilla.so.2 is in; >> /usr/lib/qt-3.1/lib >> and the same path is in my /etc/ld.so.conf > > Did you do a "ldconfig" after the installation of qscintilla? > > Detlev That did it. Thanks!!! On first observation eric looks really nice, well done. Can't wait to dig in. thanks; -- robert redhat 9.0 From tchur at optushome.com.au Sat Jul 5 19:13:29 2003 From: tchur at optushome.com.au (Tim Churches) Date: 06 Jul 2003 09:13:29 +1000 Subject: Bewildered graphs In-Reply-To: <3F06BF7C.8DC6A978@noaa.gov> References: <3F06BF7C.8DC6A978@noaa.gov> Message-ID: <1057446809.1204.20.camel@emilio> On Sat, 2003-07-05 at 22:07, Mark Fenbers wrote: > I am investigating Python for the sake of ultimately generating hydrographs > (such as this: http://ahps.erh.noaa.gov/iln/ahps/RiverDat/gifs/prgo1.png) > on-the-fly from a web server cluster. I have not used Python previously and do > not yet know if Python is very useful for this or if I am wasting my time. > > Quite frankly, I am a little bewildered. Not only is there Python, but there > are many extention modules which cloud up my view as to what I will need. > There's Scientific Python, which sounds promising, but there's also SciPy which > in itself has gnuplot, xplt and plt modules. I know enough about gnuplot to > know that it won't meet my needs because I need to be able to shade regions > above certain values such as done in yellow on the example hydrograph (the link > above). It also doesn't have many font options or the ability to place an image > such as the NOAA logo. > > Can someone kindly guide me as to what I would most likely need to replicate the > graph shown via the link above? There are indeed many options. But you might want to have a look at the delightfully named Ploticus (starring Russell Crowe...) at http://ploticus.sourceforge.net/doc/Welcome.html There is no Python interface for it, but Python is an ideal tool for building Ploticus scripts on-the-fly and running Ploticus to create the graphs on the Web server. However, Ploticus has recently become available as a callable library (libploticus) with a very simple C API which is just crying out for a Python wrapper - and a set of Python classes to abstract the interface on top of that. I would be happy to contribute to such a project, but am not able to undertake the construction of a C language wrapper. If you also need statistical analysis, I can recommend RPy (see http://rpy.sf.net) which embeds the R statistical package in Python. R does very, very nice graphics in all sorts of styles (see http://www.r-project.org), although it can be overkill for some Web server applications. Ploticus is very lightweight by comparison. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From adalke at mindspring.com Sun Jul 13 16:48:39 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 13 Jul 2003 14:48:39 -0600 Subject: mailbox_reader 1.0.2 -- Python module to read UNIX mailboxes sequentially. References: Message-ID: Me: > > What does this do that the standard Python library doesn't support? Grzegorz Adam Hankiewicz > * python 1.5.2 support. > * [round-tripping] ... Could you include those points in your documentation? It helps others to understand when to look at your library vs. some other library. Andrew dalke at dalkescientific.com From davecook at nowhere.net Sun Jul 6 14:13:07 2003 From: davecook at nowhere.net (David M. Cook) Date: Sun, 06 Jul 2003 18:13:07 GMT Subject: Red Hat 9, Python and Glade - a mixure not working? References: Message-ID: In article , Hans Deragon wrote: > Thanks for the tips. But the problem still persist. Now I run the > following: Do you have gnome widgets in your xml file? You'll need to import gnome.ui and do a gnome.init(). See the pygtk FAQ: http://www.async.com.br/faq/pygtk/index.py?req=all You might also try putting the line import pygtk; pygtk.require('2.0') at the top of your file. Also try running with python -v so you can see what modules are being loaded. > So the problem is not my code. I must assume that the glade module > for gnome is not adapted for taking in Glade 2 xml? In fact, libglade2 *only* works with glade 2 files. glade 1 files have to be converted first. > Different errors, same results. Nothing works. However the > test.glade xml file provided as an example works fine. I believe that > there is some widget in my glade2 xml file that is simply not > supported by python. I will investigate further the issue later. I've never encountered this problem with my own glade 2 files. However, I don't have a "pristine" RH 9 installation to play with right now. I suggest taking this problem to the pygtk mailing list. If it's not quickly fixable then it needs to be fixed somewhere up the line. Dave Cook From maxm at mxm.dk Mon Jul 7 06:42:31 2003 From: maxm at mxm.dk (Max M) Date: Mon, 07 Jul 2003 12:42:31 +0200 Subject: Collective memory (was: Good code patterns in Python) In-Reply-To: <3F08E2E9.8014B9A9@engcorp.com> References: <3F08E2E9.8014B9A9@engcorp.com> Message-ID: <3f094dfd$0$97234$edfadb0f@dread12.news.tele.dk> Peter Hansen wrote: > Actually, the moral is "use a revision control system". Anyone not doing > so should not be programming professionally.(*) > *) I speak as someone who programmed professionally without using a good > revision control system, for a while, and made some serious mistakes > as a result. Backups are *not* sufficient, but merely a slight step > up from doing nothing at all. Arh ... that will never happen to me ... If you start using CVS systems, whats next? Anti Virus software? Raid systems? backups? It will never end. It's all just expenses. regards Max M From sybrenUSE at YOURthirdtower.imagination.com Mon Jul 14 18:01:51 2003 From: sybrenUSE at YOURthirdtower.imagination.com (Sybren Stuvel) Date: 14 Jul 2003 22:01:51 GMT Subject: PyQT, Sharp Zaurus and color in the QTextBrowser References: <3F132103.4D18759F@engcorp.com> Message-ID: Peter Hansen enlightened us with: > Are you certain about that? It seems very unlikely that it would > outlaw use of single quotes when it is supposed to be XML-compatible, > and XML explicitly allows either single or double quotes around > attributes. I can't find it right now, but I've had the same discussion with a few collegues of mine, and according to W3C, both single and double quotes are accepted for both HTML and XML, and thus XHTML too. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? From danbmil99 at yahoo.com Sun Jul 20 10:26:53 2003 From: danbmil99 at yahoo.com (dan) Date: 20 Jul 2003 07:26:53 -0700 Subject: Tk mainloop() References: Message-ID: I asked this question yesterday (see prev. thread about calling TCL from Py & V.V) -- the solution I came up with from responses & looking at some old posts: instead of foobar.mainloop(), do this: while quitflag==0 #set this to 1 somewhere to quit yourcodehere() #whatever needs to be done foobar.update() #equivalent to TCL_DoOneCall()?or try _Tkinter.doonecall() time.sleep(0.01) #allow the Tkinter thread to run Only problem I'm having right now is occasional crash on breakdown but I think I just have to give Tk more time to close up shop. -dbm "Petr Evstratov" wrote in message news:... > Hi, I have a question: how do you execute an arbitrary function in Tk fooBar.mainloop()? > > I need to change the contents of a label every second, but I think I will also use some other functions as well... > > I hope that someone will answer my question, because I have been looking for an answer for 3 days, asking people, searching Google... and still have not found anything useful... > > Thanks, Pete From bokr at oz.net Fri Jul 18 16:15:05 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2003 20:15:05 GMT Subject: scanf string in python References: <3F178783.41DCA40F@alcyone.com> Message-ID: On Thu, 17 Jul 2003 22:37:07 -0700, Erik Max Francis wrote: >lehrig wrote: > >> I have a string which is returned by a C extension. >> >> mystring = '(1,2,3)' >> >> HOW can I read the numbers in python ? > >re.findall seems the safest and easiest solution: > >>>> re.findall(r'(\d+)', '(1, 2, 3)') >['1', '2', '3'] >>>> map(int, re.findall(r'(\d+)', '(1, 2, 3)')) >[1, 2, 3] > Did you use the regex parens for a reason I am unaware of? >>> import re >>> re.findall(r'(\d+)', '(1, 2, 3)') ['1', '2', '3'] >>> re.findall(r'\d+', '(1, 2, 3)') ['1', '2', '3'] Regards, Bengt Richter From zuckuss at apexmail.com Wed Jul 30 12:30:45 2003 From: zuckuss at apexmail.com (Andrew) Date: 30 Jul 2003 09:30:45 -0700 Subject: Exceptions as New Style Classes Message-ID: <98c4ab9a.0307300830.72dcdc74@posting.google.com> Hi, To satisfy my curiosity I was wondering if anyone knew if this behaviour was intentional? Is there a specific reason why exceptions are not allowed to be new style classes? Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 >>> class OldException: pass >>> raise OldException() Traceback (most recent call last): File "", line 1, in ? __main__.OldException: <__main__.OldException instance at 0x006AC490> >>> class NewException(object): pass >>> raise NewException() Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be classes, instances, or strings (deprecated), not NewException From guettler at thomas-guettler.de Fri Jul 4 06:53:43 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Fri, 04 Jul 2003 12:53:43 +0200 Subject: Emacs + py-mode + tkinter problem References: Message-ID: Alexander Schmolck wrote: > Thomas G?ttler writes: > >> Tom Locke wrote: >> >> > Hi All, >> > >> > I'm having trouble with the python shell within emacs. It's hanging >> > when I use tkinter. Setup is: >> > >> > Windows XP >> > emacs 21.3 >> > py-mode 4.6 >> > >> > Recipe: >> > From a python-mode buffer, launch the python shell (C-c !), then in the >> > shell >> >> Sorry, I don't know an answer since I only start >> the interactive prompt from a terminal. Since I am quite happy >> I would like to konw why you want the python interpreter in emacs? > Maybe too many people are happy with too little (essentially > edit/run-whole-program/debug cycles a la C, plus maybe using python > interactively as a calculator or to look up documenation). Yes, maybe. I am used to 1. edit with emacs 2. press Alt-TAB 3. in xterm arrowUp return 4. maybe stacktrace --> emacs: goto-line (c-g) goto [1] > If I had time > I'd write a tutorial on using ipython from within emacs for (I think) much > more effective interactive development. As it is I still haven't found the > time for a reply to a post by David Abrahams on the topic. Please announce it on python.announce thomas From usenet_spam at janc.invalid Wed Jul 16 21:35:02 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 17 Jul 2003 01:35:02 GMT Subject: [OT] sentances with two meanings References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) schreef: > It comes at least from the Latin version and I would not be surprised > if the double sense of "known" was in the Greek version too (any Greek > here?). I'm not Greek, but I still have a ancient Greek dictionary from school. :-) The verb "gignooskoo" (trying to write it with Latin letters ;) does indeed have the same "double" meaning in ancient Greek. (Of course this is not really a "double" meaning, if you think about it.) In Dutch the normal translation of "to know" is "kennen" or "weten", the sexual meaning is translated as "bekennen" (but, just like in English, it is not really common in contemporary Dutch). Interesting is that "bekennen" also has another meaning in Dutch: "to profess", "to confess"... > Now, Latin had to verbs for "to know": "scire" and "cognoscere". And "cognovisse". (I still have a latin dictionary too... :) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From nav at adams.patriot.net Tue Jul 8 09:57:27 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 08 Jul 2003 09:57:27 -0400 Subject: Python is a gem ,another successful day .... References: Message-ID: steve at ferg.org (Stephen Ferg) writes: > I'm trying to promote Python within the Federal government, and my own > agency, the Bureau of Labor Statistics. Right now, the chief > alternative at BLS to Python is Java, but not too long ago it would > have been VB and PowerBuilder. Sounds like the situation here at the where I'm trying to promote Python as a viable alternative to Java or Visual Basic. I'm currently seeing the most resistance in these areas: * Who makes Python? A lot of the culture is still mired in the idea that a corporate entity is required for a product to be fully supported, or viable in the long term. I like to remind them how well Sun's stewardship has "served" the Java community, but I need more than negative counterexamples. * Who provides training? I mean no disrespect to my coworkers, and present company is of course excluded, but a lot of the federal workforce has no incentive to learn on their own. Unless a training course is provided, with certifications and free tote bags, there is very little motivation for people to learn new technology. * How do we deploy Python? Until we upgrade all the systems here to recent versions of Redhat Linux (joke!), installing a Python environment is an extra step. I can point out that finding an appropriate JRE is a worse nightmare, but as above, I need more than negative counterexamples. We're currently in something of a holding pattern while a bit of reorganization takes place in the IT departments, but things will probably be changing rapidly (as rapidly as any change occurs in a government institution) once the organizational situation is stabilized. There was some talk of forming a SIG for Python in the US Government, did that ever go anywhere? Nick -- # sigmask.py || version 0.2 || 2003-01-07 || Feed this to your Python. print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','') From shane at zope.com Fri Jul 25 18:19:48 2003 From: shane at zope.com (Shane Hathaway) Date: Fri, 25 Jul 2003 18:19:48 -0400 Subject: How safe is modifying locals()? In-Reply-To: References: Message-ID: <3F21AD04.5060706@zope.com> Paul Paterson wrote: > I am trying to find a way to mimic by-reference argument passing for > immutables in Python. I need to do this because I am writing an > automated VB to Python converter. > > Here's an example of the VB code: > > Sub Change(ByVal x, ByRef y) > x = x+1 > y = y+1 > End Sub > > x = 0: y = 0 > Change x, y > ' Now x should be 0 and y should be 1 I might put all of the "ByRef" variables in a dictionary that gets passed back to the caller through a hidden argument. def change(x, y, _byref): x = x + 1 y = _byref['y'] = y + 1 x = 0; y = 0 __byref = {'y': y}; change(x, y, __byref); y = __byref['y'] At least this relies on nothing magical. One thing that's still wrong, though, is that you can't embed the change() call in an expression. AFAIK, in Python, assignment to a local variable absolutely requires a statement. You can get around this by splitting apart the expression and storing the result of the call in another hidden temporary variable. Even if you do that, though, exceptions will behave differently in Python than they do in VB. If an exception occurs in change() after a value has been assigned to 'y', the outer code won't get the value, and it just might affect the behavior of the outer code. You could fix that with a try: / finally: __byref = {'y': y} try: change(x, y, __byref) finally: y = __byref['y'] Suddenly it's awfully verbose and ugly, but if variables by reference are rare (as they should be), maybe it's not so bad. :-) You could go the extreme route and store all variables in dictionaries rather than use local variables, which would allow "true" references, but then you'd kill speed and readability. Better not do that. Shane From mis6 at pitt.edu Tue Jul 29 10:41:59 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2003 07:41:59 -0700 Subject: mixin class References: <3F24F8D2.E1ADFB08@web.de> <2259b0e2.0307281355.34725f83@posting.google.com> <3F262A67.57E4762C@web.de> Message-ID: <2259b0e2.0307290641.46d8e82c@posting.google.com> Udo Gleich wrote in message news:<3F262A67.57E4762C at web.de>... > What I want to do is take *two objects*, derive from both > their classes, make a new object and combine the state of > the old objects. > > I dont know if that is a good idea. I would appreciate comments > on the following solution. Especially the use of the dummy_init > function as an empty constructor looks not quite right to me. You may avoid dummy_init and have the default object.__init__ but this is not the point. The whole construction seems ugly to me. Do you have the option of using only class variables ? I mean, no explicit instance dictionary? Then you could simply create the mixin from the original classes and not merge by hand the instance dictionaries. Do you have the option of modifying the original classes to make the all structure more multiple inheritance friendly? The idea is that one should derive objects from classes, not classes from objects. What you are doing will probably work, but It is quite ugly to me.I cannot say more if I have no idea of what are your constraints. If you cannot touch the original classes, remember that you can create modifications of them, as mixin-frendly as you wish. I also have a question: why don't you override the __init__ method in M in such a way that it calls K1.__init__ and K2.__init__ according to the number of arguments? That would be the first thing would come to my mind, but maybe you have reasons why you don't want that. HTH, Michele From kyle at lakeofburningfire.org Fri Jul 4 22:52:28 2003 From: kyle at lakeofburningfire.org (Kyle Yancey) Date: Sat, 05 Jul 2003 02:52:28 GMT Subject: FYI: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> Message-ID: <1dfcgv841tebnr3dg568kg5o7gleugrkjj@4ax.com> You beat me. I've always wanted to create something similar to perlmonks for python programmers. Of course, I don't think that monkishness would be a good description of python programmers. Hmmm...perhaps pythonstuds.com :) On 3 Jul 2003 18:11:09 -0700, usenet at kyle.sent.com (Kyle Babich) wrote: >I have just opened pyBoards.com, a community for Python programmers. >Please stop by and check it out. > >http://www.pyBoards.com > >Tell me what you think, >Kyle From hokiegal99 at hotmail.com Wed Jul 16 11:57:05 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 16 Jul 2003 11:57:05 -0400 Subject: <> and != References: Message-ID: <3F1575D1.3030806@hotmail.com> Tim Peters wrote: > "<>" was deprecated instead. > That's a computer science term usually meaning it's like a mentally > disturbed uncle: we won't kill it, but we won't talk about it either > . That's very good... very good indeed. I know exactly what you mean. I'll have to use your explanation to explain 'deprecated' to my users! Thank you. From ianb at colorstudy.com Tue Jul 8 03:05:20 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Jul 2003 02:05:20 -0500 Subject: Accessing Web site contents from a Python script (with use of Cookie) In-Reply-To: References: Message-ID: <1057647920.514.363.camel@lothlorien> On Mon, 2003-07-07 at 23:50, Aki Niimura wrote: > I'm currently having a problem completing my script because the contents > I would like to access in the Web site is a dynamic content and it is > generated based on the Cookie contents which are set in another page. You should use ClientCookie: http://wwwsearch.sourceforge.net/ClientCookie/ Ian From ebolonev at rol.ru Fri Jul 4 03:53:25 2003 From: ebolonev at rol.ru (Egor Bolonev) Date: Fri, 4 Jul 2003 18:53:25 +1100 Subject: Some guidance please: A Python multitrack recorder? References: Message-ID: Hello, Dfenestr8! You wrote on Fri, 04 Jul 2003 16:15:11 +0900: D> I'm no coder. I'm just a working guy who likes to tinker with computers D> in my spare time. [Snipped] D> Also, is the Python interpreter fast enough for this sort of work? D> Especially on a pII 450Mhz with only 256 meg? The developers build such modules as tkSnack with C/C++, so they work fast. D> Would I be better off just sticking with a single track recorder, until D> the day I get around to seriously studying a compiler language like C++? Python is a kind of serious language. If you can find all low-level modules your programm need, then you have not to use C++. [Snipped] With best regards, Egor Bolonev. E-mail: ebolonev at rol.ru [ru eo en] From brian0891 at yahoo.com Thu Jul 17 00:02:10 2003 From: brian0891 at yahoo.com (Brian Olsen) Date: 16 Jul 2003 21:02:10 -0700 Subject: Choosing the right framework References: Message-ID: > I am to start on a new web project in the beginning of next week, and I > would like to use this opportunity to make the switch from PHP to Python. > Which is why I ask and don't just spend 2+ more weeks to dig further into > the above mentioned frameworks before making the decision. > > - Carsten I think the best suggestion is to understand your needs and requirements and balance them with your style of development. Then pick a few frameworks that represent that choice and try try try. You shouldn't expect yourself themselves to try them all, though. I just say to go to the tools that best interest you. Each solution offers a different way of doing web development. One might not suit your style and needs as well as the other; when you find the right one, I am sure that you will find the tool robust enough to handle the tasks you need to accomplish. Many tools are production-quality. The few that I think of that are, are: * Webware (based on a servlet model) * Quixote (a more programmer's based framework) * Albatross (module based ... I'm not sure quite.) * SkunkWeb (based on a page-model, sort of like PHP) I probably left out some, so this is in no ways exhaustive. But the choice in tool in terms of quality and the like should not bother you, because many of the m are of high-quality. I am not going to suggest what I personally like because I do not want to influence your opinion. But if you do have any questions, ask away on the mailing lists of the respective frameworks - I expect everyone on these lists to be generally friendly and knowledgeable. Brian From heikowu at ceosg.de Sat Jul 26 16:38:42 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 26 Jul 2003 22:38:42 +0200 Subject: looping through a file In-Reply-To: <3f21903c$0$27898$626a54ce@news.free.fr> References: <3eaf6668$0$1030$afc38c87@news.optusnet.com.au> <3f21903c$0$27898$626a54ce@news.free.fr> Message-ID: <1059251922.618.0.camel@d168.stw.stud.uni-saarland.de> On Fri, 2003-07-25 at 22:24, Bruno Desthuilliers wrote: > for line in thefile.readlines(): > doWhatEverWithTheLine() Or, if you're on a sufficiently new Python: for line in thefile: doWhateverWithTheLine() From shagshag13 at yahooPLUSDESPAM.fr Tue Jul 1 04:28:55 2003 From: shagshag13 at yahooPLUSDESPAM.fr (shagshag13) Date: Tue, 1 Jul 2003 10:28:55 +0200 Subject: automatically dl pages which needs cookie Message-ID: <3f01453a$0$13216$626a54ce@news.free.fr> hello, i would like to automatically download html pages that need a cookie to be set (in response of a form login) to be available. But i can't manage to do it. Does anyone has a cut and paste example somewhere ? thanks for your help. i've tried ClientCookie but didn't manage to undestand how it work. Also tried PyCurl and following code : >>> import pycurl >>> import urllib >>> curl=pycurl.init() >>> curl.setopt(pycurl.URL,mywebsite) >>> dataread="login=aaa&password=bbb" >>> curl.setopt(pycurl.POST,1) >>> curl.setopt(pycurl.POSTFIELDS,dataread) >>> curl.setopt(pycurl.COOKIEJAR,'my.txt') >>> curl.perform() but get an error that i don't undestand : Traceback (most recent call last): File "", line 1, in ? curl.perform() error: (23, 'Failed writing body') From guettler at thomas-guettler.de Wed Jul 16 07:55:59 2003 From: guettler at thomas-guettler.de (Thomas =?ISO-8859-15?Q?G=FCttler?=) Date: Wed, 16 Jul 2003 13:55:59 +0200 Subject: tkinter: Better Traceback Message-ID: Hi! Is there a way to get a better traceback in tkinter? It would be nice to see the line number of the last line of "my" code. Exception in Tkinter callback Traceback (most recent call last): File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", line 1299, in __call__ args = apply(self.subst, args) File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/lib-tk/Tkinter.py", line 1035, in _substitute e.height = getint(h) ValueError: invalid literal for int(): ?? thomas From Kepes.Krisztian at peto.hu Thu Jul 3 03:36:56 2003 From: Kepes.Krisztian at peto.hu (Krisztian Kepes) Date: Thu, 03 Jul 2003 09:36:56 +0200 Subject: Python - get key pressing ? Message-ID: Hi ! I want to create an py program what process datas for long time. But: I want to abort it if I need. Not with Ctrl+Break ! If I push a key (B, or other), the script must stop his work, and save the result created before. What I need to catch the keyboard events - without stopping a script ? Example: while False: DoWorkPeriodic() if KeyEvent=='B': SaveWork Stopit KK From bignose-hates-spam at and-zip-does-too.com.au Sat Jul 12 02:09:16 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: 12 Jul 2003 15:59:16 +0950 Subject: The "intellectual property" misnomer References: Message-ID: On 12 Jul 2003 00:27:49 -0500, Ian Bicking wrote: > Functionally, though, I think the term intellectual property here > works. Only by accepting the fallacy that there is a meaning to the term "intellectual property". There is no such thing -- not in law, not in reality. "Intellectual property law" has some meaning, to lawyers. But it is a grave mistake to conclude from that there is such a concept as "intellectual property" -- when no law recognises such a thing. Copyright law recognises some legal privileges for copyright holders. Patent law recognises some totally different legal privileges for patent holders. Trademark law recognises still more different legal privileges to trademark holders. And so on. These are all separate, and the privileges granted by one are almost completely unrelated to the privileges granted by the others. To bundle them together as "intellectual property rights" implies that they are much the same, only different in application. *That* is the "layman's understanding", and it is *wrong*. To imply that they all derive from some undefined "intellectual property" is false, confusing, and harmful in that it encourages a notion that intellectual objects are thought of as "property" when they are not -- not in law, and not in the way we use them. What the term *does* do is justify the actions of those who would restrict what we can do with intellectual works, by analogy with physical property rights. This is a direct harm, very difficult to undo -- and made much more difficult if we propagate the notion of "intellectual property". Please avoid the use of the term "intellectual property". -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From jordil2 at hotmail.com Wed Jul 16 10:31:19 2003 From: jordil2 at hotmail.com (jordi) Date: 16 Jul 2003 07:31:19 -0700 Subject: Some questions embedding Pythong in C (callback for variable assignment in the dictionary?) Message-ID: Hi, I'm starting to use Python embedded in a C program. I'm using Python to execute several scripts using as a variables information retrieved for several multithread "agents" written in C. The method is: 1- Create a thread for each agent (I use a pool thread, every agent run in a different thread) 2- Precompile a different script for each agent. 3- Make the agent retrieve its data 4- Convert this data to Python variables 5- Execute a Python script. The steps 3 to 5 are executed again and again (there is a timer that launch the execution). As it's a multithreaded program my code is something like this: - In each thread initialization: PyEval_AcquireLock(); interp = Py_NewInterpreter(); PyThreadState_Swap(interp); globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); pCode = Py_CompileString(ScriptPython, "testPython", Py_file_input ); (This "ScriptPython" is different depending on the type of agent) - Then, every time the C "agent" retrieves its data: PyEval_AcquireThread(interp); /* Here I have to modify the PyDictionary, globals or locals */ result = PyEval_EvalCode((PyCodeObject *)pCode, globals, 0/*locals*/); PyEval_ReleaseThread(interp); I have some questions: 1.- Is there any way to make the embedded Python interpret make a callback to the C program asking for variables when they are not defined in the Dictionary ? That is, implementing an "variable on-demand" method. I have a problem because an "agent" can have hundreds or thousands variables and maybe a script only uses a small number of them. Inserting all the variables every time can be very time consuming. I think Lua language can do that using "fallbacks" or "tag methods" but I don't know if Python has something like that. 2.- What is the best way to use Python embedded in a C program?. Instead of creating a new interpreter (Py_NewInterpreter();) I tried using only a Python interpreter and creating a different state for each thread: interp = PyThreadState_New(PyMainThreadState->interp); This solution was much worse than creating different Interpreters. Is it normal? 3.- Are there any optimization tricks to use in embedded Python to improve performance? 4.- Have you used any other script language for embedding in a multithreaded program? I'm looking for something portable, fast and free for commercial use. I have tested Python and Lua and Lua seems more suitable (and much faster) for simple embedding in a multithreaded program. Best regards, Jordi From hst at empolis.co.uk Tue Jul 15 10:07:34 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 15 Jul 2003 15:07:34 +0100 Subject: [OT] sentances with two meanings Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB53BDF5@hendrix.empolisuk.com> Colin S. Miller wrote > > > > Matthew 25:35 I was a stranger, and you took me in. > Care to enlighten us with the second meaning? > I'm a native English speaker, but can only see one meaning > 'I was unknown to you, yet you let me stay in your house' > Although 'took me in' could also mean 'accept as a friend' > > > Colin S. Miller > Also 'I was unknown to you and you deceived me'. Slightly colloquial _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From aahz at pythoncraft.com Wed Jul 2 11:03:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Jul 2003 11:03:48 -0400 Subject: What's the use of module spaces? (was Re: Circular Inheritance) References: Message-ID: In article , Ian Bicking wrote: > >You might encounter less problems if those classes go together in a >single module, but module boundaries are just there to help the >programmer organize code, they have little formal meaning. That's not true. Modules define a namespace, and Python's execution model makes heavy use of the "global" (read, current module's) namespace for name resolution. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ If you're familiar with the song "Woad", try reading the Subject: line again. ;-) From peter at engcorp.com Thu Jul 10 15:36:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 15:36:04 -0400 Subject: Embedding Python, threading and scalability References: <20E0F651F8B82F45ABCBACC58A2D995B0518AD@mexper1> <1057814773.188737@yasure> <7kergv8u1q5oib600e4ino24tf9fioo2gc@4ax.com> Message-ID: <3F0DC024.5A73B11B@engcorp.com> Afanasiy wrote: > > On Thu, 10 Jul 2003 05:26:14 -0000, "Donn Cave" wrote: > > >Quoth Jeff Epler : > > >At any rate, it sure isn't because Guido can't scare up an SMP machine. > > Is this the absolute truth or just something people like to say? > > If it is true I am very surprised... I think getting Guido an SMP > machine will not be very difficult, and could well be very cheap. Note the double negative in the phrase "isn't because Guido can't". That means in effect "Guido can". Nobody's disagreeing with that. -Peter From jdhunter at ace.bsd.uchicago.edu Fri Jul 25 08:37:19 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 25 Jul 2003 07:37:19 -0500 Subject: decimal to binary In-Reply-To: ("manuel"'s message of "Fri, 25 Jul 2003 12:21:55 GMT") References: Message-ID: >>>>> "manuel" == manuel writes: manuel> How to convert a decimal to binary ? thx, 1. Divide the "desired" base (in this case base 2) INTO the number you are trying to convert. 2. Write the quotient (the answer) with a remainder like you did in elementary school. 3. Repeat this division process using the whole number from the previous quotient (the number in front of the remainder). 4. Continue repeating this division until the number in front of the remainder is only zero. 5. The answer is the remainders read from the bottom up. Is this what you meant :-)? Or do you want to convert an integer to a binary string in python? If the latter, see the struct module http://www.python.org/doc/current/lib/module-struct.html John Hunter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jul 2 17:15:35 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2003 23:15:35 +0200 Subject: ANN: Pyro 3.3 beta Message-ID: <3f034b75$0$49099$e4fe514c@news.xs4all.nl> I'm glad to announce the latest version of Python's own powerful remote method invocation technology -- Pyro 3.3 beta! You can get it via http://pyro.sourceforge.net, then go to the SF project homepage download area. It is a beta version of the next Pyro release (3.3) and contains lots of interesting new features and improvements. See the change log at: http://pyro.sourceforge.net/pyro-manual/12-changes.html#latest Most important new features: - paired (fail-over) name server, fully automatic resyncing - better remote tracebacks - new style (PEP/python 2.3) logging - meta info for Name server objects Please test it as you wish, and tell me what you think of it! As always, thanks for your support and interest in Pyro. ---> What is Pyro? Pyro is an acronym for PYthon Remote Objects. Pyro is an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. 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 very good and detailed manual, and many examples to get you started right away. Have fun! --Irmen de Jong. From erhan at uzem.itu.edu.tr Wed Jul 2 10:24:55 2003 From: erhan at uzem.itu.edu.tr (Erhan Ekici) Date: Wed, 2 Jul 2003 17:24:55 +0300 Subject: Tkinter Image Button Bug Message-ID: <1057155895.3f02eb37e4d08@mail.uzem.itu.edu.tr> Hi, There is a problem in my code.I think it is Tkinter bug. Because First Code works properly and display the image on screen. In Second Code(with function), it works but doesn't display image.Instead of image, only a square with color=#dddddd comes on screen. Also , Third Code works properly and display image on screen... What is Problem..I will use this code in function..(Second Code) (My System: WinXP Pro, Python2.2 ) First Code: ************************************************************* from Tkinter import * master=Tk() toolbar= Frame(master) pfile ="C:\\Python22\\samples\\ftp\\images\\help.gif" icon = PhotoImage(file=pfile) b=Button(toolbar, image=icon, width=16,command=master.quit) b.config(background="#dddddd", bd=1, relief=FLAT) b.pack(side=LEFT, padx=2, pady=2) toolbar.config(background="#ffffff", bd=2, relief=GROOVE) toolbar.pack(side=TOP, expand=YES, fill=X) master.mainloop() ************************************************************* SECOND CODE ************************************************************* from Tkinter import * main=Tk() def toolbar(master): toolbar= Frame(master) pfile ="C:\\Python22\\samples\\ftp\\images\\help.gif" icon = PhotoImage(file=pfile) b=Label(toolbar, image=icon, width=10) b.config(background="#dddddd", bd=1, relief=FLAT) b.pack(side=LEFT, padx=2, pady=2) #toolbar.config(background="#ffffff", bd=2, relief=GROOVE) toolbar.pack(side=TOP, expand=YES, fill=X) toolbar(main) main.mainloop() ************************************************************* THIRD CODE ********************************************** from Tkinter import * main=Tk() def toolbar(master): toolbar= Frame(master) pfile ="C:\\Python22\\samples\\ftp\\images\\help.gif" icon = PhotoImage(file=pfile) b=Label(toolbar, image=icon, width=10) b.config(background="#dddddd", bd=1, relief=FLAT) b.pack(side=LEFT, padx=2, pady=2) #toolbar.config(background="#ffffff", bd=2, relief=GROOVE) toolbar.pack(side=TOP, expand=YES, fill=X) master.mainloop() toolbar(main) *************************************************** Thanks for answers :) Erhan Ekici ITU Center for Distance Learning E-mail : erhan at uzem.itu.edu.tr From peter.barth at t-online.de Tue Jul 15 03:02:32 2003 From: peter.barth at t-online.de (Peter Barth) Date: 15 Jul 2003 00:02:32 -0700 Subject: Mix lambda and list comprehension? Message-ID: <6f5b3f88.0307142302.1a1531f3@posting.google.com> Hi, trying to mix lambda expresions and list comprehension doesn't seem to work. --- >>> [lambda x:x+y for y in range(10)][9](2) 11 >>> [lambda x:x+y for y in range(10)][4](2) 11 --- I expected the second expression to return 6. What did I do wrong? Any hints? Thanks - Peter From adalke at mindspring.com Sun Jul 27 17:06:28 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 27 Jul 2003 15:06:28 -0600 Subject: Voting Project Needs Python People References: <7x65lv31hf.fsf@ruckus.brouhaha.com> <3jhTa.115229$Io.9825106@newsread2.prod.itd.earthlink.net> Message-ID: Alan Dechert: > Let me try to clarify what I'm after. The paper record should always match > the electronic record. So the allowable defects is zero. If there is a > mismatch found in the sample, we don't publish the electronic tally: we take > all the paper ballots and check them. You cannot get zero allowable defects. As best, you can get the likelihood of allowable defects to be less than one. For example, there will be hardware problems. Parts break down, the machines are exposed to large temperature swings, the scanners might be confused by a swarm of bugs, pages can stick together because of the humidity, ballots can be left in the trunk of a car 'by accident' (happened here in NM for the 2000 election). You can spend more money to reduce the likelihood of error. You can develop higher quality scanners and you can hire more people to review the ballots. But even if you scan the ballots twice by machine (each with different mechanisms) and another time by human, with descrepancies broken by another inspection, you still have the chance that all of those steps fail. A low chance, but still a chance. Even in the method you propose (machine scanning with a human double checking a sample), suppose the human doing the sampling doesn't notice the machine's result is wrong? (Boredom is insidious.) > So, if by the preliminary electronic tally a candidate won a race by 1 > percent, I want to know how many ballots we have to check (random sample) to > be certain that the result predicted is true. Right. In this case you shouldn't mind errors - you just want to be 99.99% sure that there's less than a, say, 0.05% error rate. > When I put one million into this Confidence Level Calculator, and Acceptable > Quality Level of .01, a sample of 10,000 shows a confidence level of "1." A > sample of 2000 give C.L of 0.999999998 Presumably, "1" is really > .9999999999+ more 9s. Can we get more decimal places? At most 17 9s and possibly less. Python's 'str' rounds to 1 at 13 places, while its 'repr' (which uses a more precise method) takes 17. >>> 0.99999999999999 0.99999999999999001 >>> 0.999999999999999 0.999999999999999 >>> 0.9999999999999999 0.99999999999999989 >>> 0.99999999999999999 1.0 >>> >>> str(0.999999999999) '0.999999999999' >>> str(0.9999999999999) '1.0' >>> More likely it depends on whoever wrote the calculator you're using. If you want 100% certainty (and not 99.9999+%) then you'll end up having to verify everything, which means you are no longer sampling the results. But the reason to use sampling is because the verification step is too expensive to apply it to everything, and because if you *did* test everything then you'll still need a sample to verify your verifiers. (Whether they be human or machine.) Do you have an estimate for the failure rate in the verifiers? > So I guess the Lot Fraction Defective is analgous to the predicted victory > margin. Is that right? I'm the wrong one for that - can you go over to the nearest statistics department and ask for assistance? Andrew dalke at dalkescientific.com From Olivier.POYEN at clf-dexia.com Thu Jul 3 08:22:01 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Thu, 3 Jul 2003 14:22:01 +0200 Subject: How to spawn a program with redirection as it parameter Message-ID: <8963D6370B323E4AA3241200F0EAF7318C0F63@FCEXVEXM002.dcl.int.dexwired.net> import os os.system('your sh line of command') python will be waiting. It returns the command line return result. HTH --OPQ > -----Message d'origine----- > De : TH Lim [mailto:sshark97 at hotmail.com] > Envoy? : jeudi 3 juillet 2003 12:19 > ? : python-list at python.org > Objet : How to spawn a program with redirection as it parameter > > > Hi, > > How do I do a simple thing like /bin/cat myfile.txt >> yourfile.txt > in unix? I tried with the script shown below but not successful. Am > doing it right? Pls. advise. thank you. > > #!/usr/bin/python > import os > os.spawnl(os.P_WAIT, "/bin/cat" , "/bin/cat", "myfile.txt >> > yourfile.txt") > print "Done" > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From eltronic at juno.com Sat Jul 19 17:29:52 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Sat, 19 Jul 2003 17:29:52 -0400 Subject: A challenge to the ASCII proponents. Message-ID: <20030719.213504.-133121.0.eltronic@juno.com> On Sat, 19 Jul 2003 15:59:16 +0100 Alan Kennedy writes maybe none of the below: > Martin v. Loewis > >> So what do you think about this message?: > >> > >> ???????????????? > >> > >> Look Ma, no markup. And not every character uses two bytes, > either. > >> And I can use Umlauts (??????) and Arabic (????????.????????????) > >> if I want to. > > > The final point I'd like to make [explicit] is: nobody had to ask me > how or why my xml snippet worked: there were no tricks. Nobody asked > for debugging information, or for reasons why they couldn't see it: Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit is how my email picked it up. other messages and replys were inconsistently rendered. isn't this the kind of thing the test groups were designed for? IIR, 7 bits is the standard in email & usenet. no one should expect more than 7 from any program or relay. the proper way would seem to be html using char entity's html appears to be no ones favorite format in email or usenet, so let the flames begin. I hope I haven't been hoodwinked into replying in 8bit as well. e -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.engel at recif.com Thu Jul 31 05:49:03 2003 From: marc.engel at recif.com (Marc ENGEL) Date: 31 Jul 2003 02:49:03 -0700 Subject: pythoncom: STA python COM server randomly does not receive event from other objects : deadlock References: <6411841c.0307300119.46bc0159@posting.google.com> <6411841c.0307300559.74557d9a@posting.google.com> Message-ID: <6411841c.0307310149.495028ca@posting.google.com> It's me again. I found the reason and wanted to share it with you. It is a Windows 2000 bug corrected with service pack 4. http://support.microsoft.com/default.aspx?scid=kb;en-us;321788 Indeed, my python COM object and its python client redirect stdout to my own Trace Manager. Hope it may help someone else. Marc marc.engel at recif.com (Marc ENGEL) wrote in message news:<6411841c.0307300559.74557d9a at posting.google.com>... > I'd like to add that just setting the Python COM object to Inproc > instead of Local server makes the all thing work properly. > But I need a Local server... > > It works without modifying a line of code! > > Marc > > marc.engel at recif.com (Marc ENGEL) wrote in message news:<6411841c.0307300119.46bc0159 at posting.google.com>... > > Hi all, > > > > I coded a python COM object that runs in a pythonw local server as a > > STA. > > > > This object creates and advises a VC++ COM object to receive its > > event. Those events are sent by worker threads. > > > > The VC++ object is free threaded. As a consequence call between my STA > > python object and apartment are marshalled through proxy. > > > > The python COM object regularly calls a blocking method on the VC++ > > object to synchronize. But, as it is a cross apartment call, during > > the call it can gets the event handler called thanks to the message > > pump operated by COM. > > > > But sometimes events are no received and it seems that I enter a > > deadlock. > > When I attach to the VC+ object, I can see that the thread that made > > the Fire_XX is still waiting for the call to end. > > > > Does somedy know the reason? > > > > Does the COM message pump may be different from the pythoncom message > > pump located in localserver.py : pythoncom.PumpMessages ? > > > > Thanks in advance for any hint, because this is a very blocking issue > > for my project. > > > > Marc From tim.harford at rogers.com Sat Jul 5 13:44:38 2003 From: tim.harford at rogers.com (Tim) Date: Sat, 05 Jul 2003 17:44:38 GMT Subject: Unfortunately...fortunately Message-ID: Today's Note: Unfortunately, I'm probably one of the world's laziest programmers. Fortunately, there is Python. :-) Tim From cartermark46 at ukmail.com Thu Jul 3 14:41:42 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 3 Jul 2003 11:41:42 -0700 Subject: Python is a gem, you need to keep pushing it .... References: <0gVMa.126$a%1.9289@nnrp1.ozemail.com.au> Message-ID: > same frustration as myself where managers (and people who think Microsoft > invented everything well except a watch you need to recharge every 2 days "Me too". I am a programmer at a firm of engineers. They're fixated by all things Microsoft. I try to explain to them that, perhaps, not *everything* is best done on Excel using VBA. I happened to glance at a proposal for a large job (for them) that they were bidding for; and it stated that it was to be based on Microsoft Access. *Groan*. Honest to God, if it doesn't have coloured cells all over the place, then they kind of stare at you like rabbits caught in the headlights of an oncoming car. Attempts to tell them that all this guff is difficult to put under version control because it's a binary ... you should separate code from data ... blah blah ... well, I might as well talk to a brick wall. Rant over. For now. From sshark97 at hotmail.com Thu Jul 10 12:48:45 2003 From: sshark97 at hotmail.com (TH Lim) Date: 10 Jul 2003 09:48:45 -0700 Subject: How to spawn a program with redirection as it parameter References: <1057291400.926913@yasure> Message-ID: Thanks Donn, ur explaination sure put things into perspective. before this, i was wandering why ">>" works in os.system() and not in spawn().well, now i know why. "Donn Cave" wrote in message news:<1057291400.926913 at yasure>... > Quoth sshark97 at hotmail.com (TH Lim): > | How do I do a simple thing like /bin/cat myfile.txt >> yourfile.txt > | in unix? I tried with the script shown below but not successful. Am > | doing it right? Pls. advise. thank you. > | > | #!/usr/bin/python > | import os > | os.spawnl(os.P_WAIT, "/bin/cat" , "/bin/cat", "myfile.txt >> > | yourfile.txt") > | print "Done" > > No, the '>>' operator belongs to the shell, and in spawnl there > is no shell. As another followup observes, if you want a shell, > you can use system() - > os.system('cat myfile.txt >> yourfile.txt') is about the same as > os.spawnl(os.P_WAIT, '/bin/sh', 'sh', '-c', 'cat myfile.txt >> yourfile.txt') > > Sometimes we would rather avoid the shell, because there's a risk > that when it re-evaluates the command parameters they will come > out different than we intend. In that case, there isn't any standard > function, you have to write your own. Off the top of my head, maybe > try something like > > def spawnvio(w, file, cmd, iodx): > pid = os.fork() > if pid: > if w == os.P_WAIT: > p, s = os.waitpid(pid, 0) > return s > else: > return pid > else: > try: > # Perform redirections > for n, u in iodx: > if n != u: > os.dup2(n, u) > os.close(n) > os.execve(file, cmd, os.environ) > finally: > os._exit(113) > > yrf = os.open('yourfile.txt', os.O_APPEND|os.O_CREAT) > spawnvio(os.P_WAIT, '/bin/cat', ['cat', 'myfile.txt'], [(yrf, 1)]) > os.close(yrf) > > Donn Cave, donn at drizzle.com From elainejackson7355 at home.com Sat Jul 12 17:19:14 2003 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 12 Jul 2003 21:19:14 GMT Subject: new in town References: Message-ID: That's okay, because I don't want my hand held. What I'd like is a reasonable assurance that, if I pick up this tool, I'll be able to accomplish what I have in mind. If not then, no offence, but I intend picking up a different tool. Joe Francia wrote in message news:jkZPa.75780$ZC.9188 at news.easynews.com... | Elaine Jackson wrote: | > As comforting as it is to know that there are "several ways of doing this", I'd | > be even happier if I knew the name of just one of those ways. The FAQ searcher | > doesn't seem to understand lengthy explanations and hand-waving. | > | | Gerhard is undeserving of your flippancy. He's very active in this | forum and very knowledgeable, but doesn't tolerate ambiguity and | laziness (read some of his postings). You asked a vague question, and | got a vague answer (you also used an ambiguous subject line, so be | thankful someone answered you at all). You asked "Can Python be | compiled?". Did you mean "Can the interpreter be compiled by me?" or | "Can I compile my Python scripts into a stand-alone executable?" (this | one is asked once a week) or "Can the Python interpreter be compiled | into (embedded) an executable?" The answer to all of these is yes (more | or less - see the FAQ), but since you didn't even specify a platform, | how can you expect a more detailed answer than the one you got? | | I entered "compile" into the FAQ search engine, and saw listed answers | to all of the above questions. You may want to revisit the FAQ, and you | also may want to read this page: | http://www.catb.org/~esr/faqs/smart-questions.html | | The Python community is a friendly one, but mostly, no one here will | hold your hand. If you show you've spent some time trying to solve the | problem yourself and then ask specific questions about the thing that's | stumping you, you'll get helpful responses. | | jf | From max at alcyone.com Sun Jul 6 20:40:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 06 Jul 2003 17:40:51 -0700 Subject: Newbie Question: Abstract Class in Python References: <5U2Oa.239646$jp.6482027@twister.southeast.rr.com> Message-ID: <3F08C193.DA90F4C0@alcyone.com> Kevin Bass wrote: > I am new to Python and want to know how to implement an abstract > class? I > have read through different books and I have no found this > information. > Thanks! There's no builtin way to do that in Python. Typically if I'm doing something where I want to make a class that yells at me if I 1. accidentally instantiate it directly or 2. fail to override one of its methods in a subclass, I do something like: class AbstractSomething: def __init__(self): if self.__class__ is AbstractSomething: raise NotImplementedError def aMethod(self, ...): raise NotImplementedError def anotherMethod(self, ...): raise NotImplementedError -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ They love too much that die for love. \__/ (an English proverb) From danb_83 at yahoo.com Sun Jul 13 21:18:53 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jul 2003 18:18:53 -0700 Subject: ??????? ??? ??? ??????? ??????????) )) References: <37d6f77c.0307130932.1e3adf0d@posting.google.com> <3f11ac74$0$49101$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<3f11ac74$0$49101$e4fe514c at news.xs4all.nl>... > Garber wrote: > > > ?????, ?????????? ??? ??? ??????? ????? ??????(????????, ?????? ???? ? > > exe-???? ?????????). > > Yes! > I think. > > ;-) > > On second thought, what's he saying? The Babelfish translation is "People, you polskazhite plz where to reach progu to frizer(kazhet'sya, shorter must be into yekhe-shnik outdistanced)." From jzgoda at gazeta.usun.pl Mon Jul 14 06:04:55 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 14 Jul 2003 10:04:55 +0000 (UTC) Subject: training for newbies References: Message-ID: OM pisze: > do you know any sites with free programs for newbies, which will help me in > progress? i know that only way to develop is writing programs, but in my > book i don't have programs to write, only questions.. Check out http://www.uselesspython.com and Python Cookbook at http://aspn.activestate.com -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From heikowu at ceosg.de Wed Jul 16 01:24:30 2003 From: heikowu at ceosg.de (Heiko Wundram) Date: 16 Jul 2003 07:24:30 +0200 Subject: anything like C++ references? In-Reply-To: <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com> References: <2a07hvo1ft7q7gedt4hq16g518iom905lu@4ax.com> Message-ID: <1058333069.619.103.camel@d168.stw.stud.uni-saarland.de> On Tue, 2003-07-15 at 06:27, Stephen Horne wrote: > Really. Is that what dictionaries are for? Or lists? Or other mutable > classes? I guess that's what classes are for... Just on a personal note, I've never ever needed or wished for something similar to pointer syntax in Python. Don't you tell that it's my background, I come from a C++ background, and have switched to Python only for the last two years or so. If you encapsulate your data correctly (have classes handle data that belongs together, and not pass it round in parts), everything works out great, at least for me. And I guess there's nothing more important than thinking about proper data-encapsulation before starting a project. All-beating-about-the-bush-for-nothing'ly, Heiko Wundram. From gh at ghaering.de Tue Jul 29 18:43:59 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 30 Jul 2003 00:43:59 +0200 Subject: Showing IP address of a user... In-Reply-To: <7b454334.0307291005.53ee8c07@posting.google.com> References: <7b454334.0307291005.53ee8c07@posting.google.com> Message-ID: <3F26F8AF.2010103@ghaering.de> Fazer wrote: > Hello, > > I was wondering how I can show an IP address of a person who visits a > Python web-page? Would I have to use Environment variables to access > Apache's server variables which hold such values like in PHP or what? Use this little CGI script to find the answer to your question: #!/usr/bin/env python import cgi cgi.test() -- Gerhard From letezo at fw.hu Sat Jul 12 10:29:44 2003 From: letezo at fw.hu (=?iso-8859-2?B?TOl0ZXr1?=) Date: Sat, 12 Jul 2003 16:29:44 +0200 Subject: HTML Help (CHM) file for Python 2.2.3 Message-ID: <001d01c34882$51b32870$8800a8c0@sirius> Hi Python Fans! Could you send me a download URL of a compiled HTML Help (CHM) file for Python 2.2.3 ? Thanks: Complex From srijit at yahoo.com Mon Jul 14 12:32:20 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 14 Jul 2003 09:32:20 -0700 Subject: (Suggestion) Download Options Message-ID: <221d8dbe.0307140147.6417e501@posting.google.com> Hello, Can we have a download option for upcoming Python 2.3 without TCL/Tk? Though I know the extremely popular Tkinter is the default GUI of Python, I see one immediate advantage of a download option without TCL/Tk 1) Download size is less and it is a boon for people like me with slow modem connection. 2) Tkinter with TCL/TK can be a separate add-on I look forward to opinions from members. Regards, Srijit From AndreasStud at gmx.de Sun Jul 6 04:45:14 2003 From: AndreasStud at gmx.de (Andreas Steffen) Date: 6 Jul 2003 01:45:14 -0700 Subject: vim --> python Message-ID: Hi, how can I adress the lines, which I send as input from vim to a python script (in python): for example - :1,10!python script.py Probably the same problem: how can I adress something which is piped into a python script? cat text.txt | python script.py Thanks in advance, Andreas. From s_gherman at yahoo.com Wed Jul 9 16:15:52 2003 From: s_gherman at yahoo.com (Sorin Gherman) Date: Wed, 09 Jul 2003 15:15:52 -0500 Subject: LOADING DATA INTO ARRAYS In-Reply-To: References: Message-ID: It's easy, split returns a 3-elements list in your case, while you try to read that with just 2 elements, xval, yval. Will work like this: xval,yval,zval = string.split(line) /sorin > Hi, > > I am trying to collect the following data in X,Y,Z arrays as following: > > 1.00000000000000 0.00000000000000D+000 0.00000000000000D+000 > 0.932113519778473 0.362166241174114 0.00000000000000D+000 > 0.737671227507627 0.675160099611485 0.00000000000000D+000 > 0.443073128844408 0.896485472551578 0.00000000000000D+000 > 8.83176797852179D-002 0.996092358889152 0.00000000000000D+000 > -0.145819420809848 0.989311223283493 0.00000000000000D+000 > -0.391263558087552 0.920278668726310 0.00000000000000D+000 > -0.625821331717327 0.779966448488364 0.00000000000000D+000 > -0.822296905793933 0.569058695322129 0.00000000000000D+000 > -0.953713306870443 0.300717356163965 0.00000000000000D+000 > > After loading them into X,Y,Z arrays, I should be in a position to access the > first line as X[0],Y[0], Z[0] and second line stuff as X[1],Y[1],Z[1]. > > I have written the following code which is not working for some reason. Can > anyone suggest any changes: > > ifile1 = open('fluidcylinder', 'r') #fluidcylinder contains the above data > for line in ifile1: > xval,yval=string.split(line) > x.append(xval) > y.append(yval) > > The error I am getting after the compilation is as follows: > > xval,yval=string.split(line) > ValueError: unpack list of wrong size > > > I would really appreciate if someone can help me with this. > > Thanks in advance, > > SATISH > > > > > From fredrik at pythonware.com Wed Jul 2 13:09:33 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Jul 2003 19:09:33 +0200 Subject: Tkinter Image Button Bug References: <1057155895.3f02eb37e4d08@mail.uzem.itu.edu.tr> Message-ID: Erhan Ekici wrote: > There is a problem in my code.I think it is Tkinter bug. > Because First Code works properly and display the image on screen. > In Second Code(with function), it works but doesn't display image.Instead of > image, only a square with color=#dddddd comes on screen. > Also, Third Code works properly and display image on screen... http://www.python.org/doc/FAQ.html#4.69 also see the note on this page: http://www.effbot.org/zone/tkinter-photoimage.htm (bug or not, this belongs to the "you'll only do this mistake once" category) From bokr at oz.net Sun Jul 27 14:29:41 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2003 18:29:41 GMT Subject: multiple file objects for some file? References: Message-ID: On Sun, 27 Jul 2003 13:17:50 -0400, "Tim Peters" wrote: >[Gary Robinson] >> For some code I'm writing, it's convenient for me to have multiple >> file objects (say, 2 or 3) open on the same file in the same process >> for reading different locations. >> >> As far as I can tell, there is no problem with that but I thought it >> might be a good idea to ask here just in case I'm wrong. > >Provided they're "ordinary" on-disk files (not, e.g., sockets or pipes >wrapped in a Python file object), that should be fine. Each file object has >its own idea of the current file position, and they'll all (of course) see >the same data on disk. > >You can get in deep trouble if the file mutates, though. Python's file >objects are wrappers around C's streams, and each C stream has its own >buffers. So, for example, a mutation (a file write) made via one file >object won't necessarily update the buffers held by the other file objects >(it depends on how your platform C works, but I don't know of any that >automagically try to update buffers across multiple streams open on the same >file), and then reading via some other file object may continue to see stale >data (left over in its buffer). > >For example, I bet this program will fail on your box before a minute >passes: > How about using mmap? Would that be a safe way to share (assuming you take care of any logical ordering requirements for mutation/access)? Do you have to flush every time you write (i.e., for sharing sync purposes, not to guarantee persistence)? Is there any difference re sharing issues between file vs slice spellings of updates? Is anything guaranteed atomic? Regards, Bengt Richter From martin_p at despammed.com Fri Jul 18 06:46:15 2003 From: martin_p at despammed.com (Martin P) Date: Fri, 18 Jul 2003 12:46:15 +0200 Subject: "\n" in ASCII-file Message-ID: Hello, for a short exercise-program I have to read the lines in an ASCII-file. But every line has a new-line-feed ("\n") at the end of the line. (The ASCII-file was made with Windows Notepad). Is this only because I used Windows (and Notepad)? And... is there any special method to read lines from a file without "\n"? Bye, Martin From zathras at thwackety.com Sun Jul 6 13:50:57 2003 From: zathras at thwackety.com (Michael Sparks) Date: Sun, 6 Jul 2003 18:50:57 +0100 (BST) Subject: Collective memory (was: Good code patterns in Python) In-Reply-To: Message-ID: On Fri, 4 Jul 2003, Charles Shannon Hendrix wrote: > if > > > If this is solely tabs, this is unambiguous with no special rules needing invocation. If this is spaces, again, this is unambiguous with no special rules needing invocation. If this is tabs and spaces mixed, then this looks ambiguous, and you need to look at special rules. That said, if you have one user who uses // for comments in C++ and another who exclusively uses /* */ what happens when the first user attempts to comment out the block of code by the second user? Also C has more corner cases due to allowing its block structure delimiters being slightly inconsistant than anything else. After all without checking how many C programmers could say what this means: if () if () else Is that: if if else Or is it: if if else The "problem" really boils down to choosing to use language features inconsistantly. This applies to C, C++, Python, Perl (eg allowing whitespace in regexes or not), and even functional languages. You might choose to always use braces for blocks even where not necessary, always to use tabs rather than spaces (or vice versa) and so on. In python I personally tend to find that only having one major decision to make - spaces vs tabs actually makes interaction with others code a lot simpler. > One really funny problem was when I guy reformatted his Python code, > around 15K lines of it, and basically unindented *ALL* of the code to > column 1. It was the only recoverable copy of the code too. > > He had to read the entire program line by line to recreate the logic. I changed all the permissions in /etc once by accident as well. (to 777 IIRC) This quite spectacularly busted my system, and that took a long while to sort out. At the time that was probably a similar number of lines affected by a pretty stupid simple action. What's the moral? Backup regularly and often and especially before doing something that touches a significant amount of stuff. (Where significant means >2 hours to fix) It certainly isn't "permissions are bad", nor "whitespace is bad". Inconsistent functionality abuse combined with stupidity is pretty hard for any system to cope with... Regards, Michael. From lehrig at t-online.de Fri Jul 18 01:00:28 2003 From: lehrig at t-online.de (lehrig) Date: Fri, 18 Jul 2003 07:00:28 +0200 Subject: scanf string in python Message-ID: I have a string which is returned by a C extension. mystring = '(1,2,3)' HOW can I read the numbers in python ? From bokr at oz.net Fri Jul 18 22:08:48 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Jul 2003 02:08:48 GMT Subject: properties + types, implementing meta-class desciptors elegantly? References: Message-ID: On Fri, 18 Jul 2003 08:48:44 -0400, "Mike C. Fletcher" wrote: >Hi all, > >I'm working on a base meta-type for a plug-in system, and I'd really >like to use the same rich-descriptor objects as I've used everywhere >else in the system. Basically these are descriptors that intercept >x.name, do various transformations, and then store the values in the >instance dictionary. > >Unfortunately: > > >>> type(t).pluginRole >Traceback (most recent call last): > File "", line 1, in ? > File "p:\properties\basicproperty\basic.py", line 231, in __get__ > return self.getDefault( client ) > File "p:\properties\basicproperty\basic.py", line 256, in getDefault > setattr( client, self.name, value ) > File "p:\properties\basicproperty\basic.py", line 283, in __set__ > self._setValue( client, value ) > File "p:\properties\basicproperty\basic.py", line 151, in _setValue > client.__dict__[ self.name ] = value >TypeError: object does not support item assignment > Not sure exactly what you are doing, but what does object.__setattr__(client, self.name, value) do in your context in place of client.__dict__[ self.name ] = value ? Regards, Bengt Richter From bram at norealaddress.com Thu Jul 31 11:37:37 2003 From: bram at norealaddress.com (Bram) Date: Thu, 31 Jul 2003 17:37:37 +0200 Subject: Newbie: implementing lowlevel protocol over socket int32 data handling In-Reply-To: References: Message-ID: Thank you for replying so quickly. You thought right, this resolves all my problems :-) Bram John Roth wrote: > > I took a quick look at the Wiki describing the protocol. For > something like this, I'd expect that interoperability would be > an issue, so the actual data format in the packets would be > part of the protocol specification. > > That being the case, look at the struct module. I think it does > exactly what you need. > > John Roth From ianb at colorstudy.com Tue Jul 1 18:13:01 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 01 Jul 2003 17:13:01 -0500 Subject: Suggesting for overloading the assign operator In-Reply-To: <3F01CC7B.F71C4C0B@hotmail.com> References: <6f03c4a5.0306301931.3f15fbb7@posting.google.com> <2259b0e2.0307010328.1e1b4a04@posting.google.com> <6f03c4a5.0307010910.35ca3158@posting.google.com> <3F01CC7B.F71C4C0B@hotmail.com> Message-ID: <1057097580.725.60.camel@lothlorien> On Tue, 2003-07-01 at 13:01, Alan Kennedy wrote: > Rim wrote: > > > What do you think about providing a statement to assign values > > without assigning type? > > > > '=' statement assigns value and type > > ':=' statement assigns value ony > > I think the concept has some merit. I think that sometimes it useful to ensure > that the target of a rebind operation have the same type as the object which was > bound before the rebind. > > I know that the same effect can be achieved by descriptors or overriding > "setattr" et al. Or something like this Or maybe: class stricttype(object): counter = 1 def __init__(self, required_type, doc=None, real_attr=None): self.required_type = required_type if not real_attr: real_attr = '_stricttype_attr_%i' % stricttype.counter stricttype.counter += 1 self.real_attr = real_attr self.doc = doc def __set__(self, obj, value): if not isinstance(value, self.required_type): raise TypeError, 'must be of type %r' % self.required_type setattr(obj, self.real_attr, value) def __get__(self, obj, cls): return getattr(obj, self.real_attr) def __del__(self, obj): delattr(obj, self.real_attr) def __doc__(self, obj): return self.doc class IntPoint(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return 'Point: (%i, %i)' % (self.x, self.y) x = stricttype(int) y = stricttype(int) >>> p = IntPoint(1, 1) >>> p Point: (1, 1) >>> p.x = 2 >>> p Point: (2, 1) >>> p.x = 2.2 Traceback (most recent call last): File "stricttype.py", line 44, in ? p.x = 2.2 File "stricttype.py", line 15, in __set__ raise TypeError, 'must be of type %r' % self.required_type TypeError: must be of type If we're talking about optimizations, there's no reason something like Psyco couldn't specifically look for specific descriptors like stricttype, and probably replace that implementation with something better optimized. Ian From ajw126 at york.ac.uk Wed Jul 9 08:28:38 2003 From: ajw126 at york.ac.uk (Andrew Wilkinson) Date: Wed, 09 Jul 2003 12:28:38 +0000 Subject: copy list, which way is best? /style References: Message-ID: <3f0bfc4e$0$45185$65c69314@mercury.nildram.net> Andreas Kuntzagk wrote: > Hi, > > There are three ways to (shallow)copy a list l I'm aware of: > >>>> l2=list(l) >>>> l2=l[:] >>>> l2.copy.copy(l) > > Are there any differences? Are there more (reasonable) ways? > I think the first is the most pythonic, second looks more like this other > p-language and third requires an import, so I would prefer the first. > Do you agree? > > Andreas The way I'd do it is from copy import copy l2 = copy(l1) or from copy import deepcopy l2 = deepcopy(l1) I don't know what the difference is, if any, but I think this way is more readable. HTH, Andrew Wilkinson -- Study + Hard Work + Loud Profanity = Good Code From newsgroups at jhrothjr.com Tue Jul 15 10:40:34 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 15 Jul 2003 10:40:34 -0400 Subject: Stop Python from exiting upon error in Windows References: Message-ID: "Conrad" wrote in message news:pan.2003.07.15.03.21.44.980226 at zexcite.zcom... > Years ago, Nostradamus predicted that on Mon, 14 Jul 2003 20:06:14 -0700, > Tom Plunket would write, saying: > > > Robert wrote: > > > >> How can I stop the Python interpreter from exiting when an error occurs? > > > > create a batchfile, tell Windows that the association of Python > > files is to that batch file, and put this in the file: > > > > python.exe %1 > > pause > > > > > > Or- catch the error in your mainline, and do a sys.raw_input() > > call on exception. > > > > -tom! > > Or the third, and admittedly brute force solution > I use is to fire up the DOS shell, (click on START, > then RUN, then type "command"). Depending on which > Win you're running, you may want to run DOSKEY, > which lets you cursor back up to previous commands. > > Once you've got the command window up (and doskeyed), > cd to your python source directory, and type in > something like *C:\python22\python.exe mypythonfile.py* > (leave out the *s and be sure python is in the same > place on your machine.) > > This doesn't keep the python interpreter from exiting, > but it does keep the DOS window open to let you see > your error messages. > > I admit it's ugly, but hey, I mostly develop in > FreeBSD and Linux, where the CLI is your buddy ;-) It may be ugly, but that's how I develop on my system (currently Windows XP, was 98SE until last week.) You don't have to put in the full path to Python if you rig the command prompt you're using to add Python to the path as the initialization command. That trick should also let you set up PYTHONPATH for the project. I keep a command prompt instance in each project directory, pointing to the correct initialization for the project. Then I've got a small batch file for each test module. A mouse click to switch windows, three key strokes and voila! the test runs (or not, as the case may be.) It avoids any possible problem with PythonWin polluting itself by not refreshing everything on a retest. I can't speak for Idle, but I think it's got some of the same problems of not isolating the program under test. John Roth > > Conrad > > From bgailer at alum.rpi.edu Sat Jul 12 13:22:44 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 12 Jul 2003 11:22:44 -0600 Subject: How do I have a client shutdown a win32 COM server? In-Reply-To: References: Message-ID: <5.2.1.1.0.20030712112145.028a9c28@66.28.54.253> >"Noah" wrote in message > > > Hi, > > > > How do I shutdown a win32 COM server? > > If that does not do it try: comobject.Quit() Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From peter at engcorp.com Thu Jul 3 10:13:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Jul 2003 10:13:51 -0400 Subject: Python - get key pressing ? References: Message-ID: <3F043A1F.81E6CA6@engcorp.com> Krisztian Kepes wrote: > > I want to create an py program what process datas for long time. > But: I want to abort it if I need. > Not with Ctrl+Break ! Why not? Ctrl+Break, or more typically Ctrl-C, is the de facto standard approach for terminating a console (non-GUI) application. > If I push a key (B, or other), the script must stop his work, and save the > result created before. In this case, just wrap the code with a "try/except KeyboardInterrupt" and put your "stop and save" code in the except block. (Note that Ctrl-Break will bypass this, but Ctrl-C is caught as you would expect.) Also, when posting questions of this nature it's a good idea explicitly to specify your platform (Linux, Windows, etc). -Peter From david.isal at wanadoo.fr Sat Jul 12 07:50:48 2003 From: david.isal at wanadoo.fr (David Isal) Date: 12 Jul 2003 11:50:48 GMT Subject: Python extension on Windows References: Message-ID: thank you guys for your advices ;-) From max at alcyone.com Sat Jul 12 21:49:47 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Jul 2003 18:49:47 -0700 Subject: removing spaces from front and end of filenames References: Message-ID: <3F10BABB.D548961B@alcyone.com> hokiegal99 wrote: > This script works as I expect, except for the last section. I want the > last section to actually remove all spaces from the front and/or end > of > filenames. For example, a file that was named " test " would be > renamed "test" (the 2 spaces before and after the filename removed). > Any > suggestions on how to do this? That's what the .strip method, which is what you're using, does. If it's not working for you you're doing something else wrong. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The meaning of life is that it stops. \__/ Franz Kafka From vivek at cs.unipune.ernet.in Wed Jul 16 07:43:11 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Wed, 16 Jul 2003 17:13:11 +0530 Subject: XML <=> database In-Reply-To: <20030716170049.A3736@cs.unipune.ernet.in>; from vivek@cs.unipune.ernet.in on Wed, Jul 16, 2003 at 05:00:49PM +0530 References: <20030716170049.A3736@cs.unipune.ernet.in> Message-ID: <20030716171311.A3783@cs.unipune.ernet.in> > > > There will be a three tier architechture. One web application, Web Server, > > one Application Server and the Database backend. The Web server will get the > > data as a XML document. This will be passed to the application server that > > will parse the document and will insert/Update/Delete the data in the database > > Server. Similarly the data will be retrieved from the database and will be > > converted in a XML document by the application server and will be send to the > > user's browser through the web server. > > One wonders to whom, exactly, this architecture seems like a *good* idea. > An Application server which accepts things in a mock-SQL XML language, > translates to XML and ships it off to the database? Why is that better > than having the web server send SQL directly to the database? What, > exactly, does the extra tier buy? > [It's not flexibility if all it accepts is a mock-SQL XML language... > writing SQL directly is probably easier.] > > > I told him that we can use python for this purpose as there are a lot of > > modules available for XML parsing in Python. And also it will be much easier > > for Students to learn Python as compared to Java. Somehow I managed him to > > think over it :-). But then he asked me : > > > > 1. Is there something in Python which will work as an Application server like > > EJB ?? > > EJB always struck me as a particularily bad idea, sorry. *Why* do you think > you want EJB? > > > 2. He showed me the XML Integrator which is used in Java and which > > automatically parse the XML document,convert it into a query string and > > insert it into Oracle database backend. And while retriving data it converts > > the retrieved data into a XML document. > > Does it work with arbitrary XML documents? My guess is that it works with > a very specific DTD [or Scheme, or whatever is fashionable today in the > XML world]. It is probably not that hard to write something like that > yourself, but something would already be written if someone found that > DTD useful himself. I tend to doubt it. > > Likewise, turning the database result into an XML document can often be > done with a list comprehension and cgi.escape()...about 3 lines. > Can someone please post a sample code for doing this.. > The bigger question is what you are trying to teach your students. If > the subject is "Three-tiered Applications with Java and Oracle", then > it's doubtful you can use Python. If it is "Writing Web Applications", > then I think that specing an internal architecture which seems way too > complicated for most problems is not the way to do it. Why not give > an exercise like "Write a blog" or "Write a shopping cart", and let > the students design the architecture. You can, of course, mandate > "outside requirements": "all the current stock must be kept in a specific > Oracle table". Actually we trying to show the students how to use XML+Web+Database as it is one of the hottest technology in the market :-) > -- > Moshe Zadka -- http://moshez.org/ > Buffy: I don't like you hanging out with someone that... short. > Riley: Yeah, a lot of young people nowadays are experimenting with shortness. > Agile Programming Language -- http://www.python.org/ THX and Kind Regards Vivek Kumar From oodtsen at yahoo.com.tw Mon Jul 28 05:10:08 2003 From: oodtsen at yahoo.com.tw (OOD Tsen) Date: 28 Jul 2003 02:10:08 -0700 Subject: PyIStream and COM question for WinGraphViz References: Message-ID: <38876f52.0307280110.32d56946@posting.google.com> I am the author of Wingraphviz. And I found somebody needs a samples of wingraphviz in python-language. May I have put your code as a sample on my site ? OOD Tsen / 7/28 2003 oodtsen at yahoo.com.tw From davidcfox at post.harvard.edu Tue Jul 29 17:13:41 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 29 Jul 2003 21:13:41 GMT Subject: inverse of the zip function Message-ID: <9sBVa.12998$o%2.6289@sccrnsc02> Is there a function which takes a list of tuples and returns a list of lists made up of the first element of each tuple, the second element of each tuple, etc.? In other words, the the inverse of the built-in zip function? David From uwe.schmitt at procoders.net Wed Jul 9 10:27:18 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 9 Jul 2003 14:27:18 GMT Subject: python + cluster computing Message-ID: Hi, I found several Python bindings for the MPI protocol, can anybody report some opinions and experiences ? Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From aahz at pythoncraft.com Fri Jul 11 14:07:20 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2003 14:07:20 -0400 Subject: Embedding Python, threading and scalability References: <7xvfu983ip.fsf@ruckus.brouhaha.com> Message-ID: In article <7xvfu983ip.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> Not particularly. Most threading at the application level is done for >> one or more of three purposes: >> >> * Allowing background work and fast response in a GUI application >> >> * Scalable I/O >> >> * Autonomous sections of code for algorithmic simplicity (e.g. >> simulations) > >Um, concurrent access by multiple clients for server applications? That's functionally an I/O thing, combined possibly with background work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From mertz at gnosis.cx Wed Jul 16 17:18:50 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 16 Jul 2003 17:18:50 -0400 Subject: [Announce] Gnosis Utils 1.1.0 (update) Message-ID: <6EcF/kKkX8yC092yn@gnosis.cx> ** I bit the bullet an bought more bandwidth, this notice is ** updated to reflect the permanent URL for Gnosis Utilities [Announce] Gnosis Utils 1.1.0 This release contains enhancements to gnosis.xml.objectify. Added _XO_.__repr__ method to make nodes print in a nicer, more compact fashion. Added ._seq attribute to node objects to support structure preserving convenience functions. Specifically, older versions of gnosis.xml.objectify lost information about mixed content and the order of children. E.g., >>> xml = 'Mixed content is good' >>> obj = XO(xml,EXPAT).make_instance() >>> obj.PCDATA, obj.i.PCDATA, obj.b.PCDATA (u'Mixed is', u'content', u'good') We had no way of knowing where inside the and the occur, nor even which child element occurs first. Now we can recover that information: >>> from gnosis.xml.objectify import content, children >>> content(obj) [u'Mixed ', , u' is ', ] >>> children(obj) [, ] Sequence information and convenience methods are NOT SUPPORTED (yet?) for the DOM parser, only for EXPAT! Changed default parser to EXPAT. If you have relied on the special attribute ._XML that the DOM parser attaches to nodes, you will now need to explicitly specify DOM as the parser used. However, the new sequence functions pretty well handle the job pyobj._XML used to do (in a different way). Some newer versions of PyXML report CDATA as #cdata-section nodes rather than as #text. We deal with it either way now. It may be obtained at: http://gnosis.python-hosting.com/Gnosis_Utils-1.1.0.tar.gz (this URL is different from usual since my main site was slashdotted, and I'm worried about my monthly bandwidth limit; I'll copy the file to its regular home next month). Try it out, have fun, send feedback! David Mertz (mertz at gnosis.cx) Frank McIngvale (frankm at hiwaay.net) ------------------------------------------------------------------------ BACKGROUND: Gnosis Utilities contains a number of Python libraries, most (but not all) related to working with XML. These include: gnosis.indexer (Full-text indexing/searching) gnosis.xml.pickle (XML pickling of Python objects) gnosis.xml.objectify (Any XML to "native" Python objects) gnosis.xml.validity (Enforce validity constraints) gnosis.xml.indexer (XPATH indexing of XML documents) [...].convert.txt2html (Convert ASCII source files to HTML) gnosis.util.dtd2sql (DTD -> SQL 'CREATE TABLE' statements) gnosis.util.sql2dtd (SQL query -> DTD for query results) gnosis.util.xml2sql (XML -> SQL 'INSERT INTO' statements) gnosis.util.combinators (Combinatorial higher-order functions) gnosis.util.introspect (Introspect Python objects) gnosis.magic (Multimethods, metaclasses, etc) ...and so much more! :-) From mazu at go2.pl Thu Jul 10 01:46:04 2003 From: mazu at go2.pl (mazu) Date: Thu, 10 Jul 2003 07:46:04 +0200 Subject: Problems Compiling PyQt3.7 Message-ID: I get errors about QAssistantClient while compiling PyQt 3.7, on my debian woody with Qt 3.1.2. Here is compiler message: cd qt && /usr/bin/make -f Makefile make[1]: Entering directory `/Downloads/KDE - libs/PyQt-x11-gpl-3.7/qt' g++ -c -pipe -w -O2 -D_REENTRANT -fPIC -DSIP_MAKE_MODULE_DLL -DQT_NO_DEBUG -DQT_THREAD_SUPPORT -I/usr/share/qt3/mkspecs/default -I. -I. -I/usr/include/python2.1 -I/usr/share/qt3/include -o qtcmodule.o qtcmodule.cpp In file included from qtcmodule.cpp:37: sip/qassistantclient.sip:37: qassistantclient.h: No such file or directory In file included from qtcmodule.cpp:37: sipqtQAssistantClient.h:42: parse error before `{' sipqtQAssistantClient.h:45: destructors must be member functions sipqtQAssistantClient.h:49: non-member function `property(const char *)' cannot have `const' method qualifier sipqtQAssistantClient.h:82: parse error before `private' sipqtQAssistantClient.h:84: syntax error before `&' sipqtQAssistantClient.h:87: parse error before `}' sipqtQAssistantClient.h:89: syntax error before `*' make[1]: *** [qtcmodule.o] Error 1 make[1]: Leaving directory `/Downloads/KDE - libs/PyQt-x11-gpl-3.7/qt' make: *** [sub-qt] Error 2 Anybody know any solution to this problem? I've got libqt3-mt, libqt3-mt-dev, and Qt 3.1.2already installed. -- mazu From bokr at oz.net Thu Jul 31 13:53:09 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2003 17:53:09 GMT Subject: How to get Windows physical RAM using python? References: Message-ID: On Wed, 30 Jul 2003 23:04:56 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >Mark wrote: > >> OK, How to check the amount of Windows physical RAM using python? > >You should call the GlobalMemoryStatus(Ex) function. To my knowledge, >there is no Python wrapper for it, yet, so you would need to write one. > >Regards, >Martin > ====< memorystatus.c >============================================= /* ** memorystatus.c ** Version 0.01 20030731 10:45:12 Bengt Richter bokr at oz.net ** */ #include "Python.h" #include static char doc_memstat[] = "Returns list of 7 integers:\n" " [0]: percent of memory in use\n" " [1]: bytes of physical memory\n" " [2]: free physical memory bytes\n" " [3]: bytes of paging file\n" " [4]: free bytes of paging file\n" " [5]: user bytes of address space\n" " [6]: free user bytes\n"; static PyObject * memorystatus_memstat(PyObject *self, PyObject *args) { PyObject *rv; MEMORYSTATUS ms; GlobalMemoryStatus( &ms ); if (!PyArg_ParseTuple(args, "")) /* No arguments */ return NULL; rv = Py_BuildValue("[i,i,i,i,i,i,i]", ms.dwMemoryLoad, // percent of memory in use ms.dwTotalPhys, // bytes of physical memory ms.dwAvailPhys, // free physical memory bytes ms.dwTotalPageFile, // bytes of paging file ms.dwAvailPageFile, // free bytes of paging file ms.dwTotalVirtual, // user bytes of address space ms.dwAvailVirtual // free user bytes ); return rv; } /* List of functions defined in the module */ static struct PyMethodDef memorystatus_module_methods[] = { {"memstat", memorystatus_memstat, METH_VARARGS, doc_memstat}, {NULL, NULL} /* sentinel */ }; /* Initialization function for the module (*must* be called initmemorystatus) */ static char doc_memorystatus[] = "Get win32 memory status numbers (see memstat method)"; DL_EXPORT(void) initmemorystatus(void) { PyObject *m, *d, *x; /* Create the module and add the functions */ m = Py_InitModule("memorystatus", memorystatus_module_methods); d = PyModule_GetDict(m); x = PyString_FromString(doc_memorystatus); PyDict_SetItemString(d, "__doc__", x); Py_XDECREF(x); } =================================================================== You may find a little .cmd file like this (tailored to your system) handy: [10:55] C:\pywk\ut\memorystatus>type \util\mkpydll.cmd @cl -LD -nologo -Id:\python22\include %1.c -link -LIBPATH:D:\python22\libs -export:init%1 [10:56] C:\pywk\ut\memorystatus>mkpydll memorystatus memorystatus.c Creating library memorystatus.lib and object memorystatus.exp [10:56] C:\pywk\ut\memorystatus>python (I'll indent this one space to avoid spurious quote highlights) Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import memorystatus >>> help(memorystatus) Help on module memorystatus: NAME memorystatus - Get win32 memory status numbers (see memstat method) FILE c:\pywk\ut\memorystatus\memorystatus.dll FUNCTIONS memstat(...) Returns list of 7 integers: [0]: percent of memory in use [1]: bytes of physical memory [2]: free physical memory bytes [3]: bytes of paging file [4]: free bytes of paging file [5]: user bytes of address space [6]: free user bytes DATA __file__ = 'memorystatus.dll' __name__ = 'memorystatus' >>> memorystatus.memstat() [0, 334929920, 271536128, 942825472, 861339648, 2147352576, 2129780736] Warning: Just now did this. Not tested beyond what you see!! Regards, Bengt Richter From tjreedy at udel.edu Thu Jul 17 13:27:59 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2003 13:27:59 -0400 Subject: anything like C++ references? References: <3F1256C0.4BDC816F@alcyone.com> <747bhv8r2h398bv121seft4spukd6bcsug@4ax.com> Message-ID: "Stephen Horne" wrote in message > Anyway, Algol and Fortran apparently (I didn't know this until today) > *always* used call-by-reference. Not true (about Fortran). I vaguely remember (about 1980) when IBM Fortran switched from one calling convention to another. I initially missed the one-line change in the manual update sheets. A working program started giving strange results until I finally figured out what was going on and then found the one line 'announcement'. Terry J. Reedy From erick_bodine at attbi.com Tue Jul 15 13:20:35 2003 From: erick_bodine at attbi.com (erick_bodine at attbi.com) Date: 15 Jul 2003 10:20:35 -0700 Subject: creating sparse files on win32 Message-ID: I need to create some sparse files on a win32 system (2000 & 2003 Server) in order to do some testing of another application (not python). I have been poking around the win32all extensions (win32file specifically) that come w/ ActivePython but can't find anything that allows me to create a file with the 'sparse file attribute' set. Has anyone done this in python? --ERick From mike at nospam.com Thu Jul 24 18:02:21 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 24 Jul 2003 15:02:21 -0700 Subject: Don't want to do the regexp test twice References: <20030724214457.GA874@mirk.lan> Message-ID: Egbert Bouwman wrote: > pat = re.compile(r'...') > for line in mylist: > if ... : > .... > elif ... : > .... > elif pat.search(line): > mat = pat.search(line) > elif ... : > ... > else ...: > ... > Is there a way to to do this job with only one pat.search(line) ? for line in mylist: if ... : .... elif ... : .... else: mat = pat.search(line) if mat: ... elif ... : ... else ...: ... Mike From andymac at bullseye.apana.org.au Tue Jul 8 19:29:31 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 9 Jul 2003 09:29:31 +1000 (EST) Subject: Shared vs static link performance hit --and Windows? In-Reply-To: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> References: <6btlgvgjq48mbtmu097939dl1c1gmki0qd@4ax.com> Message-ID: <20030709092503.E81274@bullseye.apana.org.au> On Tue, 8 Jul 2003, Christos TZOTZIOY Georgiou wrote: > Thanks, Skip; now if only someone more Windows-knowledgeable than me > could also comment on whether we could see a similar speed increase by > building a static Windows EXE... AFAIK, Windows & OS/2 don't really use the concept of PIC code for DLLs, as the DLLs get mapped into system address space rather than user address space, and all processes that access DLL code access the code at the same address. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From max at alcyone.com Thu Jul 3 00:45:15 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Jul 2003 21:45:15 -0700 Subject: zip() or what? References: <3F03AFA8.7030905@ihug.co.nz> Message-ID: <3F03B4DB.545DC6B5@alcyone.com> Ray Tomes wrote: > What I really wanted was this: > > [[0.1,1.1,2.1],[0.2,1.2,2.2]] > > So my question is how do I do that easily? You wanted zip(*x) > Alternatively, is there a construct to get x[*][i] if you know what I > mean? Probably [i[1] for i in x] or map(lambda i: i[1], x) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ What would physics look like without gravitation? \__/ Albert Einstein From xpm4senn001 at sneakemail.com Tue Jul 1 21:34:06 2003 From: xpm4senn001 at sneakemail.com (John Fitzsimons) Date: Wed, 02 Jul 2003 11:34:06 +1000 Subject: "Newbie" questions - "unique" sorting ? References: Message-ID: On Tue, 24 Jun 2003 22:11:59 -0500, John Hunter wrote: >>>>>> "John" == John Fitzsimons writes: Hi John, > John> (B) I am wanting to sort words (or is that strings ?) into a > John> list from a clipboard and/or file input and/or.... > John> (C) To sort out the list of "unique" words/strings. >The classic idiom for getting a unique list is to use a dictionary >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560. < snip > Thanks for your input/comments. :-) >Very large >text files (you mentioned 50MB) are extremely rare. < snip > Not if I convert news posts to a text file. Not so hard to get files >10MB that way. I expect that some would be >50MB. :-) Regards, John. -- **************************************************** ,-._|\ John Fitzsimons - Melbourne, Australia. / Oz \ http://www.vicnet.net.au/~johnf/welcome.htm \_,--.x/ http://clients.net2000.com.au/~johnf/ v From alanmk at hotmail.com Thu Jul 17 12:13:15 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 17 Jul 2003 17:13:15 +0100 Subject: Co-routines References: <3F16A34A.5742F54F@engcorp.com> Message-ID: <3F16CB1A.CC355FD1@hotmail.com> thewrights at ozemail.com.au wrote: > From the python grammar: > > funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite > > I want the statements in to be executed on a statement by > statement basis, with no particular restrictions on *what* those > statements are. It's the execution stepping I'm interested in... Might your requirements be better met by a debugger, which is feeding step instructions to a normal python program? This could be done extending the Pdb debugger class in module Lib/pdb.py to implement your own single step method. This could control various executing suites of code, according to your chosen scheduling algorithm. Or might you be better off to actually spawn separate threads, and have each thread carry out each instruction, line by line, and then enter a blocking wait for either a "continue" token from a Queue.Queue(), or "Continue" message signalled on a threading.Condition()? > the I/O in my example was just that. Or is that you want to control the states of your objects, depending on the readiness status of various I/O channels? And you want to run everything in one thread? In which case you might be looking for ultra-lightweight threads, based on generators, combined with an asynchronous I/O detection and reaction platform, such as asyncore, twisted or medusa. > I understand that there will > be all the problems on contention/race etc (just like if the > functions were going in separate threads) If the objects which are being distributed out to your (ultra-lightweight) threads are local to the functions/objects (i.e. not shared with other functions/objects) that process them, then there is no contention, and thus no locking required. How many separate "threads" of execution are you seeking to create? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From FBatista at uniFON.com.ar Thu Jul 24 15:11:44 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 24 Jul 2003 16:11:44 -0300 Subject: running python Message-ID: Platform? #- -----Mensaje original----- #- De: Iain Macalister [mailto:MACALISTER at coltonhouse43.freeserve.co.uk] #- Enviado el: Jueves 24 de Julio de 2003 3:53 PM #- Para: python-list at python.org #- Asunto: running python #- #- #- How do you run files written with python if you don't have #- the compiler and #- stuff on your computer? #- #- #- -- #- http://mail.python.org/mailman/listinfo/python-list #- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ask at me.com Sun Jul 6 19:49:40 2003 From: ask at me.com (Greg Krohn) Date: Sun, 06 Jul 2003 23:49:40 GMT Subject: python blogging software References: Message-ID: "Harald Massa" wrote in message news:Xns93B0F0F1A58A2cpl19ghumspamgourmet at 62.153.159.134... > which one should I use? Recommendations? > > Harald Are you running Zope[1]? If so, it's fairly trivial to brew your own[2]. If your homebrew always turns out stale, be cool like me and try Squishdot[3] (this _might_ be overkill if you strictly want a blog.) Hope this helps. [1] http://www.zope.org [2] http://www.evolt.org/article/A_Quick_and_Dirty_Blog_using_Zope/20/23583/ [3] http://squishdot.org/ Greg (who obviously has brew on his mind) From jjl at pobox.com Sun Jul 20 19:19:44 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Jul 2003 00:19:44 +0100 Subject: Python scripting with Paint Shop Pro 8.0 References: Message-ID: <87d6g4wzu7.fsf@pobox.com> Marc Wilson writes: [...] > There's no obvious way to specify this on the command line- in fact the > phrase "command line" doesn't seem to occur in the help. > > The scripts all start with "from JascApp import *" - does this suggest that > the scripts are callable from "plain" python? I want a "quiet" execution Yes. Do a find for 'JascApp.pyd'. Or just for '*.pyd'. > with no Windows interaction. I assume that there is a library called > JascApp. and the path would need to include that? Yes, == 'pyd' usually. But you never know the ways people (and especially large companies) like to mess about with conventional ways of doing things. The way module search paths are handled is generally less easy to predict. Even in the normal case, I can't remember how .pyd's are found, if I ever knew. Presumably Python is bundled with the application, in some form? In which case, it may not be trivial to import the module. Probably not hard once you know the answer, though . John From skip at pobox.com Wed Jul 30 09:21:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 30 Jul 2003 08:21:10 -0500 Subject: how best to handle httplib timeouts ? In-Reply-To: References: Message-ID: <16167.50758.169561.301466@montanaro.dyndns.org> rich> I'm trying to write an app to monitor an IIS server, .... what is rich> the best way to handle this ? Off-topic response perhaps, but if you want to monitor services running on remote machines, you should see what's already available. I use Nagios, , and find it excellent for the purpose (a bit complex to get started with, but very robust). Skip From news at yebu.de Fri Jul 18 03:21:59 2003 From: news at yebu.de (Karl Scalet) Date: Fri, 18 Jul 2003 09:21:59 +0200 Subject: scanf string in python In-Reply-To: References: Message-ID: lehrig schrieb: > lehrig wrote: > > >>I have a string which is returned by a C extension. >> >>mystring = '(1,2,3)' >> >>HOW can I read the numbers in python ? > > > Now I have done it like this: > tmp = mystring[1:-1] > tmplist = string.split(tmp,',') > x = int(tmplist[0]) > y = int(tmplist[1]) > z = int(tmplist[2]) > > But there should be a more convenient solution. exec('result='+mystring) print result would be shorter Karl From yaipa at yahoo.com Thu Jul 17 12:13:34 2003 From: yaipa at yahoo.com (yaipa h.) Date: 17 Jul 2003 09:13:34 -0700 Subject: Regular expression help References: Message-ID: <6e07b825.0307170813.4ccfb64a@posting.google.com> Fredrik, Not sure about the original poster, but I can use that. Thanks! --Alan "Fredrik Lundh" wrote in message news:... > David Lees wrote: > > > I forget how to find multiple instances of stuff between tags using > > regular expressions. Specifically I want to find all the text between a > > series of begin/end pairs in a multiline file. > > > > I tried: > > >>> p = 'begin(.*)end' > > >>> m = re.search(p,s,re.DOTALL) > > > > and got everything between the first begin and last end. I guess > > because of a greedy match. What I want to do is a list where each > > element is the text between another begin/end pair. > > people will tell you to use non-greedy matches, but that's often a > bad idea in cases like this: the RE engine has to store lots of back- > tracking information, and your program will consume a lot more > memory than it has to (and may run out of stack and/or memory). > > a better approach is to do two searches: first search for a "begin", > and once you've found that, look for an "end" > > import re > > pos = 0 > > START = re.compile("begin") > END = re.compile("end") > > while 1: > m = START.search(text, pos) > if not m: > break > start = m.end() > m = END.search(text, start) > if not m: > break > end = m.start() > process(text[start:end]) > pos = m.end() # move forward > > at this point, it's also obvious that you don't really have to use > regular expressions: > > pos = 0 > > while 1: > start = text.find("begin", pos) > if start < 0: > break > start += 5 > end = text.find("end", start) > if end < 0: > break > process(text[start:end]) > pos = end # move forward > > > > From martin at v.loewis.de Wed Jul 9 15:54:47 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Jul 2003 21:54:47 +0200 Subject: UTF-16-LE and split() under MS-Windows XP References: Message-ID: "Colin S. Miller" writes: > Where have I gone wrong, and what is the correct method > to verify the BOM mark? readline is not supported in the UTF-16 codec. You have to read the entire file, and perform .split. Looking at the BOM should not be necessary, as the UTF-16 codec will do so on its own. Regards, Martin From oren-py-l at hishome.net Fri Jul 18 02:57:40 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 18 Jul 2003 02:57:40 -0400 Subject: A challenge to the ASCII proponents. In-Reply-To: References: <3F142A58.80426AA4@hotmail.com> <2259b0e2.0307161620.4a9353f1@posting.google.com> <3F168011.3AEB3EFC@hotmail.com> Message-ID: <20030718065740.GA92151@hishome.net> On Fri, Jul 18, 2003 at 03:11:56AM +0000, Bengt Richter wrote: > ====< giginooskoo.html >====================================================== > > > > gignooskoo >

γίγνωσκω

> > ============================================================================== Actually, you don't need the "CHARSET=iso-8859-7". It would be required if you used the bytes 227, 223, 227, 237, 249, 243, 234, 249 to represent the characters. With numeric character references you can embed any character from the UCS repertoire regardless of the charset used. Oren From bignose-hates-spam at and-zip-does-too.com.au Wed Jul 2 19:25:22 2003 From: bignose-hates-spam at and-zip-does-too.com.au (Ben Finney) Date: Wed, 02 Jul 2003 23:25:22 GMT Subject: ASP References: Message-ID: On 2 Jul 2003 03:55:37 -0700, Padam Jain wrote: > Q1.How do u generated GUID's in Asp Pages > Q2.How do u pass x-y coordinates to ASP Pages when u click on an > Image. > Q3.How do u call a VBScript function in an Anchor Tag. > Q4.How do u access Object Instance or a variable in another Frame. I have no idea who this putative "u" person is, nor how such a person would choose to do what you're asking about. > Please kindly answer this question,its very urgent.I am stuck up here > very badly. You're stuck in the wrong newsgroup very badly. This newsgroup discusses Python, not ASP, and not "u". -- \ "Whenever you read a good book, it's like the author is right | `\ there, in the room talking to you, which is why I don't like to | _o__) read good books." -- Jack Handey | http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B From max at alcyone.com Mon Jul 21 14:47:22 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 21 Jul 2003 11:47:22 -0700 Subject: How to save web pages for offline reading? References: Message-ID: <3F1C353A.423B7773@alcyone.com> Will Stuyvesant wrote: > But I don't know the syntax for LIST. Do you? I think adding .GIF > and .CSS to this "list" is what I want?? It just means something like wget -A gif,css ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ All the people in his neighborhood turn around and get mad and sing \__/ Public Enemy From alan.gauld at btinternet.com Sat Jul 26 05:37:47 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jul 2003 09:37:47 GMT Subject: where is the awk to python translator program References: <87smounf2z.fsf@jidanni.org> Message-ID: <3f224b7b.872395578@news.blueyonder.co.uk> On Sat, 26 Jul 2003 01:25:45 -0500, Skip Montanaro wrote: > Python doesn't have the implicit looping and splitting into fields that awk > has, so you need to loop over the input and split the fields yourself: Although the fileinput module does help out with a lot of that kind of drudgery... certainly when you pass multiple filenames as arguments etc. But it still isn't awk. Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From mepython at yahoo.com Thu Jul 17 10:20:15 2003 From: mepython at yahoo.com (Samir Patel) Date: Thu, 17 Jul 2003 07:20:15 -0700 (PDT) Subject: Python2.3 logging utilities Message-ID: <20030717142015.77268.qmail@web41504.mail.yahoo.com> First of all, hats of on logging module in python 2.3. Very elegant... I have 2 questions regarding Handler class in logging: 1. SocketHandler: Can I send plain string instead of pickle binary. This will allow me to send a TCP log message to program written in other programming lang. 2. SMTPHandler: Is there any way to send an email where server requires authentication through logconfig.ini file. I send an email message to myself through logging and SMTPHandler and it works perfect, but if I want to send an email to external email address, I can't do it because replying is not allow. I can do it this in a python program by using ehlo and docmd of smtplib object, but how can I do same thing in loggers' config.ini file. Thanks in advance __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From taka at net.hr Wed Jul 9 10:37:03 2003 From: taka at net.hr (Taka) Date: Wed, 09 Jul 2003 16:37:03 +0200 Subject: format discs. References: Message-ID: On Wed, 09 Jul 2003 15:00:33 +0200, Gerhard H?ring wrote: > Taka wrote: >> On Wed, 09 Jul 2003 06:26:38 +0000, Flanagan wrote: >>>hello to all >>> >>>somebody can say to me whereupon I modulate of python I can format >>>discs. >>> >>> >>>thanks flanagan >> >> Let's presume you want to format a unix partition and that it is >> /dev/hda1. >> The do this: >> >> #!/bin/python >> >> import os >> partition = open ('/dev/hda1', 'w') >> >> for x in range(os.path.getsize('/dev/hda1'): >> partition.write ('0') >> >> partition.close() >> >> >> :) > > Didn't you mean ;-) instead of :) ? > > Your approach is hard to beat in inefficiency. > > -- Gerhard Yes, but since file partitions are usualy bigger than your physical RAM, you cannot do import string partition.write (string.zfill('0', partition.getsize('/dev/hda10')-1) From oren-py-l at hishome.net Mon Jul 7 01:55:15 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 7 Jul 2003 01:55:15 -0400 Subject: Merlin, a fun little program In-Reply-To: <3F08CFDF.6050603@earthlink.net> References: <3F08CFDF.6050603@earthlink.net> Message-ID: <20030707055515.GA70629@hishome.net> On Mon, Jul 07, 2003 at 01:37:15AM +0000, Ron Stephens wrote: > based multiple choice guesser. I re-wrote the web scraper to use Yahoo > rather than Google, as Google somehow recognizes it as a script now and > so has disabled the ability to use Google, as they say it violates their > terms of service. I certainly do not want to violate anyone's terms of > service You can still use Google for this - just sign up for the Google API. http://www.google.com/apis/ http://diveintomark.org/projects/pygoogle/ Oren From hokiegal99 at hotmail.com Sat Jul 19 20:09:49 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 19 Jul 2003 20:09:49 -0400 Subject: using functions and file renaming problem References: <3F174E76.4000302@hotmail.com> <3F1871A5.3020702@hotmail.com> Message-ID: <3F19DDCD.5040509@hotmail.com> Well, I think I'm finished. Thanks to everyone for the advice and in depth explanations. Below is the entire fix_mac_names.py script (some of it taken directly from you guys). I think my recursion is a bit of a kludge as is the format of my output, but other than that I think it's OK. I'm open to suggestions if anyone sees anything blatantly wrong with it. Thanks again! print " " import os, re, string setpath = raw_input("Path to the directory where you would like to fix names: ") print " " print "--- Replace Bad Characters in Directory Names & Filenames ---" print " " def clean_names(setpath): bad = re.compile(r'%2f|%25|[*?<>/\|\\]') #search for these bad chars.. for root, dirs, files in os.walk(setpath): for dir in dirs: badchars = bad.findall(dir) # find any bad characters newdir = dir for badchar in badchars: # loop through each character in badchars print "replaced: ",badchar," in dir ",newdir," ", newdir = newdir.replace(badchar,'-') #replace bad chars. print newdir if newdir: # If there were any bad characters in the name, do this: newpath = os.path.join(root,newdir) oldpath = os.path.join(root,dir) os.rename(oldpath,newpath) for root, dirs, files in os.walk(setpath): for file in files: badchars = bad.findall(file) # find all bad chars. newfile = file for badchar in badchars: # loop through each character in badchars print "replaced: ",badchar," in file ",newfile," ", newfile = newfile.replace(badchar,'-') #replace bad chars. print newfile if newfile: # If there were any bad characters in the name, do this: newpath = os.path.join(root,newfile) oldpath = os.path.join(root,file) os.rename(oldpath,newpath) clean_names(setpath) #1 clean_names(setpath) #2 clean_names(setpath) #3 clean_names(setpath) #4 clean_names(setpath) #5 clean_names(setpath) #6 clean_names(setpath) #7 clean_names(setpath) #8 clean_names(setpath) #9 clean_names(setpath) #10 print " " print "--- Done ---" print " " print "--- Remove Spaces from Beginning and Ending of Directory Names & Filenames ---" print " " def clean_spaces(setpath): for root, dirs, files in os.walk(setpath): for dir in dirs: old_dname = dir new_dname = old_dname.strip() if new_dname != old_dname: print "removed spaces from dir:",old_dname newpath = os.path.join(root,new_dname) oldpath = os.path.join(root,old_dname) os.rename(oldpath,newpath) for root, dirs, files in os.walk(setpath): for file in files: old_fname = file new_fname = old_fname.strip() if new_fname != old_fname: print "removed spaces from file:",old_fname newpath = os.path.join(root,new_fname) oldpath = os.path.join(root,old_fname) os.rename(oldpath,newpath) clean_spaces(setpath) #1 clean_spaces(setpath) #2 clean_spaces(setpath) #3 clean_spaces(setpath) #4 clean_spaces(setpath) #5 clean_spaces(setpath) #6 clean_spaces(setpath) #7 clean_spaces(setpath) #8 clean_spaces(setpath) #9 clean_spaces(setpath) #10 print " " print "--- Done --- " print " " From peter at engcorp.com Thu Jul 10 21:35:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Jul 2003 21:35:25 -0400 Subject: Problem running Flawfinder with Python References: Message-ID: <3F0E145D.9BFE3E2D@engcorp.com> > "Crose, Carol" wrote: > > > I need to test some lsof source code and have loaded Flawfinder 1.22 to test it. Flawfinder required Python 1.5 or better so I loaded Python 2.2.3. This is all running on an HPUX 11.11 server. > > When I run: > /opt/flawfinder-1.22/flawfinder /usr/local/bin/lsof-4.67 > I get the following error: > No such file or directory: python > > I am totally new to all these programs. Can anyone help???? If "flawfinder" is a Python script, check the first line of it for text that looks something like this: #!/usr/bin/env python or perhaps #!/usr/local/bin/python You either need the python executable installed in the specified directory or, for the /usr/bin/env version, you need it installed in a folder that is in the PATH. "echo $PATH" to see what you have now. -Peter From thedustbustr at aol.com Fri Jul 25 16:32:13 2003 From: thedustbustr at aol.com (TheDustbustr) Date: 25 Jul 2003 20:32:13 GMT Subject: stackless python: continuation module? References: <20030725152844.18704.00000635@mb-m18.aol.com> Message-ID: <20030725163213.09785.00000389@mb-m11.aol.com> Nevermind, I found a post to the Stackless mailing list that said that continuation was a builtin but now is not in the distribution. So uthreads is no more. I'm supposed to use 'import stackless' instead. Anyone have any source code using the stackless module? I found no documentation about this module. Thanks, Dustin From milyon at wp.pl Wed Jul 9 11:07:18 2003 From: milyon at wp.pl (K) Date: Wed, 9 Jul 2003 17:07:18 +0200 Subject: Odp: Newbie - No module named stdwin References: Message-ID: U?ytkownik A.M. Kuchling w wiadomo?ci do grup dyskusyjnych napisa?:cEmdnTR7Cpmct5GiRTvUqg at speakeasy.net... > Stdwin is very old and very dead; what document are you reading that > suggests using it? Most GUI development in Python is done using Tkinter, > though there's also wxWindows, PyQt, and Gtk+ interfaces available. If you > downloaded a binary Windows installer from somewhere, it probably > includes Tkinter; the other interfaces would be add-on packages. > > --amk ok thanks so how command can open a window ? From aahz at pythoncraft.com Tue Jul 15 23:39:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2003 23:39:46 -0400 Subject: Nice presentation of Dana Moore on Oscon References: <3F0E63AA.4000107@embeddedsystems.nl> Message-ID: In article , Aahz wrote: >In article <3F0E63AA.4000107 at embeddedsystems.nl>, >Gerrit Muller wrote: >> >>A very nice presentation. I do have one small comment: Python is >>characterized as "weakly typed", which should be "dynamic types", or >>what people often mean to say "not static typed". > >Unfortunately, Bruce Eckel has been perpetuating that terminology. I'm >in the process of writing a rebuttal. > >http://www.artima.com/intv/typing.html All right, my rebuttal is now at http://www.artima.com/weblogs/viewpost.jsp?thread=7590 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Not everything in life has a clue in front of it...." --JMS From sross at connectmail.carleton.ca Thu Jul 10 14:06:48 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 10 Jul 2003 14:06:48 -0400 Subject: replace value of a specific position References: <3F0DA6FB.90603@soraia.com> Message-ID: "Joe Francia" wrote in message news:3F0DA6FB.90603 at soraia.com... [snip] > >>> t = '010010101001001110100101010111' > >>> t = string.join([t[:5], '2', t[6:]], '') > >>> t > 010012101001001110100101010111 # or, without importing the string module: >>> t = '010010101001001110100101010111' >>> t = ''.join((t[:5],'2',t[6:])) >>> t '010012101001001110100101010111' From staschuk at telusplanet.net Tue Jul 1 16:03:43 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 1 Jul 2003 14:03:43 -0600 Subject: Why does it work ? In-Reply-To: ; from combe.michel@9online.fr on Tue, Jul 01, 2003 at 04:01:13PM +0200 References: Message-ID: <20030701140343.B16188@tibia.amotlpaa.bogus> Quoth Michel Combe: > I'm trying to send a mail with an attached file. > I use the following code and *it works* but I don't understand why and I > hate that. > > for filename in os.listdir(dir): > path = os.path.join(dir, filename) > if not os.path.isfile(path): > continue > ctype, encoding = mimetypes.guess_type(path) > if ctype is None or encoding is not None: > ctype = 'application/octet-stream' > maintype, subtype = ctype.split('/', 1) > if maintype == 'text': > fp = open(path) > msg = MIMEText(fp.read(), _subtype=subtype) > fp.close() > msg.add_header('Content-Disposition', 'attachment', filename=filename) > outer.attach(msg) Note, btw, that this code does not set msg on all paths to its use at the end of the for loop. If the first file is not text/*, an UnboundLocalError will be raised. If a later file n is not text/*, the file n-1 will be attached twice. You probably want: if maintype == 'text': fp = open(path) try: msg = MIMEText(fp.read(), _subtype=subtype) finally: fp.close() msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) (I've also put the fp.close() in a finally block, where it belongs.) I also wonder about the 'encoding is not None' test. But on to your question: > In the "dir" directory, I have 2 text files : > - "texte.txt" which is the text I want inside the body of the message and > - "fichier.txt" which is the file I want attached. > > Why is "texte.txt" the only file that I find in the body of the message. > Both files are text, so the MIMEText instruction shoud be executed for both > files, No ? > Also add_header should be executed for both files resulting in 2 attached > files ? You can find out for sure by, for example, adding print statements: if maintype == 'text': print >>sys.stderr, "%s is text" % path fp = open(path) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() print >>sys.stderr, "attaching %s" % filename msg.add_header('Content-Disposition', 'attachment', filename=filename) > Which instruction says what is included in the body and what is attached to > the mail ? They're all attachments with the code as written. -- Steven Taschuk staschuk at telusplanet.net "Our analysis begins with two outrageous benchmarks." -- "Implementation strategies for continuations", Clinger et al. From bdesth.nospam at removeme.free.fr Sun Jul 27 06:56:35 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2003 12:56:35 +0200 Subject: Static typing In-Reply-To: References: <3f218ef1$0$27926$626a54ce@news.free.fr> <3f219c8d$1@nntp0.pdx.net> Message-ID: <3f23ae06$0$21093$626a54ce@news.free.fr> Michael Muller wrote: > Well, it appears that I have inadvertantly trolled c.l.p. I humbly > apologize. I really just wanted to know what the status of the issue > was. I may be wrong, but I don't think anyone took your question as a troll - well, I didn't anyway. > FWIW, I do favor the addition of optional static typing for the two > reasons Scott described - interface documentation and optimization. Interface documentation may be obtained in others ways (docstring for exemple). And I'm not sure static typing would optimize anything, but not being a Python (nor anything else) guru, I would not bet my hand on this... my 2 cents... Bruno From vze4rx4y at verizon.net Sat Jul 12 03:33:51 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 12 Jul 2003 07:33:51 GMT Subject: Python Mystery Theatre -- Episode 1: Exceptions References: Message-ID: > Your goal is to sleuth through the code, identify what > was expected versus what really happened, and to > explain it briefly so that others will find it blindingly > obvious. P.S. There's extra credit if you can also devine why Python was designed/implemented with the demonstrated behaviors. Raymond Hettinger From c6re at sdsumus.sdstate.edu Wed Jul 30 22:03:10 2003 From: c6re at sdsumus.sdstate.edu (Buckshot) Date: 30 Jul 2003 19:03:10 -0700 Subject: SGI + SUN = OpenGL for Jython Message-ID: <3a838998.0307301803.4e247823@posting.google.com> It looks like SGI and Sun microsystems are teaming up and creating Java bindings for OpenGL: http://siliconvalley.internet.com/news/article.php/2241281 Sweet! Now we'll be able to use OpenGL with Jython! From tebeka at cs.bgu.ac.il Sun Jul 6 06:13:31 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 6 Jul 2003 03:13:31 -0700 Subject: command line (WinXP) References: Message-ID: <33803989.0307060213.10c6c252@posting.google.com> Hello Egor, > So, why _dir /p_ and _dir "/p"_ work not identically? Whereas _ren 1 2_ and > _ren "1" "2"_ work identically. In windows, the expansion of wildcards and special characters is done by the program and not by the shell. This means that in the first usage dir sees a /p parameter where in the 2'nd usage it looks for a file named "/p". HTH. Miki From gh at ghaering.de Tue Jul 8 21:35:23 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Jul 2003 03:35:23 +0200 Subject: anygui newbie question In-Reply-To: References: <54omgv8rb7p08uct892h6q1qck489gvoph@4ax.com> Message-ID: <3F0B715B.9090308@ghaering.de> Geiregat Jonas wrote: > Op Tue, 08 Jul 2003 20:29:53 -0400, schreef Gerard C Blais: >>I'm trying to learn anygui, running on Win98. [snip problem description] > > This has nothig to do with your question [...] Then it's often worth it NOT to answer. -- Gerhard From hwlgw at hotmail.com Mon Jul 21 12:48:26 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 21 Jul 2003 09:48:26 -0700 Subject: How to save web pages for offline reading? References: Message-ID: > [Thomas G?ttler] > Does it need to be done with pyhton? > If not, I would use wget. It has very much features. I downloaded and installed (Windows binary). The latest version didn't work, needs some DLL I don't have and the supplied DLLs give errors. An old version did work. But it downloads only the HTML, not the .GIFs in it. There is an -A option (from wget --help): Recursive accept/reject: -A, --accept=LIST list of accepted extensions. But I don't know the syntax for LIST. Do you? I think adding .GIF and .CSS to this "list" is what I want?? From clifford.wells at comcast.net Tue Jul 22 21:59:43 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: 22 Jul 2003 18:59:43 -0700 Subject: wxPython looses function "wxPython.wx.miscc" In-Reply-To: <3f5dc178.0307221405.db06016@posting.google.com> References: <3f5dc178.0307221405.db06016@posting.google.com> Message-ID: <1058925583.12166.25.camel@devilbox.homelinux.net> On Tue, 2003-07-22 at 17:54, Anand wrote: > I am calling a python script from LabVIEW. This is achieved by making > a dll call to python22.dll. It works perfectly well for most of my > code. I now want to throwup dialog boxes from python. It works just > fine if i run the code once. > > but when i call the same piece of code the second time, > wxPython.wx.miscc does not exist for some reason. I dont know how this > gets deleted. I guess this happens during some kind of clean up. The > code that i use for showing a dialog box is as follows: > > from wxPython.wx import * > app = wxPySimpleApp() > dlg = wxMessageDialog(None, Text, > 'A Message Box', wxOK | wxICON_INFORMATION) > #wxYES_NO | wxNO_DEFAULT | wxCANCEL | > wxICON_INFORMATION) > dlg.ShowModal() > dlg.Destroy() > app.MainLoop() > > when i call it the second time i get the following error: > > line 1139, in showDialog > from wxPython.wx import * > File "C:\PROGRA~1\Python22\lib\site-packages\wxPython\wx.py", line > 4, in ? > from misc import * > File "C:\PROGRA~1\Python22\Lib\site-packages\wxPython\misc.py", line > 2, in ? > import miscc > ImportError: No module named miscc Is your wxApp.MainLoop() exiting? I think there is some cleanup code that happens immediately after that. You should post your question to the wxPython list: http://www.wxpython.org/maillist.php Cliff -- Should I stand midst the breakers, Should I lie with Death my bride? -This Mortal Coil From ruach at chpc.utah.edu Thu Jul 31 15:53:09 2003 From: ruach at chpc.utah.edu (Matthew) Date: 31 Jul 2003 12:53:09 -0700 Subject: list indexing Message-ID: Hello, I am rather new to python and I have come across a problem that I can not find an answer to any where I my books. What I would like to know is if there is a way to get the index number of a list element by name. Sort of the inverse of the .index() method. For example list = ['this', 'is', 'a', 'list'] for item in list: if item = 'list': print ???? ???? Is where I want to be able to get the index number, in this case 3 from the list in a simple fasion. I know that I could do this list = ['this', 'is', 'a', 'list'] counter = 0 for item in list: if item = 'list': print counter else: counter = counter + 1 But is there an easier way? Thanks very much -matthew From mcherm at mcherm.com Thu Jul 10 15:37:32 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 10 Jul 2003 12:37:32 -0700 Subject: Deleting specific characters from a string Message-ID: <1057865852.3f0dc07ca3f68@mcherm.com> The "F/bot" writes: > I rewrote the re.sub implementation for 2.2, making it about 10 times > faster for cases like this (compared to the 2.1 version). I didn't realize that. I'll re-consider my opinion on the efficiency of re for simple substitutions. And thanks for doing it! -- Michael Chermside ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From bgailer at alum.rpi.edu Thu Jul 17 12:51:41 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 17 Jul 2003 10:51:41 -0600 Subject: Problems retrieving items from a list using a reference rather than an integer - can you help? In-Reply-To: <3f16bb84@shknews01> References: <3f15ca92@shknews01> Message-ID: <5.2.1.1.0.20030717104805.028516c0@66.28.54.253> At 04:05 PM 7/17/2003 +0100, Rogue9 wrote: >After reviewing my question I realised that I should have posted the short >piece of real code I'm working on and not tried to write some pseudo-code >to illustrate the problem I'm having.Therefore I have printed the listing >below which is quite short and hopefully won't annoy too many peopleabout >the length of my post. > >To reiterate: >The masterList holds the results for the UK lottery [snip] I sure hope you are not writing "yet another winning lottery number predictor". It is a sad commentary on mathematics education when individuals belive that one can predict the outcome of a truly random process based on any history. I for one certainly won't support any effort to further mislead people. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 From claird at lairds.com Wed Jul 2 11:05:36 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 02 Jul 2003 15:05:36 -0000 Subject: Technologic transitions (was: does lack of type declarations make Python unsafe?) References: <3064b51d.0306151228.22c595e0@posting.google.com> <3EEDDA77.E9246F25@engcorp.com> Message-ID: In article <3EEDDA77.E9246F25 at engcorp.com>, Peter Hansen wrote: . . . >No roads? What planet do you live on? Where did the horses trot, and >the wagons roll, and people walk? On the sidewalks, when they were just >lone parallel strips of pavement running between the cities? Of >*course* there were roads! In fact, it was the previous generation >of transportation which *made* the roads, deliberately or not, and >cars were just an innovative way to take advantage of them. > >Let's see: use cases for early automobiles: they didn't get tired, >you didn't have to smell their dirty asses as you trotted along, >they could go marginally faster (even at the early stage), on >average if not in "burst mode", probably cheaper at that point too. >Any idea what it cost to maintain a horse and buggy in the city >when cars came out? . . . The accounting is more interesting than you might suspect. I'll summarize by saying that a LOT of the horse->car transition had to do with factors--often "social"--other than the obvious technical ones. Early automobiles were hilariously unreliable. The rubber tires alone--oy! Also, it might surprise you how bad roads were, at least intercity ones, in the US, even until World War II. To paraphrase one experienced friend, "They'd shake modern cars to pieces on the first trip [expletives deleted]." Is there a good newsgroup for engineering history? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From martin_a_clausen at hotmail.com Fri Jul 18 10:20:18 2003 From: martin_a_clausen at hotmail.com (Mars) Date: 18 Jul 2003 07:20:18 -0700 Subject: How to identify the method that has called another method ? Message-ID: <764b8294.0307180620.37781a4@posting.google.com> Hi. I am using Python 2.2.3 and new-style classes. I want to implement a static factory method to build objects for me. My plan is to have __init__ check that it has been called from said factory method and not directly. Is there a elegant way of achieving this ? (and is this a silly idea in general ?) Regards, Martin From bokr at oz.net Mon Jul 21 21:38:35 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2003 01:38:35 GMT Subject: feature request: a better str.endswith References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200721.16ef2ea1@posting.google.com> <45228044.0307210522.1ef95144@posting.google.com> <2259b0e2.0307210918.614892ba@posting.google.com> Message-ID: On 21 Jul 2003 10:18:57 -0700, mis6 at pitt.edu (Michele Simionato) wrote: [...] >chrisperkins37 at hotmail.com (Chris Perkins) wrote in message news:<45228044.0307210522.1ef95144 at posting.google.com>... >> mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0307200721.16ef2ea1 at posting.google.com>... >> > Oops! My mistake, I forgot the islice; it should be >> > >> > the=lambda pred,seq: list(itertools.islice(itertools.ifilter(pred,seq),0,1)) >> > >> > in such a way that we exit at the first hit, otherwise one could just use >> > the standard "filter". >> >> How about: >> >> def the(pred,seq): return True in itertools.imap(pred,seq) >> >> if you really want to use the name "the" ("any" makes much more sense to me). >> >> Chris > > >That's a good idea, indeed. BTW, in this context I feel that > > if the(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > dosomething() > >is more clear than > > if any(filename.endswith, ('.jpg','.jpeg','.gif','.png')): > dosomething() > >which is confusing to me since it seems "any" is referred to "filename" >whereas it is referred to the tuple elements. > I think I'd prefer if any_true(filename.endswith, ('.jpg','.jpeg','.gif','.png')): dosomething() I suspect it will more often make sense read aloud in the general if any_true(pred, seq): than if the(pred, seq) I guess the full set of functions might be any_true, any_false, all_true, and all_false. or maybe someone can think of better short phrase? Regards, Bengt Richter From hanzspam at yahoo.com.au Fri Jul 4 13:00:58 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 4 Jul 2003 10:00:58 -0700 Subject: pyBoards.com References: <191e20c8.0307031711.42d4e46b@posting.google.com> <3f054d9a$0$13803$4d4ebb8e@news.nl.uu.net> Message-ID: <840592e1.0307040900.14e3e668@posting.google.com> "Guyon Mor?e" wrote in message news:<3f054d9a$0$13803$4d4ebb8e at news.nl.uu.net>... > I like the initiative for a messageboard for Python, but I think it would be > similar to this newsgroup.... and I am quite happy with it so I don't > really see a use for it imho Message boards are more user friendly, better organized (big plus) and more interactive. At least when I post here from Google Groups, it takes 3-6 hours for the message to arrive :P. Many questions thus are answered 5 times by different people. But I don't know if the messages would arrive quicker if I used a mail program for posting. From newsgroups at jhrothjr.com Sun Jul 13 11:11:18 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 13 Jul 2003 11:11:18 -0400 Subject: Windows XP - Environment variable - Unicode References: <3f0e77fc@epflnews.epfl.ch> <3F10795B.9000501@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in message news:m33chakd25.fsf at mira.informatik.hu-berlin.de... > "John Roth" writes: > > > The OP's question revolved around ***which*** code page was > > being used internally. Windows uses Unicode. That's not the same > > question as what code set Python uses to attempt to translate Unicode > > into a single byte character set. > > Yes and no. What Windows uses is largely irrelevant, as Python does > not use Windows here. Instead, it uses the Microsoft C library, in > which environment variables are *not* stored in some Unicode encoding, > when accessed through the _environ pointer. I've found at various times that using the C library causes lots of problems with Microsoft. > > As to more difficult, as I said above, I haven't perused the source, > > so I can't comment on that. If I had to do it myself, I'd probably > > start out by always using the Unicode variant of the Windows API > > call, and then check the type of the arguement to environ() to determine > > which to pass back. I'm not sure whether or not I'd throw an exception > > if the actual value couldn't be translated to the current SBCS code. > > Notice that os.environ is not a function, but a dictionary. So there > is no system call involved when retrieving an environment > variable. Instead, they are all precomputed. Good point. That does make it somewhat harder; the routine would have to precompute both versions, and store them with both standard strings and unicode strings as keys. Whether the overhead would be worth it is debatable. It's not, however, all that difficult to understand for the user of the facility, though. It would work exactly the same way the file functions work: if you use a unicode key, you get a unicode result. John Roth > > Regards, > Martin > From ugly_411 at hotmail.com Tue Jul 29 03:41:09 2003 From: ugly_411 at hotmail.com (W F) Date: Tue, 29 Jul 2003 03:41:09 -0400 Subject: VideoCapture and camera settings. Message-ID: I haven't done much experimentation, so I am hoping someone will be able to save me the trouble. Does anyone know how to specify quickcam settings such as exposure time and gain when using snapshot in VideoCapture module? Thanks! Wes _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From bokr at oz.net Mon Jul 21 00:28:22 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Jul 2003 04:28:22 GMT Subject: Unfortunate exception on dict item assignment (and why aren't slices hashable?) References: Message-ID: On Sun, 20 Jul 2003 20:48:16 -0500, Jeff Epler wrote: >>>> {}[:] = None >Traceback (most recent call last): > File "", line 1, in ? >TypeError: unhashable type > >I'd have expected something like 'TypeError: unslicable type' >meaning that you can't slice a dict, not that slice()s aren't hashable. > >In fact, I wonder why slices *aren't* hashable. I can imagine wanting >to write something like the following: Seems like you could (untested!) > class X: from types import SliceType # BTW, why is slice a builtin function, not a type? > # ... > def __getitem__(self, idx): if isinstance(idx, self.SliceType): idx = (idx.start, idx.stop, idx.step) # and adjust self.calculate_xxx to match. > if not idx in self._cache: > # potentially expire an item and > if isinstance(idx, slice): > self._cache[idx] = self.calculate_slice_expensively(idx) > else: > self._cache[idx] = self.calculate_idx_expensively(idx) > return self._cache[idx] > >Jeff > Regards, Bengt Richter