From martin.vonloewis at hpi.uni-potsdam.de Thu May 22 09:17:27 2003 From: martin.vonloewis at hpi.uni-potsdam.de (Martin v. Löwis) Date: Thu, 22 May 2003 15:17:27 +0200 Subject: pydoc and latin-1/iso-8859-1/scandinavian letters References: Message-ID: > This thought also occurred to me earlier today and - blimey! - it > really was the console settings of my Linux. I just hadn't paid any > attention to it before. :| > > Nonetheless, thanks for the answers. However, this just hides the real problem. Requiring the console to use the encoding of the doc strings is clearly insufficient. It would be much better if the docstrings where Unicode objects, and pydoc would transparently encode the doc strings in the terminal's encoding. Fortunately, Python already supports Unicode doc strings, so all that is needed is to change pydoc to use the terminal's encoding. Regards, Martin From w_w at gazeta.pl Wed May 28 04:34:30 2003 From: w_w at gazeta.pl (Witek) Date: Wed, 28 May 2003 10:34:30 +0200 Subject: postgresql notifications In-Reply-To: References: Message-ID: Gerhard H?ring wrote: >> I'm using pypgsql to connect to postgresql database (7.2, 7.3). >> I recieve PgNotify object using notifies() method of connection >> object, but it's fields values are random chars and wrong process id. >> Is there someone, who put it to work? > The pyPgSQL source distribution includes examples for notifications > (examples/demo2a.py, examples/demo2b.py). > Please report back if you still have problems. They are not working under Linux or Windows. I tried examples from gnumed project as well. witek From connell at noflashspam.net Tue May 13 05:02:32 2003 From: connell at noflashspam.net (Ed Connell) Date: Tue, 13 May 2003 09:02:32 GMT Subject: Printing in a generic way - like the rest of Python References: <0r0wa.386$vs.311@newssvr17.news.prodigy.com> <7k8vl4fj.fsf@python.net> Message-ID: "Thomas Heller" wrote in message news:7k8vl4fj.fsf at python.net... > > > >How can I print a file in a generic way in both Widows and Linux? I've > > > >searched for the answer but have not found it. > > > > > > I assume you mean something more than basic ASCII text? > > > > > > > No, I mean something as simple as printing an ASCI text file. (I mean > > sending the file to the system printer.) My program ran just fine in Linux, > > (I used system( 'lpr %s' % filename ) and it worked just fine. Now I want > > to make the same program run in MS-Windows, and wondered if there is some > > generic way to send files to the printer as there are generic ways to delete > > a file, say, and all sorts of other stuff. > > I just tried this, and it worked (on XP pro, with a printer connected > via network): > > p = open("lpt1:", "w") > p.write("Hello, World\n") > p.close() > > Thomas Thank you, Thomas. I'd like to find a generic routine, but perhaps I'll have to ask os what kind of system it's running on and the use conditionals to do the appropriate thing. Ed From staschuk at telusplanet.net Wed May 28 22:39:31 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 28 May 2003 20:39:31 -0600 Subject: type converion in python In-Reply-To: ; from ulope@gmx.de on Thu, May 29, 2003 at 01:59:49AM +0200 References: Message-ID: <20030528203931.A2686@tibia.amotlpaa.bogus> Quoth Ulrich Petri: [...] > # i'm assuming buf is buffer with data > #i dont know how much bytes a uint2 has.... > bytes_per_uint = 2 > > list_of_ints = [int(buf[i:i+bytes_per_uint]) for i in > xrange(len(buf)/bytes_per_uint)] The OP doesn't need '1234' -> 1234, which is what int() does; he needs '\x12\x34' -> 0x1234 or something similar. For that the struct module is probably most convenient, as Peter said. (That said, you *could* use int() if you were really enthusiastic about it: >>> int(''.join(['%02x' % ord(c) for c in '\x12\x34']), 16) 4660 or >>> import binascii >>> int(binascii.hexlify('\x12\x34'), 16) 4660 But I'm not sure why you'd want to, given that the struct module exists.) -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From maschio_77 at hotmail.com Tue May 13 14:16:11 2003 From: maschio_77 at hotmail.com (Federico) Date: Tue, 13 May 2003 20:16:11 +0200 Subject: modifing function's parameters global value References: Message-ID: Here is an example: x=1 def func(y): y=y+1 print y print x func(x) print x I have 1 2 1 but I'd like to have 1 2 2 there is no way to modify a parameter in a function? In C I used pointers... Thanks From rganesan at myrealbox.com Mon May 26 06:09:10 2003 From: rganesan at myrealbox.com (Ganesan R) Date: 26 May 2003 15:39:10 +0530 Subject: State of Python References: <9eabe547.0305160511.1c5516a0@posting.google.com> <84fc4588.0305230356.71011e77@posting.google.com> <5b04353b.0305260141.569c6db6@posting.google.com> Message-ID: >>>>> "N" == N K writes: >> You're in luck :-). O'Reilly India has published the Indian edition of Alex >> Martelli's "Python in a Nutshell". While it's still not carried in local >> bookstores, I was able to order online at http://www.cb-india.com/ and get >> it delivered in Bangalore without problems. >> > Last time i searched for a Python book here in Bangalore ( 1 yr back) > , I was able to get Wesely Chun's Python book - Its also a good one. ( > I got it from PRISM,Jayanagar) You're correct. I forgot about "Core Python Programming" - that one is also easily available in Bangalore from http://www.sapnaonline.com. 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 kkto at csis.hku.hk Thu May 15 22:07:58 2003 From: kkto at csis.hku.hk (Isaac To) Date: 16 May 2003 10:07:58 +0800 Subject: 123.3 + 0.1 is 123.3999999999 ? References: <3EC3BCCD.3090605@nospam.com> <7iznlnek5v.fsf@enark.csis.hku.hk> Message-ID: <7iptmjej9d.fsf@enark.csis.hku.hk> >>>>> "Isaac" == Isaac To writes: Jeff> Has the python community converged on a favored solution for Jeff> financial/currency apps? An uninformed use of floats as currency Jeff> would have obvious pitfalls. Jeff> I hope to write some order/inventory apps for a client who uses Jeff> product unit prices with variations of as little the Jeff> ten-thousandths of a cent, and unit counts of millions of items. Jeff> It would be reassuring to have the necessary float() issues for Jeff> fixed-accuracy calculation encapsulated in a reusable class. Does Jeff> a decent one already exist? Isaac> The type that you have mentioned is already there. It is called Isaac> long integers. By the way, I think even if you use float, there is no "obvious pitfall" in financial/currency apps. Normal IEEE double-precision floating point numbers has 16-17 significant digits of precision. It means unless you are doing things like adding up two numbers one of the size 1e13 (i.e., ten trillions) and another of size 1e-3 (and then subtract the first), you are pretty fine by just rounding to the nearest 1e-3. (Who the hell will actually do that?) That you want to multiply two numbers one as small as 1e-5 and one as large as 1e15 is not a problem either, since multiplications do not cause much loss in precision. Somehow people keep yelling that they can't stand the inaccuracy of floating points, without actually looking at how inaccurate (or actually, accurate) they are. Regards, Isaac. From txo at cs.nott.ac.uk Thu May 8 10:10:38 2003 From: txo at cs.nott.ac.uk (Turhan Ozen) Date: Thu, 08 May 2003 15:10:38 +0100 Subject: define References: <3EBA50CB.2040306@cs.nott.ac.uk> Message-ID: <3EBA655E.90804@cs.nott.ac.uk> Could you show me a simple macro pre-processor example or a web page about it, please. From nav at adams.patriot.net Wed May 7 17:45:11 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 07 May 2003 17:45:11 -0400 Subject: It never fails (bsddb retirement in 2.3) References: <16053.21638.294836.796997@montanaro.dyndns.org> <16054.25509.716572.243588@montanaro.dyndns.org> <7g1xzbbf3x.fsf@pikespeak.metacarta.com> Message-ID: Skip Montanaro writes: > Alas, with your 1.85 version there are still bugs, different bugs, > but bugs nonetheless. I will have to look into that; so far everything works as expected, though I think I will write a test to make sure that the data in the btree db file is exactly the same as the data in the text file. > You also still have the file version issue to deal with when you do > upgrade to a newer version. A bridge I will burn when I get to it. :^) Probably not a serious problem, since the db file is recreated whole when the text file is changed. I can force a rebuild of the db file simply by deleting it. What I can't do is get the admins to install a new Berkeley db library without more stick than I currently have. Nick -- #include /* SigMask 0.3 (sig.c) 19990429 PUBLIC DOMAIN "Compile Me" */ int main(c,v)char *v;{return !c?putchar(*v-1)&&main(0,v+ /* Tweaks welcomed. */ 1):main(0,"Ojdl!Wbshjti!=obwAqbusjpu/ofu?\v\1");} /* build: cc -o sig sig.c */ From jdhunter at ace.bsd.uchicago.edu Fri May 16 11:42:20 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 May 2003 10:42:20 -0500 Subject: Date type In-Reply-To: ("Batista, Facundo"'s message of "Fri, 16 May 2003 12:15:57 -0300") References: Message-ID: >>>>> "Batista," == Batista, Facundo writes: Batista> #- Tim Peters has developed a new datetime module for Batista> python 2.3. Batista> Same problem as above, I can't get Python updated. You can't install software but you can use an external pure python module, is that correct? I don't exactly see the logic there, but... In any case, there is a pure python prototype of the 2.3 datetime module that may work for you I think this may be the most recent version, but am not sure http://cvs.zope.org/*checkout*/Zope3/src/datetime/_datetime.py?rev=1.32.2.1&content-type=text/plain Here is a test with that file, saved as datetime.py in a tmp dir >>> from datetime import datetime >>> d = datetime(2003,5,16) >>> dir(d) ['__add__', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__radd__', '__reduce__', '__repr__', '__safe_for_unpickling__', '__setattr__', '__str__', '__sub__', '__weakref__', '_checkOverflow', '_date__cmp', '_date__day', '_date__getstate', '_date__month', '_date__setstate', '_date__year', '_datetime__cmp', '_datetime__day', '_datetime__getstate', '_datetime__hour', '_datetime__microsecond', '_datetime__minute', '_datetime__month', '_datetime__second', '_datetime__setstate', '_datetime__year', '_dst', '_tzinfo', '_utcoffset', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year'] Hope this helps, John Hunter From lists at gregfortune.com Sun May 11 05:18:35 2003 From: lists at gregfortune.com (Greg Fortune) Date: Sun, 11 May 2003 02:18:35 -0700 Subject: n00bie help with file input and parsing References: Message-ID: Well, I just wrote a csv parser that will read that input file, but then realized that wasn't the main question in your post ;o) Teach to me to stay up this late.. jason wrote: > Hi All, > > I am trying to write a program which takes the input from a csv file > called input.txt. This file contains the following: > > "1","2","3","10064299","5","6","7","8","9" > "1","2","3","10064862","5","6","7","8","9" > "1","2","3","10064908","5","6","7","8","9" > "1","2","3","10161170","5","6","7","8","9" > "1","2","3","10161925","5","6","7","8","9" > ..... > etc. > #quick, dirty way lines = string.split(inp, '\n') for x in lines: print string.split(x, ',')[3] > I also have files separate text files named QH10064299.txt, > QH10064862.txt, QH10064908.txt etc. > > Basically, what I need to do is parse the "10064299" string from the > input.txt file, strip the quotation marks, and add a QH and .txt onto > the end so it matches one of other separate files. Then I need to > open this file up in append mode, and add all the other information to > it. k, you should have the filename from above. Just open the file in append mode.. > > For example, if I pulled the 10064299 from the 1st line of input, I > would then add the QH and .txt to make QH10064299.txt. Then I would > open this file for appending and append: > > 1 > 2 > 3 > 10064299 > 5 > 6 > 7 > 8 > 9 > > NB all quotes removed. Someone told me this could be written in about > 10 lines of Python code, could anyone help me out? I have never > before used Python. cheating a little, you can do it in 5 lines = open('input.txt', 'r').readlines() for x in lines: out = open('QH' + string.split(x, ',')[3], + '.txt', 'a') out.write(string.join(string.split(x, ','), '\n')) out.close() Do yourself a favor and check out the excellent documentation available at python.org. Download a copy for yourself.. As you get more familiar with the language, the Library Reference section is about the only thing you'll ever need :) Greg Fortune Fortune Solutions From p-abel at t-online.de Wed May 21 08:39:12 2003 From: p-abel at t-online.de (Peter Abel) Date: 21 May 2003 05:39:12 -0700 Subject: indirect function calls and variable variables References: Message-ID: <13a533e8.0305210439.cd4f8f@posting.google.com> Randall Smith wrote in message news:... > Question: Is it feasible to make indirect function calls in python? > > Example: > > > def f1(): > blah blah > blah blah > def f2(): > foo doo > doo foo > def f3(): > yik yak > mee yow > def fInfinity(): > yo yo > yaw yaw > > #what i'm trying to avoid > def do_f(f): > if f == 'f1': f1() > if f == 'f2': f2() > if f == 'f3': f3() > if f == 'fInfinity': youGetThePoint() > > #what i'd like to do instead > def do_f(f): > f() # this doesn't work, but maybe you get the point. > > It depends, how you want to use **do_f(f)**. Either f is a functionpointer or a string. 1) Functionpointer (as easy, as you want): >>> def f1(): ... print 'f1()' ... >>> def f2(): ... print 'f2()' ... >>> def f3(): ... print 'f3()' ... >>> def do_f(f): ... f() ... >>> do_f(f1) f1() >>> do_f(f2) f2() >>> do_f(f3) f3() 2) As string (nearly as easy): >>> def do_f_asText(f): ... eval(f)() ... >>> do_f_asText('f1') f1() . and so on . > > While I'm at it, can Python do variable variables? > In PHP: > $var = 'hey' > $$var = 'dude' > > echo $dude > > output: hey > > I used this alot in PHP. Is there a way to do it in Python? > Sure >>> var='hey' >>> dude='var' >>> eval(dude) 'hey' >>> var='Something else' >>> eval(dude) 'Something else' >>> > Randall Regards, Peter From davide at yahoo.com Fri May 16 11:40:19 2003 From: davide at yahoo.com (davide at yahoo.com) Date: 16 May 2003 15:40:19 GMT Subject: Linking to a library in your own directory References: <20030516.090326.165344818.1666@nets.com> Message-ID: In comp.os.linux.misc Jay O'Connor wrote: > libpq.so, which it cannot find (not being installed) . I an put > libpq.so.3 in my own directory, but I'm not sure how I can get other > programs to see it so the link it in. export LD_LIBRARY_PATH=/where/is/your/library Davide From bokr at oz.net Thu May 29 01:49:33 2003 From: bokr at oz.net (Bengt Richter) Date: 29 May 2003 05:49:33 GMT Subject: sleep and Timer References: <3ed4d6ac$0$2013@echo-01.iinet.net.au> Message-ID: On Wed, 28 May 2003 23:34:18 +0800, "Rob Hall" wrote: >I have a thread which needs to download a web page and process it >periodically (every couple of minutes). Up until now, in the thread I have >had something like this: > >def run(self): > while self.quit = false: > DO SOME STUFF > time.sleep(120) What if instead of sleeping you had an event object and waited for it with a timeout of 120, e.g., evt.wait(120) if evt.isSet(): # means another thread set the event, meaning kill # die here -- should be immediately after event is set #otherwise just let loop continue around > E.g., (Warning! Not tested beyond what you see below): ====< periodic.py >================================= import threading, time evt = threading.Event() def periodic(dt, reps): for i in xrange(reps): print i, time.clock()-t0 evt.wait(dt) if evt.isSet(): print 'dead', time.clock()-t0 break pt = threading.Thread(target=periodic, args=(5, 20)) t0 = time.clock() pt.start() time.sleep(16) print 'killing time =,', time.clock()-t0 evt.set() ==================================================== [22:44] C:\pywk\clp>periodic.py 0 0.00135519979349 1 5.00633264665 2 10.0135268551 3 15.0207151968 killing time =, 16.0019351616 dead 16.0219212157 Note that the cutoff didn't wait for the next full 5 seconds to elapse. Note also that I haven't tried this exact thing before, so there may be a pitfall. HTH Regards, Bengt Richter From duncan at NOSPAMrcp.co.uk Thu May 8 04:43:35 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 8 May 2003 08:43:35 +0000 (UTC) Subject: How to split() by multiple characters? References: Message-ID: nforest at airpost.net (Nick Forest) wrote in news:d83b5be4.0305080038.53741bec at posting.google.com: > Given an piece of text in a long string, how to split() it by ',' or > '.' or ';' ... > > i.e. text.split ( '[,.;]' ) > > Of course, the code doesn't work. :-( > Is there any good way to do this? > >>> import re >>> re.split('[,.;]', "Once,upon;a.time") ['Once', 'upon', 'a', 'time'] -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From ianb at colorstudy.com Mon May 19 03:58:49 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 19 May 2003 02:58:49 -0500 Subject: A little disappointed so far In-Reply-To: References: Message-ID: <1053331129.674.5.camel@lothlorien> On Mon, 2003-05-19 at 02:38, Alex Martelli wrote: > >> open ($file) || die "Couldn't open $file" > >> strikes me as rather readable. And concise. > > > > In Python, just write: > > f = open(file) > > > > If there is an exception, an error message will be generated explaining > > why the file could not be opened and your script will terminate. > > > > The problem with your Perl code is that it doesn't really help with > > problem diagnosis i.e. does the file not exist, is it a directory, do I > > not have the necessary permissions, etc. > > That's just because the die statement's argument above isn't using the > normal idiomatic Perl form, which would be: > > die "Couldn't open data file $file: $!" > > where the $! gives the details of the error. Not Perl's fault for > once -- it's just as possible to erroneously and anti-idiomatically > omit printing the error details in a Python except clause. You have to go to more trouble with the Python, like: try: f = open(file) except IOError, e: print "Couldn't open %s" % file # Equivalent improvement: # print "Couldn't open %s: %s" % (file, e) If you don't try to handle the error yourself, you get a long-winded and distracting traceback, but you also get the appropriate message. The "idiom" for primitive error handling is nil -- don't do anything, and errors happen loudly and with some diagnostic information. So I think it *is* Perl's fault that doing even primitive error handling requires an idiom. But arguing on Perl's flaws is probably silly in a Python group... Ian From bram at nospam.sara.nl Wed May 7 12:32:02 2003 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 7 May 2003 18:32:02 +0200 Subject: MySQLdb multithreaded Message-ID: <20030507183202.06a8e7d9.bram@nospam.sara.nl> Hello, MySQLdb package claims thread-safety. I am doing a lot of multithreaded queries, which give me crashes. single thread is OK. Can I have multiple threads use the same connection to the db, or does each thread require its own connection? I am using MySQLdb 0.9.2 on debian/x86 and python2.2.1 thx, Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Specialist. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "I heard if you play the NT-4.0-CD backwards, you get a satanic message." "Thats nothing, if you play it forward, it installs NT-4.0" ------------------------------------------------------------------------------ From fperez528 at yahoo.com Thu May 22 18:52:54 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 22 May 2003 16:52:54 -0600 Subject: I know I'm gonna feel dumb in the Morning.... References: <6e07b825.0305221445.6de3c230@posting.google.com> Message-ID: yaipa h. wrote: > Now I've made 'fLst' a list explicitly. Sooooo why doesn't this work? b/c sort works in-place and returns None cheers, f From jidanni at dman.ddts.net Sat May 3 20:53:39 2003 From: jidanni at dman.ddts.net (Dan Jacobson) Date: Sun, 04 May 2003 08:53:39 +0800 Subject: are final newlines appended if output lacks it? Message-ID: <874r4blegc.fsf@jidanni.org> Doing help() print explains how the blank got in here, $ python -c "print 'wow',;print 'pow',"|od -c 0000000 w o w p o w \n 0000010 But not the newline. Why? -- http://jidanni.org/ Taiwan(04)25854780 From evan at 4-am.com Fri May 2 12:13:45 2003 From: evan at 4-am.com (Evan Simpson) Date: Fri, 02 May 2003 11:13:45 -0500 Subject: why no break N levels, as in other leading languages? In-Reply-To: <31575A892FF6D1118F5800600846864D012008E2@intrepid> References: <31575A892FF6D1118F5800600846864D012008E2@intrepid> Message-ID: <3EB29939.80508@4-am.com> Simon Brunning wrote: > How about: > > goto 'Matched' > tag 'Matched': Two new keywords for a minor feature? Hah! how-to-get-a-PEP-rejected-at-lightspeed-ly yrs, Evan @ 4-am From peter at engcorp.com Mon May 5 12:51:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 May 2003 12:51:18 -0400 Subject: Pushing Python to Windows workstations References: Message-ID: <3EB69686.60936780@engcorp.com> C42 wrote: > > I need to install Python and win32all to all of the PCs on my > Windows domain (100+). I have domain admin rights and would like to push > Python/win32all to the workstations automatically. > > Does anyone have a list of what the Python installer does, so I can > perform the same procedure remotely? Or, is there an easier way to do this? Can you consider not installing it on all machines, but running from a network install? We don't have 100 machines here... only about 55 at the moment, but they all have access to a nice central install complete with win32all. Works nicely, no worries about maintaining 55 machines... -Peter From wobh at helium.barsoom.invalid Fri May 30 16:29:55 2003 From: wobh at helium.barsoom.invalid (William Clifford) Date: 30 May 2003 20:29:55 GMT Subject: has anyone implemented perl's HTML::Element and related modules for python? Message-ID: I ask because I was just starting to use them when I got curious about this python thing. -- William Clifford wobh at yahoo.com http://wobh.home.mindspring.com From skip at pobox.com Thu May 1 16:20:34 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 1 May 2003 15:20:34 -0500 Subject: Where did you learn to unit test? How did you learn? In-Reply-To: <3EB17F1A.8D407EDB@engcorp.com> References: <1147e466.0304290638.287687f6@posting.google.com> <3EB17F1A.8D407EDB@engcorp.com> Message-ID: <16049.33170.831853.101393@montanaro.dyndns.org> Peter> Skip, was this the play-by-play of a programming pair working Peter> through an example of test-driven development ala XP (probably Peter> with "Chet" or maybe Uncle Bob), complete with the wrong paths Peter> they temporarily travelled and eventually working code? I'm sure Peter> we can dig up a reference to that somewhere... Doesn't sound familiar. I'm certain pair programming wasn't involved, and don't recognize "Chet" or "Uncle Bob". Skip From g2h5dqi002 at sneakemail.com Mon May 19 20:46:21 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 20 May 2003 12:46:21 +1200 Subject: beauty and python In-Reply-To: References: <5c197e55.0305172359.204f2e6b@posting.google.com> Message-ID: > On Sun, 2003-05-18 at 00:59, rahul garg wrote: >>i was wondering what would happen if i tell a non-enlightened >>girl(i.e. one who has not yet discovered the joys of python >>programming) that she is as beautiful as python. I wouldn't recommend it. She's likely to mis-hear that as "you are as beautiful as a python", which, unless she's one of those rare people with a fondness for reptiles, isn't going to go down well at all... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From robert at 963.net Tue May 27 02:11:38 2003 From: robert at 963.net (robert) Date: Tue, 27 May 2003 14:11:38 +0800 Subject: How to set SO_RCVTIMEO and SO_SNDTIMEO on Solaris8 Message-ID: <00ec01c32416$d5fd65e0$0a01a8c0@frank> Hello, How to set SO_RCVTIMEO and SO_SNDTIMEO via socket.setsockopt python2.2.2 for Solaris8. When set it using the following command: s=socket(AF_INET,SOCK_STREAM) s.setsockopt(SOL_SOCKET,SO_RCVTIMEO,pack("ll",30,0) The following error message will be get: socket.error: (99, 'Option not supported by protocol') I don't know how to set SO_RCVTIMEO and SO_SNDTIMEO value in python2.2.2 for solaris Thanks in advance! Sincerely XiaoZheng Ning From aleaxit at yahoo.com Fri May 23 10:12:26 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 23 May 2003 16:12:26 +0200 Subject: readline in while loop References: <1053691812.352985@seven.kulnet.kuleuven.ac.be> <1053698200.750697@seven.kulnet.kuleuven.ac.be> Message-ID: Geert Fannes wrote: > i'm indeed a C++ programmer. then i have another question: suppose i > have 2 files and i want to read from both of them. things like this do > not work: > > f1=file("file1","r"); > f2=file("file2","r"); > for line1 in f1 and line2 in f2: > print line1,line2; > > any idea how i can solve this? In 2.3, import itertools for line1, line2 in itertools.izip(f1, f2): print line1, line2 should do exactly what you want (if one file has fewer lines than the other, this will stop at the length of the shorter). In earlier releases, without itertools, you'd have to accept the fact that everything is put in memory at once: for line1, line2 in zip(f1, f2): print line1, line2 or else break the simmetry between the files, e.g.: iterfile2 = iter(f2) for line1 in f1: line2 = iterfile2.next() print line1, line2 (this would fail with a StopIteration exception of file2 had fewer lines than file1 -- that can of course be fixed but how to fix it depends on what you're after!) or go for a different control structure such as: while 1: line1 = f1.readline() line2 = f2.readline() if not line1 or not line2: break print line1, line2 Alex From news at exultants.org Tue May 20 01:45:54 2003 From: news at exultants.org (Van Gale) Date: Tue, 20 May 2003 05:45:54 GMT Subject: On the Speed of ReST In-Reply-To: References: Message-ID: <3EC9C108.9000202@exultants.org> Jane Austine wrote: > What can I do to speed it up? Should I look for something else like re > module? Well, the most obvious answer would be to cache the results. If you use a "lazy cache" algorithm then all you need to do is delete the generated version in cache anytime the original reST source changes. I think using reST is a good idea for a wiki (in other words, it is worth going through any kind of effort to improve performance), but if you decide you don't want to use reST I would recommend using the parser from Moinmoin (compatibility can't be bad eh?) or using PyTextile from Mark Pilgrim . PyTextile might only be appropriate for shorter texts like weblogs and forums though. Not sure how well it would scale up to larger documents. It uses 're'. Van From staschuk at telusplanet.net Thu May 1 16:08:53 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 1 May 2003 14:08:53 -0600 Subject: Where did you learn to unit test? How did you learn? In-Reply-To: <16049.30979.396353.224147@montanaro.dyndns.org>; from skip@pobox.com on Thu, May 01, 2003 at 02:44:03PM -0500 References: <1147e466.0304290638.287687f6@posting.google.com> <16049.30979.396353.224147@montanaro.dyndns.org> Message-ID: <20030501140853.D820@tibia.amotlpaa.bogus> Quoth Skip Montanaro: > > * What exactly is a unit test? > > A set of unit tests is an executable specification of the functional > requirements for a piece of software. A single unit test associates a > particular input with an expected output. For each test you are saying, "If > I execute X, the result should be Y." If that's not the case, the test > fails. (Of course, if it succeeds there is still the possibility that you > wrote the test incorrectly. ;-) Elaborating on this last point: "What tests the tests?" is a reasonable question. Doctrine on this point is that the tests should be so simple that they can be seen to be correct just by reading them. Thus, they are "too simple to break". This doctrine also applies to the code under test; don't bother testing something if it's too simple to break. A canonical example is accessor methods (in languages which make heavier use of them, such as Java): private int x; public int getX() { return x; } Don't test this kind of thing; it could only fail if the JVM or compiler goes haywire, if the hardware fails, or something of that order. In other words, a test of such an accessor is not actually a test of the accessor; it is a test of the JVM, the compiler, the hardware, etc.. That's a waste of your time. (Of course, if getX() at some point became more complicated, computing its return value or something, *then* it might deserve some tests.) Dave Brueck stated the underlying principle very nicely here about a week ago: "test until the cost of a bug in deployed code is lower than the cost of finding the bug through more testing". -- Steven Taschuk 7\ 7'Z {&~ . staschuk at telusplanet.net Y r --/hG- (__/ )_ 1^1` From bkc at Murkworks.com Mon May 19 11:05:34 2003 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 19 May 2003 11:05:34 -0400 Subject: Microthreads References: Message-ID: "Chris Liechti" wrote in message news:Xns937F814878E7cliechtigmxnet at 62.2.16.82... > yes ;-) > > 1.7s on my P4 2.5GHz 0.9s on my Centrino (1.6GHZ PentiumM) with Python 2.3b1, command-line) My new Dell D800 laptop. I'm amazed at just how fast this thing runs Python. I think it's fast because it has a huge cache From progoth at progoth.com Fri May 30 15:32:18 2003 From: progoth at progoth.com (Steven Scott) Date: Fri, 30 May 2003 15:32:18 -0400 Subject: regex, repeating group Message-ID: say I'm working with this: str = """body body body -><- Meeting Info From:you Attendees:me Date:now ID:0""" I have this regular expression to get the data after colons, which I'm using in re.search: regex = r'-><-\n.+?\n(?:.+?:(.*?)\n?){4}$' my problem is that this (when I call .groups()) only returns the last datum, ('0',). if I make the outer group non-grouping I only get ('ID:0', '0')....still not any of the other lines of data. if I take out the {4} and copy and paste the whole group so it's listed 4 times, everything works right: ('you', 'me', 'now', '0') so is there a way I can get this to work without pasting a copy for each match? -- Steven Scott [progoth at progoth.com] Don't give up fighting, 'til nothing else stands in your way..Don't give up talking, until there's nothing left to say....But no matter what you do, don't ever compromise what you believe. --The Ataris From tjreedy at udel.edu Mon May 12 11:46:17 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 May 2003 11:46:17 -0400 Subject: Complexity of splits References: Message-ID: "Jean-Guillaume Pyraksos" wrote in message news:jeapy-98A462.15570212052003 at malibu.unice.fr... > As I am digging into my Python studies, I started translating some > elementary Lisp recursive algorithms... The answer to your question below depends on your purpose of doing the above. Lets assume that its to learn more about Python in relation to your current knowledge of Lisp, so that efficiency and feasibilily with loooong lists is not a concern. > a primitive operation in Python, did I miss it ? Probably. What's the > name of that operation so that the recursive algorithm stays O(n) ? I > don't want (for now) to translate it into a loop. Leaving aside the difference between linked vs. array implementation, the key difference is that Lisp lists are built back to front (and split apart front to back in reverse) while Python lists are built front to back, and so should be split in reverse back to front. So 'last = L.pop()' (with L becoming 'rest') is the primative you are looking for. Your basic strategy is to use that to replace car and cdr and work in reverse after copying (if you want to keep the original intact, as Alex mentioned) and reversing (with L.reverse() as a separate statement), if necessary. Terry J. Reedy From jtk at yahoo.com Thu May 8 14:50:33 2003 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Thu, 8 May 2003 14:50:33 -0400 Subject: parser API style - methods take path or file vs sep methods for path and file Message-ID: I wrote a small application-specific data-munging CSV parser/transformer, and want to make a suitable API around the fundamental parseLine(string) function, to support different canned ways of using the parser in throwaway scripts. def parseLine(s): return s # transform, return row-string of csv values def parseMultilineString(s): return s # multiline string of row-strings of csv values def parseFileToStringList(f): return parsedLines # list of row-strings of csv values def parseFileToMultilineString(f): return s # multiline string of row-strings of csv values def parseFilePathToStringList(p): return parsedLines # list of row-strings of csv values def parseFilePathToMultilineString(p): return s # multiline string of row-strings of csv values Each method after parseline was trivial due to reuse, but would I be better off (more pythonic) to incorporate the duplicate 'Path' methods into smarter 'File' methods? It wouldn't be hard to treat the single paramater like a file, raise an exception if readlines() fails, try the parameter as a string filespec, and finally raise another exception if that fails too. But *should* I do this, or are files and paths different enough that you should duplicate methods for each to protect the API user? Thanks. From cswiger at mac.com Mon May 5 21:27:48 2003 From: cswiger at mac.com (Chuck Swiger) Date: Mon, 05 May 2003 21:27:48 -0400 Subject: File locking In-Reply-To: References: Message-ID: <3EB70F94.6040905@mac.com> Jason Miller wrote: [ ... ] > Is there a portable (i.e. *nix, win32, mac) way to lock files in python? > From what I know about these platforms it doesn't seem likely, but I > figured I'd ask. Alex Martelli provided a reference for Python code which invokes underlying OS primitives like lockf() or fcntl(). Regardless of what you do in your Python code, however, the underlying OS mechanisms for locking don't always work well together: there exist platforms where lockf(), fcntl(), and flock() don't know about each other's locks. Sure, better platforms handle the interactions properly, but mixing types of locking *will* bite you or someone else down the line. Oh, yes, and you really don't want to try locking files on anything but a local filesystem: rpc.lockd (used by NFS) and Samba's Windows-style locking have had a history of frequent locking problems. [1] Also note that if you are working with remote filesystems, or anything having to do with email, Usenet news, or similar you should use explicit .lock files as well. SysV Unices-- ie, Solaris-- wants you to use something called maillock(). And Rich $alz of INN also wrote a nice program called shlock in ~200 lines of C for doing locking for UUCP and Usenet news. [2] -- -Chuck [1]: The Samba Team has done an amazing job and have been improving Samba's locking quite steadily, and I don't especially want to criticise their efforts. However, I wouldn't write a trading system or a medical software system which tried to lock via a Samba-based fileshare. (The less I say about rpc.lockd, the better. :-) [2]: The important idea here is that your lockfile should contain the PID of the process which holds the lock, so that another process trying to acquire the lock can get a lock held by a process which died, or be able to break the deadlock. This type of locking has been adapted by system startup scripts which keep the PID of a process (like a Unix daemon) under /var/run. I need to start hacking Python somewhere, would a Python version of shlock be of interest to anyone? From bokr at oz.net Thu May 15 15:22:04 2003 From: bokr at oz.net (Bengt Richter) Date: 15 May 2003 19:22:04 GMT Subject: Python Coredump on FreeBSD References: <0pCdnbUTkYU6W16jXTWcow@speakeasy.net> Message-ID: On Thu, 15 May 2003 11:56:07 -0500, "A.M. Kuchling" wrote: >On Thu, 15 May 2003 17:27:18 +0200, > Harald Schneider wrote: >> Thanks ! You are genious! This works perfectly stable! >> import pre as re > >Well, until the PCRE code gets ripped out of some future version of Python; >in 2.3 importing 'pre' gets a DeprecationWarning. 'pre' also doesn't >support Unicode. > >I'll still like to see the pattern causing the problem; perhaps someone can >suggest an improved pattern, or maybe there's a bug to be fixed. (Or did I >miss seeing the pattern in a previous posting in this thread?) > Not that I can find in http://groups.google.com/groups?q=%22Python+Coredump+on+FreeBSD%22+group:comp.lang.python I'm curious too as to what the pattern was ;-/ Regards, Bengt Richter From jepler at unpythonic.net Thu May 8 17:01:36 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 8 May 2003 16:01:36 -0500 Subject: Specifying a module when Unpickling In-Reply-To: References: Message-ID: <20030508210134.GB11919@unpythonic.net> On Thu, May 08, 2003 at 04:24:34PM -0400, Markus Wankus wrote: > My problem is - my *binary* pickles are now out in the wild and I need to > support and deal with them... I wonder if there is a way to apply your > module-passing-on-load mechanisms to the standard Pickle module...hmmm. If you can use the regular (not cPickle) module, it looks like you can override Unpickler.find_class to do something clever. find_class is used by load_inst and load_global, which would mean that it would be used both to find the class m.C when reloading a pickled instance of m.C, and reloading an object which happens to contain a reference to m.C. So, this might not be good enough. You might also override load_global to call Unpickler.find_class(self, module, name) and solve this problem (I suggest to override this and not load_inst because load_global is much smaller, and you're essentially duplicating the function's body except for the one call) Jeff From joconnor at nets.com Mon May 26 11:47:35 2003 From: joconnor at nets.com (Jay O'Connor) Date: Mon, 26 May 2003 08:47:35 -0700 Subject: python IRC & Command line References: <3ED02DF6.D15D5516@engcorp.com> <3ED21F9C.D441DE01@engcorp.com> <3ed2213a.47634234@news.cybermesa.com> <3ED222F6.93D85E75@engcorp.com> Message-ID: <20030526.084728.492067917.1140@nets.com> In article <3ED222F6.93D85E75 at engcorp.com>, "Peter Hansen" wrote: > Jay O'Connor wrote: >> >> On Mon, 26 May 2003 10:07:24 -0400, Peter Hansen >> wrote: >> >> >"Michael P. Soulier" wrote: >> >> Just to add to that statement, I direct you to RedHat Linux. The >> >> installer, and the majority of the sysadmin code, is all Python. >> > >> >RPM uses Python, but I'm uncertain the rest of that statement is >> >correct. Could you provide a link to a reference for this info? >> > [snip] >> Those are the only two I have direct experience with, but it's fairly >> easy to go trooping through the directories and find RedHat Python >> stuff > > Sure it is, but doing so doesn't in even the remotest way back up the > claim that the "majority of the sysadmin code is Python"... Well, a cursory look turns up a heck of a lot of Python code in a RedHat linux system. I took out everything in /usr/lib/Python1.5 and /usr/Python2.x but there is a lto of site-packages stuff that looks like it was provided by RedHat as well. Anaconda is the installer and there's a lot of stuff in there for user configuration, network configuration ,etc... A lot of basic stuff like adduser, addgroup, etc..is still going to be written in C, but most of the tools around those utilities seem to be written in Python [jay at altaica jay]$ locate *.py ... /var/mailman/Mailman/Archiver/Archiver.py /var/mailman/Mailman/Archiver/HyperDatabase.py /var/mailman/Mailman/Archiver/HyperArch.py /var/mailman/Mailman/Archiver/__init__.py /var/mailman/Mailman/Archiver/pipermail.py /var/mailman/Mailman/Bouncers/BouncerAPI.py /var/mailman/Mailman/Bouncers/Caiwireless.py /var/mailman/Mailman/Bouncers/Catchall.py /var/mailman/Mailman/Bouncers/Compuserve.py /var/mailman/Mailman/Bouncers/DSN.py /var/mailman/Mailman/Bouncers/Exim.py /var/mailman/Mailman/Bouncers/GroupWise.py /var/mailman/Mailman/Bouncers/Microsoft.py /var/mailman/Mailman/Bouncers/Netscape.py /var/mailman/Mailman/Bouncers/Postfix.py /var/mailman/Mailman/Bouncers/Qmail.py /var/mailman/Mailman/Bouncers/SMTP32.py /var/mailman/Mailman/Bouncers/SimpleMatch.py /var/mailman/Mailman/Bouncers/Smail.py /var/mailman/Mailman/Bouncers/Yahoo.py /var/mailman/Mailman/Bouncers/__init__.py /var/mailman/Mailman/Cgi/Auth.py /var/mailman/Mailman/Cgi/__init__.py /var/mailman/Mailman/Cgi/admin.py /var/mailman/Mailman/Cgi/admindb.py /var/mailman/Mailman/Cgi/edithtml.py /var/mailman/Mailman/Cgi/handle_opts.py /var/mailman/Mailman/Cgi/listinfo.py /var/mailman/Mailman/Cgi/options.py /var/mailman/Mailman/Cgi/private.py /var/mailman/Mailman/Cgi/roster.py /var/mailman/Mailman/Cgi/subscribe.py /var/mailman/Mailman/Autoresponder.py /var/mailman/Mailman/Bouncer.py /var/mailman/Mailman/Cookie.py /var/mailman/Mailman/Crypt.py /var/mailman/Mailman/Defaults.py /var/mailman/Mailman/GatewayManager.py /var/mailman/Mailman/Deliverer.py /var/mailman/Mailman/Digester.py /var/mailman/Mailman/EncWord.py /var/mailman/Mailman/Errors.py /var/mailman/Mailman/Handlers/AfterDelivery.py /var/mailman/Mailman/Handlers/Acknowledge.py /var/mailman/Mailman/Handlers/Approve.py /var/mailman/Mailman/Handlers/CalcRecips.py /var/mailman/Mailman/Handlers/Cleanse.py /var/mailman/Mailman/Handlers/CookHeaders.py /var/mailman/Mailman/Handlers/Decorate.py /var/mailman/Mailman/Handlers/HandlerAPI.py /var/mailman/Mailman/Handlers/Hold.py /var/mailman/Mailman/Handlers/Replybot.py /var/mailman/Mailman/Handlers/SMTPDirect.py /var/mailman/Mailman/Handlers/Sendmail.py /var/mailman/Mailman/Handlers/SpamDetect.py /var/mailman/Mailman/Handlers/ToArchive.py /var/mailman/Mailman/Handlers/ToDigest.py /var/mailman/Mailman/Handlers/ToUsenet.py /var/mailman/Mailman/Handlers/__init__.py /var/mailman/Mailman/ListAdmin.py /var/mailman/Mailman/HTMLFormatter.py /var/mailman/Mailman/Logging/MultiLogger.py /var/mailman/Mailman/Logging/Logger.py /var/mailman/Mailman/Logging/StampedLogger.py /var/mailman/Mailman/Logging/Syslog.py /var/mailman/Mailman/Logging/Utils.py /var/mailman/Mailman/Logging/__init__.py /var/mailman/Mailman/Utils.py /var/mailman/Mailman/LockFile.py /var/mailman/Mailman/pythonlib/StringIO.py /var/mailman/Mailman/pythonlib/__init__.py /var/mailman/Mailman/pythonlib/nntplib.py /var/mailman/Mailman/pythonlib/cgi.py /var/mailman/Mailman/pythonlib/rfc822.py /var/mailman/Mailman/pythonlib/smtplib.py /var/mailman/Mailman/pythonlib/tempfile.py /var/mailman/Mailman/versions.py /var/mailman/Mailman/MailCommandHandler.py /var/mailman/Mailman/MailList.py /var/mailman/Mailman/Mailbox.py /var/mailman/Mailman/Message.py /var/mailman/Mailman/Pending.py /var/mailman/Mailman/SecurityManager.py /var/mailman/Mailman/Version.py /var/mailman/Mailman/__init__.py /var/mailman/Mailman/aliases.py /var/mailman/Mailman/htmlformat.py /var/mailman/Mailman/mm_cfg.py /var/mailman/bin/paths.py /var/mailman/cron/paths.py /var/mailman/scripts/paths.py /usr/bin/gnome-upgrade.py /usr/bin/pydb.py /usr/bin/pydbcmd.py /usr/bin/pydbsupt.py /usr/bin/kdelnk2desktop.py /usr/lib/anaconda/installclasses/custom.py /usr/lib/anaconda/installclasses/laptop.py /usr/lib/anaconda/installclasses/reconfig.py /usr/lib/anaconda/installclasses/server.py /usr/lib/anaconda/installclasses/upgradeclass.py /usr/lib/anaconda/installclasses/upgradeonly.py /usr/lib/anaconda/installclasses/workstation.py /usr/lib/anaconda/iw/account_gui.py /usr/lib/anaconda/iw/auth_gui.py /usr/lib/anaconda/iw/bootdisk_gui.py /usr/lib/anaconda/iw/bootloaderpassword_gui.py /usr/lib/anaconda/iw/bootloader_gui.py /usr/lib/anaconda/iw/checklist.py /usr/lib/anaconda/iw/confirm_gui.py /usr/lib/anaconda/iw/congrats_gui.py /usr/lib/anaconda/iw/dependencies_gui.py /usr/lib/anaconda/iw/examine_gui.py /usr/lib/anaconda/iw/fdisk_gui.py /usr/lib/anaconda/iw/firewall_gui.py /usr/lib/anaconda/iw/format_gui.py /usr/lib/anaconda/iw/installpath_gui.py /usr/lib/anaconda/iw/iw_gui.py /usr/lib/anaconda/iw/keyboard_gui.py /usr/lib/anaconda/iw/language_gui.py /usr/lib/anaconda/iw/language_support_gui.py /usr/lib/anaconda/iw/mouse_gui.py /usr/lib/anaconda/iw/network_gui.py /usr/lib/anaconda/iw/package_gui.py /usr/lib/anaconda/iw/partition_gui.py /usr/lib/anaconda/iw/partmethod_gui.py /usr/lib/anaconda/iw/progress_gui.py /usr/lib/anaconda/iw/silo_gui.py /usr/lib/anaconda/iw/timezone_gui.py /usr/lib/anaconda/iw/upgrade_migratefs_gui.py /usr/lib/anaconda/iw/upgrade_swap_gui.py /usr/lib/anaconda/iw/welcome_gui.py /usr/lib/anaconda/iw/xconfig_gui.py /usr/lib/anaconda/autopart.py /usr/lib/anaconda/bootloader.py /usr/lib/anaconda/comps.py /usr/lib/anaconda/configFileData.py /usr/lib/anaconda/constants.py /usr/lib/anaconda/desktop.py /usr/lib/anaconda/dispatch.py /usr/lib/anaconda/elilo.py /usr/lib/anaconda/exception.py /usr/lib/anaconda/firewall.py /usr/lib/anaconda/flags.py /usr/lib/anaconda/floppy.py /usr/lib/anaconda/fsset.py /usr/lib/anaconda/gettext_rh.py /usr/lib/anaconda/gui.py /usr/lib/anaconda/gzread.py /usr/lib/anaconda/harddrive.py /usr/lib/anaconda/image.py /usr/lib/anaconda/installclass.py /usr/lib/anaconda/textw/bootdisk_text.py /usr/lib/anaconda/textw/bootloader_text.py /usr/lib/anaconda/textw/complete_text.py /usr/lib/anaconda/textw/confirm_text.py /usr/lib/anaconda/textw/constants_text.py /usr/lib/anaconda/textw/fdisk_text.py /usr/lib/anaconda/textw/firewall_text.py /usr/lib/anaconda/textw/installpath_text.py /usr/lib/anaconda/textw/keyboard_text.py /usr/lib/anaconda/textw/language_text.py /usr/lib/anaconda/textw/mouse_text.py /usr/lib/anaconda/textw/network_text.py /usr/lib/anaconda/textw/packages_text.py /usr/lib/anaconda/textw/partition_text.py /usr/lib/anaconda/textw/partmethod_text.py /usr/lib/anaconda/textw/progress_text.py /usr/lib/anaconda/textw/silo_text.py /usr/lib/anaconda/textw/statusline_text.py /usr/lib/anaconda/textw/timezone_text.py /usr/lib/anaconda/textw/upgrade_text.py /usr/lib/anaconda/textw/userauth_text.py /usr/lib/anaconda/textw/welcome_text.py /usr/lib/anaconda/textw/xconfig_text.py /usr/lib/anaconda/timer.py /usr/lib/anaconda/installmethod.py /usr/lib/anaconda/instdata.py /usr/lib/anaconda/isys.py /usr/lib/anaconda/iutil.py /usr/lib/anaconda/kbd.py /usr/lib/anaconda/kickstart.py /usr/lib/anaconda/language.py /usr/lib/anaconda/lilo.py /usr/lib/anaconda/log.py /usr/lib/anaconda/milo.py /usr/lib/anaconda/monitor.py /usr/lib/anaconda/mouse.py /usr/lib/anaconda/network.py /usr/lib/anaconda/packages.py /usr/lib/anaconda/partitioning.py /usr/lib/anaconda/pcmcia.py /usr/lib/anaconda/raid.py /usr/lib/anaconda/readConfigFile.py /usr/lib/anaconda/rescue.py /usr/lib/anaconda/silo.py /usr/lib/anaconda/simpleconfig.py /usr/lib/anaconda/splashscreen.py /usr/lib/anaconda/syslogd.py /usr/lib/anaconda/text.py /usr/lib/anaconda/timezone.py /usr/lib/anaconda/translate.py /usr/lib/anaconda/tree.py /usr/lib/anaconda/upgrade.py /usr/lib/anaconda/urlinstall.py /usr/lib/anaconda/users.py /usr/lib/anaconda/videocard.py /usr/lib/anaconda/xf86config.py /usr/lib/anaconda/xkb.py /usr/lib/anaconda/xserver.py /usr/lib/anaconda-runtime/check-repository.py /usr/lib/anaconda-runtime/checkcards.py /usr/share/printconf/util/import_printtool_queues.py /usr/share/printconf/util/printconf_backend.py /usr/share/printconf/util/printconf_conf.py /usr/share/printconf/util/printconf_gui.py /usr/share/printconf/util/printconf_tui.py /usr/share/printconf/util/printconf_version.py /usr/share/printconf/util/scan_usb_devices.py /usr/share/apps/knewsticker/scripts/fyensget.py /usr/share/dateconfig/dateBackend.py /usr/share/dateconfig/date_gui.py /usr/share/dateconfig/dateconfig.py /usr/share/dateconfig/mainWindow.py /usr/share/dateconfig/timezoneBackend.py /usr/share/dateconfig/timezone_gui.py /usr/share/hwbrowser/DeviceGeneric.py /usr/share/hwbrowser/DeviceDisk.py /usr/share/hwbrowser/DeviceList.py /usr/share/ksconfig/basic.py /usr/share/ksconfig/auth.py /usr/share/ksconfig/bootloader.py /usr/share/ksconfig/checklist.py /usr/share/ksconfig/firewall.py /usr/share/ksconfig/install.py /usr/share/ksconfig/ksconfig.py /usr/share/ksconfig/ksconfig_gui.py /usr/share/ksconfig/network.py /usr/share/ksconfig/packages.py /usr/share/ksconfig/partWindow.py /usr/share/ksconfig/partition.py /usr/share/ksconfig/raidWindow.py /usr/share/ksconfig/savedialog.py /usr/share/ksconfig/savefile.py /usr/share/ksconfig/scripts.py /usr/share/ksconfig/xconfig.py /usr/share/redhat-config-users/groupProperties.py /usr/share/redhat-config-users/checklist.py /usr/share/redhat-config-users/groupDialog.py /usr/share/redhat-config-users/groupWindow.py /usr/share/redhat-config-users/mainWindow.py /usr/share/redhat-config-users/redhat-config-users.py /usr/share/redhat-config-users/userProperties.py /usr/share/redhat-config-users/userWindow.py /usr/share/serviceconf/CheckList.py /usr/share/serviceconf/servicemethods.py /usr/share/serviceconf/serviceconf.py /usr/share/serviceconf/translate.py /usr/share/gnumeric/0.67/python/gnumeric_defs.py /usr/share/gnumeric/0.67/python/gnumeric_startup.py /usr/share/redhat-config-network/netconfpkg/ADSLInterface.py /usr/share/redhat-config-network/netconfpkg/ConfPAP.py /usr/share/redhat-config-network/netconfpkg/Conf.py /usr/share/redhat-config-network/netconfpkg/DeviceList.py /usr/share/redhat-config-network/netconfpkg/ConfSMB.py /usr/share/redhat-config-network/netconfpkg/DialupDruid.py /usr/share/redhat-config-network/netconfpkg/EthernetHardwareDruid.py /usr/share/redhat-config-network/netconfpkg/Firewall.py /usr/share/redhat-config-network/netconfpkg/HardwareList.py /usr/share/redhat-config-network/netconfpkg/InterfaceCreator.py /usr/share/redhat-config-network/netconfpkg/IsdnInterface.py /usr/share/redhat-config-network/netconfpkg/ModemInterface.py /usr/share/redhat-config-network/netconfpkg/NCCallback.py /usr/share/redhat-config-network/netconfpkg/NCCipe.py /usr/share/redhat-config-network/netconfpkg/NCCompression.py /usr/share/redhat-config-network/netconfpkg/NCDevice.py /usr/share/redhat-config-network/netconfpkg/NCDeviceList.py /usr/share/redhat-config-network/netconfpkg/NCDialup.py /usr/share/redhat-config-network/netconfpkg/NCHardwareList.py /usr/share/redhat-config-network/netconfpkg/NCProfileList.py /usr/share/redhat-config-network/netconfpkg/NCWireless.py /usr/share/redhat-config-network/netconfpkg/NC_functions.py /usr/share/redhat-config-network/netconfpkg/NCisdnhardware.py /usr/share/redhat-config-network/netconfpkg/NetworkList.py /usr/share/redhat-config-network/netconfpkg/NewInterface.py /usr/share/redhat-config-network/netconfpkg/PasswordCrypt.py /usr/share/redhat-config-network/netconfpkg/ProfileList.py /usr/share/redhat-config-network/netconfpkg/ProviderList.py /usr/share/redhat-config-network/netconfpkg/TokenRingHardwareDruid.py /usr/share/redhat-config-network/netconfpkg/__init__.py /usr/share/redhat-config-network/netconfpkg/cipeconfig.py /usr/share/redhat-config-network/netconfpkg/deviceconfig.py /usr/share/redhat-config-network/netconfpkg/devicetype.py /usr/share/redhat-config-network/netconfpkg/dialupconfig.py /usr/share/redhat-config-network/netconfpkg/dslconfig.py /usr/share/redhat-config-network/netconfpkg/editadress.py /usr/share/redhat-config-network/netconfpkg/editdomain.py /usr/share/redhat-config-network/netconfpkg/edithosts.py /usr/share/redhat-config-network/netconfpkg/ethernetconfig.py /usr/share/redhat-config-network/netconfpkg/ethernethardware.py /usr/share/redhat-config-network/netconfpkg/genClass.py /usr/share/redhat-config-network/netconfpkg/hardwaretype.py /usr/share/redhat-config-network/netconfpkg/isdnhardware.py /usr/share/redhat-config-network/netconfpkg/modemconfig.py /usr/share/redhat-config-network/netconfpkg/provider.py /usr/share/redhat-config-network/netconfpkg/providerdb.py /usr/share/redhat-config-network/netconfpkg/tcpdialog.py /usr/share/redhat-config-network/netconfpkg/tokenringconfig.py /usr/share/redhat-config-network/netconfpkg/tokenringhardware.py /usr/share/redhat-config-network/netconfpkg/wirelessconfig.py /usr/share/redhat-config-network/netconf.py /usr/share/rhn/register/config.py /usr/share/rhn/register/hardware.py /usr/share/rhn/register/text_config.py /usr/share/rhn/register/rhnreg.py /usr/share/rhn/register/translate.py /usr/share/rhn/register/tui.py /usr/share/rhn/register/checklist.py /usr/share/rhn/register/configdlg.py /usr/share/rhn/register/gui.py /usr/share/rhn/register/progress.py /usr/share/rhn/actions/__init__.py /usr/share/rhn/actions/errata.py /usr/share/rhn/actions/hardware.py /usr/share/rhn/actions/packages.py /usr/share/rhn/actions/systemid.py /usr/share/rhn/actions/up2date_config.py /usr/share/rhn/up2date_client/bootloadercfg.py /usr/share/rhn/up2date_client/__init__.py /usr/share/rhn/up2date_client/checkbootloader.py /usr/share/rhn/up2date_client/clap.py /usr/share/rhn/up2date_client/config.py /usr/share/rhn/up2date_client/elilocfg.py /usr/share/rhn/up2date_client/getMethod.py /usr/share/rhn/up2date_client/grubcfg.py /usr/share/rhn/up2date_client/hardware.py /usr/share/rhn/up2date_client/iutil.py /usr/share/rhn/up2date_client/lilo.py /usr/share/rhn/up2date_client/lilocfg.py /usr/share/rhn/up2date_client/rhnDefines.py /usr/share/rhn/up2date_client/rhnHTTPlib.py /usr/share/rhn/up2date_client/rpmSource.py /usr/share/rhn/up2date_client/text_config.py /usr/share/rhn/up2date_client/translate.py /usr/share/rhn/up2date_client/up2date.py /usr/share/rhn/up2date_client/up2dateUtils.py /usr/share/rhn/up2date_client/wrapper.py /usr/share/rhn/up2date_client/advisorywin.py /usr/share/rhn/up2date_client/checklist.py /usr/share/rhn/up2date_client/configdlg.py /usr/share/rhn/up2date_client/gui.py /usr/share/rhn/up2date_client/progress.py /usr/share/rhn/up2date_client/userpass.py /usr/share/rhn/__init__.py /usr/share/apacheconf/ApacheControl.py /usr/share/apacheconf/ApacheBase.py /usr/share/apacheconf/ApacheConf.py /usr/share/apacheconf/ApacheGizmo.py /usr/share/apacheconf/CheckList.py /usr/share/bindconf/FwdZone.py /usr/share/bindconf/dnsdata.py /usr/share/bindconf/dnsdata_base.py /usr/share/guppi/scripts/python/Guppi/__init__.py /usr/share/guppi/scripts/python/Guppi/data_impl/__init__.py /usr/share/guppi/scripts/python/Guppi/plot/__init__.py /usr/share/rpmlint/DistributionCheck.py /usr/share/rpmlint/AbstractCheck.py /usr/share/rpmlint/BinariesCheck.py /usr/share/rpmlint/Config.py /usr/share/rpmlint/ConfigCheck.py /usr/share/rpmlint/PostCheck.py /usr/share/rpmlint/Pkg.py /usr/share/rpmlint/FHSCheck.py /usr/share/rpmlint/FilesCheck.py /usr/share/rpmlint/Filter.py /usr/share/rpmlint/I18NCheck.py /usr/share/rpmlint/InitScriptCheck.py /usr/share/rpmlint/LSBCheck.py /usr/share/rpmlint/MenuCheck.py /usr/share/rpmlint/SignatureCheck.py /usr/share/rpmlint/SourceCheck.py /usr/share/rpmlint/SpecCheck.py /usr/share/rpmlint/TagsCheck.py /usr/share/rpmlint/check-install.py /usr/share/rpmlint/compile.py /usr/share/rpmlint/rpmlint.py -- Jay O'Connor http://www.r4h-music.com "God Himself plays the bass strings first, when He tunes the soul" From skip at pobox.com Tue May 20 11:48:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 20 May 2003 10:48:09 -0500 Subject: persistant web state In-Reply-To: <20030520.091027.706043324.1320@nets.com> References: <20030520.091027.706043324.1320@nets.com> Message-ID: <16074.20025.444410.700700@montanaro.dyndns.org> Jay> I'm lloking for a technique to allow me to keep memory alive Jay> between invocations of a cgi program. What I mean is that if I Jay> have two cgi requests come into a script, they should be able to Jay> access the same data in memory and not have to load from a Jay> database. Why not have a long-running process manage a shared memory segment using mmap? Your CGI processes could then attach to that segment. Skip From codedivine at yahoo.co.in Sun May 18 03:59:09 2003 From: codedivine at yahoo.co.in (rahul garg) Date: 18 May 2003 00:59:09 -0700 Subject: beauty and python Message-ID: <5c197e55.0305172359.204f2e6b@posting.google.com> hi. i was wondering what would happen if i tell a non-enlightened girl(i.e. one who has not yet discovered the joys of python programming) that she is as beautiful as python. (on the other hand think about 'as ugly as perl'). rahul garg From alloydflanagan at attbi.com Fri May 23 13:40:09 2003 From: alloydflanagan at attbi.com (A. Lloyd Flanagan) Date: 23 May 2003 10:40:09 -0700 Subject: Python boy References: Message-ID: Simon Brunning wrote in message news:... > 95> > > Cheers, > Simon Brunning > --LongSig My advocacy of Python at my company led one co-worker to dub me "python boy" weeks ago. So I've printed out the story and posted it on my cubical. The link didn't work for me. If you can't find it either, Gentle Reader, try http://story.news.yahoo.com/news?tmpl=story&cid=583&ncid=583&e=11&u=/nm/20030522/od_nm/life_cambodia_python_dc From cybersamurai at mac.com Tue May 27 09:49:39 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Tue, 27 May 2003 10:49:39 -0300 Subject: How can I use Python for dinamic pages on Apache In-Reply-To: <3ED363CF.4010604@ghaering.de> References: <3ED362F5.9060601@mac.com> <3ED363CF.4010604@ghaering.de> Message-ID: <3ED36CF3.6060402@mac.com> Some easy . : ) You have some list of documentations about this? -- Gerhard H?ring wrote: > Luiz Siqueira Neto wrote: > >> How can I use Python for dinamic pages on Apache > > > - CGI > - mod_python > - tons of other possiblities, like Quixote + mod_scgi > > Do you have anything special in mind? > > -- Gerhard > > From anti-spam.dbroadwell at mindspring.com Tue May 13 00:38:04 2003 From: anti-spam.dbroadwell at mindspring.com (David Broadwell) Date: Tue, 13 May 2003 04:38:04 GMT Subject: Laughing at myself References: <3ebfc7f4$1_2@hpb10302.boi.hp.com> Message-ID: "Bengt Richter" wrote in message > I too am among the many who are indebted here, though I prefer to think we > all find our true paths ourselves. Of course, Alex leaves big footsteps ;-) Aye, that he does. -- David Broadwell From fperez528 at yahoo.com Fri May 9 16:06:15 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 09 May 2003 14:06:15 -0600 Subject: string interpolation (was: Newbie can't figure out documentation practices) References: <3ebc01b1$0$195$e4fe514c@dreader3.news.xs4all.nl> Message-ID: Iwan van der Kleyn wrote: > Fernando Perez wrote: >> My point in all of this is that python, while overall incredibly clean in >> its design, lacks an easy way of accessing object member data for string >> interpolation. > > By design yes, in practice no. In the CookBook you can find a solution > (or hack if your prefer). Instead of using locals() you use a custom > class which accesses the 'namespace' of the caller through the > sys._getframe() function. > > Personally I would argue that Python's powerfull introspection > facilities often negates the call for Yet Another Feature to be included > in Python :-) Personally I would argue that for a newbie, the fact that print "x=%(x)s" % locals() works while print "self.x=%(self.x)s" % locals() doesn't, and that the solution requires _getframe, should be seen as a language wart. _getframe is a hackish feature (which I use a lot, in fact :), which is rather advanced and shouldn't IMHO be necessary for something as simple as the above. The leading _ should be a 'not for newbies' warning, if nothing else. Plus, messing with the stack by hand isn't exactly in the 'blindingly obvious' category, I think ;) That said, I like your solution quite a bit, so thanks! See comment next: > class Eval: > globals = globals() > def __getitem__(self, key): > self.locals = sys._getframe(1).f_locals > key = key % self > return eval(key, self.globals, self.locals) which I'd modify to: class Eval: def __getitem__(self, key): self.globals = sys._getframe(1).f_globals self.locals = sys._getframe(1).f_locals key = key % self return eval(key, self.globals, self.locals) so that it can be placed in a separate module instead of relying on the current module's globals. Otherwise you'd have to recopy the code to every module where you want to use it for globals to be correctly accessed. Best regards, Fernando. From aahz at pythoncraft.com Fri May 2 15:30:53 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 May 2003 15:30:53 -0400 Subject: why no break N levels, as in other leading languages? References: <87ptn2xx5o.fsf@jidanni.org> Message-ID: In article , Skip Montanaro wrote: > >Also, if you need to break out of a triply nested loop you may want to >consider an algorithm redesign anyway. ;-) "May", yes. Consider this bit from my TextDB module: try: for ORlist in includes: try: for filter in ORlist: for field in curr_fields: for item in record[field]: if item.lower().find(filter) >= 0: raise Found else: raise NotFound except Found: continue except NotFound: continue else: result.append(record) I think it's pretty nifty that I figured out how to use overlapping exceptions (combined with else) to avoid tracking how many matches there are in a series of ANDed conditions. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From alanmk at hotmail.com Fri May 30 09:47:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 30 May 2003 14:47:49 +0100 Subject: Help with coroutine-based state machines? References: <3ED622CA.4B01E3C1@hotmail.com> Message-ID: <3ED76105.CB8F3ECF@hotmail.com> Steven Taschuk wrote: > [Much good advice on appropriate use of generators elided] > Moreover, when the state functions are generators, you can write > "states" such as > > def foo(self): > for nextstate in [self.state0, self.state1, self.state2]: > yield nextstate > > But this is not a state in the normal sense of "state machine"; > each time you reach this "state", the machine's behaviour is > different, due solely to differences in the history of execution > (instead of due to, e.g., differences in input, which would be > legitimate). The real state of the machine is the combination of > the states of all of the iterators. Had you said this to me a month ago, I wouldn't have had a clue what you were talking about. But now I understand, and I agree that what I coded could be "dangerous" for, say, someone trying to debug the code and who does not understand how the history of execution and the resumption of "states" affects the current state of the machine. But if that principle is correct, i.e. that "states" in a "machine" should not have "after-effects", then surely that same argument could be applied to the concept of coroutines as a whole? At some level, every object/module/codeobject+data is a state-machine. But objects that use coroutines have "after-effects", so they perhaps should not be used to implement state-machines (i.e. objects). Hmmm. How to resolve this paradox? >> Which is why python generators are only "semi"-coroutines, as >> opposed to full coroutines. Because, without a dispatcher function, >> you can only yield control to the calling function, rather than any >> resumable state that you have a reference to. [...] > In part, yes. But even with the dispatcher, you can't call > another function and have *it* transfer control to another > coroutine, suspending the whole call stack. (Not transparently, > anyway; it could be done by replacing all calls to functions with > yields to a dispatcher.) I don't understand. But I think I need to work through and code a good few examples before I'll be in a position to know what I don't understand, and before I could ask meaningful questions. Thanks much. kind regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From trislam at hotmail.com Sun May 25 05:16:45 2003 From: trislam at hotmail.com (trislam at hotmail.com) Date: Sun, 25 May 2003 05:16:45 -0400 Subject: Change the email address . . . Message-ID: Hello, Can some one please tell me how to change the name of the mailing list. I am attempting to use mailman as a one way post to keep a large group of people current on up coming events. I created a test list called mailinglist1 at domain.com. The "From:" line on the email that I send out reads mailinglist1-admin at domain.com. I am trying to change this email address to read info at domain.com. I want to mask the "mailing list" email. The info at domain.com is a regular email that has nothing to do with the list. It is an email address users can send me an email apart from the list. I did change the return email address to info at domain.com but I still want to change the sending email address. Thanks in advance! Triz -------------- next part -------------- An HTML attachment was scrubbed... URL: From Loko at caramail.com Thu May 15 05:50:37 2003 From: Loko at caramail.com (Loko) Date: 15 May 2003 02:50:37 -0700 Subject: Dynamic variable names ... with imported libraries. Message-ID: <399d6c30.0305150150.2d7e8bd9@posting.google.com> Hi I searched for this topic in the archives, and on 1997/04/16, Gred Stein wrote : -------------------- >>> var = 'spam' >>> locals()[var] = 'eggs' >>> spam 'eggs' ------------------- This is very interesting, but it does not seem to work for imported variables : >>> import Atllib >>> print Atllib.my_constant Content of my_constant >>> var = 'Atllib.my_constant' >>> locals()[var] Traceback (most recent call last): File "", line 1, in ? locals()[var] KeyError: Atllib.my_constant >>> globals()[var] Traceback (most recent call last): File "", line 1, in ? globals()[var] KeyError: Atllib.my_constant It would be usefull to me to write such code, it's a simple testcase but I have in my library a list of some ZIP codes, and associates arrays for them, etc ... Thanks Loko From antonmuhin at sendmail.ru Fri May 23 11:25:22 2003 From: antonmuhin at sendmail.ru (Anton Muhin) Date: Fri, 23 May 2003 19:25:22 +0400 Subject: lyst[:None] In-Reply-To: References: Message-ID: Jacek Generowicz wrote: > Given that the name lyst refers to a list, I'd like to limit the > number of elements returned by the slice > > lyst[:limit] > > by setting the value of limit. > > Now, what if I want to include the option of getting all the elements > from the list? Is there a value of limit which would lead to the > desired behaviour? > > -1 does not work: the upper limit is exclusive, so the last element is > left out > > -0 does not work: it just evaluates to 0 > > None does not work: subscripts must be integers > > Is there a way of doing this on one line? > > (Yes, I know I can split it up onto several lines, and probably should > if I want humans to understand the code ...) I might be missing something, but still I would prefer: def get_elements(l, count = None): if count: return l[:count] else: return l[:] hth, anton. From frobozz_electric at hotmail.com Fri May 16 13:34:59 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 16 May 2003 17:34:59 GMT Subject: how-to do black magic (using metaclass?) References: Message-ID: After seeing this posting, I've updated my recipe, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768, with one more convenience method. autoproperties() will automate the creation of readable and writeable properties for your classes. >From reading your post, I gather that you want to be able to do is something like the following: #info.txt file contents foo=1,bar=2,fro=3,boz=4 then in your Python program, you can do things like this: # assumes you've added rowo.py (see recipe) module to your path from rowo import autoproperties # read and prepare property information from file fd = open('./info.txt') info = fd.readline() info = info.split(',') info = [tuple(i.split('=')) for i in info] infodict = dict(info) # use autoproperties() to automate the creation of # readable and writeable properties for instances of MyClass class MyClass(object): autoproperties(**infodict) instance = MyClass() print 'instance.foo: %s' % instance.foo print 'instance.bar: %s' % instance.bar instance.foo = 'changed' print 'instance.foo: %s' % instance.foo print 'instance._MyClass__foo: %s' % instance._MyClass__foo # This outputs... instance.foo: 1 instance.bar: 2 instance.foo: changed instance._MyClass__foo: changed This is the behaviour I think you were asking for. If you really want to use metaclasses, you can use the following recipe as a starting point: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965 I'm a bit curious as to why you would want to be able to create properties from a file, especially if you will not know in advance what the names of those created properties will be. How did you plan to use them? Anyway, I hope this is helpful to you, Sean > > The recipe > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768 > > and its (long) discussion should give you a head start. > Heh. It /is/ a very long discussion isn't it...Maybe I can get Mr.Ascher or the webmaster to trim it down a little. We'll see... From news at yebu.de Mon May 26 07:57:56 2003 From: news at yebu.de (Karl Scalet) Date: Mon, 26 May 2003 13:57:56 +0200 Subject: constructor overloading like Java ? In-Reply-To: References: Message-ID: Hello Markus, Markus Jais wrote: > class MyObject > { > public MyObject() > { > System.out.println("uno"); > } > } > class MyClass > { > private int a; > private MyObject my; > > public MyClass(int a) > { > this.a = a; > } > public MyClass(MyObject my) > { > this.my = my; > } > } you cannot have more than one contructor, but you could handle this case inside _the_ constuctor: class MyClass: def __init__(arg): if type(arg) == type(0): self.a = arg elif isinstance(arg, MyObject): self.my = arg in the latter case, arg is a MyObject or a subclass of it (as with Java) HTH, Karl From fredrik at pythonware.com Thu May 15 15:52:37 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 May 2003 21:52:37 +0200 Subject: [TKinter] get a canvas items's id... References: Message-ID: "polux" wrote: > ...after having clicked on it ! is it possible ? > > I know i've clicked on an item with a certain tag, but the only way I've > foud to get its id is to use find_closest.... inside the event handler, ids = canvas.find_withtag(CURRENT) should work (this returns a tuple containing the identities of all items with that tag). From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu May 29 17:53:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 29 May 2003 23:53:19 +0200 Subject: select on windows: must import socket first? In-Reply-To: <3ed67f24$0$617$a1866201@newsreader.visi.com> References: <3ed67de7$0$49112$e4fe514c@news.xs4all.nl> <3ed67f24$0$617$a1866201@newsreader.visi.com> Message-ID: <3ed68150$0$49112$e4fe514c@news.xs4all.nl> Grant Edwards wrote: > Under Windows, select can't be used for anything except > sockets, so there's really no use for importing select w/o > importing socket. I suppose you could put a call in the select > module to start up winsock if it hasn't already been done, but > what's the point? There's no point, indeed. But I was just wondering if this is a conscious omission of the init call, or that somebody forgot something ;-) > I'm guessing that the select call is probably actually part of > winsock and not really part of Win32... You're probably right. But couldn't it be implemented using WaitForMultipleObjects() ? Never mind. Don't want to mess with that. --Irmen From dave at nullcube.com Fri May 9 05:01:36 2003 From: dave at nullcube.com (Dave Harrison) Date: Fri, 9 May 2003 19:01:36 +1000 Subject: solaris 9 and MySQLdb fix Message-ID: <20030509090136.GA4112@dave@alana.ucc.usyd.edu.au> for those who care/are curious/might come across the same problem ... turns out that the solaris gcc compiler is buggy. you need to do a -v on the ./setup.py install then find the gcc command used, then do a -v on that then take the first gcc command shown, remove the parameter "-z text" run the command as it then is, and re-run the install script. damn that was a pain ;-) From martin at v.loewis.de Sun May 4 11:12:05 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 04 May 2003 17:12:05 +0200 Subject: unary star In-Reply-To: <20030504170428.D22359@prim.han.de> References: <20030504170428.D22359@prim.han.de> Message-ID: <3EB52DC5.2080306@v.loewis.de> holger krekel wrote: > I can see good uses for getting the unary-star syntax "*args" > in other than function call contexts. E.g. > > head, *rest = l Yes, that might be a good use. However, it is quite different from David's proposed extension. > Anyway, trying to leverage the unary-star syntax for other than > "function call parameter" contexts seems worthwhile to me. Only on a case-by-case basis. I can't see the advantage of (a,b,c,*d) over (a,b,c)+d The second alternative is probably better, as it would be more portable: the first alternative can function in Python 2.4, earliest. There should be one-- and preferably only one --obvious way to do it. Regards, Martin From mahboob at bellsouth.net Thu May 29 00:22:11 2003 From: mahboob at bellsouth.net (Mahboob) Date: Thu, 29 May 2003 00:22:11 -0400 Subject: Variable arguments to a Python function Message-ID: How can I pass variable number of arguments to a Python function and access them inside the function? In Perl, you could write sub all_of { my $result = 1; while ( @_) { $result *= shift; } return result; } (From Mastering Algorithms with Perl, pg 569) You can compute the product of any number of variables with the above function. Thanks, -- Mahboob From bgporter at artlogic.com Fri May 16 10:41:31 2003 From: bgporter at artlogic.com (Brett g Porter) Date: Fri, 16 May 2003 10:41:31 -0400 Subject: State of Python In-Reply-To: <8YWcnXt_dpfQd1mjRTvU3Q@speakeasy.net> References: <9eabe547.0305160511.1c5516a0@posting.google.com> <8YWcnXt_dpfQd1mjRTvU3Q@speakeasy.net> Message-ID: A.M. Kuchling wrote: > On 16 May 2003 06:11:43 -0700, > John Howard wrote: > >>etc about Python in recent months? I regularly receive several >>magazines (dobbs, computerworld, etc) and seen very few if any >>articles touting Python. I have had great success using the language > > > Really? I just started a new DDJ subscription, and the first two issues > (May and June) both had articles that mentioned Python: one presented an > algorithm for canonicalizing graphs, and one used Python in an example to > call an embedded XML-RPC server. The latter article even said something > like "Notice how the C example is 50 lines, and the Python one is only > seven." In an odd bit of timing, I had an article in the April issue of DDJ that used Python to talk to an embedded XML-RPC server. I thought it was a little odd to see another article so similar to mine so soon afterwards, but I guess it's one of those things that's 'in the air' right now. DDJ seems to have articles that use or mention Python about 5-6 times a year. From badchoice at gmx.li Thu May 1 08:02:04 2003 From: badchoice at gmx.li (badchoice at gmx.li) Date: Thu, 1 May 2003 14:02:04 +0200 Subject: The behavior of List.insert References: Message-ID: <20030501140204.08f87daa.badchoice@gmx.li> > > mylist = [1,2,3,4,5], > > mylist.insert(-1,99) will make mylist to be [99,1,2,3,4,5] > > just wonder why not let it to be [1,2,3,4,99,5] > http://rgruet.free.fr/PQR2.2.html s.insert(i, x) same as s[i:i] = [x] if i >= 0 From staschuk at telusplanet.net Fri May 30 16:00:00 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 30 May 2003 14:00:00 -0600 Subject: Preferred exception style? In-Reply-To: ; from gry@ll.mit.edu on Fri, May 30, 2003 at 03:32:08PM -0400 References: Message-ID: <20030530140000.B1735@tibia.amotlpaa.bogus> Quoth George Young: [...] > Furthermore, the parenthesis form allows for more than just > a string value. E.g.: > class GetRunFailed(Exception): > def __init__(self, reqobj, dberrormsg=None, > domainerr='Run does not exist'): [...] Positional parameters (but not keyword arguments) can be passed with the comma syntax, using a tuple in the second place: raise GetRunFailed, (reqobj, dberrormsg, domainerr) The familiar special case for 1-tuples occurs here too, of course. -- Steven Taschuk staschuk at telusplanet.net "Tomorrow never happens." -- Janis Joplin From altis at semi-retired.com Mon May 19 12:54:44 2003 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 19 May 2003 09:54:44 -0700 Subject: ANN: Python Powerpoint slideshow References: Message-ID: This is probably a good time to quote a section from Mark Pilgrim's DiveIntoPython [http://diveintopython.org/odbchelper_funcdef.html] An erudite reader sent me this explanation of how Python compares to other programming languages: statically typed language A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages. dynamically typed language A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value. strongly typed language A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it. weakly typed language A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion. So Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters). ka "Stephen Ferg" wrote in message news:b16e4ef7.0305190508.747fe35e at posting.google.com... > http://home.att.net/~stephen_ferg/projects/python_java_side-by-side.html The discussion of dynamic vs. static, and strong vs. weak, typing wasn't really satisfactory, so I've added an appendix that discusses these terms. It might be a useful resource if you get into a debate as to whether Python is, for instance, "strongly" typed or not. -- Steve From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed May 14 18:11:50 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 15 May 2003 00:11:50 +0200 Subject: Bug in CPython 2.2.1? - resend In-Reply-To: References: Message-ID: <3ec2bf25$0$49099$e4fe514c@news.xs4all.nl> Fernando Perez wrote: > I'm wondering if the following is a bug in Python. I'm using the 2.2.1 > interpreter supplied with RedHat 8.0: > > Python 2.2.1 (#1, Aug 30 2002, 12:15:30) > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 > > Here's how to reproduce the problem: > > [~]> cat test.py > import readline > readline.get_completer_delims() > > [~]> echo 'execfile("test.py");print 10' | python > python: Objects/stringobject.c:111: PyString_FromString: Assertion `str != > ((void *)0)' failed. > Abort Using Python 2.2.2 on Mandrake 9.1, I get a segmentation fault when doing this. Seems that something fishy is indeed going on here. (SIGSEGV in strlen(), according to gdb. I use the stock Python from Mandrake 9.1) However, a Python 2.3b compiled by myself on the same box works fine. It seems that the bug (whatever it was) has disappeared already... --Irmen From phil at riverbankcomputing.co.uk Thu May 8 11:28:30 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 8 May 2003 16:28:30 +0100 Subject: Gui Advice Needed: wxPython or PyQT ? In-Reply-To: References: <8d3e714e.0305051833.65da42bc@posting.google.com> <28bua.106423$K35.2720018@news2.tin.it> Message-ID: <200305081628.30908.phil@riverbankcomputing.co.uk> On Thursday 08 May 2003 4:08 pm, David Bolen wrote: > Alex Martelli writes: > > I think the #1 issue (and maybe the only significant one) with Qt for > > most people is its complicated, and potentially costly or bothersome, > > licensing. > > That's what it is for me at least. > > > If you're in sharp situations -- a commercial software house choosing > > what to use for your programming (in which case a few thousand dollars > > may be no big deal given all the other expenses each of your programmer > > employees must incur for you, salary foremost:-), or at the other extreme > > a developed committed to doing GPL development for free OS's only -- it's > > not too bad -- you purchase professional or enterprise licenses as > > needed, or on the other hand choose the GPL or QPL licenses, and off you > > go. > > The pricing can definitely also be a hurdle for commercial shops, > certainly for smaller ones with existing tools in place. For example, > we're primarily a Windows shop, and have existing MSDN licenses. > Purely on a technical level Qt is a serious alternative (perhaps even > a leader) to wxPython if we wanted to move to Python for our primary > product GUIs, and even the more attractive because of their embedded > system support as we also do some custom embedded hardware > development. > > If it was just a few thousand dollars it would be an easier sell, but > for a 6-developer team it's about $12,000 USD fixed, plus almost > $4,000 USD per year for support. And if I want to take advantage of > the portability moving to such a solution permits (for other > platforms), I still have to incur the fixed costs all over again. And > no site licenses so I've got to keep other costs associated with new > developers. > > Is that a fraction of other overhead costs? Sure, but not an > insignificant one. I can do a lot with that kind of money on a per > developer basis. Heck our MSDN licenses are less than half that of Qt > (even less since we're in renewals) and that's without taking into > account any of the volume licensing programs. But the problem is > really when contrasting it with something like wxPython, when it's not > just if Qt is better, but is it better to be worth that much > difference in cost. Clearly, I don't expect it to be free, but as > libraries go, Qt is a pretty costly one. > > So this has probably rambled somewhat off-topic for this group, but it > seems to me that by its pricing, Trolltech has really aimed their > commercial licenses at bigger shops - maybe that's a natural > consequence of being such good supporters of the GPL/open source > development community. It's a shame because I really do like their > product, but not enough to take the bite out of the budget line. My experience with the commercial version of PyQt doesn't agree with this. While some organisations have licenses for dozens of developers, most are single user licenses. Phil From list-python at ccraig.org Tue May 13 17:04:40 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 13 May 2003 17:04:40 -0400 Subject: passing by refference In-Reply-To: References: <9xRw+ks/KrpJ089yn@the-wire.com> Message-ID: Joshua Marshall writes: > See > > http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?call-by-value > > What you describe is call-by-value. There is an implicit copy of the > arguments passed to a function, though not a deep-copy. The values > that are being copied are often references. If you look at http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?call-by-value You will see that it also describes Python's calling strategy. Python always passes the address of an argument variable rather than the contents of said variable. That assignment will overwrite that address is not related to the passing strategy. -- Christopher A. Craig "There is no subject, however complex, which--if studied with patience and intelligence--will not become more complex." New Speaker's Handbook From srix123 at hotmail.com Tue May 13 22:08:55 2003 From: srix123 at hotmail.com (srix123 at hotmail.com) Date: 13 May 2003 19:08:55 -0700 Subject: Newbie Question Message-ID: <1675b97b.0305131808.664afb0b@posting.google.com> How to render ZSQL result with a page template(ZPT). I'm using DCOracle2. From bokr at oz.net Fri May 30 20:27:48 2003 From: bokr at oz.net (Bengt Richter) Date: 31 May 2003 00:27:48 GMT Subject: [2,3,4,7] --> "2-4,7" ? References: Message-ID: On Thu, 29 May 2003 15:11:21 -0400, George Young wrote: >[python 2.3a1] >I have a list of "names" like: > ['6','7','mx8','mx09','mx10','8','9','10','foo'] >which needs for concise and clear display to become a string like: > > "6-7,mx8-10,8-10,foo" Don't you need to be able to reconstitute the original sequence from the abbreviated one? I.e., how would you know to go backwards to 'mx09' vs 'mx9' ? [...] Regards, Bengt Richter From cswingle at iarc.uaf.edu Mon May 12 15:24:08 2003 From: cswingle at iarc.uaf.edu (Christopher Swingley) Date: Mon, 12 May 2003 11:24:08 -0800 Subject: curses curiosity In-Reply-To: <20030512174733.GA28837@iarc.uaf.edu> References: <20030512174733.GA28837@iarc.uaf.edu> Message-ID: <20030512192407.GC28837@iarc.uaf.edu> Andrew Cooke identified the problem as one involving the cursor. After putting a character in the lower right corner, the cursor is moved to the right of it, which is off the screen. One seeming hack to make this work would be to do: #! /usr/bin/env python import curses import curses.wrapper def main(window): (max_y, max_x) = window.getmaxyx() window.addch(max_y - 1, max_x - 2, ord('+')) # OK window.addch(max_y - 2, max_x - 1, ord('+')) # OK # window.addch(max_y - 1, max_x - 1, ord('+')) # ERR? window.insch(max_y - 1, max_x - 2, ord('+')) # OK window.refresh() while 1: c = window.getch() if c == ord('q'): break curses.wrapper(main) Now I've got: + ++ in the lower right, but I can work around this. Is there another, more elegant way? Thanks, Chris -- Christopher S. Swingley email: cswingle at iarc.uaf.edu IARC -- Frontier Program Please use encryption. GPG key at: University of Alaska Fairbanks www.frontier.iarc.uaf.edu/~cswingle/ From defender at austin.rr.com Wed May 7 20:00:46 2003 From: defender at austin.rr.com (defender) Date: Thu, 08 May 2003 00:00:46 GMT Subject: Need help with input redirection Message-ID: <3EB99F98.6020303@austin.rr.com> Greetings All: I'm looking for a way to redirect input from one program into a python program. For example: $tcpdump | pythonprog.py The objective is to take the text output of one running program and pipe it into the python program for parsing and processing. It is important during this process that I: 1) Not use a file as an intermediate step (I can already do that), and 2) The program feeding my python program *does not terminate*. That is, it keeps running and my python program keeps independently processing the input and doing stuff with it while the other program continuously feeds it. This suggests a threading model, which I already know how to do. The piece I haven't figured out is how to get the input into the python program in a continuous mode. I'm assuming it has something to do with sys.stdin? Anyone have any ideas how to continuously feed text data to a python program from an external data source that does not terminate? Any help would be appreciated. Thanks in advance! Mark From alanmk at hotmail.com Tue May 13 09:57:16 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 13 May 2003 14:57:16 +0100 Subject: Convert CPython library with C Code to Jython and Java References: Message-ID: <3EC0F9BC.92D36F08@hotmail.com> Thomas wrote: > I want to port a Python library that contains C code to Jython and > Java. What is the easiest way to do that? > > (1) Convert C library to Java. > (2) Somehow integrate compiled .pyd library into Jython and Java. > (3) Any other solution? > > Since I don?t have enough C know-how, I would prefer not to go for > option (1). Can you recommend me any workaround? Thomas, You didn't mention why you want to do this, i.e. why the algorithm (i.e. C code) has to run under a JVM? Perhaps a distributed object system, such as pyro or CORBA, would do the job much more simply? These would allow you to call code running in native process from code running in a JVM, and vice versa, without requiring porting, etc. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From kossay_omary at yahoo.com Sat May 3 20:50:18 2003 From: kossay_omary at yahoo.com (Kossay Omary) Date: Sat, 3 May 2003 17:50:18 -0700 (PDT) Subject: win32file module functions seem to fail very simple test case. In-Reply-To: <000801c311aa$ce7b5e90$0905a143@DGLTVN21> Message-ID: <20030504005018.3923.qmail@web20501.mail.yahoo.com> I took a look at the WindowsXP system info tool and it says that thefaulting application is pythonw.exe and the faulting module is kernel32.dll I am using win32all-152 I also noticed in my system info tool, under "Loaded Module":1- Python module was marked as "Not Available", instead I found Python2.2 module.2- I did find the module PythoTypes22.dll but did not find the module Pythoncom22.dll (although it is found under C:\windows\system...) Any ideas???Thanks,Kossay Kossay Omary wrote:I am almost sure that this is a problem with my configuration or my use of the functions. I just do not know how to debug this. I am running the following code on WindowsXP with Python2.2 ,after I execfile('...') the following code, I get a message from windows that the application pythonw was aborted and it asksme if I want to send an error log to microsoft. The code (you need to create the dummy file C:\existing_file):Please help. These are my first steps with windows file handling. import win32file def closeFile(handle): handle.Close() def openFile(filename): # returns a handle to the Windows file return win32file.CreateFile(filename.upper(), win32file.GENERIC_READ, \ 0, None, win32file.OPEN_EXISTING, 0, None) def readChar(handle): err = 0 char = None err, char = win32file.ReadFile(handle, 1, None) return char if __name__ == '__main__': # this will now fail #handle = openFile('C:\\MyFiles\\Python\\Modem\\ttt') handle = openFile('C:\\existing_file') print readChar(handle) closeFile(handle) --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bkc at Murkworks.com Thu May 8 11:07:14 2003 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 8 May 2003 11:07:14 -0400 Subject: snake running on embedded device References: Message-ID: I ported Python 2.3a2 to uC5272 running uClinux (8 meg ram, 4 meg flash) That port also included libxslt and libxml2 linked in statically. Tight squeeze, but it works. 175 pystone/sec . a rocket! Fortunately we're moving to X-scale ;-) All I needed to do was tweak ./configure, use VPATH makefiles and tweak Makefile.pre.in -- Novell DeveloperNet Sysop #5 _ "piter" wrote in message news:b9cujv$et9$1 at news.onet.pl... > Hi folks, > > I'd like to port python to embedded system based on STMicroelectronics 5514 > chip. > It has limited memory to 8 MB and is diskless. > Mission impossible? > Any hints? > > Piter > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tim at lesher.ws Mon May 26 20:05:28 2003 From: tim at lesher.ws (Tim Lesher) Date: 26 May 2003 17:05:28 -0700 Subject: [Q]:Generate Unique ID's References: <3ECE8494.5A6EA6EB@easystreet.com> <3ECE9B3F.3040002@soraia.com> <7xn0hdguox.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xn0hdguox.fsf at ruckus.brouhaha.com>... > Joe Francia writes: > > There's a CreateGuid() funtion in the pywintypes modules, which is > > part of the ActiveState python distribution (which includes the Win32 > > Extensions): > > I don't think you can rely on that function to create vast quantities > of unique ID's, e.g. one for each row of a billion-row database. > Usually those Windows guids are partly constant (based on MAC address). > They also can be a privacy leak in some situations, because they reveal > the MAC address. So I think it's better to use a random number. Actually, they're no longer based on MAC addresses; they haven't been for several iterations of the OS. They're now based on a much better, entropy-based PRNG (the same one on which the Windows crypto subsystem is based), so if you're using a PRNG to generate GUIDs, you're essentially doing the same thing. -- Tim Lesher tim at lesher.ws From medved at fcc.net Wed May 21 14:48:38 2003 From: medved at fcc.net (Ted Holden) Date: Wed, 21 May 2003 14:48:38 -0400 Subject: specifying a quantization table for a jpeg file in PIL? Message-ID: Is it possible to specify a quantization table when saving an image as a jpeg file using the PIL? The basic need here is to save an image using the same quantization table as another image. Ted Holden medved at fcc.net From johnroth at ameritech.net Thu May 8 09:44:59 2003 From: johnroth at ameritech.net (John Roth) Date: Thu, 8 May 2003 09:44:59 -0400 Subject: define References: <3EBA50CB.2040306@cs.nott.ac.uk> Message-ID: "Turhan Ozen" wrote in message news:3EBA50CB.2040306 at cs.nott.ac.uk... > in c it is possible to define > > #define PH x[1] > > so PH = 3 means x[1]=3 > > how can I do this in python? No. Python does not have a preprocessor. I'm not at all sure I'd want to do what you seem to want anyway: it seems that it is unnecessarily obscure. John Roth > From alan_salmoni at yahoo.com Tue May 20 06:51:14 2003 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 20 May 2003 03:51:14 -0700 Subject: Announcement: Obfuscated Python competition References: <3ec91012$1_2@hpb10302.boi.hp.com> Message-ID: Graham Nicholls wrote in message news:... > Jeff Epler wrote: > > I reckon its possible to write bad code in any language. So if it hasn't > been done already, how about an obfuscated Python competition. > > Prize : One of my Perl books - lets see: "Perl in a Nuthouse" looks good. > Hmm - surely a good book on Python might be more in order?! ;) And like some of the other posters suggested, I could see lambda making frequen appearances in such a contest... Alan James Salmoni SalStat Statistics http://salstat.sunsite.dk From pballard at ozemail.com.au Wed May 7 04:00:58 2003 From: pballard at ozemail.com.au (Peter Ballard) Date: 7 May 2003 01:00:58 -0700 Subject: The most annoying typo error... Message-ID: <9d5509fa.0305070000.55b11d6@posting.google.com> ....Is when I do something like this: x = somefunction(a, b, c, d), and when I run Python I get a TypeError error. You spotted the error immediately didn't you? The line of code above has a trailing comma, so that x is suddenly a tuple; and so when I get around to using x I get a TypeError. I don't know about anyone else, but for me, this error always takes a long time to track down. So my question is: has anyone come up with some way of alerting users to this sort of error? (e.g. more verbose TypeError messages? Emacs warning ["Did you really mean to create a 1 element tuple?"??) Just wondering. Regards, Peter Ballard Adelaide, AUSTRALIA pballard at ozemail.com.au http://www.ozemail.com.au/~pballard/ "Love your enemies, and pray for those who persecute you" - Jesus (Matthew 5:44, NIV) From gh at ghaering.de Sun May 18 07:47:05 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 18 May 2003 13:47:05 +0200 Subject: filter directory In-Reply-To: <20030518103318.GB749@thomas-guettler.de> References: <3ec5a861$0$8986$afc38c87@news.optusnet.com.au> <20030518103318.GB749@thomas-guettler.de> Message-ID: <3EC772B9.50200@ghaering.de> Thomas Guettler wrote: > On Sat, May 17, 2003 at 01:11:29PM +1000, Psybar Phreak wrote: > >>ok - does anyone know how to : >> >>filter the contents of a folder depending on the extension? > > > This script lists all files ending with ".txt". Is this what you want? > > import os > > my_files=[] > for file in os.listdir("."): > if file.lower().endswith(".txt"): > my_files.append(file) > > print my_files Better: import glob my_files = glob.glob("*.txt") Also, 'file' is a builtin in Python 2.2+, so it's good practise to not shadow it. -- Gerhard From ianb at colorstudy.com Fri May 2 19:35:45 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 02 May 2003 18:35:45 -0500 Subject: HTML Parser chokes on WordHTML... In-Reply-To: References: Message-ID: <1051918545.1075.39.camel@lothlorien> On Fri, 2003-05-02 at 13:14, Harald Massa wrote: > So... is there any replacement for the HTMLParser from the python.lib > which even can eat Microsoft Word HTML ? You might want to try running mxTidy on the HTML first: http://www.lemburg.com/files/python/mxTidy.html Ian From topsoil at mail.com Sun May 11 01:15:06 2003 From: topsoil at mail.com (gk) Date: Sun, 11 May 2003 01:15:06 -0400 Subject: Need help with Python programming problem. References: Message-ID: <20030511011506.7c44e990.topsoil@mail.com> On Sun, 11 May 2003 00:28:27 GMT "King Kuta" wrote: > Take a look here. It might help you figure out something. > http://www.ibiblio.org/obp/thinkCS/thinkCSpy/chap15.htm > > What other newsgroups have you askesked help to? > > Kuta > Thanks for all the help guys. I really appreciate it. Will probably end up churning something weird. From heiko at ph0enix.homelinux.org Sat May 24 12:16:54 2003 From: heiko at ph0enix.homelinux.org (Heiko Wundram) Date: 24 May 2003 18:16:54 +0200 Subject: Safe Pickling In-Reply-To: References: Message-ID: <1053793014.1026.16.camel@d168.stw.stud.uni-saarland.de> On Sat, 2003-05-24 at 16:56, Alex Martelli wrote: > If that is all you need, then maybe module marshal, in the standard > Python library, may be sufficient? Problem being that marshal explicitly states: Warning: The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. I assume that you can cause e.g. a function or a module to be called if you just send a .pyc file for unmarshalling... I've started to create a stripped down pickler myself now, which just pickles objects that are base Python objects; maybe this functionality could be included in some future version of Python directly... Heiko Wundram. From claird at lairds.com Fri May 30 09:29:06 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 30 May 2003 13:29:06 -0000 Subject: Python fot medium/large size projects References: <3ED73E93.90D59FF0@engcorp.com> Message-ID: In article <3ED73E93.90D59FF0 at engcorp.com>, Peter Hansen wrote: >Rosinger wrote: >> >> In your opinion, how suitable is Python for medium to large projects? >> By this I mean around 15 developers, where a framework is built and >> developers can build code based on it. >> >> I don't want to ask specific questions, so not to bind the discussion >> to a specific topic. Any opinion will be appreciated. > >Python is arguably one of the most capable languages around for this kind >of environment. My group, currently down to ten, has been as high as >about 15 Python-only developers, working on a project with (as of now) >something like 100K lines of code. . . . When I pretend I'm a C programmer--OK, it's not pretense--my reaction to this is, "Your people can only handle 10,000 LOC each!?" This deserves a response I don't think I can articulate now. Briefly, my guess is that Peter's ten people manage a LOT of "function points". -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From snag at jool.po Fri May 9 02:21:24 2003 From: snag at jool.po (kpop) Date: Fri, 9 May 2003 07:21:24 +0100 Subject: geting the time from a remote computer References: <7xvfwldozf.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xvfwldozf.fsf at ruckus.brouhaha.com... > "kpop" writes: > > The problem is how do i get the time froma a computer on the internet. > > Perhaps theres a way in one of the modules for ftp, or one of the other > > internet related ones . > > Can anyone tell me a way to do this . > > There's an example of a simple SNTP client in the Python cookbook. > I wrote a Linux clock-setting script around it: > > http://www.nightsong.com/phr/python/setclock.py > > Maybe you can adapt that for Windows. thanks thats just what i needed From skip at pobox.com Thu May 8 14:24:33 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 8 May 2003 13:24:33 -0500 Subject: unicode to string conversion In-Reply-To: <000701c3158d$52fb0360$410100a4@utente65> References: <000701c3158d$52fb0360$410100a4@utente65> Message-ID: <16058.41185.434413.777621@montanaro.dyndns.org> Luca> I would like to translate Luca> u'questa \xe8 bella' Luca> into Luca> 'questa ? bella' Luca> and put the result into a new variable I love easy questions! >>> u = u'questa \xe8 bella' >>> s = u.encode("iso-8859-1") >>> print s questa ? bella Skip From danb_83 at yahoo.com Sat May 3 20:09:18 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 3 May 2003 17:09:18 -0700 Subject: PEP 315: Enhanced While Loop References: Message-ID: "Ben Allfree" wrote in message news:... ... > At one point, quite a few BASIC and Pascal flavors had a repeat..until > or do..while loop construct. It seems that it faded away, and I'm not sure > why. Repeat...until is part of Standard Pascal, but hardly anyone uses Pascal anymore. For BASIC, the only flavor I've seen that had a posttest loop construct (other than conditional GOTO) was QBasic, which had a DO...LOOP block that allowed all 4 possible combinations of pretest/posttest and WHILE/UNTIL, so your code could have been written ' option 1: pretest WHILE ' This could also be done by the older WHILE...WEND construct MakeMoney DO WHILE Poor() MakeMoney LOOP ' option 2: pretest UNTIL MakeMoney DO UNTIL NOT Poor() MakeMoney LOOP ' option 3: posttest WHILE DO MakeMoney LOOP WHILE Poor() ' option 4: posttest UNTIL DO MakeMoney LOOP UNTIL NOT Poor() While this was a good syntax for a language that delimited blocks with pairs of statements (e.g., FOR...NEXT, FUNCTION...END FUNCTION), unfortunately it wouldn't work well in Python. Personally, I'm satisfied with while True: MakeMoney() if not Poor(): break From Gareth.McCaughan at pobox.com Thu May 1 20:16:23 2003 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Fri, 2 May 2003 01:16:23 +0100 Subject: but I don't want to print the trailing ".0" References: <87k7daxpc9.fsf@jidanni.org> Message-ID: Dan Jacobson wrote: > What is the "in crowd" method to enhance s.py so I don't have to use > sed to get what I want? > $ cat s.py > steps=(1500,1250,1000,625,500) > for i in steps: > print i/100.0 #how do I enhance this line, please? what %f thingy? print "%g" % (i/100.0) > By the way, any dumbness here?: > for arg in sys.argv[1:]: #no --help yet, never mind. > freq=string.atof(arg) > remainder=int(round(freq*1000))%9 > if not remainder: ... > > pydoc string says string.atof is obsolete it seems, oh, I see, I am > supposed to use float(), ok, I wish it said that there on pydoc string. > How about int(round( ? Looks goofy. It's right, whether or not it looks goofy. If you mean that round() ought to return an integer, then you're probably unaware of the fact that it can round to a number of decimal places other than 0. :-) > BTW, I believe I'm doing this to avoid this wackyness: > $ python -c 'a= 3.3*100000;print a,a % 500' > 330000.0 0.0 #OK > $ python -c 'a=33.3*100000;print a,a % 500' > 3330000.0 500.0 #Yuck It's not clear whether you've worked out what's going on here, so I'll tell you :-). The numbers 33/10 and 333/10 aren't exactly representable as IEEE double-precision floating-point numbers, so when you ask Python for 3.3 or 33.3 it gives you the nearest approximation it can. Those numbers are: - for 3.3: 7430939385161318 * 2**-51 - for 33.3: 4686558362232422 * 2**-47 When you multiply these by 100000 and round to the nearest representable IEEE double-precision float, you get: - for 3.3*100000: 5669356830720000 * 2**-34 - for 33.3*100000: 7151120547839999 * 2**-31 It just so happens that the first of these is exactly equal to 330000, whereas the second is just slightly less than 3330000; 2**-31 less, in fact. So when you reduce them modulo 500, the first gives exactly 0 and the second gives 500-2**-31. Which is close enough to 500 that when you print it it just says "500.0". > BTW, > $ python -Qwarnall someotherprog.py > someotherprog.py:34: DeprecationWarning: classic float division > print arg + ":", step/100.0 > OK, then can it or somebody tell me how it prefers me to change it? > If I have the .0 trailing aren't I safe for decades to come? The bit of Python that issues the warning is buried quite deep; by the time it has control, the fact that the denominator came from a floating-point literal has been forgotten. But -Qwarnall is not intended for human use; it's for use with the "fixdiv.py" script. You run your program using -Qwarnall, dumping the warnings to a file, and then fixdiv.py grovels over that file and works out which instances of division might need to change. Not producing spurious warnings simply isn't any part of what -Qwarnall is about. -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From donn at drizzle.com Wed May 21 01:50:58 2003 From: donn at drizzle.com (Donn Cave) Date: Wed, 21 May 2003 05:50:58 -0000 Subject: passing by refference References: Message-ID: <1053496256.660521@yasure> Quoth aahz at pythoncraft.com (Aahz): | In article , | Greg Ewing (using news.cis.dfn.de) wrote: | > |> P.S. I make no apology for using the word "reference" either, since I'm |> also stating what the reference is referring to. I don't understand |> why there is so much opposition to using this word when talking about |> Python. I maintain that, to correctly understand Python's data model, |> you need some concept in your brain that's functionally equivalent to a |> reference -- so why not call it that? | | I'm saving up time for a longer response to Donn, but here's a short | one: I'm not at all opposed to using "reference" and indeed I use it all | the time. I just think that using "binding" is preferable in most cases | because it gets people out of the pointer mindset. Python bindings work | differently from C pointer references, and because so many people in the | Python community work in both Python and C/C++, I think that "binding" | creates clarity. That's odd - maybe I've been losing touch with C/C++ but I thought "reference" there was a C++-only thing that's sort of an alternative to dealing with pointers. I guess it's possible that "pointer references" could be common usage in the C world without me knowing it - I only write C, don't talk about it all that much. The reference part of that expression seems kind of superfluous, though. Donn Cave, donn at drizzle.com From cswiger at mac.com Mon May 5 12:07:08 2003 From: cswiger at mac.com (Charles Swiger) Date: Mon, 5 May 2003 12:07:08 -0400 Subject: stdout from spawn? In-Reply-To: Message-ID: <9F81BF4E-7F13-11D7-8414-003065ABFD92@mac.com> On Monday, May 5, 2003, at 11:46 AM, Cipo Fuzo wrote: > pid = > os.spawnvp(os.P_NOWAIT,'tar',('tar','-tvf','/dev/tape','>','/tmp/ > tar.out')) > > tar errors out because it gets '>' and '/dev/tape' as an argument. Spawn is a Windowsism for fork()ing a subprocess, right? It calls "tar" directly, without invoking a shell...and shells are the things which handle the ">" redirection. > I need to start this in the background, and also need the process id. > > Any ideas? You can either perform the redirection yourself, by opening the /tmp/tar.out file and connecting stdout/stderr from tar to that file. Take a look at "pydoc popen2". -Chuck From ianb at colorstudy.com Fri May 30 21:18:54 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 30 May 2003 20:18:54 -0500 Subject: CGI question: safe passwords possible? In-Reply-To: References: Message-ID: <1054343934.10517.68.camel@lothlorien> On Fri, 2003-05-30 at 19:55, Gerhard H?ring wrote: > > You can find free code for doing MD5 or SHA hashing in JavaScript, and > > then use code kind of like: > > > >
> >[...] > > Riiiight. So how exactly does this help against a man-in-the-middle > attack? Adding the proper salt to protect against this (I would suggest timestamp + IP address) is another exercise left to the reader. Using client-side scripting isn't the worst thing in the world. It has the potential to be quite secure. If you're worried about man-in-the-middle, then nothing short of SSL (with properly signed certificates) will work. But really, man-in-the-middle is more a talking point than a real threat. People use those arguments to raise the bar on security, but that sort of criticism is seldom useful or constructive. The likelihood of a man-in-the-middle attack is far, far less than the likelihood of having your connection sniffed -- solving the sniffing problem is a real improvement in security. Ian From skip at pobox.com Thu May 22 10:47:34 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 22 May 2003 09:47:34 -0500 Subject: file closing In-Reply-To: <3ECCAA43.8060405@removethis.free.fr> References: <3ecc22aa$1@news.iconz.co.nz> <3ECCAA43.8060405@removethis.free.fr> Message-ID: <16076.58118.905901.246867@montanaro.dyndns.org> [second case] >> file('test.dat','w').write(chr(0)*1000000) >> where the second one relies on garbage collection? Laotseu> Yes, AFAIK. More precisely, it relies on reference counting. There's no cycle which needs to be broken, so CPython's cyclical garbage collection isn't involved. Skip From jamierh_76 at hotmail.com Thu May 22 21:02:04 2003 From: jamierh_76 at hotmail.com (Jamie) Date: Fri, 23 May 2003 13:02:04 +1200 Subject: XML parsing speed Message-ID: Hi all, Do any of you know of any tricks/techniques to speed up XML parsing in Python? The SAX takes 40+ seconds to parse 1.5 MB of XML data. Have any of you managed to get around this problem? Many thanks, Jamie From nav at adams.patriot.net Fri May 2 09:04:25 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 02 May 2003 09:04:25 -0400 Subject: It never fails (bsddb retirement in 2.3) References: <3EB17D2E.BD082750@engcorp.com> Message-ID: The data file looks like this: some_database_name database at hostname1 possiblydifferent at anotherhost anotherone at yetanother anotehrdatabase foo at barhost blah at blahblahost And so on, and so on. There might be blank lines in there, or lines with comments. The programs that I'm rewriting are CGIs, so they are transient with very short lifespans. That's what makes a quick B-Tree/ISAM file lookup very appealing. I don't have enough control over the systems running the CGIs to ensure there's a long-running daemon available to answer requests. The data file is quite large (750K in text), so I'd rather not load a pickled hash table every time a CGI program starts up. Some of the suggestions that have been made about optimizing the solution are interesting, but not especially relevant to the problem domain. I probably should have specified the problem more exactly, but my main concern as voiced in the original post was compatibility issues with the 2.3 as relates to the bsddb module. I really do appreciate the suggestions, though! Nick -- #include /* SigMask 0.3 (sig.c) 19990429 PUBLIC DOMAIN "Compile Me" */ int main(c,v)char *v;{return !c?putchar(*v-1)&&main(0,v+ /* Tweaks welcomed. */ 1):main(0,"Ojdl!Wbshjti!=obwAqbusjpu/ofu?\v\1");} /* build: cc -o sig sig.c */ From max at alcyone.com Fri May 16 17:07:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 16 May 2003 14:07:21 -0700 Subject: Python's qw References: <3EC4924B.1060306@nospam.com> <3EC49477.6ABC2FFE@alcyone.com> <3EC54103.9010209@nospam.com> Message-ID: <3EC55309.C93C2D6@alcyone.com> A Puzzled User wrote: > Erik, thanks for your post. The old fashion way, you mean > just using > a = ['sunflower', 'tulip', 'jasmine'] > ? Yes. > It is because I probably have a list of about 80 > items, and it is more editing work to add and > maintain the list. For long lists, something like: a = [ 'sunflower', 'tulip', 'jasmine', ... ] might be in order. -- 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 triumph of imagination over intelligence. \__/ H.L. Mencken From peter at engcorp.com Tue May 27 15:51:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 May 2003 15:51:02 -0400 Subject: os.popen2 :URGENT References: Message-ID: <3ED3C1A6.E96E8AAC@engcorp.com> Ali Dada wrote: > > small but very urgent question (project rpesentation tommorow!!!) > > i need to call a command line program from python, but the program prompts for a > user input ('y' for yes or 'n' for no). how can i write, using python, one of > those values??? > > i thought of using something like os.popen('my_program')[1].write('y') > > but it didn't work, the program said: received broken pipe signal If you want to write to the pipe whose file handle is returned by popen(), you must open it with "w" mode, as documented at http://www.python.org/doc/2.0/lib/os-newstreams.html -Peter From martin_a_clausen at hotmail.com Tue May 6 18:05:37 2003 From: martin_a_clausen at hotmail.com (Mars) Date: 6 May 2003 15:05:37 -0700 Subject: os.system on "program files" References: Message-ID: <764b8294.0305061405.13647162@posting.google.com> Hi Cipo If your quotes below are cut and paste, the cause of the error might be the spelling mistake in "c:\prgoram files..." which should be "c:\program files" Just an idea. Mars Cipo Fuzo wrote in message news:... > Hello, > > I'm executing a program from c:\program files\... on windows. > I've found previous articles that suggest putting "s around > the executable path, which works, BUT: > > The executable I'm calling requires on of its arguments to be > in "s: > > >>> os.system(r'"c:\prgoram files\imagemagick\convert.exe" -draw "text 0 0 hello" in.jpg out.jpg') > > I get: > > 'c:/program' is not recognized az an internal or external command > > if I take the "s off the argument: > > >>> os.system(r'"c:\prgoram files\imagemagick\convert.exe" -draw text 0 0 hello in.jpg out.jpg') > > convert starts, but now it's not getting the correct arguments. > > > Is this a bug in os.system? > Any ideas how to solve this? > > Thanks, > Cipo From h_schneider at marketmix.com Thu May 15 17:01:05 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Thu, 15 May 2003 23:01:05 +0200 Subject: Python Coredump on FreeBSD References: <0pCdnbUTkYU6W16jXTWcow@speakeasy.net> Message-ID: Sorry -- file attached. The file is read completely and split into lines. Each line is split by the ":". Comments # are ignored. The resulting datastructure is an array of arrays assigned to self.lib The code calling re is this: for filter in self.lib: if re.compile(filter[1],re.I|re.M|re.S).search(self.msg[filter[0]]) <> None: return(filter[2]) filter[1] is the pattern, [2] is the returncode, [0] is a key of a dictionary containing the strings which are searched. As you see, the only special thing here are some long OR-chained regex which seem to exhaust the limited stack on BSD. Even splitting them to shorter expressions causes a crash. The Linux and Win32 implementation are not affected ... --Harald ------------------------- file -------------- # Structure: # Variable (case sensitive) : Regular Expression : Result Code (NEWLINE) # Spoolfile.envelope:mail from.*?.*?rcpt to.*?:NODOMAIN_CRON Spoolfile.lastslog:ErrString.*?MAIL FROM.*?not permitted.*?\n.*?\nSMTP-Error.*?(syntax|expected after|qualified domain)|SMTP-Error.*?synta.*?from field:SYNTAX_FROM Spoolfile.lastslog:ErrString.*?RCPT TO.*?not permitted.*?\n.*?\nSMTP-Error.*?(syntax|expected after|qualified domain)|SMTP-Error.*?synta.*?(to|rcpt|recipient) field:SYNTAX_TO SMTP-Error:Too many wrong rcpt:SYNTAX_TO SMTP-Error:IP address.*?AOL.*?open:ANTISPAM_AOL SMTP-Error:spamcop|osirusoft:ANTISPAM_BLACKLIST SMTP-Error:rejected.*?spam:ANTISPAM SMTP-Error:quota|mailbox.*?full|storage|user.*?too many messages:QUOTA SMTP-Error:Unknown local part|(user|mailbox|account|recipient|Addressee).*?(unknown|invalid|not found|not here)|(no such|doesn't have|invalid|unknown).*?(account|user|mailbox|recipient|addressee):USER_UNKN OWN SMTP-Error:(unroutable|unrouteable) address|cannot route to:UNROUTABLE SMTP-Error:(mailbox|account|user).*?(unavailable|disabled|inactive):MAILBOX_ UNAVAILABLE SMTP-Error:dynamic.*?(address|IP)|name lookup failed:RELAY_DENIED_DYNIP? SMTP-Error:blacklisted:RELAY_BLACKLISTED? SMTP-Error:(free|open).*?relay:RELAY_OPEN? SMTP-Error:unable to relay|message.*?rejected|relaying denied:RELAY_DENIED SMTP-Error:Too (much|many).*?try again.*?later|busy|SMTP service not available:SERVER_OVERLOAD SMTP-Error:Domain of sender.*?does not exist|invalid.*?sender.*?domain":SENDER_INVALID SMTP-Error:authentication.*?failed|Not Authorised:AUTH_FAILED SMTP-Error:too big:TOO_BIG SMTP-Error:no.*?field (present|given):HEADER_INVALID ErrString:RCPT TO.*?not permitted by remote SMTP server:RELAY_DENIED ErrString:Error connecting to remote address|End of socket stream data:NETWORK? ErrString:Invalid server address:DNS_FAILED? ErrString:loop:LOOP_KILLED ErrString:Unknown SMTP authentication mode:AUTH_FAILED ErrString:Server shutdown:SERVER_OVERLOAD ErrString:Timeout error:TIMEOUT From grante at visi.com Tue May 27 11:32:35 2003 From: grante at visi.com (Grant Edwards) Date: 27 May 2003 15:32:35 GMT Subject: pacp in python? References: Message-ID: <3ed38513$0$644$a1866201@newsreader.visi.com> In article , Frank Zheng wrote: > Hi, guys: > Does anyone know if there exists a module in Python can do the same > work as the winpcap on windows? And where can I get it? There's pylibpcap for Unix. It's been ported to Win32, but I haven't tried it yet [still on my list of things to do]. http://sourceforge.net/projects/pylibpcap/ http://pylibpcap.sourceforge.net/ http://mail.python.org/pipermail/python-list/2003-March/154651.html -- Grant Edwards grante Yow! if it GLISTENS, at gobble it!! visi.com From steve at ferg.org Sun May 18 12:07:20 2003 From: steve at ferg.org (Stephen Ferg) Date: 18 May 2003 09:07:20 -0700 Subject: weak versus dynamic, definitional origins References: Message-ID: > Got into > an argument with a coworker the other day who was insisting > that strong=static. Funny coincidence. I just put up a page with Java/Python comparing Python and Java, and of course this issue came up. In researchingg it, I came to the conclusion that this is an area of big confusion, in part because different people use the same term to mean different things. Origins of the different usages are obscure. Anyway, if you would like to see what I came up with (and an answer in which strong DOES NOT = static), look at the last page of: http://home.att.net/~stephen_ferg/projects/python_java_side-by-side.html Hope this helps with your coworker! :-) -- Steve Ferg (steve at ferg.org) From mcfletch at rogers.com Mon May 5 03:53:04 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 05 May 2003 03:53:04 -0400 Subject: PEP263 (Specifying encoding) and bytecode strings In-Reply-To: References: Message-ID: <3EB61860.3010103@rogers.com> Alex Martelli wrote: ... >>Is there some way to specify that all strings are bytecodes, and not >>encoded characters? >> >> ... >Couldn't resourcepackage just insert a suitable encoding "declaration", >which is after all a comment and thus innocuous for any previous >release of Python -- or else emit non-ascii chars as escape sequences? > > Our question could be rephrased then as: What encoding declaration means "treat strings as streams of bytes, not encoded characters"? (That is, emulate previous version's operation). Or, if you prefer, what is the "unencoded encoding" called? Regarding emitting escaped characters, it can be done, but you wind up with significant bloating of the files (these are binary files much of the time, having to include ~4 bytes for every one byte is an ungood thing). Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From alanmk at hotmail.com Thu May 29 11:10:02 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 29 May 2003 16:10:02 +0100 Subject: Help with coroutine-based state machines? Message-ID: <3ED622CA.4B01E3C1@hotmail.com> Greetings all, I've got a few questions about generators, coroutines, etc, that I've been meaning to ask for several weeks. But I knew it would take time to explain. So I left it until I had the time to write it up properly. And it turned out that there was a lot more to it than I originally foresaw, mainly because I wanted the concepts to be as clear as possible. As I wrote it and rewrote it and rewrote it, it quickly grew to be a length more suitable for an article than a Usenet post. But because I was asking questions about stuff I didn't know, an article wasn't appropriate. So, the post/thing itself is given below. It's quite long, and a little rambling in parts. You'll probably need some time available to work through it all, if you're interested. If any of the good people in the group can help me anwser some of the questions, I'll write this all up more concisely, and put it on it's own web page. Thanks for any assistance you can offer. Alan. =============================================================== State machines. --------------- I've been playing around with state machine paradigms, seeking an optimum paradigm with three primary requirements in mind. 1. That the paradigm be as simple to code as possible. 2. That machines developed using the paradigm be as flexible as possible, and ideally inheritable. 3. That the paradigm be as resource-efficient as possible. (not so important). "Traditional" Paradigms. ------------------------ I played around with a few traditional state-machine paradigms, the kind you see posted, for example, in the Cookbook. They were mostly based on declaring machines or even individual states as objects, and sometimes requiring explicit declaration of all state transitions and events. To me, most of them seemed difficult to work with, because of the need to modify up to 3 or 4 different variables (in different sections of the code) in order to make the simplest modification to a state or event. While I recognise the benefit of such approaches in more formal or rigourous circumstances, I needed more flexibility. So, none of more "traditional" paradigms (that I found) really stood out as what I was looking for in terms of simplicity and expressiveness. Generators and state machines. ------------------------------ But then I came across David Mertz excellent article describing the use of generators to implement state machines, and I was bigtime impressed. http://www-106.ibm.com/developerworks/linux/library/l-pygen.html This article was the "dawning point" for me, when (I think) I finally "got" generators, and the flexibility that they offer. If you haven't read David's article before, I recommend that you do if you are going to continue reading this post, because I'll be continually referring to the generator-based state machine implementation in that article. Simplifying the model. ---------------------- However, once I did finally "get it", when I looked back at the example code in the article, I found myself easily confused by the code. Trying to get my head around the important difference between the generator-function and the generator-iterator, while also trying to follow the dictionaries and tuples needed for dispatch, mixed in with a non-generator function (using classic 'return's) for state classification and namespace declarations to access data, left me a little spun out. So I decided to try and simplify the model a little. Code for a full working example (but a different state machine) is given below. I left it all in one piece rather than split it up and sprinkle it through the discussion points. I have included code snippets where it is necessary to illustrate a point. Eliminating global data. ------------------------ The first thing that I found confusing was the use of global data. Instead, it seemed more natural to me to encapsulate the state machine in a class, and to use instance variables of objects of that class to contain instance data. That way, no namespace (i.e. "global") declarations would be required: the data could be simply accessed through the self object. Cleaning up the dispatch table. ------------------------------- When I wrapped it all in a class, and removed the "cargo" and namespace declarations, I realised that the generators were all yielding a simple string, containing the name of the next state, like so yield 'newstate' This would be then looked up in a "jump table", i.e. a dictionary mapping the state names to generator-iterators representing the states, like so while 1: newstate = jumptable[newstate].next() This jumptable, containing the instantiated generator-iterator objects, would be set up at start time. This seemed to me superfluous, since I had already named all of the states, through the names of the generator-functions themselves: why should I need a string to identify them as well? Also, having a jump table means that I have to maintain state names in three different places: the name of the generator-function, the name of the state in the jump-table and when instantiating the generator-iterator. So, if I wanted to do away with the jumptable, I would have to yield the generator-iterator for the next state directly to the dispatcher, and have the dispatcher call its .next() method. But how would I refer to the generator-iterator, when the states name in the instance dictionary (self) referred to the generator-function, not a generator-iterator. I would have to come up with some way to directly yield the generator-iterator object for the state, but accessing them using their generator-function names. A state change could then be declared as yield newstate And dispatching would then simply become while 1: newstate = newstate.next() Sweet. Much simpler :-) Turning generator-functions into generator-iterators. ----------------------------------------------------- In order to do away with the jump table, I decided that all names (in the instance dictionary) which referred to generator-functions be changed so that they referred instead to the corresponding instantiated generator-iterators. This would mean that state changes would be indicated by a statement like yield self.newstate To do this, here is the little bit of hackery that I came up with: at __init__ time of the state-machine object, it modifies the instance dictionary, replacing generator-functions with their instantiated generator-iterators. def __init__(self): statenames = ['state1', 'state2', 'state3', 'state4'] for name in statenames: # Turn each generator-function into an instantiated # generator-iterator self.__dict__[name] = eval ('self.%s()' % name) # Obviously, there must be a generator-function # in the class corresponding to each element of statenames list, e.g. def state1(self): while 1: if self.readytogo: yield self.state2 else: yield self.state3 This turns every reference to a generator-function into a reference to the corresponding instantiated generator-iterator. Differentiating generator-functions from functions. --------------------------------------------------- I'm not happy with the way that I have to explicitly list the state names. I tried to find a way to differentiate between functions and generator-functions while reflecting on the instance' dictionary. Pseudo code for this would look like import types for k in self.__dict__.keys(): if type(self.__dict__[k]) is types.GeneratorType: self.__dict__[k] = eval ('self.%s()' % k) But there isn't a generator type in the types module? So, that's a question I'd like to ask: can anyone tell me how to discover the generator-functions of an object, and differentiate them from ordinary functions? A full working example. ----------------------- Now's the time for a full example. In order to simplify it, I chose a different state machine from that in David's article. It's a very simple state machine: one that counts from one number to another in a specified increment, and then stops. The paradigm is capable of a lot more than that (I've just used it very successfully to control multiple independent automated users in a load testing simulation, for example): but I want this example to be short and concise. #---------------------------------------------- # This code is also available at # http://xhaus.com/alan/python/FSMgenpy.html # class FSM: def __init__(self, startnum, incrnum, stopnum): for name in ['idle','start','increment','checkfinished','finished']: self.__dict__[name] = eval ('self.%s()' % name) self.startnum = startnum self.incrnum = incrnum self.stopnum = stopnum self.counter = 0 self.exit = 'exitsentinel' def idle(self): while 1: # We could wait for some condition here. print "Idle state: %d" % self.counter yield self.start def start(self): while 1: self.counter = self.startnum print "Start state: %d" % self.counter yield self.increment def increment(self): while 1: self.counter = self.counter + self.incrnum print "Increment state: %d" % self.counter yield self.checkfinished def checkfinished(self): while 1: if self.counter >= self.stopnum: yield self.finished else: yield self.increment def finished(self): while 1: print "Finished state: %d" % self.counter yield self.exit def dispatch(self, startstate): newstate = startstate while 1: next = newstate.next() if next == self.exit: return else: newstate = next if __name__ == "__main__": m = FSM(1,5,50) m.dispatch(m.idle) m.dispatch(m.idle) #---------------------------------------------- Pausing or stopping from the state machine. ------------------------------------------- You will notice that I have slightly modified the dispatch function, compared to the one described above. It now looks for a sentinel value signifying exit from the state machine. This is because the only way in which the state machine can suspend operation and relinquish control is to return from a non-generator function. If any form of return is attempted from inside a generator-iterator, or an exception such as a StopIteration() is raised, then that generator-iterator will be destroyed and the state-machine will stop working. Furthermore, it won't be possible to create a new generator-iterator, because we've overwritten the reference to the generator-function in the instance dictionary! Hmm, maybe that is too much a hack :-| Anyway. The addition of the sentinel value for exiting or suspending the state machine means that we can now suspend and resume the machine at will. It can be suspended by yielding a "suspend" state (which would be a simple string sentinel value to the dispatcher), and then resumed by calling the dispatch method with a new or saved starting state. The example "main" function given above runs the example state machine through its paces twice. When you run it, take a look at the value of the counter in the "idle" state, and how it differs between invocations. Combinining with threads. ------------------------- In the example usage I described above, where I used this paradigm to control automated testers, each automated tester ran in its own thread. Each had a dedicated input Queue.Queue, through which it would receive commands. Which would then be carried out by setting instance data and transferring to the relevant state. In order to check for messages in the incoming queue, at least one of the states must check if there any entries in the queue. In simple cases, this can be a blocking wait, where the Queue.Queue.get() does not return until a message is available. If you need the machine to be going off doing tasks in its parallel thread, but still checking for messages, e.g. stop commands, then a non-blocking .get(), carried out at a regular interval, is recommended. However, making the time intervals too short can significantly consume your cpu cycles. Also, I found that threading.Condition() variables were very useful as a mechanism for synchronisation between threads, and integrated well with the "resumable function" concept. Paradigm found. --------------- To me, this paradigm of state machines is simplicity itself. Thus, it fulfills my primary goal of having a simple paradigm: I really can't see any way for the code to be simpler, in textual terms at least. Furthermore, because all of the parameter parsing involved in function calls is avoided, it should be also more cpu-efficient than a "procedurally" based model. (Actually, I haven't done any timing to validate this, but I can't see how the generator version could be slower?) Parameter passing. ------------------ However, this avoidance of parameter parsing has a downside: you can't pass parameters between states :-) Which would be a problem in most real-world state-machines, which would most likely be processing external data streams of some form. The two ways that I can think of for getting data into the state-machine are 1. Sending parameters wrapped up in a message object on a Queue.Queue. This would be recommended in a multi-threaded situation. 2. By setting instance variables of the state-machine object directly. This could be dangerous in a multi-threaded situation. I am aware of Raymond Hettingers PEP 288: Generator Attributes, and now appreciate the problem that it is trying to solve. And I also appreciate the "cargo" problem David was trying to solve in his article. If anyone has any improved methods to passing parameters in the paradigm I've described above, I'd like to hear about it. Generator Gestalt. ------------------ It was only while stepping through the execution path of the code above that I finally understood some of the sophisticated flow-control mechanisms that generators offer: if you temporarily "forget" that there is a dispatcher function involved, you see the thread of execution far more naturally: named units of python code where the data and the code that manipulates it are very closely associated: The flow of control passes seamlessly back and forth between the named units: There is no stack giving you an ancestry or history of invocations: Each "state" in the state-machine implementation really *is* an encapsulated, resumable state. The "temporal locality" of the code (as opposed to the "spatial locality" of traditional code) greatly aids readability, and modifiability, IMHO. The code seems more natural, more "encapsulated", because data is generally only modified in code that is "close" to the declaration of the state machine "event" to which it relates. Also, the ease with which the flow between states can be modified (i.e. no mucking with state or transition declarations, lookup tables or parameter values) greatly increases the flexibility of the code. It also seems to me that this paradigm should have significant cpu-efficiency advantages over other paradigms, and potentially make python-implemented algorithms cpu-competitive with statically typed and compiled languages based on a traditional function paradigm, such as Java or C. At the beginning, when writing real state machines with the above paradigm, I found myself getting weird bugs and subtle deviations from expected behaviour. For example, a counter might start at 2, rather than an expected, recently initialised, 1. But mostly they weren't bugs at all, they were inherent flaws I designed into the state-machine. Sometimes when writing and debugging the code, I mistakenly assumed that the code was being entered from the top each time, i.e. directly after the while statement, as it would be in "procedural" code. But rather, the real situation was that the code was being resumed in the statement immediately after the last executed yield statement. Once I had discarded this last preconception, it all fell into place (anybody know a Buddha smilie O:-) Generators: powerful stuff, to be sure, to be sure. Although I know there was at some stage controversy about the rate at which new features were/are being introduced into python, I'm convinced that advanced features like generators are a necessary step for python to remain competitive in conceptual terms, compared to other languages. New concepts in computer hardware, such as massively parallel computing or hyperthreading, and new classes of computational problems such as protein folding, will require new conceptual approaches from computer languages. Generators are those concepts, or are at least the precursors of the future concepts. (I hope that one day I will also "get" Continuations, and Co-Routines, and am now at least in the position of having identified some of what I don't know about Stackless Python %~} <= my brain is seriously starting to wobble....... Sorry, wrong meeting ;-) For a moment there, I thought I was at the "Stackless Revolution" meeting, which is on *Tuesday* nights, down the docks....... Ah, the Zen of Python :-) Inheritance. ------------ Lastly, about my final requirement: That hopefully my state-machine paradigm should support extensibility, or ideally inheritance. Although I haven't yet tried to do it, I imagine that subclassing these state-machine classes should work perfectly well, as long as the instantiation of generator-functions to generator-iterators is properly managed. Request for comments. --------------------- As I mentioned above, there are a number of questions in this post which prevent it from being an explanatory article about this paradigm. However, if (as I hope :-) the great and knowledgable people in this group help me out with ironing out the wrinkles, I'll write it up and post it on its own page. And finally: infinite loops. ---------------------------- Another question I just thought of: Each of the state generator-functions must be wrapped inside an infinite while loop, so that the states never "run out of values". These while loops clutter the code somewhat, and it would be nice to not need them. I wonder if it would be possible to remove them? On second thoughts, maybe not. At least not without fundamentally changing the meaning of the yield keyword (is that what "yield every" is for?). Or maybe some incantation with __metaclasses__? And really finally: notification of state change. ------------------------------------------------- Since I've still got your attention ;-) another thing that I plan to address, perhaps with __metaclasses__, is sending notification about state changes to registered objects, without having to stick in explicit callback notifications in every state. This could be simply done by putting a name attribute on every generator-iterator, and notifying the notifiable objects in the dispatch loop. So the __init__ would be like this statenames = ['state1', 'state2', 'state3', 'state4'] for state in statenames: self.__dict__[state] = eval ('self.%s()' % state) self.__dict__[state].name = state and the dispatch would become while 1: next = newstate.next() for o in self.notifiableobjects: o.notifystatechange(next.name, self) newstate = next But it would be cooler to use __metaclasses__ B-) Really really finally: event-driven processing loops. ----------------------------------------------------- And for the last moebius-twist of all, I've been trying to picture how I could integrate state-machines like this with an asynchronous event-driven server framework like twisted, medusa or asyncore. I read some posts about "sources" and "sinks", but methinks it may be more complex than that. Particularly, it is the "psuedo-threading" which I don't quite get. Any pointers to relevant articles/emails/postings/sourcecode greatly appreciated. No, really, really finally: light bulb switches on... ----------------------------------------------------- A very interesting thought just struck me. The state changes in the examples above always 'yield'ed the next state from the current state machine, i.e. 'yield self.newstate'. But if there were multiple objects all operating this state machine paradigm, they could yield back and forth to each other, simply by saying "yield other.newstate" (obviously they must hold a reference to 'other'). If 'other's dispatching mechanism operated by the same principle, and was capable of suspending the state machine through 'return'ing a value instead of generating the next state, then input could be processed by being fed into one state-machine object and the final processed output being returned from another connected state-machine object. So I could build a network of mutually 'yield'-ing state machines to process a stream of input. Also, the interim states in the state-machine network could be suspended when no input was available, by 'yield'ing a generator-iterator which generates the resume state, when its .next() method is called. This would have the effect of resuming the state machine network directly in place from where it 'yield'ed, when the input becomes available. I think I see the beginnings of the answer to my asycnore question. O-) <= brain settles back down to a bose-einstein state of calm awareness Ah! So that's what full coroutines are? One or more objects, 'yield'ing control back and forth between a set of resumable states, without the need for a dispatcher function? Which would mean that you could call a "function" on one object and get the return value from a different "function" on the same object, or even a different "function" on a different object. Which could make a right mess of a traditional function call stack. Which is why Stackless python is as it is. Ah, the soft chink of the penny dropping.......why is my head suddenly full of Feynmann diagrams.......? Which is why python generators are only "semi"-coroutines, as opposed to full coroutines. Because, without a dispatcher function, you can only yield control to the calling function, rather than any resumable state that you have a reference to. So how would the interface between "procedural" and coroutine code work in the full coroutine world? Presumably, there would be no difference between a generator-function and a generator-iterator: or at least, there would be no need to explicitly instantiate the generator-iterator? And they could be passed parameters on each invocation? And the top-of-stack data structure would have to be designed to represent the free flow back and forth between resumable states of multiple objects. And generator-iterators would not be "broken" by 'return'ing a value or raising an exception? Implementation question: Why does this asymmetry exist in the current (c)python generator implementation? It seems to me that it should be reasonably straightforward to get around......... Continuations. -------------- If I've got it right about coroutines, then what is the last step of understanding required for Continuations? What do continuations offer that coroutines don't? Is it that continuations allow resumption of states across thread boundaries? Thanks for reading this far through my ramblings :-) kind regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From marcus at infa.abo.fi Wed May 7 16:59:42 2003 From: marcus at infa.abo.fi (Marcus Alanen) Date: 7 May 2003 23:59:42 +0300 Subject: The most annoying typo error... References: <9d5509fa.0305070000.55b11d6@posting.google.com> Message-ID: On 7 May 2003 01:00:58 -0700, Peter Ballard wrote: >x = somefunction(a, b, c, d), > >and when I run Python I get a TypeError error. > >You spotted the error immediately didn't you? The line of code above >has a trailing comma, so that x is suddenly a tuple; and so when I get >around to using x I get a TypeError. > >I don't know about anyone else, but for me, this error always takes a >long time to track down. Hi, I've had the same problem myself quite extensively. The only "solution" I came up with, but which actually helped, was practise, practice, practise. ;) It's not particularly _good_ advice. I still do lot's of completely trivial typing errors, usually related to variable names and/or namespaces. Worse, I _find_ these kinds of errors now and then from our code. (This naturally suggests that we should do more & better unittests, assertion checks etc.) But I agree, it is annoying: how many of you noticed I spelled both "practice" and "practise" above? ;-) Marcus From ray at rays-web.com Fri May 23 05:37:20 2003 From: ray at rays-web.com (Ray Smith) Date: 23 May 2003 02:37:20 -0700 Subject: HELP needed: Tricks for licensing Python software References: Message-ID: <5654fff9.0305230137.5638b6c2@posting.google.com> Hi Pekka, I agree with what others have said, one point that maybe hasn't been spelled out fully are the problems that these security *features* cause your honest customers. What happens if the user doesn't have a network card? What if their network card breaks or is replaced for some reason? What happens if they change PC's? What happens if you don't respond to emails to update their keys? What if you go out of business? Does that mean your clients can never change any part on their PC? Eventually your honest customers will get sick of the *restrictions* your putting on them and find an alternative package. (Not all of them but a certain percenatge will - a large percentage) Two companies that I deal with that bought in these features and then removed them within 12 months: * AcuCorp (AcuCOBOL), * Sheridan (now Infragistics) Python is a *child* of the Open Source movement and these types of restrictions are the reason why so many people develop and use open source software. This reason is probably why the free giving Python community (don't you just love 'em!) probably won't put to much effort into helping you restrict users. Regards, Ray Smith ray at rays-web.com Pekka Niiranen wrote in message news:... > Has anybody tried to implement license key > for Python script in Windows ? > > For example, distributed Python program > could be tied to the MAC address of the PC: > Before program could be used, the user must > give the MAC address of his PC that is used > as seed for generating license key for the software. > Thus, the program could not be run on any other > machine without installing the same > network card to it. > > I would hate to learn writing C extensions > just for this. Any ideas ? > > -pekka- From gh at ghaering.de Wed May 21 10:52:12 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 21 May 2003 16:52:12 +0200 Subject: putting Image from database in cgi app In-Reply-To: <3ECB909C.30805@ghaering.de> References: <3ECB7324.4080501@ghaering.de> <3ECB909C.30805@ghaering.de> Message-ID: <3ECB929C.2060406@ghaering.de> Gerhard H?ring wrote: > Fredrik Lundh wrote: > >> Gerhard H?ring wrote: >> >>> In the end, using the temp file is probably the easiest solution, at >>> least as long as the web technology you use is CGI. >> >> >> and you never have more than one visitor at a time, or don't care >> if people don't get the right cover... > > > How would that be a problem? Just create a unique name for the temp > file, put in a directory, like, say "cache/" and have a cron job that > periodically deletes old temp files. > > Are there possible circumstances where that approach would be problematic? Apart from the obvious DoS vulnerability ;-) -- Gerhard From forestiero at qwest.net Thu May 15 21:26:13 2003 From: forestiero at qwest.net (DogWalker) Date: Thu, 15 May 2003 18:26:13 -0700 Subject: Need information-- Python Architecture References: Message-ID: May be of some help: http://manatee.mojam.com/pyvmwiki "Aahz" wrote in message news:b9e6c7$m64$1 at panix1.panix.com... In article , kkm25 wrote: > >I had a question. I need to give an architecture audit on some opensource. >Me and my teammates have chosen python. That's a big bite, particularly for a class project. How well do y'all already know Python? >Could someone please tell me, How I should go about the process of deriving >it's architecture. > >1. Should I be looking at the sourcecode?? >2. If so what part of the source code should be concntrated upon. >3. How exactly should I go about looking for it's architecture. Python's architecture is best described as the union of several architectural building blocks, each of which itself has a moderately large architecture. I'd suggest concentrating on one specfic aspect of Python's architecture (perhaps the syntax or the bytecode engine, though I'd personally do it on the object model). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From aleax at aleax.it Mon May 5 03:41:13 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 05 May 2003 07:41:13 GMT Subject: Should I write a book on Python Metaprogramming ? References: Message-ID: David Mertz wrote: > Hi gang, > > Regular readers know who I am... so I won't bother with any more than > the overblown bio in the proposal text itself. > > Here's the story though: For a number of months, I have had in mind the > idea of writing a book called _Metaprogramming in Python_. A book is a > lot of work, and not a lot of money--and the more I think about it, the > more I am a little apprehensive about really doing the title justice > (and in a way the genuinely helps readers). Nonetheless, I think I can > claim with only slight immodesty that no one, other than perhaps the > Martellibot, would do a better job with this particular subject. Thanks for the kudos! But, all modesty apart, you may indeed be right, in terms of the intersection of the sets of people who have such exoteric curiosities AND are proven book-writers. And I personally do not intend to write such a book (I _do_ dream of covering such advanced issues, not as deeply as you will, as part of the book I dream about, which would be about design patterns and OO programming in general, with Python used as the main illustration language). > So here's my questions to c.l.py. Would you want a book along the below > lines at all? Do you only want it if it focusses closely on Python? Or Personally, yes, and indeed I think it would help to focus on 2.3 only AND only on the newstyle object model within it -- the quirks and anomalies of the classic object model would IMHO be a distraction, not an addition, to a book that, if properly focused, might charm its intended audience. > would you rather have a book that addressed several languages fairly > equally, with Python just one among them? Are the outlined chapters the > ones you would expect? Or is something missing? Or unnecessary? > Assuming the suggested chapters point in the right directions, what > specific topics would you want to see covered within each one? Personally, I would suggest a sharper distinction between: -- clear tutorial+reference illustration of the TOOLS available in each category (with toy examples just to show how they work); -- design patterns showing appropriate USE of said tools (with examples taken from existing programs where they are used or could/should have been used -- "taken" as in "excerpted"); -- substantial illustrative examples (made up for the purpose) showing how a set of tools could be used in practice, or, even more usefully, how two different sets could alternatively be used and what are the tradeoffs in choosing between them. I guess you could do that within each chapter, but that might make it harder to compare and contrast. I believe your target audience, which is composed of very advanced programmers, does not necessarily need the step-by-step motivation that shows all about a given tool or approach right after it's introduced -- it's easily mature enough to appreciate a sharper separation in two or three parts as above. If you could ensure including exercises (some with solutions, other without) this would very substantially increase the potential worth of your book as a textbook in some advanced university course. > Table-of-contents: > > I. Introduction to Metaprogramming. > II. Behavior protocols for Python objects > III. Overloading operators and enhancing basic datatypes. Aren't II and III rather overlapping? Perhaps they should be merged, with short shrift given to the basics and more care about exoteric parts. > IV. Higher order functions. > V. Function and class factories. Again, isn't there some overlap here (less than between II/III)? > VI. Metaclasses. > VII. Code generators and code parsers. Do you intend to cover iterators and generators and their use and (arguably) abuse? If so, where would that coverage fit? I really hope the book eventuates -- particularly because I look forwards to reading it and picking up a trick or two myself!-) Alex From joshway_without_spam at myway.com Tue May 13 15:07:22 2003 From: joshway_without_spam at myway.com (Joshua Marshall) Date: Tue, 13 May 2003 19:07:22 +0000 (UTC) Subject: passing by refference References: <9xRw+ks/KrpJ089yn@the-wire.com> Message-ID: Terry Reedy wrote: ... > To me, call-by-value implies a copy operation, which Python does not > do. I think call-by-assignment or call-by-name-binding is more > accurate. Given a definition "def f(parname1, parname2): " and > a call "f(exp1, exp2)" the interpreter evaluates expressions exp1 and > exp2 as usual and then binds parname1 and parname2 to the resulting > objects, but in the local namespace of f instead of in the namespace > where the expressions were evaluated. A function call is like a > series of cross-namespace assignment statements. Once this is > understood, the effect of modifying mutable arguments is > understandable. > Terry J. Reedy See http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?call-by-value What you describe is call-by-value. There is an implicit copy of the arguments passed to a function, though not a deep-copy. The values that are being copied are often references. From scott.daniels at acm.org Fri May 16 14:01:10 2003 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 16 May 2003 11:01:10 -0700 Subject: Classes, virtual methods ? In-Reply-To: References: Message-ID: <3ec5275d$1@nntp0.pdx.net> Rony wrote: > ...Is there a way of calling foo of the master class of B > with an instance of B... Perhaps you meant something like this (2.2.2 and 2.3 do it): class A(object): def foo(self): print "in class A" class B(A): def foo(self): print "in class B" super(B, self).foo() m = B() m.foo() Scott David Daniels Scott.Daniels at Acm.Org From martin at v.loewis.de Tue May 27 08:43:33 2003 From: martin at v.loewis.de (=?ISO-8859-9?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 May 2003 14:43:33 +0200 Subject: python 2.2.2 installation In-Reply-To: References: Message-ID: <3ED35D75.3030508@v.loewis.de> Hakan Ko?ak wrote: > I have already installed python 1.5 which comes with redhat 7.2 I want > to install python 2.2.2 which I downloaded from python.org Did you notice that these are Redhat 8 RPMs? > i understand that some libraries are missing but which ones. Some one > know which libraries are missing and where to get them? I recommend that you don't try. Instead, you should try building Python from the source RPM (either the generic one, or the Redhat8-adjusted one). Regards, Martin From anthony at interlink.com.au Wed May 21 21:24:58 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 22 May 2003 11:24:58 +1000 Subject: IDLE not working on RedHat 9 In-Reply-To: References: Message-ID: <200305220124.h4M1OwE24246@localhost.localdomain> >>> Otto Hoel wrote > Hi, > Python works, but IDLE does not. Here is what I get when trying to run it: > > [root at costaplenty idle]# ./idle.py > Traceback (most recent call last): > File "./idle.py", line 3, in ? > import PyShell > File "./PyShell.py", line 13, in ? > from Tkinter import * > ImportError: No module named Tkinter Install the tkinter-2.2.2 RPM. Anthony From lists at gregfortune.com Mon May 19 17:18:27 2003 From: lists at gregfortune.com (Greg Fortune) Date: Mon, 19 May 2003 14:18:27 -0700 Subject: Python Style Question References: <6ee58e07.0305191003.395d1b3a@posting.google.com> Message-ID: Lothar Scholz wrote: > In the python windows library i find a lot of code like the following: > > > TypeBrowseDialog_Parent=dialog.Dialog > class TypeBrowseDialog(TypeBrowseDialog_Parent): > "Browse a type library" > > > where is here the advantage over the easier and much more normal way > to > do things: > > > class TypeBrowseDialog(dialog.Dialog): > "Browse a type library" > > > When i look at the code i must not go through an extra indirection to > recognize what is done there and more important the first code style > can't be handled by static code analysers very well. Looks like the coder expected a performance improvement. If it gets executed the way I expect, the second example requires a lookup through the dialog module each time the class is instantiated. The first only requires the lookup when the module loads and binds the results of the lookup into the module namespace. If the class is getting instantiated many, many times, the performace increase might be noticable. You might try replacing one of those class in the win32 library (one that you would expect to get instatiated often) with the simpler code and see if you notice a slowdown... Greg Fortune Fortune Solutions From tjreedy at udel.edu Mon May 19 17:30:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 May 2003 17:30:48 -0400 Subject: A little disappointed so far References: Message-ID: <2IOdnSLBl7X90FSjXTWcqQ@comcast.com> "Joshua Marshall" wrote in message news:baatpl$k3f$1 at ginger.mathworks.com... > This doesn't matter - "++" dosen't need to affect the integer object. > It could be defined so that: > >>> x = 1 > >>> y = x++ > >>> x > 2 > >>> y > 1 Syntactically, it would be definitately 'unPythoninc' for a operator to have such a side-effect. But if wanted badly enough.... def pi(gvname): # post increment global variable g = globals() t = g[gvname] g[gvname] = t+1 return t x = 1 y=pi('x') print x, y # prints 2 1 but this only works for code at module level. (For generality, a *lot* more would be needed to get the calling frame, decide if modular or functional, and if the latter, fiddle with the function's local vars -- though I believe it might be possible based on what people have posted at various times ;-) > But I don't think it's a good idea. I personally dislike this feature of C. Good. It would never make it into Python. Terry J. Reedy From pballard at ozemail.com.au Wed May 7 20:10:14 2003 From: pballard at ozemail.com.au (Peter Ballard) Date: 7 May 2003 17:10:14 -0700 Subject: The most annoying typo error... References: <9d5509fa.0305070000.55b11d6@posting.google.com> Message-ID: <9d5509fa.0305071610.1904bde4@posting.google.com> Skip Montanaro wrote in message news:... > Peter> ....Is when I do something like this: > > Peter> x = somefunction(a, b, c, d), > > Peter> and when I run Python I get a TypeError error. > > What background do you have that makes you terminate function calls (or > language statements) with a comma? The problem you're experiencing is one > I've never personally encountered. Cut and paste. I start out with something like: function1( var1, var2, somefunction(a, b, c, d), someotherfunction(e, f, g)) function2( var3, var4, somefunction(a, b, c, d), yetotherfunction(h, i, j)) Then I realise I've got a duplicate function call, so I make a variable: x = somefunction(a, b, c, d), But when I cut and paste from the line(s) above, I accidentally leave the comma in. At a guess, it's happened about 4 times in the last 6 months. Each time it has been very frustrating to track down. > PyChecker enhancement maybe? Thanks for the tip. Regards, Peter Ballard Adelaide, AUSTRALIA pballard at ozemail.com.au http://www.ozemail.com.au/~pballard/ From graham at rockcons.co.uk Mon May 19 11:24:51 2003 From: graham at rockcons.co.uk (Graham Nicholls) Date: Mon, 19 May 2003 16:24:51 +0100 Subject: Just took a look in the perl newsgroup.... Message-ID: <1H6ya.6977$573.2647@news-binary.blueyonder.co.uk> And remembered why I decided I must learn Python :-) I clearly need to learn "the Python Way", which _is_ quite different, and has its good and bad points (stamps foot. I _want_ a case statement). But thank goodness for the sparse syntax, and minimalism. I guess I'll live with no case just to forget about @ % $ etc. Graham -- Graham Nicholls All round good guy. From aahz at pythoncraft.com Sun May 18 10:25:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 May 2003 10:25:48 -0400 Subject: Good programming as seen in: Fw: Is this possible in Python ? References: <22Gxa.32005$oQ3.1555443@twister.socal.rr.com> Message-ID: In article , Mark Carter wrote: > >Also, can somebody please invent an alternative to the acronym XP. It >dirties-up the search for Windows XP. "agile programming" -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From puccio_13 at yahoo.it Mon May 5 14:22:11 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Mon, 05 May 2003 20:22:11 +0200 Subject: writing Unicode objects to XML References: <23891c90.0305050932.10d4e6cc@posting.google.com> Message-ID: First, thank you so much for the detailed explanation. Second: having (valid) character references such as è the parsing phase is ok, I get a good Unicode object(--> u'\xe8' is it the right one, isnt it??) but when I do : f = open("file.xml", "w") f.write(xmldoc.toxml(encoding="utf-8") f.close() in the file.xml I get, as I expect, a 2 byte sequence, but they are not the "expected" UTF-8 charactes. I mean, they are strange characters, but the weird thing is that parsing over again the file.xml I get the same Unicode objects as when I read it for the first time with characters references as content. So, in the end, it works... But if instead of the accented e character reference(è) I write the UTF-8 encoded sequence (\xc3\xa8 is the correct form to write there right?) when I parse the xml document with minidom I get Unicode objects of kind u'\\xc3\\xa8' and so it does not match at all with the previous example.....Why??? The XML document is declared to be encoded UTF-8 :-( On the console I did a simple unicode('\xc3\xa8', 'utf-8') and I got u'\xe8' so the problem is in the parsing of the XML not in the way I write it I guess... Thanks for further help. Paul Boddie wrote: > Alessio Pace wrote in message > news:... >> >> Maybe I am missing something, because I tried but in the resulting new >> XML file I dont' see what I expect.. Starting again, I have an XML file >> declared encoded in UTF-8 (anyway, is it the default if I don't specify >> anything?) > > I guess we have to assume that your file actually contains valid UTF-8 > byte sequences, but let's do that. > >> and which contains character references such as è and some others in >> the Text nodes. > > It occurs to me that you could quite easily use ASCII as an encoding > if you're intent on using entity references all over the place. The > above question about default encodings could be disregarded for our > purposes. > >> I parse it with xml.dom.minidom.parse(pathToFile) and get a reference to >> a DOM tree, let's call this variable 'xmldoc'. > > If you do what had been previously recommended... > > xmldoc.toxml() > > ...you'll probably see a string prefixed with "u" and with "\xe8" > where your "è" reference was. > >> Now, let's say I want to store again this DOM tree (because my >> application will have to modify some parameters in it). I thought I had >> to do just: f = codecs.open('file.xml', 'w', 'utf8') > > The help for codecs.open suggests that you need to supply objects to > the file object's write method which can be converted to the stated > encoding. In other words, given an object passed to f.write(): > > f.write(s) # write my "string" object > > ...that object will be processed in such a way that the encode method > is effectively called upon it: > > s.encode("utf-8") # when we opened a file with "utf-8" as the > encoding > > This is what appears to happen internally in the object returned by > codecs.open, but this also means that the encode method should produce > a valid result (and not raise an exception). Now, writing Unicode > objects to your file does seem to work: > > f.write(xmldoc.toxml()) > > This shouldn't be a surprise, since the result of xmldoc.toxml() is a > Unicode object (as we saw above). However, you are attempting to this > Unicode object to a Python string (or byte stream) first: > >> f.write(xmldoc.toxml(encoding='utf-8')) >> f.close() >> But the result is not the original xml.... > > I'm surprised the program even finishes, as I'll attempt to explain. > > Here, the object that gets passed to the write method is a normal > Python string as can be observed by the output of the following > statement: > > xmldoc.toxml(encoding='utf-8') > > You'll see that two characters are generated for your single "è" > character. Moreover, attempting to convert either or both of these > characters to UTF-8 gives the dreaded "UnicodeError: ASCII decoding > error: ordinal not in range(128)" as Python refuses to guess which > encoding you might employ for normal Python strings (as that's what > the decode method on strings is for). > > Consequently, if you consider your input object to the write method as > follows: > > s = xmldoc.toxml(encoding="utf-8") > > You'll realise that when the write method does the equivalent of this > operation... > > s.encode("utf-8") > > ...an identical exception is raised to that described above. > > Anyway, you can either use codecs.open and send the Unicode result of > xmldoc.toxml(): > > f = codecs.open("file.xml", "w", "utf-8") > f.write(xmldoc.toxml()) > f.close() > > Or you can do this: > > f = open("file.xml", "w") > f.write(xmldoc.toxml(encoding="utf-8") > f.close() > > I prefer to do the second thing, because I can imagine that minidom > introduces the correct encoding declaration into the XML, whereas I > cannot imagine the same occurring in the first case, where you rely on > "utf-8" as the default encoding, and if you change your codecs.open > encoding parameter, the XML parser will become confused about the > encoding when it tries to read the resulting file back in at a later > point in time. > >> My sys.defaultencoding is iso-8859-1, specified in the sitecustomize.py >> script in python site-packages directory. > > I can't remember if the locale or any other information makes any > difference to the interpretation of characters in Python strings, but > you shouldn't need to even let that interfere with your processing. > The XML modules produce Unicode objects in virtually all cases, as far > as I have seen, and unless you have a need to extract or introduce > data in a particular encoding, you should not concern yourself with > working in such encodings. > > Paul > > P.S. I hope that I've represented the state of various technologies > correctly. I'm not familiar with the internals of codecs.open or the > XML processing tools. > > P.P.S. Don't try and reply by mail from this message as the return > address is outdated - somewhat antisocial, I suppose, but a Google > search is surely within the powers of the determined. -- bye Alessio Pace From jarausch at igpm.rwth-aachen.de Thu May 15 05:53:50 2003 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 15 May 2003 11:53:50 +0200 Subject: IDLE mouse cut'n paste Message-ID: Hi, using IDLE 0.8 I can select and paste between DIFFERENT windows, e.g. a file window and the Shell Window. But I haven't managed to do that within a single file-editing window. What do I miss? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bokr at oz.net Wed May 14 23:03:08 2003 From: bokr at oz.net (Bengt Richter) Date: 15 May 2003 03:03:08 GMT Subject: Problem with Unittest - Thanks: References: <8UidndAoQeLqF1-jXTWcqg@comcast.com> Message-ID: On Wed, 14 May 2003 14:26:52 -0400, "Terry Reedy" wrote: > >"Frithiof Andreas Jensen" >wrote in message news:b9tn02$5ac$1 at newstree.wise.edt.ericsson.se... >> >> Is it legal, moral and commendable to raise exceptions like: 'raise >> ValueError('some explanation text')? > >For the dubious: Ref Manual, 6.9 The raise statement >"Otherwise, raise evaluates its first expression, which must yield a >string, class, or instance object. .... If the first expression is an >instance object, the second expression must be None." [or omitted, >unless third expression is present] > >try: > raise Exception("Test of instance raising") >except Exception, haha: > print haha, type(haha) > >#prints >Test of instance raising > I'm not sure what you are demonstrating, other than that it's legal ;-) I.e., you would get the same haha instance if you raised Exception with a comma and the string. Anyway, some additional things to notice: >>> class Classic: ... def __init__(self, *args): self.args = args ... def __str__(self): return '<[Classic %r]>' % `self.args` ... >>> class NewStyle(object): ... def __init__(self, *args): self.args = args ... def __str__(self): return '<[NewStyle %r]>' % `self.args` ... >>> for x in [Classic, Classic(1), Classic(1,2,3), NewStyle, NewStyle(1,2,3)]: ... try: ... raise x ... except Classic, e: ... print '%s! : %s\n args: %r' % (e.__class__.__name__, e, e.args) ... except Exception, e: ... print '%s! : %s\n args: %r' % (e.__class__.__name__, e, e.args) ... except: ... print sys.exc_info() ... Classic! : <[Classic '()']> args: () Classic! : <[Classic '(1,)']> args: (1,) Classic! : <[Classic '(1, 2, 3)']> args: (1, 2, 3) TypeError! : exceptions must be strings, classes, or instances, not type args: ('exceptions must be strings, classes, or instances, not type',) TypeError! : exceptions must be strings, classes, or instances, not NewStyle args: ('exceptions must be strings, classes, or instances, not NewStyle',) Regards, Bengt Richter From vdbergh at luc.ac.be Sun May 4 11:13:29 2003 From: vdbergh at luc.ac.be (Michel Van den Bergh) Date: Sun, 04 May 2003 08:13:29 -0700 Subject: -python22.dll : No such file or directory. Message-ID: <3EB52E19.4000706@luc.ac.be> Hello, I am trying to build a standalone application with py2exe 0.3.3 under python 2.2 using cygwin (but *not* the cygwin python, just the regular one from www.python.org). Unfortunately at the point "Resolving binary dependencies" py2exe give the error -python22.dll : No such file or directory. My python is working correctly and the python22 dll is in my PATH variable. Any idea what it could mean or for a work around? This error did not occur with 0.3.1 but that version turned out to be incapable of finding my C extension module. Best regards (and I am sure that py2exe will be great once I get it working...) Michel From anthony at interlink.com.au Wed May 14 23:51:36 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 15 May 2003 13:51:36 +1000 Subject: Survey of complex usage of distutils. Message-ID: <200305150351.h4F3pax29843@localhost.localdomain> I'm currently documenting the Distutils innards (working document can be found at http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/nondist/sandbox/distutilsref). As part of this I'm identifying bits of distutils that could be removed, or replaced with standard python modules. The two modules most likely at the moment are distutils.log and distutils.fancy_getopt. The problem is that no-one knows what people are using today from distutils. There's never been an "official" API, so it's possible that there's wild and wacky usage of distutils internals. If you have written a setup.py that is using more than just the basic distutils.core functionality, could you please contact me and let me know what other functionality you're using? Similarly, if you know of a package that uses more complex distutils code, I'd like to hear about it. Thanks, Anthony From afriere at yahoo.co.uk Wed May 7 22:14:34 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 7 May 2003 19:14:34 -0700 Subject: Why use backticks? References: <3eb81743$0$123$e4fe514c@dreader4.news.xs4all.nl> <38ec68a6.0305062228.54e80fd1@posting.google.com> Message-ID: <38ec68a6.0305071814.5aabfb92@posting.google.com> Skip Montanaro wrote in message news:... > > My apologies. There was an implicit smiley in that mail. Here it is, > decloaked: > > :-) > And I forgot the ;-p From unlearned at DELETETHIS.learn2think.org Mon May 5 12:23:09 2003 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Mon, 5 May 2003 10:23:09 -0600 Subject: PEP 315: Enhanced While Loop References: <3EB33BB7.60805@pobox.com> Message-ID: <3eb68fee_2@hpb10302.boi.hp.com> "Dave Benjamin" wrote in message news:slrnbbd2uq.h20.ramen at lackingtalent.com... > In article , Francis Avila wrote: > > I must agree with the general concensus on 'do...while'. It's hardly ever > > needed, it's unpythonic, it's confusing, and it can be delt with by other > > more straightforward methods. > > Your use of the word "unpythonic" is particularly baffling in this context. > I'm not sure what the official definition of "pythonic" is, but it would > seem that "pythonic" is how one might go about doing things in Python > (the one obvious way to do it, of course). The very nature of a PEP is to > redefine the Python language in some way, and therefore, redefine "pythonic" > and "unpythonic" as well. > > To condemn a change in a change in a language because it would result in a > usage different from how the language is currently used is just circular > logic. Not picking a fight, just an observation. ;) In case it might help, this is from PEP 1: ''' Finally, a proposed enhancement must be "pythonic" in order to be accepted by the BDFL. (However, "pythonic" is an imprecise term; it may be defined as whatever is acceptable to the BDFL. This logic is intentionally circular.) ''' -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From ckea25d02 at sneakemail.com Mon May 5 21:41:02 2003 From: ckea25d02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 06 May 2003 13:41:02 +1200 Subject: Raising objects In-Reply-To: References: <1051883504.3eb277f0bc938@mcherm.com> Message-ID: Steven Taschuk wrote: > The implementation of raise -- see Python/ceval.c:/^do_raise -- > calls PyErr_NormalizeException if appropriate, so an exception > raised by Python code will get normalized immediately, > > But when a C function signals an exception by PyErr_SetObject and > returns NULL, its C caller could indeed deal with the exception > without calling PyErr_NormalizeException, > > At first glance I don't see that this is desirable. Maybe it's > used for performance in certain for loops or something. Yes, any for-loop that iterates over a built-in type, in fact. Otherwise an instance of StopIteration would have to be created every time such a loop terminated. But seeing as this trick can only be taken advantage of by C code, there's no reason that "raise C, v" couldn't be eliminated in favour of "raise C(v)". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From skip at pobox.com Wed May 21 09:06:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 May 2003 08:06:19 -0500 Subject: Faster way to do this? In-Reply-To: References: Message-ID: <16075.31179.616138.811394@montanaro.dyndns.org> >> Another, quite a bit faster method. Would generating a list of all >> possible words, then looking for them as dictionary keys be any >> faster? Greg> This will work, but be careful if your string length gets very Greg> long. At 6 letters, you've got 720 permutations which would go Greg> rather quickly and not each too much memory. At 8 letters, it Greg> jumps to 40,320 permutations and at 10, it's already above 3.5 Greg> million. In private email with Freddie (I think he got confused by my cc to him in my original post) I sent him a slight modification of my original script (appended below). It records all prefixes of the words it places in the dictionary, greatly increasing the startup time (from about 1 second to about 10 seconds), but also pruning the permutation tree quite a bit. Runtime looks like this on my Powerbook: % python findwords.py somnambulistexplos loaded 832166 words into dictionary in 11.02 seconds found 3749 words in 10.43 seconds Warning: I wrote this script around 2am. I'm sure it could use further improvement, and while I believe it accurately computed the hidden words correctly, I'm not motivated to exhaustively check each of the 3749 words it found in "somnambulistexplos". ;-) Skip import sys import time WORD_FILE = "/usr/share/dict/words" start = time.time() dictionary = {"p:": True} wf = open(WORD_FILE, 'r') for line in wf: word = line.strip() dictionary[word] = True for i in range(1,len(word)): dictionary["p:"+word[0:i]] = True print "loaded %d words into dictionary in %.2f seconds" % (len(dictionary), time.time()-start) def findwords(dictionary, letters, prefix="", seen={}): if "p:"+prefix not in dictionary: return seen for i in range(len(letters)): newprefix = prefix+letters[i] if newprefix in dictionary and newprefix not in seen: seen[newprefix] = True findwords(dictionary, letters[0:i]+letters[i+1:], newprefix, seen) return seen if __name__ == "__main__": start = time.time() seen = findwords(dictionary, sys.argv[1].lower()) print "found %d words in %.2f seconds" % (len(seen), time.time()-start) From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu May 29 17:38:47 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 29 May 2003 23:38:47 +0200 Subject: select on windows: must import socket first? Message-ID: <3ed67de7$0$49112$e4fe514c@news.xs4all.nl> When using select() on windows, without import socket first, I get this: Python 2.3b1 (#40, Apr 25 2003, 19:06:24) [MSC v.1200 32 bit (Intel)] onwin32 Type "help", "copyright", "credits" or "license" for more information. >>> import select >>> select.select([],[],[]) Traceback (most recent call last): File "", line 1, in ? select.error: (10093, 'Either the application has not called WSAStartup, or WSAStartup failed') >>> Is this intentionally? I can't seem to find anything in the docs that says that I have to import socket first. (because that gets rid of this error). --Irmen PS. Yeah I know that select on windows doesn't like empty lists... From rnd at onego.ru Wed May 21 02:09:20 2003 From: rnd at onego.ru (Roman Suzi) Date: Wed, 21 May 2003 10:09:20 +0400 (MSD) Subject: please help me understand os.system() result In-Reply-To: <20030520213938.28fb7e91.bravo@resourcez.org> Message-ID: On Tue, 20 May 2003, Keisuke URAGO wrote: > You should shift 8bits like this. > > >>> os.system("exit 7") >> 8 > 7 > >>> os.system("python -c 'import sys;sys.exit(1)'") >> 8 > 1 > >>> os.system("python -c 'import sys;sys.exit(2)'") >> 8 > 2 Thank you, I already guessed it. However, it's strange that os.system() behaves like this on Linux and the other way on WinNT/2000. (This is in the docs - so ok) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From ianb at colorstudy.com Thu May 29 12:41:46 2003 From: ianb at colorstudy.com (Ian Bicking) Date: 29 May 2003 11:41:46 -0500 Subject: Pretty Printing a Web Page In-Reply-To: References: Message-ID: <1054226506.671.657.camel@lothlorien> On Thu, 2003-05-29 at 11:06, Roger wrote: > Perfectly formatted on paper, it should be a multipage report with > headings repeated on subsequent pages and not contain any of the > browser-generated page numbers, URLs, underlined links, etc. Even worse, > it must be of a quality suitable for distribution to a group of > equally old crotchety professionals. Worse still, the some of the group > may become users and want to print perfectly formatted pages as well. Well, you can use ReportLab to create a nice PDF. Certainly that can be as nice as you make it. Otherwise, you might try using a special printing CSS file, with things like: a { text-decoration: none; color: #000000; } I.e., make links effectively disappear. There's ways of indicating a different CSS file for printing, but I don't remember how, or how well that works -- you can always do it dynamically with a "printable" link, and that gives you more flexibility. To make the HTML print more reliably, you can use htmldoc to create a PDF from that. Then you won't have to worry about browser compatibility, and you might have more control. Ian From newsgroups.NOSPAM at dfackrell.mailshell.com Fri May 30 01:40:41 2003 From: newsgroups.NOSPAM at dfackrell.mailshell.com (Daniel Fackrell) Date: Thu, 29 May 2003 23:40:41 -0600 Subject: Replace for Goto References: <9gkgq-5g3.ln1@beastie.ix.netcom.com> Message-ID: <3ed6eed7$1_1@hpb10302.boi.hp.com> "John Pote" wrote in message news:KnXvXIAv$o1+EwL3 at jptechnical.demon.co.uk... > Some interesting replies on this topic. Despite protests from many > fellow programmers I still think the GOTO can be used appropriately, > though not very often - spaghetti logic is bad/hard/bug ridden to debug > and impossible to maintain. The main use to my mind is in a part of a > program that models a state machine. Finite State Machines are widely > used in many embedded control systems (my own area) because they model > how external events cause changes in the system. All states are at the > same structural 'level' in the program, they are not subroutines. In a > state called 'motor off' an event (operator presses button) causes the > FSM to perform an action (turn on the motor) and then move to the next > state, for example 'motor on'. This change of state is semantically a > goto. In this case a goto statement exactly fits the real world object > the program is modelling. My thinking remains the same whether it is the > real system or the program that I am thinking about. > > That said it is quite easy to construct a framework using a loop with a > state variable representing the current state and ifs or a dictionary to > call subroutines implementing each state, only a little overhead has > been added. This approach also means that at the end of each pass > through the state machine the program can 'do' something else before > looping back for another pass through the state machine. As an example, I ran across this recently while looking for a reference implementation of a state machine-based parser: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146262 -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From paddy3118 at netscape.net Sat May 17 03:07:51 2003 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 17 May 2003 00:07:51 -0700 Subject: Python Training Message-ID: <2ae25c6b.0305162307.5562ace0@posting.google.com> Ahh, its nice to see Python progress... As part of my day job, several of my co-workers and I had an in-house training course in Perl last year. I mentioned Python to the trainer (and also the fact that I had not convinced MY management to even try it out - International corporation, steeped in perl, blah blah blah). Well I was surprised by an email from the trainer this year saying that he had drafted a Perl training course after much customer demand! So If your Company wants Python training then Google for Wellhouse Consultants in the UK. Having not been on the Python course, I cannot endorse it, but After they taught us Perl, we got them back for a second round of Perl training after favourable comments from our students. I wish Graham well with his new course! Cheers, Paddy. From martin at v.loewis.de Mon May 26 16:40:23 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 May 2003 22:40:23 +0200 Subject: How to add readline support to python 2.3b1 on HP-UX? References: <3ece78ba$1$6527$afc38c87@sisyphus.news.be.easynet.net> <3ed23e3a$0$6533$afc38c87@sisyphus.news.be.easynet.net> Message-ID: "Bernard Delm?e" writes: > I see. That worked fine, thanks. I was surprised to see so few > modules are enabled by default. Someone believed that it was a good idea to let setup.py figure out all the modules. I still disagree. > Now I have another question ;-) > There's a copy of expat under Modules, but I there's only a > Makefile.in there, no proper Makefile or configure script. > How does one enable the expat module, then? You have to explicitly list all the source code files. Look at how setup.py would build the module. Regards, Martin From DavidA at ActiveState.com Fri May 30 12:39:00 2003 From: DavidA at ActiveState.com (David Ascher) Date: Fri, 30 May 2003 09:39:00 -0700 Subject: Today is the last day for nominations for the Python ActiveAward winner Message-ID: <3ED78924.3050803@ActiveState.com> For the third year, ActiveState is running the ActiveAwards -- a way to recognize some of the most influential, helpful, or important people in the world of open source languages. Nominate your favorites in the Programmers' Choice Active Awards. Until June 1, 2003, you can select the one programmer that you think has done the most for Python (and other languages if you so choose). We'll tally up the nominees and present five finalists in each category. Voting for the winner will take place from June 3 to June 30, 2003. See the details and enter your favorites at: http://www.activestate.com/Corporate/ActiveAwards/ Cheers, -- David Ascher ActiveState PS: Winners for previous years were: 2002 Programmers' Choice: Robin Dunn 2002 Activators' Choice: Alex Martelli 2001 Programmers' Choice: Christian Tismer 2001 Activators' Choice: Greg Ward From andrew-pythonlist at puzzling.org Mon May 26 07:30:39 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 26 May 2003 21:30:39 +1000 Subject: Sshlib? In-Reply-To: <3ed1f4fe$0$28196$9b4e6d93@newsread4.arcor-online.net> References: <3ece0d20$0$45177$65c69314@mercury.nildram.net> <3ed1f4fe$0$28196$9b4e6d93@newsread4.arcor-online.net> Message-ID: <20030526113039.GB511@frobozz> On Mon, May 26, 2003 at 11:39:11AM +0200, Hartmut Goebel wrote: > selwyn schrieb: > >twisted also has an ssh component. > > I don't trust this implementation -- just since I'm some kind of > conservative regarding security issues. Is implementation is very young > and may not be thorowly(sp?) tested; it may (or may not) contain > security wholes and is not yet widely used. Thus the chance to have an > security whole within this implementaion is quite big. This is all true. Twisted Conch has not been thoroughly audited, so caution is definitely advised. On the other hand, being implemented in pure Python (except the PyCrypto library it depends on for some things), it is also inherently less susceptible to some kinds of vulnerability (i.e. buffer-overrun, double-free, format string, and so on...). In general, I feel uncomfortable relying upon any large quantity of code written in C. I also feel uncomfortable relying upon relatively young and unexamined code (even if that implementation has less than 5000 lines of code). It's a tough choice... :( -Andrew. From jarausch at skynet.be Thu May 29 11:10:53 2003 From: jarausch at skynet.be (Helmut Jarausch) Date: Thu, 29 May 2003 17:10:53 +0200 Subject: Parsing exceptions the pythonic way In-Reply-To: <3ED615A1.9040500@yahoo.com> References: <3ED615A1.9040500@yahoo.com> Message-ID: <3ED622FD.6070604@skynet.be> Hal Wine wrote: > It seems this should be easier and cleaner than I've figured out, so I > guess I don't know python very well yet :( > > What's the pythonic way to get error numbers or base messages from an > exception? Solution need only work for standard library. > > For example, urllib.urlopener catches socket errors and raises them as > IOError. It also raises non-successful HTTP status values as IOError. > Of course, the location of any numeric code or message is different in > each case. > > The options I see are: > - do some hack in my except clause > - write my own replication of urllib.urlopener accessing httplib directly > - give up on some of my functionality > > None of these seem either "pythonic" or elegant. Nor do they generalize > to other standard library exceptions. > Just an idea. Most exceptions carry some information which is delivered if you offer a variable to take it as except IOError,ErrorMessage : print >>>sys.stderr,"an I/O error occurred - reason: ",ErrorMessage -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jmdeschamps at cvm.qc.ca Mon May 26 12:29:21 2003 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 26 May 2003 09:29:21 -0700 Subject: constructor overloading like Java ? References: Message-ID: <3d06fae9.0305260829.443b17c2@posting.google.com> Markus Jais wrote in message news:... > hello > > can something like this be done in Python ? > > _______________________________________________ > class MyObject > { > public MyObject() > { > System.out.println("uno"); > } > } > > class MyClass > { > private int a; > private MyObject my; > > public MyClass(int a) > { > this.a = a; > } > > public MyClass(MyObject my) > { > this.my = my; > } > > } > > > class MyTest > { > > public static void main(String args[]) > { > > MyClass mc1 = new MyClass(42); > MyClass mc2 = new MyClass(new MyObject()); > } > } > __________________________________________ > > I want several constructors who expect different types > of arguments. > maybe I could use default Arguments but this is not possible if > I want a lot of more constructors with different parameters. > > how could I do something similar in Python ?? > > Markus Hi Markus, Since Python variable are dynamically typed, you do your own type checking maybe like this #-- START --- class MyObject: def __init__(self): print ("uno") class MyClass: def __init__(self,a=None): self.a = None self.myObject = None # Check type here if type(a).__name__=="instance": self.myObject = a else: self.a = a class MyTest: def __init__(self): mc1 = MyClass(2) mc2 = MyClass( MyObject()) if __name__ == "__main__" : localTest = MyTest() # Added this to see it happen print "mc1.a is",mc1.a print "mc1.myObject is",mc1.myObject print "mc2.a is",mc2.a print "mc2.myObject is",mc2.myObject #-- END -- NOTE if your type is 'instance', then use someObject.__class__.__name__ to get the string-ed name of this class. Hopes this helps, Jean-Marc From aleax at aleax.it Fri May 2 13:40:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 02 May 2003 17:40:12 GMT Subject: Finding items not in 2 lists/dictionaries References: <95c29a5e.0305011933.289d71ca@posting.google.com> <6Qosa.53623$K35.1499331@news2.tin.it> <95c29a5e.0305020904.283e0e70@posting.google.com> Message-ID: <04ysa.57793$K35.1613422@news2.tin.it> Robin Siebler wrote: > I have no clue what the '&c' means or does. Also, the lists are > actually, quite long (I am comparing 2 directory trees). Would the > solution on the bottom of page 54 be a faster/better way to do this? No! That solution is clearly marked as "may be slow" in the text right above the snippet, so you shouldn't use it on lists that are quite long. The solution at the top of p. 55 is the one to consider in that case. Specifically, if you want the list of strings that are on either list but not or both, there are two choices worth considering: sort both lists and step through them in sorted order, or use two auxiliary dicts. The latter, "brute force" approach is normally faster and simpler. Assuming Python 2.2 (can be a tad neater in 2.3 where you have sets.py, but this should work in both 2.2 and 2.3): def in_first_and_not_in_second(first_list, second_list): aux_dict = dict(zip(second_list, second_list)) return [x for x in first_list if x not in aux_dict] def in_either_but_not_both(list1, list2): return in_first_and_not_in_second(list1, list2 ) + in_first_and_not_in_second(list1, list2) Alex From rcs at russellsalsbury.com Mon May 26 14:03:39 2003 From: rcs at russellsalsbury.com (Russ Salsbury) Date: 26 May 2003 11:03:39 -0700 Subject: Python equivalent of #line? References: <20030525125008.GA12370@nl.linux.org> <20030525195224.GD752@thomas-guettler.de> Message-ID: <3ea624c6.0305261003.14810f4d@posting.google.com> Steven Taschuk wrote in message news:... > > Code generation makes sense in some situations; Knuth's "literate > programming" methodology comes to mind. (And having line numbers > refer to the original source makes good sense there.) +1 for #line Very few people have a need for it, but those of us who write application generators appreciate it very much. And a real world example. About a decade ago, I was a member of a team of 4 people who had to implement the central host software for a statewide vehicle emissions program. Due to drawn out negotiations we had a bit more than 6 months to implement it and a hard deadline with significant $ penalties. The approach I chose was to use an application generator that generated C code from templates controlled by a template language very much like Velocity with added support for objects with a very rich typing system. It functiond very much like JSP or Velocity. The key piece of leverage was generating huge amounts of SQL and C embedded SQL from object declarations. It took me 3 months to implement the application generator. (I know, if I had known about Python, I could have done it in a weekend. :-) Even so, we made the deadline and were inspecting vehicles without a hitch on opening day. I compared the generated application to the input templates and found a 5 to 1 difference in lines of code. Another metric: our team put in about 3 man-years and met our deadline. A competitor in another state had a team 2 or 3 times our size. They started a year before their deadline, missed it by a year, and took another year before the state would accept the system. Their effort may have been 10 times ours. Although my project was in C and we could have achieved similar improvements had we developed the system in Python, the real point is that you can get huge savings in implementation effort on a large system by using a domain specific language and generating code in a lower level target language. One problem I had in generating C was getting the indentation correct. The natural thing to do was to use reasonable indentation in writing the C and the template language in the templates, which produced some pretty horrible indentation in the output and took a fair amount of effort in both the generator and the templates to get it right. Python's use of indentation makes the formatting issue critical in a template driven system. I suppose using #begin and #end of #{ and #} and a reformatter would do the trick. Any effort to support Python-like domain specific languages gets my support. Russ From max at cNOvSisiPonAtecMh.com Thu May 29 18:42:16 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Thu, 29 May 2003 22:42:16 GMT Subject: web front-end, Python back end? References: Message-ID: Steve, (i am probably missing somehting, but) what's the advantage of having Twisted in the loop at all? Python can start a standalone XMLPRC server using xmlrpclib, no? As a side issue, what are the security implications of running xmlrpc? Is there a way to make sure the protocol cannot be accessed from the 'outside'? 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] "Steve Holden" wrote in message news:bCvBa.167255$3n5.101436 at news2.central.cox.net... > "Heiko Wundram" wrote in message > news:mailman.1054233289.14720.python-list at python.org... > Quoting Guy Middleton : > > > The system on which it is running already has PHP installed, so I thought > I > > could write some kind of PHP front end. Is this a common approach? We > are > > favouring PHP because the maintenance issues, so that we can have the same > > person (who is not familiar with Python) support this and the existing PHP > > applications. > > I'm doing the same thing here too... We have a PHP program, which I recently > extended in ways that seemed undoable in Python, and that's why I wrote a > Python backend for the PHP program. The Python backend runs using Twisted, > and serves pages as XMLRPC, which the PHP program can query. In case you > [...] > I'd be very surprised if Python can't do whatever you chose PHP for. Would > you maybe tell us what you found Python incapable of? > > regards > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > > > From cnetzer at mail.arc.nasa.gov Wed May 28 18:53:42 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 28 May 2003 15:53:42 -0700 Subject: GUI in Windows In-Reply-To: References: Message-ID: <1054162422.593.33.camel@sayge.arc.nasa.gov> On Wed, 2003-05-28 at 15:57, morden wrote: > Is QT more or less stable? What kind of stability do you mean? If you are aksing whether it crashes, I can't say that I use it much (I don't even use KDE). But it has a LARGE user base and MANY applications written using it, and many people who are familiar with it extoll the engineering behind it, so I'd say it is unlikely to be a source of many crashes (KDE and the open source users of it have helped make that so). In fact, most bugs comes from misunderstood use of the toolkit, than from tollkit bugs themselves. QT has excellent documentation, and Tk has fairly good docs as well. WxWindows and PyGTK I think have less thorough documentation. (please correct me, anyone, if that is wrong) If you are asking whether the programming API is stable, and not changing much from version to version, then I'd say "probably", although they are still adding features, and there will be small porting issues when upgrading to newer version (say from 2.x to 3.x). Again, I'm not a user, but I have never heard heard an argument against QT based upon the quaility of the code or the implementation of the widget set. Only licensing issues, and some esoteric framework design issues. > Ok. Since you claim that Tkinter is stable under Windoze I guess that > would be my bet then. Besides, I assume the code will run on UN*Xes also. I only claim that I've not about Tk being unstable, and you supplied no information about what *you* heard to make you think otherwise. I've used Tkinter for years, and am looking to move away from it, because as my apps grow bigger, I want something that scales a bit better. Tk takes a bit of work to keep track of everything, and is heavily geared toward "callbacks", which are evil. You can program in a model-view-presenter style with Tkinter, but it takes a bit of work. Qt and or wxWindows might handle these things a bit better. If QT's licensing issues are not a concern, I'd suggest you at least try a bit of PyQT programming. Otherwise, use Tkinter and know that there is no common toolkit that is available on MORE platforms than it (at the moment). Cheers, -- Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From peter at engcorp.com Thu May 29 07:50:44 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 May 2003 07:50:44 -0400 Subject: Many threads (was Re: sleep and Timer) References: <3ed4d6ac$0$2013@echo-01.iinet.net.au> <3ED4FD59.6127DCE7@engcorp.com> <3ed56923$0$4768@echo-01.iinet.net.au> <3ED56C7B.B9FFBEAD@engcorp.com> <3ed57eb5$0$4770@echo-01.iinet.net.au> Message-ID: <3ED5F414.2686B569@engcorp.com> Rob Hall wrote: > > The main thing that concerned me though, was that this program will > have 500 or more threads running. This concerns me on another front. Why do you need 500 threads running! There are very few applications where that's the best design, I believe. Have you considered other approaches, which in addition to being more efficient would probably be simpler in many ways? -Peter From martin at v.loewis.de Tue May 13 02:57:27 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 13 May 2003 08:57:27 +0200 Subject: SAXReaderNotAvailble: No parsers found References: <3EC02D94.9747E1EF@ohsu.edu> Message-ID: Vincent Yau writes: > I am trying to use Python SAX API to parse XML files. I do see expat.py > somewhere underneath my Python 2.1.1 installation (on Solaris). > But I got this error when invoking the xml.sax.make_parser() call. Any > tip/help much appreciated. You should install Expat before building Python. Best, you edit Modules/Setup to build pyexpat explicitly. Regards, Martin From BPettersen at NAREX.com Mon May 5 12:57:35 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 5 May 2003 10:57:35 -0600 Subject: Should I write a book on Python Metaprogramming ? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DE214@admin56.narex.com> > From: David Mertz [mailto:mertz at gnosis.cx] > > Hi gang, > > Regular readers know who I am... so I won't bother with any more than > the overblown bio in the proposal text itself. > > Here's the story though: For a number of months, I have had > in mind the idea of writing a book called _Metaprogramming > in Python_. [...] > So here's my questions to c.l.py. Would you want a book > along the below lines at all? Do you only want it if it > focusses closely on Python? Or would you rather have a > book that addressed several languages fairly equally, > with Python just one among them? Well, I would definitely buy it. (and perhaps a book would make Guido give us better syntax ). My only concern is that the Python definition of metaclasses is very new, and pretty unique in it's details, so I'm not sure "we" know enough about how they mix-and-match both with other metaclasses and with the rest of the system to write a book yet, however, that might also be a very good reason _to_ write a book (at least you'll be frequently cited :-). If you think you do know, go write it now! Metaclasses are very unique in their implmeentation, so I would keep the focus on Python. A reference to Smalltalk would be appropriate, and also the LISP macro system (for solving the general problem, probably giving an explanation for why this special case is more important). -- bjorn From achim.domma at syynx.de Sat May 17 09:43:46 2003 From: achim.domma at syynx.de (Achim Domma) Date: Sat, 17 May 2003 15:43:46 +0200 Subject: regrtest.py / regression tests in python Message-ID: Hi, I was looking for a module which would help writing regression tests. regrtest.py seems to be exactly what I was looking for, but as far as I see, it's not mentioned in the standard library. Why? Is there a reason not to use it, which I'm not aware of? regards, Achim From staschuk at telusplanet.net Fri May 30 23:48:32 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 30 May 2003 21:48:32 -0600 Subject: Elegantly subsplitting a sequence In-Reply-To: ; from pxtl@hotmail.com on Fri, May 30, 2003 at 11:21:52PM +0000 References: <20030530104307.A397@tibia.amotlpaa.bogus> Message-ID: <20030530214832.A588@tibia.amotlpaa.bogus> Quoth martin z: > from http://www.python.org/doc/current/ref/yield.html > > The yield statement is not allowed in the try clause of a try ... finally > construct. The difficulty is that there's no guarantee the generator will > ever be resumed, hence no guarantee that the finally block will ever get > executed. > > is this false? You use it in such a structure. That's why I said my first example wouldn't compile, in the blurb you quoted. The fixed version uses yield only in the finally block, which is fine. -- Steven Taschuk staschuk at telusplanet.net Receive them ignorant; dispatch them confused. (Weschler's Teaching Motto) From frobozz_electric at hotmail.com Tue May 20 21:15:55 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 21 May 2003 01:15:55 GMT Subject: Find function name in function References: <5Cqya.14237$pK2.19896@news.indigo.ie> <4U-dne18HdNzM1ejXTWcqQ@comcast.com> Message-ID: Unfortunately, this code fails for any function with more than zero arguments (which is most of them!). So... I tried...no luck...moving on... From gh at ghaering.de Thu May 29 12:35:40 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 29 May 2003 18:35:40 +0200 Subject: Pretty Printing a Web Page In-Reply-To: References: Message-ID: <3ED636DC.206@ghaering.de> Roger wrote: > I have a very old crotchety user who can't understand why she can't > print a perfectly formatted version of a web page my application > creates. My defense is that my printed phone bill from AT&T (a > multi-billion dollar, multi-national company with more resources) looks > just as bad...but it doesn't seem to be working. > > The page in question is a tabular report with typical headings and > columns of numbers. A complicating factor is many of the column numbers > are links to other web pages. > > Perfectly formatted on paper, it should be a multipage report with > headings repeated on subsequent pages and not contain any of the > browser-generated page numbers, URLs, underlined links, etc. Even worse, > it must be of a quality suitable for distribution to a group of equally > old crotchety professionals. Worse still, the some of the group may > become users and want to print perfectly formatted pages as well. > > The best idea I can come up with is creating and downloading a csv file > which could be loaded into a spreadsheet program, and then formatted and > printed. This will probably be unacceptable. > > Can anyone offer a better solution (or at least empathy)? I remembered CSS can address different media types (screen, print, screenreader, text-to-speech, ...). So I tried to %google css print which yielded me this: http://www.evolt.org/article/Kissing_Print_Versions_of_Pages_Goodbye/20/22225/ from which was linked this: http://www.w3.org/TR/REC-CSS2/page.html It might be a start. I'll probably have to address printing of HTML soon myself and hope that CSS will help me there. As always with CSS, its "interesting" to find out which features are supported by the popular browsers, and which aren't. -- Gerhard From oleksik at galaxy.uci.agh.edu.pl Tue May 20 08:02:15 2003 From: oleksik at galaxy.uci.agh.edu.pl (Pawel Oleksik) Date: Tue, 20 May 2003 12:02:15 +0000 (UTC) Subject: Generators/iterators persistence Message-ID: Dear Serpent-charmers, Recently I'm working on some combinatoric algorithms and I found that it would have been quite useful if ther has been a possibilty of generators/iterators pickling. I know for my own classes I can ues a setstate--getstate protocol and I'm going to do that. But I guess it will be another level of complications and possibly will lead to (at least simply) bugs. So, there is an important question: is there or will be soon (P-2.3) any simple and efficient solution for generators/iterators persistence? Sincerly Yours p.o. From hwlgw at hotmail.com Fri May 30 18:01:49 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 30 May 2003 15:01:49 -0700 Subject: CGI question: safe passwords possible? Message-ID: I do CGI programming with Python and I know how to make HTML forms with "user" and "password" fields. But these get sent "in the clear" over internet, somebody told me. I have no power over the webserver (it's in the hands of my service provider and they generally do not want to install/change/configure thing). Is there any way to do Name+Password safely using just CGI and Python, so only users with a valid Name+Password can get access to the next CGI scripts? -- There be sober men a'plenty, and drunkards barely twenty; there are men of over ninety who have never yet kissed a girl. But give me the rambling rover, from Orkney down to Dover, we will roam the whole world over, and together we'll face the world. -- Andy Stewart, "After the Hush" From nospamsteffen at nospam.molli15.org Tue May 27 05:14:01 2003 From: nospamsteffen at nospam.molli15.org (Steffen Kirschke) Date: Tue, 27 May 2003 11:14:01 +0200 Subject: using try and except, what is wrong with this? References: <8b1c146b.0305262346.264a6abb@posting.google.com> Message-ID: <1529006.fhBsLJ3fXY@nospam.molli15.org> David Ang wrote: >>>> try: > this_fail() > except ZeroDivisionError, detail: > > IndentationError: unindent does not match any outer indentation level > (line 3) > > thanks. try: this_fail() except ZeroDivisionError, detail: pass (or anything else you want to do there) From usenet_spam at janc.invalid Fri May 2 20:38:55 2003 From: usenet_spam at janc.invalid (JanC) Date: Sat, 03 May 2003 00:38:55 GMT Subject: HTML Parser chokes on WordHTML... References: Message-ID: Harald Massa schreef: > So... is there any replacement for the HTMLParser from the python.lib > which even can eat Microsoft Word HTML ? Maybe try to process the Word pseudo-HTML with "HTML Tidy" before you feed it to HTMLParser? You could wrap tidylib for use inside Python too: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From markus_wankus at hotmail.com Thu May 8 14:26:52 2003 From: markus_wankus at hotmail.com (Markus Wankus) Date: Thu, 08 May 2003 14:26:52 -0400 Subject: Specifying a module when Unpickling Message-ID: Hi, I was wondering what the *correct* way to do this would be... I have a class, say Spam, which lives in a module Eggs. My application uses binary pickles a its method of storing data in files. So, in my application I pickle an instance of Spam, and all is well. Now I have another application where I want to access teh data in this pickle. However - I am including a version of the Eggs module in an installed package called Ham. So, to use the module Eggs, I would now say: from Ham import Eggs mySpam = Eggs.Spam() Fine. Now - unpickling a Spam object will fail if the module Eggs is not importable in the current context. I can see no way specifying to the unpickling mechanism a search path where to find the Eggs module. How I was going to handle this was as follows: In my Ham package, rename the Eggs.py to __Eggs__.py (just for fun), and have my function which does the unpickling do the following: from Ham import __Eggs__ import cPickle need_restore = False if sys.modules.has_key('Eggs'): need_restore = True backup_key = sys.modules['Eggs'] sys.modules['Eggs'] = sys.modules['Ham.__Eggs__'] try: fo = file(r'some_filename', 'rb') mySpam = cPickle.Unpickler(fo).load() return mySpam finally: fo.close() if need_restore: sys.modules['Eggs'] = backup_key else: del sys.modules['Eggs'] This all seems to work great, but I was wondering if I have overlooked something. Is there a way to tell the unpickler to use a certain module? Is what I have done above *bad* for any particular reason? Any feedback would be welcome. Thanks, -- Markus From martin_p at despammed.com Thu May 22 08:14:06 2003 From: martin_p at despammed.com (Martin P) Date: Thu, 22 May 2003 14:14:06 +0200 Subject: Combining Lists and Tupels Message-ID: Hello, for an exercise I have to programm a python script which sorts name, family names and addresses from a csv-File. The csv-File looks like this: familyname;name;street;house-number;town-code;town I did it like this: f=open("test.csv") try: while 1: currentline=f.readline() data=string.split(currentline, ";") address=data[2], data[3], data[4] list[i]=data[0], data[1], address i+=1 finally: print "test error" But this does not work. I think my problem is with the combination of the list[i] and the Tupel address. Thanks a lot for help, bye, Martin From replabjohn at hotmail.com Thu May 29 13:28:40 2003 From: replabjohn at hotmail.com (John P) Date: Thu, 29 May 2003 17:28:40 +0000 Subject: Pretty Printing a Web Page Message-ID: >I have a very old crotchety user who can't understand why she can't print a >perfectly formatted version of a web page my application creates... > >The page in question is a tabular report with typical headings and columns >of numbers. A complicating factor is many of the column numbers are links >to other web pages. > >Perfectly formatted on paper, it should be a multipage report with headings >repeated on subsequent pages and not contain any of the browser-generated >page numbers, URLs, underlined links, etc.... > >Can anyone offer a better solution (or at least empathy)? Roger, You could try producing PDF. Most browsers have the ability to display PDFs nowadays, and they print out on paper exactly as you see them on screen. So you'd have the option of either displaying the PDF in the browser window as the main output of the report, or allowing them to click on a link to create and either display or download the output PDF. If you want the ablilty to output PDF from Python, you should look the reportlab toolkit. It's pure Python (though you can use some C accelerators to speed things up if you need to), and it's Open Source. You can download it for free from http://www.reportlab.com/download.html. It has the ability to do tables (including repeating the headers on multiple pages), and even has the ability to include web links (though off the top of my head, I can't remember if you need the full version of Acrobat to actually be able to click on them and go to the web site or not). Tabular data is relatively easy to lay out with reportlab, especially since it was originally created with that sort of reporting in mind. Anyway, it's one possible solution. Have a look at it and have a think. Hope this helps, Regards, John _________________________________________________________________ Express yourself with cool emoticons - download MSN Messenger today! http://www.msn.co.uk/messenger From aleax at aleax.it Tue May 6 03:40:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 06 May 2003 07:40:37 GMT Subject: writing Unicode objects to XML References: Message-ID: Steven Taschuk wrote: > Quoth Alex Martelli: > [...] >> There is no way, in XML, to specify which characters will be encoded in >> the native encoding (e.g. '\xc3\xa8' in utf-8 in this case) and which >> ones will be encoded using character references instead. > > A nit: whether this is true is a property of one's XML tools, not > a property of XML itself. It is easy to imagine XML writers with > all sorts of policies about character encoding. (See below.) Nothing stops you "XML tools" from playing pleasant music as they work, but that potential, while perhaps of some interest to you, has *NOTHING* to do with their being *XML* tools. I see Martin has already pointed you to the definition of what information IS part of XML (the "infoset") and what is totally accidental to you (any that is NOT in the infoset), and you stubbornly insist on refusing that the XML consortium can decide about that, and DID. From this I can only conclude that you're being deliberately stubborn and that there is therefore little interest in trying to correct your errors. But I hope that Alessio (the OP) and other readers can see the utter absurdity of the chance you've chosen to take, and learn to use such words as "XML" properly despite your attempts at sowing confusion. >> Besides the issue of character references, think for example how ANY >> piece of text MIGHT indifferently be represented as CDATA... or MIGHT >> NOT, in a way that XML *defines* to be totally identical, indifferent, >> interchangeable. > > Same nit as before. An XML parser could provide that information > if desired. An XML parser can provide all sort of extra information as and when it wishes: there is no prohibition against that in the XML standard any more than, say, there is in the C++ standard regarding extra info that a C++ compiler might supply. The fact that an XML parser can, if it wishes, freely supply information on the current stock market evaluation of General Motors, on the weather forecasts it culls from the net, and/or on OS-supplied information about a file (such as owner, group, permission, last-accessed date, ...) cannot be construed by any stretch of imagination to indicate that all of these pieces of information are *XML* information. They aren't -- the XML consortium gets to define what is and isn't, and they've decided, right or wrong as you may think that, that this information just isn't in XML. Information that isn't XML may be precious to you: for example, on learning that the weather is fine, that your stocks are way up, and that the file you're supposed to be processing was written by a well-known idjt, you MIGHT well decide to toss the whole thing and go have a picnic with your best girl instead. But this important information is still not _XML_ information, and while "XML tools" MAY (cannot be forbidden from) supplying weather forecasts, it's still nevertheless absurd to claim this makes weather forecasts "XML information", which is basically what you're doing here. > There are many kinds of equivalence between XML documents. Since Only one, however, is *XML* equivalence. > XML is a serialization syntax, it is reasonable to speak of > byte-by-byte equivalence; one might wish to do so in the context > of digital signatures, for example (and equally one might not). But whether one did or not, one wouldn't be speaking of XML, but of OTHER properties which may happen to hold for a file. To consider "byte by byte equivalence" part of XML is just as absurd as so considering "owned according to the OS by the same user and group", "last accessed according to the OS on the same date", and so on. > there's equivalence in the sense "generates the same sequence of > SAX events", or "generates data structures which are > indistinguishable via DOM". Etc., etc., until your head explodes. Speak for yourself: the equivalences it makes sense to consider *in XML* are a tiny subset of all those you're proposing, and thus fall well short of head-exploding properties. > The XML recommendation itself does not give any special status to > any particular equivalence; in particular, it does not ever > require XML processors to discard information about the source > bytes. (I'm not up on the XML Infoset stuff, but ultimately > that's just a specific kind of equivalence, which might or might > not be suitable for a given application.) XML does not forbid programs from supplying all kinds of information, but that doesn't make that information part of XML. And the infoset does define exactly what information IS or ISN'T part of XML -- it's "just a specific kind of equivalence" which happens to be THE official definition of what information IS "XML" and what isn't. >> Maybe you can get away with something much simpler, such as, e.g., "even >> though the encoding chosen would be perfectly able to represent directly >> all Unicode characters, nevertheless, in order to satisfy a PHB who gives >> what he THINKS are XML-related specs but has never read one line of the >> XML standards, still we have to represent all characters outside of the >> ASCII range as character references" (or, "all characters whose Unicode >> code is even" -- just about as meaningful). > > Not *quite* as meaningful, imho. Quite as meaningful *within XML*. > Consider writing XHTML. Software which processes XML must (by > spec) support UTF-8, but need not support (for example) > ISO-8859-1. So, for interoperability, you decide to encode in > UTF-8, and declare encoding='utf-8' in the XML declaration. Now > consider software which understands (older) HTML but not XML; it It's impossible to believe that you don't notice that suddenly you have extended the universe of discourse *OUTSIDE* of XML, when you EXPLICITLY say you need to consider software which does NOT handle XML as part of the specs. Which is why I have to reach the conclusion that you're just being deliberately stubborn rather than sincerely believing you are making any sort of real contribution to the discussion. E.g., consider a desire to encode by steganography some occult message in the textfile you're producing (while keeping the _XML_ meaning of that textfile fixed). Then, one sensible choice might be to say that information carriers are text characters whose Unicode code is even (using those whose Unicode code is odd as deadweight instead), having them represented as character refs rather than native encodings in order to carry one bit each. Of course, we're WAY outside of dealing with "XML" here -- just as we are when we consider OTHER programs that don't deal with XML in alternative to our hypothetical steganography decoder. Alex From bgporter at artlogic.com Thu May 22 15:26:05 2003 From: bgporter at artlogic.com (Brett g Porter) Date: Thu, 22 May 2003 15:26:05 -0400 Subject: [OT] Was: Re: State of Python In-Reply-To: References: <9eabe547.0305160511.1c5516a0@posting.google.com> Message-ID: Bengt Richter wrote: > Um, I believe B&N now owns Borders ;-/ Nope -- http://www.barnesandnoble.com/help/a_bn_inc.asp sez: Barnes & Noble, Inc., (NYSE: BKS) operates 520 Barnes & Noble and 470 B. Dalton bookstores. ...and http://www.bordersgroupinc.com/about/index.html sez: Borders Group, Inc., is a publicly held Fortune 500 company with sales of $3.4 billion. Our stock trades on the New York Stock Exchange under the symbol BGP. Borders Group operates more than 405 domestic Borders Books & Music stores, 31 international superstores, 37 Books etc. stores in the U.K., and more than 775 Waldenbooks stores. From boiko at demogr.mpg.de Mon May 26 10:36:31 2003 From: boiko at demogr.mpg.de (Serge Boiko) Date: Mon, 26 May 2003 10:36:31 -0400 Subject: how to extend an instance of visual class: was using RADs in OO way References: Message-ID: On Fri, 23 May 2003 13:05:28 -0500, Donnal Walter wrote: > > A year or two ago I developed a set of "visual proxies" for various data > modeling classes using wxPython. The implementation itself worked pretty > well, but in practice this pattern didn't fit my framework as well as I > had hoped. In the end, I abandoned that approach for what I call the > Model-View-Presenter (MVP) framework similar to Dolphin Smalltalk. It > differs from the MVC architecture in that each "Presenter" wraps a > wxPython "View" and adds code to automatically connect to a "Model" > inside the data model (as well as simplifying layout, and so on). > > If you want to see some code, look in the CVS repository at: > http://sourceforge.net/projects/mindwrapper > > Look under Mindwrapper/presentation. It is still quite preliminary, but > it might give you some ideas. Thanks, Donald, Your code is very interesting and I it's really inspired me. -Serge ========================================================================= Dr. Serge Boiko Laboratory of Advanced Statistical Methods Max-Planck Institute for Demographic Research Rostock, Germany From bokr at oz.net Fri May 9 12:50:03 2003 From: bokr at oz.net (Bengt Richter) Date: 9 May 2003 16:50:03 GMT Subject: List of available codecs References: Message-ID: On 08 May 2003 07:19:12 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >bokr at oz.net (Bengt Richter) writes: > >> How close is >> import codecs >> codecList = [x for x in dir(codecs) if x.find('_decode')!=-1 or x.find('_encode')!=-1] >> ? > >Almost useless. People would expect "koi8-r", "iso-8859-2", "cp1252", >etc in the result, as these are all strings you can pass to codecs.lookup. > D'oh ;-/ Regards, Bengt Richter From dave at pythonapocrypha.com Sat May 17 16:16:48 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 17 May 2003 13:16:48 -0700 (PDT) Subject: TCP Portforwarding In-Reply-To: <20030517152634.GA754@thomas-guettler.de> References: <20030517152634.GA754@thomas-guettler.de> Message-ID: On Sat, 17 May 2003, Thomas Guettler wrote: > I want to forward a tcp port to a remote machine: > > localhost:2000 --> remote:80 > > All requests to localhost:2000 should be forwarded to remote:80. I > thought that this would be easy, but it is more difficult as I > thought. > > I think this should be possible with less than 100 lines. Or am I > wrong? That's seems about right for something simple, although it may grow beyond that with error handling code. Is this port-forwarder protocol agnostic or do you know something about the nature of the traffic? > socket.recv() needs a buffer length. Which length is advisable? Doesn't matter too much for many applications - use 64k. > What are the pros and cons of select vs. poll? Poll is more efficient and can handle a larger number of active connections. If you're doing less than about 1000 then it won't matter too much which you use. -Dave From sandysj at juno.com Mon May 12 12:14:01 2003 From: sandysj at juno.com (Jeff Sandys) Date: Mon, 12 May 2003 16:14:01 GMT Subject: [OT] developers needed References: Message-ID: <3EBFC849.A767A3B4@juno.com> How would it be different than (or an improvement of) PAWS? http://w3.one.net/~wolf/PAWS.shtml Thanks, Jeff Sandys Michael Anckaert wrote: > ... > I'm developping a text adventure written entirely in Python. ... From gh at ghaering.de Fri May 30 09:06:23 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 30 May 2003 15:06:23 +0200 Subject: control the directory installation of files with bdist_wininst? In-Reply-To: <62ec7e1c.0305300446.2a2e3279@posting.google.com> References: <62ec7e1c.0305300446.2a2e3279@posting.google.com> Message-ID: <3ED7574F.4030701@ghaering.de> David wrote: > I've made a window installer of some files with bdist_wininst. but I > didn't succeed to control the directory installation. > The file created with bdist_wininst makes the installation of my files in > C:\python22. > I'd like to change this directory installation. You can't currently install stuff outside the Python root dir. Making the install path user-selectable at install time has been on the TODO list for some time (look into the source for the bdist_wininst for this). FWIW my modules usually end up in site-packages. -- Gerhard From warlock at eskimo.com Fri May 9 04:46:13 2003 From: warlock at eskimo.com (Jim Richardson) Date: Fri, 9 May 2003 01:46:13 -0700 Subject: Gui Advice Needed: wxPython or PyQT ? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 9 May 2003 08:49:44 +0100, Phil Thompson wrote: > On Thursday 08 May 2003 11:05 pm, David Bolen wrote: >> Phil Thompson writes: >> > The number of users refers to the number of concurrent users. I >> > think the Qt license is similar. It is the customer's responsibility >> > to ensure that the usage does not contravene the license. Most >> > organisations will buy additional licenses to eliminate the risk - >> > (...) >> >> Are you sure about this? I think I'll follow up with TrollTech (since >> this would help me out), but from their Qt commercial license info at >> http://www.trolltech.com/products/qt/licensing.html: >> >> "It is a per-developer license. It is assigned to an individual. It >> may be transferred, but only every six months and within the same >> organization. To transfer a license contact sales at trolltech.com." >> >> which sure sounds to me like a pure per-developer license and not a >> concurrent license. >> >> Likewise, from your site the phrase: >> >> "The right for a single developer to write applications under both >> Windows and UNIX/Linux." >> >> led me to believe it was a pure per-developer license and not >> concurrent. If it's really concurrent, that's a big improvement to my >> mind. > > The PyQt licenses are based on the Qt ones - but I did make changes and this > may have been one of them because I simply didn't want the hassle of tracking > individual users. I prefer to spend my time improving the package. A PyQt > license is not tied to a named developer. > > Phil > BTW. Thanks for PyQT, it's loads of fun :) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+u2rVd90bcYOAWPYRAnNmAJ4qMUACnvfcuf5R7CMQW8iuzuHcKwCdELk5 sprY+/NNKhFvwCIxGa+03zw= =C9Xq -----END PGP SIGNATURE----- -- Jim Richardson http://www.eskimo.com/~warlock Linux, because eventually, you grow up enough to be trusted with a fork() From hst at empolis.co.uk Thu May 29 11:41:23 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Thu, 29 May 2003 16:41:23 +0100 Subject: Array design question Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F4BA@hendrix.empolisuk.com> Peter Slizik wrote: > > Hi pythoners, > > after changing some messages in the 'Two dimensional > array' thread, > the discussion turned into somewhat philosophical debate on the way > Python works with arrays. > > I've been working with languages like PHP and Perl for some time. > Things so simple in PHP looks very difficult in Python (at > least for me). > > Simple PHP code > > a[1] = 'aaa' > a[2] = 'bbb' > a[3] = 'ccc' > > will in Python read > > a.append('aaa') > a.append('bbb') > a.append('ccc') > > which is in my opinion uglier than PHP code. > > I just don't understand, why Python doesn't allow to exceed array > boundaries. PHP and Perl would resize the array in this case. > > Let's have a simple example. Suppose we have the file in format > 7 "Text 1" > 5 "Text 2" > 3 "Text 3" > ... > ... > > Our task is to read the content of the file into the array. > > Simple PHP code > > while( !eof() ) { > line = readline(); > (number, text) = split(line); > array[number] = text; > } > > seems untranslatable into Python. The first attempt to store > an object > with index 7 into array before other 6 objects are stored there, will > cause an exception. But the numbers in the input file aren't in any > special order. > > Is there any reason why Python designers chose this concept? > Wouldn't it > be more convenient to have PHP-like arrays in Python too? > > -- Peter I think part of your problem is that you are comparing a PHP array with a Python list, whereas a PHP array is much more akin to a python dict. So an equivalent of your PHP code in Python is: array = {} for aline in afile: number, text = split(aline) array[number] = text which bears more than a passing resemblance to your PHP code. _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From nav at adams.patriot.net Fri May 2 12:00:58 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 02 May 2003 12:00:58 -0400 Subject: It never fails (bsddb retirement in 2.3) References: <7x1xziibnz.fsf@ruckus.brouhaha.com> Message-ID: "Martin v. L?wis" writes: > That looks like bsddb 1.85, indeed, except that it is perhaps > DEC/Compaq/HP modified. DEC rarely touched anything without adding their own special... flavor to it. > Ok. If you want bsddb185 to be built by default with setup.py, please > submit a patch to SF. That patch should [ .. ] > If you can't/don't want to produce such a patch, you might want to find > somebody else who does. I'm going to save your message and see if time allows me to follow through. I'm also going to try Skip's suggestion of modifying Setup/Modules and site.py in combination to get the behavior I had in 2.2.2. There's been an implication in a couple of messages I've received that I'm trying to hold the Python community back, or prevent it from moving forward with a better library. That's not the case at all. I don't think it's unreasonable of me to be perturbed that behavior that I relied upon in one version has changed, especially since one of the selling points of Python is that it traditionally is very backwards compatible. When "import bsddb" gives a new set of features and requires a different library from the one that a previous version used quite happily, I consider that not being backwards compatible. Discovering these issues is part of a beta test, is it not? Wouldn't it make sense, to some degree, to require the _new_ functionality use a new module name, instead of changing the behavior of an existing one? I'm trying very hard to get Python accepted where I work. Anything that makes installing it more complicated is going to make it harder to get it accepted. Overt breakage of backwards compatibility is going to be even wose. Due to the nature of the work environment, I ma not have root access on the systems, and I will have to write up instructions for installing the software. With that in mind, would I be better off using a different library, or abandoning this avenue for improving the performance of the programs in question? Well, thanks to anyone who's bothered to read the rambling post that this message has become... 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 max at alcyone.com Fri May 30 18:16:03 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 30 May 2003 15:16:03 -0700 Subject: CGI question: safe passwords possible? References: Message-ID: <3ED7D823.F3E9D51D@alcyone.com> Will Stuyvesant wrote: > I do CGI programming with Python and I know how to make HTML forms > with "user" and "password" fields. But these get sent "in the clear" > over internet, somebody told me. I have no power over the webserver > (it's in the hands of my service provider and they generally do not > want to install/change/configure thing). Is there any way to do > Name+Password safely using just CGI and Python, so only users with a > valid Name+Password can get access to the next CGI scripts? There are ways to minimize the duration of the password exposure (e.g., authenticate and redirect to another page that bundles the session information in an unreadable "ticket" that binds to the user and IP address so someone else can't use it for its duration), but with pure CGI there's no way to eliminate the exposure itself. The only solution is to run the CGI scripts under SSL, which requires changing the Web server. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ It's just another day / And nothing's any good \__/ Sade From danb_83 at yahoo.com Mon May 5 01:31:18 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 May 2003 22:31:18 -0700 Subject: _tkinter installation problem with Python 2.3b1 Message-ID: I'm installing Python 2.3b1 on my Linux box, by compiling from source (with gcc 2.95.2 and glibc 2.2.5). Everything seems to work fine except the _tkinter module. building '_tkinter' extension gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/home/dan/.Python-2.3b1/./Include -I/usr/local/include -I/home/dan/.Python-2.3b1/Include -I/home/dan/.Python-2.3b1 -c /home/dan/.Python-2.3b1/Modules/_tkinter.c -o build/temp.linux-i686-2.3/_tkinter.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/home/dan/.Python-2.3b1/./Include -I/usr/local/include -I/home/dan/.Python-2.3b1/Include -I/home/dan/.Python-2.3b1 -c /home/dan/.Python-2.3b1/Modules/tkappinit.c -o build/temp.linux-i686-2.3/tkappinit.o gcc -shared build/temp.linux-i686-2.3/_tkinter.o build/temp.linux-i686-2.3/tkappinit.o -L/usr/X11R6/lib -L/usr/local/lib -ltk8.4 -ltcl8.4 -lX11 -o build/lib.linux-i686-2.3/_tkinter.so *** WARNING: renaming "_tkinter" since importing it failed: libtk8.4.so: cannot open shared object file: No such file or directory running build_scripts But the file /usr/local/lib/libtk8.4.so does exist. What's going on? From graham at rockcons.co.uk Mon May 19 15:28:39 2003 From: graham at rockcons.co.uk (Graham Nicholls) Date: Mon, 19 May 2003 20:28:39 +0100 Subject: Announcement: Obfuscated Python competition References: <3ec91012$1_2@hpb10302.boi.hp.com> Message-ID: Jeff Epler wrote: > On Mon, May 19, 2003 at 11:10:41AM -0600, Daniel Fackrell wrote: >> ---- >> #include >> int main() { >> int x; >> x = 0; >> x = ++x + ++x + x++ + x++; // This is legal C code, but what does it >> do? printf("x is %d", x); >> return 0; >> } >> ---- >> gcc under Cygwin/Linux: "x is 10" >> cc on HPUX: "x is 8" >> gcc under HP/UX: "x is 3" >> >> Just as a note, there were no warnings or errors while compiling. > > This is syntactically valid C code, but the standard specifically states > that it produces undefined results. > > And, I should note, I *do* get compiler errors on this program: > $ gcc -Wall -ansi -pedantic fackrell.c > fackrell.c: In function `main': > fackrell.c:5: warning: operation on `x' may be undefined > fackrell.c:5: warning: operation on `x' may be undefined > fackrell.c:5: warning: operation on `x' may be undefined > fackrell.c:5: warning: operation on `x' may be undefined > fackrell.c:5: parse error before '/' token > Quite. > Jeff I reckon its possible to write bad code in any language. So if it hasn't been done already, how about an obfuscated Python competition. Prize : One of my Perl books - lets see: "Perl in a Nuthouse" looks good. BTW I reckon I'll have to keep up to date in both Perl & Python if I'm going to make the switch - theres a _lot_ of perl out there. Some of it is readable ( I reckon my own code to be readable, and take a pride in it being so, but who knows...) Graham -- Graham Nicholls All round good guy. From aleax at aleax.it Fri May 16 09:56:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 16 May 2003 13:56:17 GMT Subject: OT: Mandrake 9.1 References: Message-ID: <566xa.183807$K35.4298988@news2.tin.it> Aahz wrote: > IIRC, someone (Alex?) was complaining about not getting Mandrake 9.1 > shipped on time. I finally received my copy today, and I had a much Yep, it was me. I installed it on a brand-new machine and is seems to be doing just fine (except that I can't get it to do sound -- within KDE, haven't tried other ways -- in any form). Then my main machine running 9.0 suddenly decided to go crazy on me after many months of solid and reliable service -- in the end, in desperation, I tried upgrading to 9.1 and at long last got it working again. Sound seems to have disappeared without a trace (!) but apart from that I did manage to fix just about everything else I've tried so far. Finally, my new Fujitsu Piranha from EmperorLinux just came with Mandrake 9.1 preinstalled (at my request -- they normally install their own distro) and there everything I tried (sound included) appears to work. Overall, it seems a satisfactory upgrade (and maybe one day I'll have enough time to invest to find out where the sound went on my two desktops...!). > Yeah, yeah, next time I'll stick with Debian. Well, yes, it IS a temptation one gets some of the time;-). Alex From kdahlhaus at yahoo.com Wed May 21 15:37:03 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 21 May 2003 12:37:03 -0700 Subject: Newbie poll: GUI building in Python References: Message-ID: <283adf56.0305211137.38f36ced@posting.google.com> I use SpecPython which is a plugin for SpecTCL which is a free TCL gui builder. Also, the newly resurrected FLTK python wrappers can generate code from the FLTK FLUID gui builder. C42 wrote in message news:... > After spending some time researching wxPython and Tkinter, I can't help > but wonder, "Do most people create their original GUI designs from a > text file or do they use some other tool (wxDesigner, etc.)?" > > I must admit that I am from a VB world and designing my GUIs via text is > somewhat unusual to me. From max at alcyone.com Tue May 6 17:52:18 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 May 2003 14:52:18 -0700 Subject: Why use backticks? References: <3eb81743$0$123$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <3EB82E92.B554CE86@alcyone.com> Iwan van der Kleyn wrote: > But why this rather obscure use of backticks? Is there any use for > them > except making code harder to read ? :-) Nope. Common convention dictates that the use of repr directly is preferable to that of backquotes. -- 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 impossible to love and be wise. \__/ Francis Bacon CatCam / http://www.catcam.com/ What do your pets do all day while you're at work? Find out. From g2h5dqi002 at sneakemail.com Tue May 20 21:08:15 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 21 May 2003 13:08:15 +1200 Subject: language aesthetics In-Reply-To: References: Message-ID: Mike Rovner wrote: >>[Perl] leads straight to madness, in an orgy of syntax and notation like the >>programming world has never seen before. Oh well, we'll see... > > Why, IMHO APL was similar mad and insane :) It's a very different flavour of insanity, though, IMO. Perl is just a random hodgepodge, whereas APL is a distillate of elegance, conciseness and consistency that's too potent for human consumption... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From timr at probo.com Thu May 15 23:40:56 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 15 May 2003 20:40:56 -0700 Subject: Where does win32 python command prompt history happen? References: <3ec27298_2@news.unc.edu> Message-ID: Nomad wrote: >> >>in win9x days one had to enably doskey in the auotexec.bat file to get this. >>afaik, at least since win2k, this has been part of the command prompt. I >>doubt it is in the kernel, but it is part of windows. > >I don't think it's part of windows while it's in the Python >interactive console. Why not? Python gets its input by reading from stdin. As soon as it reads from stdin, the process is under the control of Windows. As far as I know, the original poster is correct: doskey maintains this history automatically. >IIRC it's part of the readline library. It is on the Linux-like systems, but I didn't think gnu readline was part of Python on Windows. Plus, it doesn't answer the original question "where is the history stored"? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aahz at pythoncraft.com Tue May 6 19:53:28 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2003 19:53:28 -0400 Subject: Raising objects References: Message-ID: In article , Michael Chermside wrote: >Aahz wrote: >>Greg Ewing wrote: >>> >>> there's no reason that "raise C, v" couldn't be eliminated in favour of >>>"raise C(v)". >> >> I see no point in making that change until print is no longer a >> statement. > >What on earth is the connection between raise and print? They're both statements that use a comma form instead of call form. >From my POV, there's no special advantage to removing the comma form of raise, so it might as well stay until we fix print. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From owen at nojunk.invalid Wed May 7 11:40:11 2003 From: owen at nojunk.invalid (Russell E. Owen) Date: Wed, 07 May 2003 08:40:11 -0700 Subject: The most annoying typo error... References: <9d5509fa.0305070000.55b11d6@posting.google.com> Message-ID: It hits me often enough that I wish it were a syntax error or that one could enable a warning for it. But I usually track it down fairly quickly. To those who wonder how such a thing could happen, I personally find it creeping in occasionally when editing existing code, e.g. via sloppy modification of an argument list. -- Russell In article <9d5509fa.0305070000.55b11d6 at posting.google.com>, pballard at ozemail.com.au (Peter Ballard) wrote: >...You spotted the error immediately didn't you? The line of code above >has a trailing comma, so that x is suddenly a tuple; and so when I get >around to using x I get a TypeError. > >I don't know about anyone else, but for me, this error always takes a >long time to track down.... From linux42 at freemail.c3.hu Thu May 8 05:59:10 2003 From: linux42 at freemail.c3.hu (Nagy Gabor) Date: Thu, 8 May 2003 11:59:10 +0200 Subject: memory usage In-Reply-To: References: Message-ID: <20030508095910.GH4316@swordfish.capgemini.hu> On 03-May-07 14:16, John Machin wrote: > Nagy Gabor wrote in message news:... > > I wrote a simple datafile parser, and it is quite memory hungry, and I > > don't know if this is what I should expect, or is there a bug in my code. > [snip] > > def ParseFields(): > > fields = [] > > for ...: > > Data = StringIO.read( length) > > You probably have trailing spaces or leading zeroes here; if so, this > would be adding to your memory problem. Yes, I have some, but the vast majority of the memory consumption was not the data stored, but the objects themselves. > > tmp = TD() > > tmp.Tag = T(name = 'name') > > tmp.Data = Data > > fields.append(tmp) > > So for each field, you create a TD instance. One of the attributes of > this TD instance is a *NEW* T instance. This is *TWO* *NEW* class > instances per field. I repeat, PER FIELD. Yes. > You don't say what, if anything, you are doing with the Flag, Class, > and Name attributes of the T-instance. Given that you have field.Data, > what is field.Tag.Value? Does *every* instance of a field need a > field.Tag.Name? You should exploit the (presumed) homogeneity of your > data by factoring out the data description to a higher level e.g. one > per column per table, instead of one per field. E.g. all the > descriptive info for the 23rd column/field in table/record-type "XYZ" > can be found in field_description["XYZ"][22] i.e. field_description is > a dictionary of lists. You would also build an inverted index to get > the field number (e.g. 22) from the field name (e.g. > "salary_of_data_modeller") Since the memory wasted does not come from the data I wanted to store, I did not try to make everything so complex. > You should also consider combining the T and TD classes -- it is not > apparent from your code if the current separation achieves anything > positive; negatives include waste of memory and CPU, plus visual and > mental clutter. Actually, I have combined the T and TD classes. Thus creating only one new class instance per field gave me 122M memory usage (so about the half, what I had before). I have omitted every class instance now, and store every data in a tuple, and the memory usage has dropped to 43M. Anyway, when I learnt OO paradigm, I learnt that if I think of something as a different "thing", I should create a class for that. Right now, T contains information about the encoding/representation of the field in the source file (which is needed to display or to recode it), and TD contained the field data (and T). To save memory, now I have only one TD object per field, containing everything, which I don't really like. I think this is visual and mental clutter. For example there are data from different sources, where T would not present. Now it will always be there. I don't like this, but if it cuts memory requirement in half, OK. Alas, the tuple thing I cannot use (which would anyway be a complete throw away of the whole OO paradigm), as this particular source and format had a lowest level with 600k fields, but other sources and formats don't have a common lowest level. So I have to waste 2 times the memory required if I go on using 1 class, or I could try to rewrite everything, and store the leaf nodes in tuples. Maybe I'll to this. > Of course you could avoid the effort involved in a design strategy > rethink and get some big-enough tactical wins by (1) using __slots__ > [mentioned by others, but they didn't remind you that this works only > with new-style classes; __slots__ is silently ignored in a classic > class] Actually I found out that using new style classes took about 1/4 of the memory thang an old style one, (when empty), and this gave me about 30M. Using __slots__ in a new style class did not give me any more memory gain. > Looking at the other dimension of your MxN problem, why do you think > you need to keep each row/record in memory? Because you cannot tell in which object will a newly read field be attached to. So I cannot start the writeout until the whole source is read. Generally. Some formats are special, of course. Usually I could write out subtrees, as the fields are usually sorted, so the fields related to an object come after each other. Regards, G From tbryan at python.net Tue May 20 08:02:45 2003 From: tbryan at python.net (Tom Bryan) Date: Tue, 20 May 2003 12:02:45 GMT Subject: A little disappointed so far References: <3EC82983.F53B4543@alcyone.com> Message-ID: Graham Nicholls wrote: >>> > What things seem very hard? >>> Regular expressions. >> >> In most cases where you'd need them in other situations, you can avoid >> them. I avoid regexps at all costs. > No, I completely disagree. Without regexps, I may as well use c, which I > can code in my sleep. I'm not sure that's what he meant. The string methods are quite powerful and clear. (See the string module, but know that most of the string module's functions are now methods on the strings themselves.) The os.path module is also quite handy. Finally, since strings are immutable lists of characters, you can index and slice them. What I found in porting many Perl scripts to Python is that I could (and should!) replace about half of the regular expressions with something else from Python. I think that since regexps are built into Perl, many Perl programmers use regexps to do something as simple as # does the string end in a slash if ($myString =~ /\/$/) Where in Python, that would be if myString[-1] == '/': For problems that really require a regular expression, use the re module. It is as powerful as Perl regexps, but it will certainly not be quite so convenient. That was my experience anyway. Having switched from Perl to Python for most of my shell and string processing needs, I can say two things. 1) For occasional use, Python is much easier to remember. I use it every few weeks. When I used to do that with Perl, I kept forgetting important built in stuff and special cases. 2) For steady use, Python nudged me toward better and more reuse. A script file is already in a module with its own namespace, ready to be reused. To reuse a script, I started to package work into functions. I built data structures (classes), often attaching behavior (methods) to them over time. After a few weeks, I found that writing code in Python had become much faster because I already had packaged up a bunch of code in a reusable manner. With access to those modules, I was usually able to concentrate on the interesting bits of a problem because all of the "easy" stuff was already done in the modules. It sounds like you do a lot of Perl, so the first point probably doesn't really matter to you. As far as the second point, if you already have a bunch of packages or modules in Perl, then you're already there in Perl. I just found this type of packaging for reuse to be difficult in Perl. In Python, it's just the opposite. I find it difficult to write code without accidentally packaging it well. That's why everything I write in Python starts out like this def main(): pass if __name__ == '__main__': main() That way, I can start writing code for main. If I find something that seems generally useful, I push it out into a function or a class. Then, with that "if __name__ == '__main__'" guard, other modules can safely import this module to access that function or class. After doing this for a while, I move similar functions and classes into their own module. Since main already just calls a function, say foo(), I just move the definition of foo to some common module Bar and write from Bar import foo I find that Bar grows quickly into something useful for even small projects. Try it for a few weeks and see whether you end up growing your own in house modules full of stuff that you can reuse. ---Tom From theller at python.net Thu May 22 03:50:46 2003 From: theller at python.net (Thomas Heller) Date: 22 May 2003 09:50:46 +0200 Subject: Using a type library with win32com References: <3fa18b12.0305210619.2b51e0f3@posting.google.com> Message-ID: <4r3npgh5.fsf@python.net> jpersson1 at yahoo.com (Jan Persson) writes: > Hi, > > I have not seen a good answer to this in the previous (old) postings, > so here we go again. > > I would like to create a COM-server in Python (with an ordinary > IDispatch interface) together with a type library (tlb file), so that > environments which relies on type library information can be able to > instantiate my class. > > From the previous postings I have learnt to do the following: > > 1. Create the Python class that implements my automation-server. > 2. Create an IDL-file and compiled it with midl.exe. > 3. Take the resulting tlb-file and register it with REGTLIB.EXE > 4. Register the Python class with > win32com.server.register.UseCommandLine(). > > But this does not seem to work. > > Is this the correct way to do it or is win32com able to generate > typelib information on it's own? > > Does anyone have a working example on how to accomplish this? If you want to live on the edge, you could check out the ctypes' COM framework. It is supposed to have good support for type libraries and will allow to implement and use custom and dual interfaces (pure dispinterfaces are not too much my target for now). There are some severe limitations at the moment because it is work in progress, but the basic components are in place (except that currently you can only implement local servers, not inproc servers). I just started writing some documentation, and there is a sample which implements (and uses) a dual interface described in a type library: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/ctypes/ctypes/docs/sum_sample.stx?rev=1.1&content-type=text/vnd.viewcvs-markup The ctypes home page is at http://starship.python.net/crew/theller/ctypes.html. Thomas From mal at egenix.com Wed May 14 16:19:32 2003 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 14 May 2003 22:19:32 +0200 Subject: ANN: eGenix mxODBC Zope Database Adapter, Version 1.0.6 Message-ID: <3EC2A4D4.6070709@egenix.com> ________________________________________________________________________ ANNOUNCEMENT EGENIX.COM mxODBC Zope Database Adapter Version 1.0.6 Available for Zope 2.3 - 2.6 on Windows, Linux and Solaris ________________________________________________________________________ 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. Unlike Zope's ZODBC Zope DA, the mxODBC Zope DA works on Windows XP/NT/2000/98/95, Linux and Solaris using the same interface on all platforms. 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. ________________________________________________________________________ FEATURES * Zope Level 3 Database Adapter: the mxODBC Zope DA is fully multi-threaded and can handle multiple connections to multiple databases. * Fully compatible to Z SQL Methods. * Drop-in compatible to the ZODBC DA: the mxODBC Zope DA provides the same interfaces as Zope's ZODBC DA to allow a smooth upgrade path from this simplistic adapater to the high performance mxODBC Zope DA. * Fully compatible to the Znolk SQL Wizard Product and other similar products relying on the common database schema access methods .tables() and .columns(). * Connection Pooling: physical database connections are pooled and kept open, to reduce the connection overhead to a minimum. This is especially important for high latency database connections and ones like Oracle which take a considerable amount of time to setup * Parallel Execution of Queries on a single logical connection: the mxODBC Zope DA can manage any number of physical connections on a single logical connection. This enables running truly parallel Z SQL Method queries -- a feature not available in other Zope DAs. * Robust Mode of Operation: connections which have timed out or go away due to network problems are automatically reconnected. * Cross-platform Connection Objects: The Zope DA will automatically choose the right platform specific ODBC manager for you. * Per Connection Adjustable ODBC Interface: mxODBC comes with many different subpackages to choose from on Unix. The Zope DA allows you to select these subpackages on a per-connection basis. * Per Connection Error Handling: you can tell each connection whether it should report ODBC warnings or not; furthermore all warnings and errors are made available as list .messages on the DatabaseConnection object. * Transaction safe automatic reconnect: when the DA finds that a connection has timed out, it automatically tries a reconnect and replays the transaction on the connection (unlike other DAs which break the transaction scheme by doing a reconnect without replay). * Built-in Schema Cache: this results in improved performance under heavy load. * Database Schema Access: all ODBC catalog methods are made available for much better database schema inquiry. The catalog methods allow building generic database interrogation or manipulation tools and facilitates writing database independent Zope products. * Lazy Connect: the mxODBC Zope DA only connects to the database backends when a connection is actually requested. This results in a better use of resources compared to other Zope DAs. ________________________________________________________________________ NEWS Version 1.0.6 includes the following changes and enhancements: * The lazy connect feature was turned into a per-connection option. This gives you more control over which connections are maintained in connect-on-demand state and which are always connected. * A new option was introduced to let the mxODBC Zope DA return the natively used mxDateTime values instead of converting them to Zope's DateTime instances. This is a faster if you're dealing with a lot of date/time values and also provides more flexibility in data access. See the mxDateTime documentation for full details on what this package can offer. * A bug in the version 1.0.5 lazy connect feature was fixed. In short: mxODBC Zope DA is continuing to become the number one solution for integrating relational databases with Zope applications. ________________________________________________________________________ UPGRADING If you have already bought mxODBC Zope DA licenses, you can use these license for the updated version as well. There is no need to buy new licenses. The same is true for evaluation license users. ________________________________________________________________________ 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, May 14 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ EuroPython 2003, Charleroi, Belgium: 41 days left From http Mon May 12 06:07:40 2003 From: http (Paul Rubin) Date: 12 May 2003 03:07:40 -0700 Subject: string interpolation (Was: Newbie can't figure out documentation practices) References: <3EBF6C65.428712C5@alcyone.com> Message-ID: <7xr874jx5f.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > I don't know, it doesn't seem all that awful to me in Python: > > >>> name = "John" > >>> age = 23 > >>> "The age of %(name)s is %(age)d." % locals() > 'The age of John is 23.' I'm sorry, but that is awful. From gustav at morpheus.demon.co.uk Sat May 10 18:09:43 2003 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Sat, 10 May 2003 23:09:43 +0100 Subject: Abstracting algorithms (graph depth first search) References: Message-ID: "Raymond Hettinger" writes: > I took the class based approach and it is just a fast as a toplevel > function. Users subclass the solver and supply ann iterator or > generator for the edges from each node. That's good to know. Instinctively, it felt like it would be slow, but instinct isn't a particularly good guide here... > The generic solver is about 25 lines. That's the frustrating thing - writing this stuff really is easy in Python. The problem comes in remembering the details of the algorithms. I can write 25 lines of Python no problem. 25 *working* lines seem to elude me, though :-) I'm still working through the options and trying to decide whether the extra 25 lines of infrastructure are worth the time saved making sure the algorithm's correct :-) But I was definitely right in one thing - graph algorithms are complex enough to be interesting, without being too specialised to be worth bothering with unless you have a specific need. [Just wrote a Python version of some C++ graph code, which took a fraction of the space, and was far more readable. Thanks, Guido :-)] Paul. -- This signature intentionally left blank From jdhunter at ace.bsd.uchicago.edu Wed May 7 16:46:36 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 07 May 2003 15:46:36 -0500 Subject: Used to 'file = open(...)', now what? In-Reply-To: <20030507204048.GA22228@pedos.es> (Grzegorz Adam Hankiewicz's message of "Wed, 7 May 2003 22:40:48 +0200") References: <20030507204048.GA22228@pedos.es> Message-ID: >>>>> "Grzegorz" == Grzegorz Adam Hankiewicz writes: Grzegorz> But with Python 2.2 file() is a builtin constructor, Grzegorz> making open deprecated, possibly dropped in a future Grzegorz> version. Now what would be the "usual" way to name file Grzegorz> variables without hiding the constructor? I sometimes use fh = file('somefile.dat') # for file handle or fi = file('somefile.dat', 'r') # for file input fo = file('somefile.dat', 'w') # for file output or if you like longer names inFile = file('somefile.dat', 'r') outFile = file('somefile.dat', 'w') Also, often you don't need to name it at all for line in file('somefile.dat'): print line I don't think there is 'a preferred way'. JDH From aleax at aleax.it Thu May 8 06:57:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 08 May 2003 10:57:35 GMT Subject: How to split() by multiple characters? References: Message-ID: Nick Forest wrote: > Given an piece of text in a long string, how to split() it by ',' or '.' > or ';' ... > > i.e. text.split ( '[,.;]' ) > > Of course, the code doesn't work. :-( > Is there any good way to do this? Standard library module re is one way. If you want to avoid re, you can do it with string operations too, e.g.: >>> text = 'fee,fie;foo.fum' >>> import string >>> tt = string.maketrans(',;', '..') >>> text.translate(tt).split('.') ['fee', 'fie', 'foo', 'fum'] i.e.: translate all characters you want to use as splitters into just one of them, then split by that one. When you have TWO good alternatives, you may sometimes want to choose between them on the basis of performance. The timeit.py module in the Python 2.3 standard library is great for that, e.g.: [alex at lancelot Lib]$ python timeit.py -s''' text="fee,fie;foo.fum" import string tt = string.maketrans(";,","..") ''' 'text.translate(tt).split(".")' 100000 loops, best of 3: 3.65 usec per loop [alex at lancelot Lib]$ python timeit.py -s''' text="fee,fie;foo.fum" import re punct = re.compile("[.;,]") ''' 'punct.split(text)' 100000 loops, best of 3: 5.83 usec per loop Of course, you'll want to use a text value that is more representative of the kinds of texts you DO often have to split, as well as run this on the machines that matter to you and the Python versions you'll be using "in production" (fortunately, although it's in the standard library for 2.3, module timeit.py seems to run just fine with 2.2.2 as well!). Personally, I nominate timeit.py as THE outstanding enhancement of Python 2.3 -- I love many of the others (the performance improvement in particular), but timeit.py is the one I find myself using all of the time -- seems to provide an innocuous way for programmers' typical obsession with performance and micro-optimization to discharge itself harmlessly, cleansing their souls to choose idioms on the basis of clarity, maintainability and readability, as of course SHOULD be done:-). Alex From nirina at mail.blueline.mg Sat May 31 08:16:59 2003 From: nirina at mail.blueline.mg (Raseliarison nirinA) Date: Sat, 31 May 2003 16:16:59 +0400 Subject: Request for feedback on my first Python program References: Message-ID: <005801c3276e$eeecfba0$f7a2383e@raseliar> "Scott Meyers" writes: > - Is it better to get into the habit of (a) importing modules and using > fully qualified names or (b) importing selective names from modules > and using them without qualification? That is, which is generally > better? > > import sys # a > sys.exit(1) > > from sys import exit # b > exit(1) > i cannot tell which is better. personally, i choose between them following the context. for example, with the form (a), one can use the same function names in several modules. and when i use Tkinter, i always call: from Tkinter import * sometimes, the built-in function __import__ is useful: SYS = __import__('sys') QUIT = getattr(SYS,'exit') QUIT(1) if you want only one function from a module, you can specify its name, like this: from sys import exit as QUIT QUIT(1) also, take a look at the imp module: >>> import imp >>> help(imp) Help on built-in module imp: NAME imp FILE (built-in) DESCRIPTION This module provides the components needed to build your own __import__ function. -- nirinA -- From matthiasjanes at lycos.com Mon May 26 06:24:17 2003 From: matthiasjanes at lycos.com (Matthias Janes) Date: 26 May 2003 03:24:17 -0700 Subject: CTypes wnetaddconnection2 Message-ID: <6fe9740b.0305260224.65c4c5e2@posting.google.com> I have one question about the usage of "CTypes" I have some scripts using the "Mark Hammond's win32all" win32all-153.exe extention. I would like for certain reason to use the CTypes module. Could not figure out some things - maybe you could help me - with some kind of hints. 1. FIRST get Remote Access to a PC : parts of my script at this moment #!/usr/bin/env python #________________________________________________________________________# # # BEGIN: get privileged user access to Pc # import win32net, win32netcon, win32wnet IP = "10.199.61.3" LocalName = None RemoteMachine = "\\\\" + IP ProviderName = None win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY,LocalName,RemoteMachine,ProviderName,"PrivilegedUser","PrivilegedUserPassword") # # END:get privileged user access to Pc #________________________________________________________________________# CTypes so far:get privileged user access to Pc MS-INFO: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wnet/wnet/wnetaddconnection2.asp DWORD WNetAddConnection2( LPNETRESOURCE lpNetResource, LPCTSTR lpPassword, LPCTSTR lpUsername, DWORD dwFlags ); MS-INFO END! #!/usr/bin/env python #________________________________________________________________________# # # BEGIN: CTypes: get privileged user access to Pc # import ctypes IP = "10.199.61.3" LocalName = None RemoteMachine = "\\\\" + IP ProviderName = None RESOURCETYPE_ANY = 0x0 a=ctypes.windll.mpr.WNetAddConnection2A(RESOURCETYPE_ANY,LocalName,RemoteMachine,ProviderName,"PrivilegedUser","PrivilegedUserPassword") # # END:get privileged user access to Pc #________________________________________________________________________# GET error: ValueError: Procedure probably called with too many arguments (8 bytes in excess) I'm not sure - do I have to make for the 'lpNetResource' DWORD WNetAddConnection2( LPNETRESOURCE lpNetResource, LPCTSTR lpPassword, LPCTSTR lpUsername, DWORD dwFlags ); something like a Structure and how would this be ??? class RECT(Structure): _fields_ = [("upperleft", POINT), "lowerright", POINT)] Thanks for any help. regards, Matthias Janes From aahz at pythoncraft.com Fri May 16 14:02:57 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 May 2003 14:02:57 -0400 Subject: passing by refference References: <87znlng7cf.fsf@charter.net> Message-ID: In article <87znlng7cf.fsf at charter.net>, Doug Quale wrote: > >If you don't agree that this describes call-by-value argument passing, >tell us what Python does differently. Be very specific. All right, you explain this: >>> x = 'foo' >>> '%s' % (x,) What gets printed by the %s? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From BPettersen at NAREX.com Wed May 7 19:47:37 2003 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 7 May 2003 17:47:37 -0600 Subject: Gui Advice Needed: wxPython or PyQT ? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192022DE2F7@admin56.narex.com> > From: Ron Stephens [mailto:rstephens at vectron.com] > > "Bjorn Pettersen" wrote in message > news:... > > > I'm not aware of anything similar for Python/Windows > > (although I haven't really been looking, so please > > prove me wrong :-) > > > > Since I allready own the VS/NET, it's basically free (to > > mee :-), so my problem now is how can I get it to work > > with Python instead of C#? > > > > -- bjorn > > The only thing I can suggest to you is to try PythonCard. It is the > only tool I have found that is as easy as Visual Studio, although > simpler and different. It might not be as easy as Visual Studio for > all tasks, of course, and it is still alpha, but I think you would > enjoy trying it out. It is based on wxPython, but makes creating > simple input-output GUIs pretty amazingly simple. It's nice, although the seven step/3 downloads installation process didn't strike me as a good sign . I think it made me figure out what my problem is though... I can't ever remember the name of the events or the event-handlers. With C#, you double click on the button in design view, which takes you to the codeview, with a ready generated skeleton for your handler... -- bjorn From anton at vredegoor.doge.nl Wed May 7 04:52:23 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 07 May 2003 10:52:23 +0200 Subject: Improve this recursive code please! References: <3EB7DF65.55A50CD4@sarcastic-horse.com> Message-ID: #! /usr/bin/env python """ Function bins returns a list with all possible ways of distributing m bricks into n bins. The partition code is based on pseudo code from Kreher and Stinson. """ def starters(L): #helper function for anagram, returns a list of 2-tuples n,np,R = len(L),1,range(len(L)) bf = [L[:i].count(L[i]) for i in R] for i in R: np = np*(n-i)/(bf[i]+1) return [(i,np*L[i:].count(L[i])/n) for i in R if not bf[i]] def anagram(L,index=0): #return an anagram of list L remain, res, T = index, [], L[:] while T: for j,k in starters(T): if remain-k < 0: res.append(T.pop(j)) break remain -= k return res def nperm(L): #return the number of possible anagrams of list L return reduce(lambda a,b:a+b,[k for j,k in starters(L)]) class Partition: #helper class for partition information def __init__(self,m): self.m = m self.parts = [0]*(m+1) def dump(self,numparts): return [ self.parts[i] for i in range(1,numparts+1)] def recPartition(a,m,B,N,accu=[]): # helper function generates all partitions of m if m == 0: accu.append(a.dump(N)) else: for i in range(1, min([B,m])+1): a.parts[N+1] = i recPartition(a,m-i,i,N+1,accu) return accu def genPartitions(m,n): # generates a list of all partitions of m into at most n parts a = Partition(m) return [x for x in recPartition(a,m,m,0) if len(x) <= n] def bins(m,n): #all possible ways to distribute m bricks into n bins res = [] for p in genPartitions(m,n): while len(p)< n: p+=[0] for i in range(nperm(p)): res.append(anagram(p,i)) return res def test(): #test function bins numbricks, numbins = 3,4 bb = bins(numbricks, numbins) print len(bb) for x in bb: print x if __name__ == '__main__': test() output: >d:\python23\pythonw -u bins.py 20 [1, 1, 1, 0] [1, 1, 0, 1] [1, 0, 1, 1] [0, 1, 1, 1] [2, 1, 0, 0] [2, 0, 1, 0] [2, 0, 0, 1] [1, 2, 0, 0] [1, 0, 2, 0] [1, 0, 0, 2] [0, 2, 1, 0] [0, 2, 0, 1] [0, 1, 2, 0] [0, 1, 0, 2] [0, 0, 2, 1] [0, 0, 1, 2] [3, 0, 0, 0] [0, 3, 0, 0] [0, 0, 3, 0] [0, 0, 0, 3] >Exit code: 0 From frithiof.jensen at removethis.ted.ericsson.dk Tue May 13 10:57:54 2003 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 13 May 2003 16:57:54 +0200 Subject: Problem with Unittest: Message-ID: Hi, I am trying to test some software using unittest with Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 and I am having some problems with exceptions: The simple test script below yields: E ====================================================================== ERROR: test_duffer (__main__.dufferTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\tedfrje\traders_toolkit\test_duffer.py", line 12, in test_duffer self.assertRaises(ValueError(), duffer()) File "C:\tedfrje\traders_toolkit\test_duffer.py", line 7, in duffer raise ValueError() ValueError ---------------------------------------------------------------------- Ran 1 tests in 0.010s FAILED (errors=1) In my opinion, the script should PASS because I specified that a ValueError() was the PASS criteria. What am I doing wrong? Test Script source: """ Try some unittest functions """ import unittest def duffer(): raise ValueError() class dufferTest(unittest.TestCase): def test_duffer(self): self.assertRaises(ValueError(), duffer()) def suite(): duffer_suite = unittest.makeSuite(dufferTest,'test') return unittest.TestSuite((duffer_suite,)) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(suite()) # done. From alanmk at hotmail.com Mon May 12 09:28:11 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 12 May 2003 14:28:11 +0100 Subject: Environment variables - Expand References: <915e0a69.0305120314.34f62f96@posting.google.com> Message-ID: <3EBFA16B.315243D2@hotmail.com> Dips wrote: > For instance, the following command doesn't expand %WINDIR% > automatically > file_name = '%WINDIR%\WIN.INI' > file = os.open(file,'r') OK, you're describing several different problems here. If you want to embed the value of a string variable into another string variable, the python syntax is string1 = "%s\\WIN.INI" % "C:\\WinNT" Now, if you want that Windir to be an environment variable, you can do as follows. import os string1 = "%s\\WIN.INI" % os.getenv("WINDIR") > In actual 'file_name' is fed as command-line argument and so can > contain any environement variables. But this is different. If you want to use command line arguments, use sys.argv. For example import sys filename = sys.argv[1] However, if you are setting the filename parameter using Windows command shell commands, then all of the relevant environment variable substitution and expansion should be carried out by the Windows command shell, and happen before python does anything. For example SET WINDIR=C:\winnt python myscript.py %WINDIR%\WIN.INI In this case, the Windows command shell should substitute the value of the WINDIR variable *before* it passes the argument to python. So the first argument will become "C:\winnt\WIN.INI". So python should see the argument "C:\winnt\WIN.INI", with no environment variable substition required from you. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From andrew at acooke.org Mon May 5 16:06:26 2003 From: andrew at acooke.org (andrew cooke) Date: Mon, 5 May 2003 16:06:26 -0400 (CLT) Subject: Should I write a book on Python Metaprogramming ? In-Reply-To: <43765.127.0.0.1.1052164628.squirrel@127.0.0.1> References: <7h31xzd1akd.fsf@pc 150.maths.bris.ac.uk> <43765.127.0.0.1.1052164628.squirrel@127.0.0.1> Message-ID: <2297.10.2.0.2.1052165186.squirrel@127.0.0.1> andrew cooke said: [...] > for me that's a much more interesting book than one that focuses on higher > order abstractions (it also implies a very language-specific focus, hence > my confusion about how the book could be general). however, i get the > impression i'm in a distinct minority (even more so considering i'm not > that bothered about code examples :o) so it's probably not the book you > should be writing... (otoh i can think of several books - sicp, cousineau > + mauny - that already do that kind of thing very well, although not in > python) PS i guess i want "on lisp" rather than sicp, if you get my drift... PPS http://mitpress.mit.edu/sicp/ <- sicp -- http://www.acooke.org/andrew From staschuk at telusplanet.net Mon May 19 15:53:18 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 19 May 2003 13:53:18 -0600 Subject: A little disappointed so far In-Reply-To: ; from graham@rockcons.co.uk on Mon, May 19, 2003 at 11:44:58AM +0100 References: <3ec82283.12251706@news.cybermesa.com> <3EC82BDA.99A62358@alcyone.com> Message-ID: <20030519135318.C853@tibia.amotlpaa.bogus> Quoth Graham Nicholls: [...] > Absolutely, but as I mentioned, the docs won't print if you download teh A4 > version. Go on , try it ... ( I don't _think_ its just me - the a4 > versions are much larger than the US ones). [...] I'll take your word for it. I haven't tried printing any of those pdfs and have no motive for doing so. > [...] Browsing online is a pain when > your in the middle of editing. It's about at this point that I realize you and I are from different planets. On my planet, online documentation is the only way to go, *especially* when editing. Are you marooned here on Earth too? -- Steven Taschuk o- @ staschuk at telusplanet.net 7O ) " ( From Frank at no.spam Mon May 12 04:17:23 2003 From: Frank at no.spam (Frank) Date: Mon, 12 May 2003 04:17:23 -0400 Subject: Can't start Tix References: Message-ID: On Fri, 9 May 2003 00:01:37 -0400, "Tim Peters" wrote: >[Frank] >> Tix is described in section 16.2 of the Python Library Reference >> 2.2.2. 16.2.1 has 3 lines of test code, which fails when I try them; >> it also mentions that the tix83.dll should be in the same directory >> with the tk83.dll. I have the Tk source and .dll, but only find the >> source for Tix. /Python22/DLLs has tk83.dll (and others), but not the >> .dll for Tix. > >That's so: at present, Tix is not included in the PythonLabs Windows >distribution. > >> I shur would like to know what happened, or what was supposed to >> happen. Did the Lib Ref just get ahead of itself? > >It's describing where you should put the files if you install Tix yourself. >It could be clearer about that. > >> The project I'm working on is being done in Python because of the cross >> platform capabilities, so I can't use *nix specific features. > >I don't know anything about Tix (which goes a way toward explaining *why* >Tix isn't in the PLabs Windows distro -- I build that distro, & I haven't >had the "spare time" to tackle a big package I don't understand or use; >there is a report about this open on SourceForge, BTW), but I'd be very >surprised if it were Unix-specific. (And if you figure out how to build and >install Tix on Windows so that it works well with Python, share what you >learn in the SF report!) > Thanks all. I'll keep looking at Tix on the side, but it looks like it's not ready to be used in anything that needs to bo cross-platform and easy for a novice in another location to install Frank From jermnsar at hotmail.com Tue May 20 04:06:47 2003 From: jermnsar at hotmail.com (Jeremy Lowery) Date: 20 May 2003 01:06:47 -0700 Subject: checking pyc files against source code Message-ID: <87a3f443.0305200006.19183e75@posting.google.com> I've implemented a new loader using ihooks, overriding the load_source method. new types have been added to get_suffixes in the hooks. (appending new ones to imp.get_suffixes()). I also compile the source code into pyc files to make importing the modules in subsequent python runs faster (It is faster b/c the compilation of the custom files takes a good chunk of CPU time). However, now when the custom files are edited, no change is seen until the .pyc file is deleted and then recreated by the import mechanism. I figure some os.getmtime stuff will be needed, but I"m not sure where. I would like it to behave like normal python files (If you change the .py file, the .pyc file is automatically recreated. Not sure where in the plumbing this happens). Any help? here is the code for load_source def load_source(self, name, filename, file): print 'having to load %s' % filename source = file.read(-1) file.close() cname = name[name.rfind('.')+1:] compiler = Compiler(source=source, moduleName=cname) code = str(compiler) module = imp.new_module(name) module.__file__ = filename exec code in module.__dict__ sys.modules[name] = module tfname = tempfile.mktemp('.py') try: f = open(tfname, 'w') except (OSError, IOError): return module f.write(code) f.close() py_compile.compile(tfname, '%s%spyc' % (os.path.splitext(filename)[0], os.extsep)) os.remove(tfname) return module From anti-spam.dbroadwell at mindspring.com Tue May 13 13:36:12 2003 From: anti-spam.dbroadwell at mindspring.com (David Broadwell) Date: Tue, 13 May 2003 17:36:12 GMT Subject: Getting all items above/below of a selected item.................... References: Message-ID: Note: cross-post from tutor list. -- David Broadwell From tim.one at comcast.net Fri May 23 10:47:42 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 23 May 2003 10:47:42 -0400 Subject: Can I get the total memory usage of Python? In-Reply-To: Message-ID: [Cameron Laird] > What's the feasibility of an enhancement in a future > version of Python to provide greater introspective > power in regard to memory allocation? I'll naively > speculate that, if we can just agree on an interface, > it should impose no particular runtime costs; every- > thing necessary is already available on the C side, and needs only to > be exposed. -- Except that there's no standard way in C to query the platform malloc about how much memory it's actually using, and all mallocs have hidden overheads. When allocating a large number of small objects, malloc overhead can be more than half the story. In 2.3 pymalloc takes most of that out of the platform malloc's hands (although it still grabs *large* chunks from the platfrom malloc, and pymalloc still can't know how much overhead the platform malloc chews up for those). From ckea25d02 at sneakemail.com Tue May 6 20:56:03 2003 From: ckea25d02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 07 May 2003 12:56:03 +1200 Subject: PEP263 (Specifying encoding) and bytecode strings In-Reply-To: References: <3EB672BB.FD22F434@engcorp.com> Message-ID: Alex Martelli wrote: > But NOTE that the encroachment is all ONE WAY: it's become perfectly > acceptable American English to say "deprecate" in the meaning that was > originally only held by "depreciate" Does that mean accountants calculate the deprecation of assets now? :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ark at research.att.com Sun May 25 19:38:11 2003 From: ark at research.att.com (Andrew Koenig) Date: Sun, 25 May 2003 23:38:11 GMT Subject: A syntax idea for one-liners References: Message-ID: Beni> I've recently discovered a backward-compatible and relatively simple Beni> and elegant syntax for encoding arbitrary sets of python statements Beni> with different indentations in a single line. In order to convince me that your proposal works, you will have to tell me how to distinguish your proposed syntax from cases already permitted by the Python syntax in which a : is followed by a statement on the same line. For example, the following is legal in Python today: if x < y: x = y I am not convinced that your proposal is always unambiguous in all contexts that involve statements such as the one above. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From squeeze at klerobs.org Tue May 13 15:12:40 2003 From: squeeze at klerobs.org (Squeeze) Date: Tue, 13 May 2003 21:12:40 +0200 Subject: Need help for a python project Message-ID: Hi guys ! I know you read something like a hundred post a day and you might be tired of long thread, so I'll try to be short : I'm to write a mini web-based administration tool, and since I fell in love with Python some weeks ago, I really would like to use it. The tool is supposed to manage the users and groups of a distant unix server, ? la Webmin, working with Apache, and MySql (if needed). But Im kinda stuck : I don't know where to start actually ... I know it's related with something to do with /etc/passwd, but I badly lack experience of this kind of thing.... It's my first job, and I really don't wanna disapoint my job, if you know what I mean, so any hints, advice, or help would be looooved. Or maybe you know some open source project where I might find ideas on how to start ? Help me Obi-Wan Kenobi. You're my only hope. Squeeze From bkc at Murkworks.com Thu May 22 19:49:31 2003 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 22 May 2003 19:49:31 -0400 Subject: Slow Ref cleanup in 2.2.1 with 100K+ objects on Linux. - or SAP DBAPI problem? Message-ID: I've run into a strange situation, looking for commentary. I'll have done my own workaround by the time you get this, so I don't need a critical answer. I've written a program to copy database records from Interbase to SAP. I have to change foreign key values during this process by looking up parent table records as child records are copied. I'm copying one table at a time, but a child may reference several other parent tables. I keep a cache using a dict of these other records. So .. 230K+ records have been copied, and during this process it probably pulled in 200K+ other related parent records and is keeping all of those in RAM (duh, bad design). But interestingly, the copy subroutine has finished, and is "returning" to it's parent, however the process seems hung. I thought I had read somewhere about a problem cleaning up ref's (There aren't any cycles in this case), but I can't recall exactly. This is python 2.2.1 on RH 9 Dual XEON 2.2 GHZ machine with 1GB RAM. Look at top: 7:35pm up 38 days, 9:07, 4 users, load average: 6.37, 6.93, 6.68 198 processes: 173 sleeping, 1 running, 24 zombie, 0 stopped CPU0 states: 3.3% user, 1.4% system, 0.0% nice, 94.1% idle CPU1 states: 2.4% user, 3.1% system, 0.0% nice, 93.3% idle CPU2 states: 0.4% user, 0.5% system, 0.0% nice, 98.1% idle CPU3 states: 0.2% user, 0.4% system, 0.1% nice, 98.3% idle Mem: 1030372K av, 1020480K used, 9892K free, 0K shrd, 2624K buff Swap: 4096552K av, 1370228K used, 2726324K free 21208K cached PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND 16173 bkc 10 -5 988M 762M 718M D < 0.3 75.7 38:00 python2 SQLCopy.py -e /tmp/copyerrors2.txt --copy STSouthTables STSouthTablesS Charges + And vmstat [bkc at strader /service]# vmstat 5 procs memory swap io system cpu r b w swpd free buff cache si so bi bo in cs us sy id 0 1 0 1370228 9668 2572 19964 0 0 2 1 0 1 1 1 1 0 2 0 1370228 9692 2628 22872 816 0 1431 131 840 1423 2 2 96 0 12 4 1370284 10192 2632 23652 55 1902 466 1927 1010 993 1 2 97 0 17 4 1370284 10180 2632 23684 26 1466 32 1466 985 623 1 1 98 0 17 4 1370680 10064 2364 23960 37 1468 38 1468 931 326 1 1 98 0 3 0 1370604 9336 2100 31420 402 230 2690 314 921 1381 3 4 93 It looks to me like all the processes are deadlocked trying to swap in. I niced python a little but that made no change. Note the load average is right up there, but the CPU time is 95% idle! Anyone seen a condition like this before? -- Hey, I tried to ^C it and I got: -11987 COMMUNIC sql03_catch_signal: caught signal 2 -11987 COMMUNIC sql03_catch_signal: caught signal 2 I had to kill it. I wonder if it was blocked in SAP DBAPI and it's not a cleanup problem. Oh well, just musing I'll re-run this with a smarter cache design and see what happens. -- Novell DeveloperNet Sysop #5 _ From jason_nospam at oes.co.th Sat May 31 08:19:35 2003 From: jason_nospam at oes.co.th (Jason Smith) Date: Sat, 31 May 2003 19:19:35 +0700 Subject: Encrypting much data with AES and M2Crypto Message-ID: Hi. I am working on a small open source backup tool. It is based on Knoppix, and it uses Python to make full hard drive backups over Samba or NFS. Everything works, except the encryption. Basically, the software will upload an AES-encrypted HDD image. Firstly, I have been working under the assumption that M2Crypto is the de-facto Python cryptography toolkit. Is this true? At any rate, I'm using an M2Crypto.BIO.CipherStream object as in the package's demo/bio_ciph_test.py usage. The problem is, the algorithm seems to be more useful for encrypting small amounts of data in memory, as it is adding up to an additional block of ciphertext to the output. (That's because a block algorithm like AES must have its input in block-sized chunks. To handle smaller chunks, usually you pad the last input block, then you write down how many bits to throw away in the last byte of the input.) But, since I will be feeding the CipherStream many gigabytes, I need to prevent this behavior, until of course I encrypt the last part of the hard drive image. (Also, when decrypting, M2Crypto only seems to be outputting 4096 bytes, but the above bug is more of a show-stopper.) Thanks for any feedback with this issue. -- Jason Smith Open Enterprise Systems Bangkok, Thailand From schorsch at schorsch.com Sat May 24 06:58:27 2003 From: schorsch at schorsch.com (Georg Mischler) Date: Sat, 24 May 2003 12:58:27 +0200 Subject: PEP idea - Daemon References: Message-ID: Ryan Morillo wrote: > Am I the only one that thinks we should add daemonization to the os > module? > [...] > Probably name it background (for the windows types, easy to remember). > What do ya'll think? Some issues: What is called a daemon in unix, should most often be implemented as a system service on Windows. Those are two very different approaches to the same problem, that can't easily be packed into one module. If you're just talking about sending processes to the background in general, then there are still a few non-trivial differences. On unix, you have to offer the choice of creating a new process group or not, and probably some other things that I can't think of right now. On Windows, there are differences between subprocesses that are supposed to open windows of their own or not, just to mention the most obvious. There are a lot of other options when starting processes, like their priority, resource inheritance strategies, and so on. Note also that there is no obvious way to send an *existing* process into the background, because fork() and exec() are rolled into one single monster called CreateProcess(). You normally have to make your choice outside of the new process and then live with the results. If you want to be thorough about that stuff, you might end up with a module that contains a hell of a lot of platform specific options. Maybe this isn't so much of a problem if you can figure out reasonable defaults. Or you could offer several predefined task specific configuration selections, that do the right thing on each platform. If you factor in the subtle and not so subtle differences between Windows versions, you might end up with quite a puzzle... Next you'll need to handle stdin/stdout/stderr in a reasonable fashion. Each of them could be connected to a file, returned as a pipe, or closed. And then you need to think about process termination. Maybe you want your background job to become totally independent, maybe you want to keep a handle, so you can query its status and kill/suspend/resume it as necessary. I don't think that much of that should go into the os module directly, as the issues are just too diverse. I'm guessing that you rather want a new module (eg. "process") that bundles all those tasks into a class. If you're lucky, then you'll end up with something that is actually useable, but still general enough to attract a wider audience. I have a group of fairly straightforward but not extremely clean modules that do at least some of the above in a way that served my purposes so far. If you're interested, then I could try to strip them of external dependencies, and send them to you per e-mail as a starting point (or as an example of what not to do in case you shouldn't like them... ;). -schorsch -- Georg Mischler -- simulations developer -- schorsch at schorsch com +schorsch.com+ -- Lighting Design Tools -- http://www.schorsch.com/ From phd at phd.pp.ru Tue May 6 06:11:26 2003 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 6 May 2003 14:11:26 +0400 Subject: ANN: nohtml 1.10 Released In-Reply-To: References: Message-ID: <20030506101125.GA13121@phd.pp.ru> Hello! On Mon, May 05, 2003 at 10:50:07PM +0000, Tim Daneliuk wrote: > By piping a given user's email through 'nohtml.py' first, only the > textual portion of the message will actually be delivered. This is > especially useful if you run mailing lists and want to stop HTML > from ever reaching them. Ever saw mimedecode.py? NAME mimedecode.py - decode MIME message SYNOPSIS mimedecode.py [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename] DESCRIPTION Mail users, especially in non-English countries, often find that mail messages arrived in different formats, with different content types, in different encodings and charsets. Usually this is good because it allows us to use apropriate format/encoding/whatever. Sometimes, though, some unification is desireable. For example, one may want to put mail messages into an archive, make HTML indicies, run search indexer, etc. In such situations converting messages to text in one character set and skipping some binary atachmetnts is much desireable. Here is the solution - mimedecode.py! This is a program to decode MIME messages. The program expects one input file (either on command line or on stdin) which is treated as an RFC822 mesage, and decoded to stdout. If the file is not an RFC822 message it is just piped to stdout one-to-one. If the file is a simple RFC822 message it is just decoded as one part. If it is a MIME message with multiple parts ("attachments") all parts are decoded. Decoding can be controlled by command-line options. First, Subject and Content-Disposition headers are examined. If any of those exists, is is decoded according to RFC2047. Content-Disposition header is not decoded - only its "filename" parameter. Encoding header's parameters is in violation of the RFC, but widely deployed anyway, especially in the M$ Ophice GUI (often referred as "Windoze") world, where programmers are usually ignorant lamers who never even heard about RFCs. Correct parameter encoding specified by RFC2231. This program decodes RFC2231-encoded parameters. Then the body of the message (or current part) decoded. Decoding starts with looking at header Content-Transfer-Encoding. If the header specifies non-8bit encoding (usually base64 or quoted-printable), the body is converted to 8bit. Then if its content type is multipart (multipart/related or multipart/mixed, e.g) every part is recursively decoded. If it is not multipart, mailcap database is consulted to find a way to convert the body to plain text. (I have no idea how mailcap could be configured on said M$ Ophice GUI, please don't ask me; real OS users can consult my example at http://phd.pp.ru/Software/dotfiles/mailcap.html). The decoding process uses first copiousoutput filter it can find. If there is no filter the body is just passed as is. Then Content-Type header consulted for charset. If it is not equal to current default charset the body text is recoded using Unicode codecs. Finally message headers and body are flushed to stdout. OPTIONS -h --help Print brief usage help and exit. -V --version Print version and exit. -c Recode different character sets in message body to current default charset; this is the default. -C Do not recode character sets in message body. -f charset Force this charset to be the current default charset instead of sys.getdefaultencoding(). -d header Add the header to a list of headers to decode; initially the list contains headers "From" and "Subject". -D Clear the list of headers to decode. -p header:param Add the (header, param) pair to a list of headers' parameters to decode; initially the list contains header "Content-Disposition", parameter "filename". -P Clear the list of headers' parameters to decode. -b mask Append mask to the list of binary content types; if the message to decode has a part of this type the program will pass the part as is, without any additional processing. -e mask Append mask to the list of error content types; if the message to decode has a part of this type the program will raise ValueError. -i mask Append mask to the list of content types to ignore; if the message to decode has a part of this type the program will skip it, instead a line "Message body of type XXX skipped." will be issued. -t mask Append mask to the list of content types to convert to text; if the message to decode has a part of this type the program will consult mailcap database, find first copiousoutput filter and convert the part. The last 4 options (-beit) require more explanation. They allow a user to control body decoding with great flexibility. Think about said mail archive; for example, its maintainer wants to put there only texts, convert Postscript/PDF to text, pass HTML and images as is, and ignore everything else. Easy: mimedecode.py -t application/postscript -t application/pdf \ -b text/html -b 'image/*' -i '*/*' When the program decodes a message (or its part), it consults Content-Type header. The content type is searched in all 4 lists, in order "text-binary-ignore-error". If found, appropriate action performed. If not found, the program search the same lists for "type/*" mask (the type of "text/html" is just "text"). If found, appropriate action performed. If not found, the program search the same lists for "*/*" mask. If found, appropriate action performed. If not found, the program uses default action, which is to decode everything to text (if mailcap specifies filters). Initially all 4 lists are empty, so without any additional parameters the program always uses the default decoding. ENVIRONMENT LANG LC_ALL LC_CTYPE Define current locale settings. Used to determine current default charset (if your Python is properly installed and configured). BUGS The program may produce incorrect MIME message. The purpose of the program is to decode whatever is possible to decode, not to produce absolutely correct MIME output. The incorrect parts are obvious - decoded Subject headers and filenames. Other than that output is correct MIME message (tested with mutt mail reader). The program does not try to guess whether the headers are correct. For example, if a message header states that charset is iso8859-5, but the body is actually in koi8-r - the program will recode the message to wrong charset. AUTHOR Oleg Broytmann COPYRIGHT Copyright (C) 2001-2002 PhiloSoft Design LICENSE GNU GPL NO WARRANTIES This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. SEE ALSO mimedecode.py home page: http://phd.pp.ru/Software/Python/#mimedecode Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From staschuk at telusplanet.net Sun May 11 16:18:10 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 11 May 2003 14:18:10 -0600 Subject: Improve this recursive code please! In-Reply-To: <20030511135150.A627@tibia.amotlpaa.bogus>; from staschuk@telusplanet.net on Sun, May 11, 2003 at 01:51:50PM -0600 References: <3EB7DF65.55A50CD4@sarcastic-horse.com> <20030511135150.A627@tibia.amotlpaa.bogus> Message-ID: <20030511141810.C627@tibia.amotlpaa.bogus> Quoth I: [...] > Not a mathematician, but the number of arrangements for m bricks > and n bins is > m+n-1 choose m > Proving this by induction is not difficult, though as usual for > such proofs, neither is it particularly, er, insight-bringing. I > don't see a combinatoric proof at the moment, but no doubt there's > a nice one. Should have been obvious... Arrange m Os and n-1 |s in a row. The |s are bin boundaries; the Os are bricks. Example, with eight bricks in four bins: O O O | O | | O O O O That's the arrangement (3, 1, 0, 4). This is equivalent to replacing n-1 of m+n-1 Os with |s, so there's m+n-1 choose n-1 ways to do it. (Note that m+n-1 choose m = m+n-1 choose n-1.) -- Steven Taschuk staschuk at telusplanet.net "Telekinesis would be worth patenting." -- James Gleick From cnetzer at mail.arc.nasa.gov Thu May 1 20:03:17 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 01 May 2003 17:03:17 -0700 Subject: why no break N levels, as in other leading languages? In-Reply-To: <87ptn2xx5o.fsf@jidanni.org> References: <87ptn2xx5o.fsf@jidanni.org> Message-ID: <1051833797.527.8.camel@sayge.arc.nasa.gov> On Thu, 2003-05-01 at 12:52, Dan Jacobson wrote: > In bash there is > $ help break > break: break [n] > Exit from within a FOR, WHILE or UNTIL loop. If N is specified, > break N levels. > > In python did that Guido fella (who by the way looks like he's the > kind of kid who gets picked on by bullies, [blah blah blah] After a quick check of your website I must say that... well... nevermind. > ... oops, where were we? Anyway, in python did he forget > about giving it a N ability or is there of course some higher > principle involved? He did not forget it. It is just a completely dumb idea for a feature that I'm sure it never even came close to entering his mind. If you REALLY must abort from deep inside nested loops (or recursion), without using a boolean flag value to control the continued looping (or recursion), you could raise an exception (an of course catch it outside all the loops (or recursion). -- Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From bokr at oz.net Tue May 6 11:45:40 2003 From: bokr at oz.net (Bengt Richter) Date: 6 May 2003 15:45:40 GMT Subject: PEP263 (Specifying encoding) and bytecode strings References: Message-ID: On Mon, 5 May 2003 20:56:55 -0400, "Terry Reedy" wrote: > >"Mike C. Fletcher" wrote in message >news:mailman.1052166614.10808.python-list at python.org... >> Terry Reedy wrote: >> >> >I am a little puzzled by some of the questions and comments in this >> >thread. Am I missing something? >> > >> Probably the purpose of resource-package :) , namely automatically >> embedding sets of binary resources in Python source-code files. > >You're right. I've never done this (yet ;-) and did not think of it. > >> What I'd like from Pep 263 is a way to make the declaration "this >file >> has no encoding" or "these strings are byte-sequences, *not* Unicode > >This is what I asking about with > >> >. If there is not yet a way to say encoding = None or encoding = >bytes, ... > >> >So? This should only matter if you are putting zlib.compress() >output or >> >decompress() input into source code, such as for testing each >function >> >separately. > >> Which is exactly what resource-package does (though for portable >access >> to the files during package embedding/deployment, not necessarily >> testing). > >Now I understand better. Using the Python interpreter beyond its >defined limits is attractive but slightly dangerous. Multiplying half >the compresser output by 4 (for net expansion about 2) is certainly >not inviting. I see these possible courses of action. > >* Get a null encoding option into PEP263 and its implementation. >There should be a way to tell the interpreter to handle the sequence >of bytes the same way it currently does after escape processing. > >* Do nothing now and ignore the warning or adjust now to suppress >them, and wait for future hammers to fall when they do. > >3. Write your own importer. (One halfway tack would be to readin, >expand 'illegal' bytes, and explicitly feed to eval or compile.) > >4. Investigate the new import-from-zipfile facility. If you are zlib >compressing large ascii texts, compress the entire file instead of >just the quoted text. If you have inherently binary data, expand the >hi-bit bytes (expanding file by 2 if half are such) and, again, >compress the whole file, not just the data strings. > How about an optional explicit __END__ by itself on a line to end program source and the assumption of the declared encoding? That way binary stuff can be appended. You could append multiple chunks by prefixing them with a delimited ascii integer containing the byte count (you could do that in binary also, but it might be interesting to be able to do an all-ascii appendage), e.g., three sections, with a two-section tail of sections with post-fixed lengths that you read from the back and seek back to find the beginnings of. The beginning of post-fixed-length sections is delimited by the [?] length prefix. E.g., __END__ [10]0123456789[?]012345[6]The End ;-)[11] The easy way to append binary to a source would then be something like (untested) import os fs = file('the_source','ab') fb = file('the_binary','rb') b = fb.read() fs.write('__END__'+os.linesep+'[?]') fs.write(b) fs.write('[%s]'%len(b)) For access, the whole binary tail after the __END__ line could be made into a string bound to e.g., __MODULE_DATA__. You could parse it yourself or make a utility function that would return a file-like object for reading a selected section, e.g., f = moduledata(section_number). I guess you'd modify the tokenizer to recognize the __END__ line and create a special string token from the rest of the bytes, that could eventually get bound to __MODULE_DATA__. If the binary data really was e.g., a raw unicode file, you'd need to apply appropriate decode/encode when you access a __MODULE_DATA__ section as a byte stream, depending on what you wanted to do. Regards, Bengt Richter From cybernut at uswest.net Wed May 21 12:55:29 2003 From: cybernut at uswest.net (cybernut) Date: Wed, 21 May 2003 10:55:29 -0600 Subject: help on ultra newbie program please References: Message-ID: "Andrew Walkingshaw" wrote in message news:slrnbcnbc2.126.andrew-usenet at athena.jcn.srcf.net... > In article , cybernut wrote: > > # Waits until a password has been entered. Use control-C to break out with > > out > > # the password > > > > #Note that this must not be the password so that the > > # while loop runs at least once. > > password = "foobar" > > > > #note that != means not equal > > while password != "unicorn": > > password = raw_input("Password:") > > print "Welcome in" > > Presumably this is the original program. > > What you want is something like: > > (program starts - hope the comments are useful) > > # set password to be blank initially > password = "" > # and create a variable to count the number of failed login attempts > numfailures = 0 > > while numfailures < 3: > password = raw_input("Password: ") > if password == "unicorn": > # success, so get out of the loop > break > else: > # increment number of attempts by one > numfailures = numfailures + 1 > > if numfailures == 3: > # then the user failed to log in three times > print "Access denied." > else: > # numattempts < 3, so no more than two failed attempts > # therefore - allow access > print "Welcome in." > > > This, when run, produces output which looks like - > > adw27 at pond:~/siesta-zrw2o8-large-new 1014 $ > :; python test.py > Password: unicorn > Welcome in. > adw27 at pond:~/siesta-zrw2o8-large-new 1015 $ > :; python test.py > Password: asd > Password: asd > Password: wed > Access denied. > > You might want to investigate the python-tutor at python.org mailing list: > it's full of people who like to help new programmers with this kind of > thing! > > Hope this helps, > > - Andrew > > -- > Andrew Walkingshaw | andrew-usenet at lexical.org.uk > Thanks a bunch Andrew! That makes sense to me. Also appriciate the tip on that mailing list. From aleax at aleax.it Sat May 3 12:28:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 03 May 2003 16:28:07 GMT Subject: Python in a Nutshell is available on Safari References: <0eg7bvkpin39gsudod53hbpr6ljesf7pol@4ax.com> Message-ID: Rene Pijlman wrote: > FYI, "Python in a Nutshell" has become available on Safari: > http://safari.oreilly.com/?xmlid=0-596-00188-6 Excellent! Thanks for the news. So, it seems they missed their target of "within April" only by a couple days at most. Alex From unlearned at DELETETHIS.learn2think.org Thu May 15 15:55:46 2003 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Thu, 15 May 2003 13:55:46 -0600 Subject: passing by refference References: <9xRw+ks/KrpJ089yn@the-wire.com> <3ec3e547$1_3@hpb10302.boi.hp.com> Message-ID: <3ec3f0c2$1_1@hpb10302.boi.hp.com> "Joshua Marshall" wrote in message news:ba0pv6$oqt$1 at ginger.mathworks.com... > Daniel Fackrell wrote: > ... > >> Yes, I agree this is an accurate description of Python. CLU function > >> invocation seems to have call-by-value semantics as well (by my > >> definition and, I believe, the standard definition). And like python, > >> values are object references. > > > > At the machine level, all that can ever be passed to a > > procedure/function/method/whatever is a value, so in a sense, all languages > > could be considered to be strictly call-by-value. > > No, this is not what I was implying. The difference between > call-by-value and other argument-passing schemes is entirely semantic. > For example, the difference between call-by-value and > call-by-reference can be seen by doing an assignment to a formal > parameter. In a call-by-reference world, this can rebind a variable > in your caller's scope, in a call-by-value world, this does not. > Call-by-reference is often implemented by passing a pointer behind the > scenes. In Python, however, a callable can directly change objects in the caller's scope as a consequence of passing. This can happen e.g. when a list l is passed and the callable executes l.append(). In a call-by-value world, what is passed to the callable is strictly a copy. Nothing about it gives any information which can be used to modify the argument that was passed. Consider: >>> def append(l, item): ... l.append(item) ... >>> l = [1, 2, 3] >>> l [1, 2, 3] >>> append(l, 4) >>> l [1, 2, 3, 4] How can this be explained by call-by-value? As pointed out by (I believe) Fredrik Lundh and Tim Peters, the traditional uses of the terms call-by-value and call-by-reference both fall short of describing Python's passing scheme in important ways. Luckily, as has also been said, we are not confined to these two terms. As CLU's passing model is (as far as I can tell from the small amount I've read about it) identical to that used in Python, it seems to make sense to use the terms that were invented for the purpose of describing CLU's passing model, namely call-by-sharing and call-by-object. -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From http Sat May 31 18:24:44 2003 From: http (Paul Rubin) Date: 31 May 2003 15:24:44 -0700 Subject: CGI question: safe passwords possible? References: <3ED86146.F2029ADB@alcyone.com> <1054368881.10515.265.camel@lothlorien> <7x1xyfgxq6.fsf@ruckus.brouhaha.com> Message-ID: <7xsmquwy8j.fsf@ruckus.brouhaha.com> hwlgw at hotmail.com (Will Stuyvesant) writes: > I am building a prototype for an application. For this > I would very much like to do CGI programming with > Python. I already have most of it figured out, with > Python and CGI, in a nice way, independent of host or > operating system etc. But the customer insists on > "security". They are not too tech-savvy about > security, even less than I am. So I could just try to > sell them something that is not secure at all, like the > prototype I have now using HTML forms with "user" and > "password" fields. .... The way to secure what you're doing is with SSL. Do not roll your own cryptography in Python or in any other language. If your hosting provider doesn't support SSL, that's fine, it's a prototype. Tell the customer that the prototype doesn't have SSL enabled but the real version will have it. Then make arrangements for SSL hosting for the real version. Yes you do have a problem about password distribution and what to do if a user forgets their password. You should read the book "Security Engineering" by Ross Anderson. There is a heck of a lot more to security than encrypting a password. From h_schneider at marketmix.com Wed May 14 01:22:19 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Wed, 14 May 2003 07:22:19 +0200 Subject: Python Coredump on FreeBSD References: Message-ID: I also tried a value of 1024 with no result. Is there any alternative to the re module ? -- Harald "Andrew MacIntyre" schrieb im Newsbeitrag news:mailman.1052854103.6953.python-list at python.org... > On Tue, 13 May 2003, Harald Schneider wrote: > > > With the patch applied it runs longer, but then dies with > > > > python in realloc(): warning: modified (chunk-) pointer > > Segmentation fault (core dumped) > > > > Think I'll have to move away from threading on FreeBSD - It's definately not > > stable. > > You do have the option of trying the LinuxThreads port, though I can't > tell you how to get Python's configure script to recognise LinuxThreads on > FreeBSD. I gather that using LinuxThreads is recommended for MySQL on > FreeBSD. > > BTW, I thought that the patch you referred to only upped the thread stack > to 128kB. Elsewhere, I've read that Linux defaults to 1MB stacks for > threads. Did you try this much larger value? > > -- > Andrew I MacIntyre "These thoughts are mine alone..." > E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 > andymac at pcug.org.au | Belconnen ACT 2616 > Web: http://www.andymac.org/ | Australia > > From hemanexp at yahoo.com Sun May 4 03:24:57 2003 From: hemanexp at yahoo.com (perl lover) Date: Sun, 4 May 2003 00:24:57 -0700 (PDT) Subject: Setting & validating dialog box entries Message-ID: <20030504072457.77413.qmail@web41705.mail.yahoo.com> hi, i am using tkSimpleDialog box to display employee name and number. I want my entry box should contain some intial values set in "body" routine while loading the dialog box. Which fuction is used to set a value for entry widget? Moreover how can i ensure my entry widget contains proper values? That means name box should not allow numbers and salary box should not contain string. As soon as i type an invalid character ( a number in name box) i expect an message box to be poped out stating the error instead of displaying the messagebox after pressing "Ok". How can i get a messagebox as soon as the condition is violated? My program is given below. from Tkinter import * import tkMessageBox import tkSimpleDialog import string root = Tk() Button(root, width=10, height=10).pack() class MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.empname = Entry(master) self.eno = Entry(master) self.empname.grid(row=0, column=1) self.eno.grid(row=1, column=1) # Here i want to set values for entry widgets #self.empname.configure(textvariable = "suresh") def validate(self): try: name= string(self.empname.get()) eno = string.atoi(self.en.get()) self.result = name, eno return 1 except ValueError: tkMessageBox.showwarning("Bad input", "Illegal values, please try again") return 0 def apply(self): name = string.atoi(self.empname.get()) eno = string.atoi(self.eno.get()) print name, eno # or something MyDialog(root) root.mainloop() __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From dave at nullcube.com Thu May 8 01:48:23 2003 From: dave at nullcube.com (Dave Harrison) Date: Thu, 8 May 2003 15:48:23 +1000 Subject: compiling in sax modules for python Message-ID: <20030508054823.GA3466@dave@alana.ucc.usyd.edu.au> Hey all, I need to install the xml.sax parsing package for Python2.2 however I've only ever done it during the actual compile of the language itself. I know (really really hope ;-) that there is another way to do it. The machine is a SunOS9 machine. Help ? From donn at u.washington.edu Fri May 2 12:28:10 2003 From: donn at u.washington.edu (Donn Cave) Date: 2 May 2003 16:28:10 GMT Subject: stdin / stdout doubts.. References: Message-ID: Quoth Alessio Pace : | Hi, I have some doubts about the way I deal with stdin and stdout. | I do: | import sys | | multi_line_text = sys.stdin.read() | # do something on the text | # ... | sys.stdout.write(modified_multi_line_text) | | Is this the preferable way? Or is there another way to make Python read from | stdin/write to stdout It's the right way as a general rule. You could probably make the "print" statement work for output, but it doesn't look like it would suit your application as well. In some exotic situations, on certain platforms (UNIX) you might have reasons to use the posix read and write functions, for example if you have been using select() to determine if data is available for input. Donn Cave, donn at u.washington.edu From postmaster at ibmx232 Fri May 23 20:26:32 2003 From: postmaster at ibmx232 (postmaster at ibmx232) Date: Sat, 24 May 2003 09:26:32 +0900 Subject: Delivery Status Notification (Failure) Message-ID: This is an automatically generated Delivery Status Notification. Unable to deliver message to the following recipients, due to being unable to connect successfully to the destination mail server. qaz2wsx at netsgo.com q8487 at netsgo.com -------------- next part -------------- An embedded message was scrubbed... From: ?????? Subject: ?? ?????? ?????? Date: 22 May 2003 08:46:49 +0900 Size: 10186 URL: From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed May 21 20:48:02 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 22 May 2003 02:48:02 +0200 Subject: Advice on teaching a 1 day Python class In-Reply-To: References: Message-ID: <3ecc1e42$0$49099$e4fe514c@news.xs4all.nl> Norm Matloff wrote: > I have a quick Python tutorial, at > > http://heather.cs.ucdavis.edu/python.html 404 --Irmen From fredrik at pythonware.com Thu May 15 12:38:10 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 May 2003 18:38:10 +0200 Subject: 123.3 + 0.1 is 123.3999999999 ? References: <3EC3BCCD.3090605@nospam.com> Message-ID: "An Anonymous Coward" wrote: > In Python 2.2.2 > > >>> float("123.4")+0.1 > 123.5 > > >>> float("123.3")+0.1 > 123.39999999999999 > > >>> float("123.1") + 1 > 124.09999999999999 > > how come there are these inaccuracies? It's the way binary floating point numbers work (if you're going to squeeze an infinite range of numbers into a limited number of bits, you have to cheat). The Python tutorial has the full story: http://www.python.org/doc/current/tut/node14.html > I just tried in Perl > > print eval("123.3") + 0.1; > > and it gives > 123.4 Perl lies. So does Python, if you ask it to: >>> print eval("123.3") + 0.1 123.4 >>> print float("123.3") + 0.1 123.4 From gerrit at nl.linux.org Tue May 27 11:19:28 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 27 May 2003 17:19:28 +0200 Subject: Convenient Online Documentation? In-Reply-To: <002a01c323ba$6c7c98e0$f5a2383e@raseliar> References: <002a01c323ba$6c7c98e0$f5a2383e@raseliar> Message-ID: <20030527151928.GA10915@nl.linux.org> Raseliarison nirinA schreef op maandag 26 mei om 22:17:02 +0000: > or in a Python interpreter, > >>> from pydoc import help > >>> help() The first line isn't even necessary, at least not on my system: $ python Python 2.3b1+ (#12, May 25 2003, 11:55:29) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. 0 >>> help() Welcome to Python 2.3! This is the online help utility. yours, Gerrit. -- 5. If a judge try a case, reach a decision, and present his judgment in writing; if later error shall appear in his decision, and it be through his own fault, then he shall pay twelve times the fine set by him in the case, and he shall be publicly removed from the judge's bench, and never again shall he sit there to render judgement. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From kendear_nospam at nospam.com Fri May 16 03:25:08 2003 From: kendear_nospam at nospam.com (A Puzzled User) Date: Fri, 16 May 2003 07:25:08 GMT Subject: Python's qw Message-ID: <3EC4924B.1060306@nospam.com> Since Python doesn't have qw, is the following a proper/usual way to simulate it? thanks. >>> a = """sunflower tulip jasmine""" >>> string.split(a, "\n") ['sunflower', 'tulip', 'jasmine'] From bens at replytothegroupplease.com Sat May 24 14:39:02 2003 From: bens at replytothegroupplease.com (Ben S) Date: Sat, 24 May 2003 19:39:02 +0100 Subject: High memory usage - program mistake or Python feature? References: <3ECE203B.4080707@klix.ch> Message-ID: Gerald Klix wrote: > It is difficult to diagnose if we can't see the whole program. > But I suppose the re module makes some (superflous) copies. > I would like to see the figures form LoadLogFile alone. That is the whole program, pretty much. The rest is just reading a query string from an HTTP request so that it can get a filename to pass to LoadLogFile. Then there are several lines that use 'for' over the results returned from GetLinesContainingCommand, which only returns 20 or 30 lines at most. > Some performance hints: > You can gain a little by using xreadlines. It does > not read the whole file ant once. But if you map > the sequence to another sequence you gain almost nothing. If I use xreadlines (and drop the string stripping) I suppose I would gain a lot on memory but lose out on speed (due to multiple passes over the file), right? This isn't necessarily a bad thing since it's running as a CGI script, and therefore the bottleneck is usually going to be the network, I expect. Thanks for your other ideas, too. -- Ben Sizer http://pages.eidosnet.co.uk/kylotan From tim.one at comcast.net Tue May 13 22:26:40 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 13 May 2003 22:26:40 -0400 Subject: passing by refference In-Reply-To: <87of2671rm.fsf@charter.net> Message-ID: [Jeremy Hylton] >> If we care to debate terminology, then neither call-by-value nor >> call-by-reference apply. Python has call-by-object semantics. As far >> as I know, the first use of call-by-object was in a description of CLU. [Doug Quale] > Python is call-by-value. The values are objects, but the argument > passing mechanism doesn't say anything about what values are in the > language. Sorry, that didn't make sense. It's true that, in CPython, pointers to objects are passed under the covers, in C's call-by-value fashion, but that's an implementation detail, and has no visible effect on the Python language's semantics. Call-by-object really is the best description of Python's semantics. If you do a literature search, you'll also see that described as "call by object reference" and "call by sharing". Call-by-value it ain't -- unless you view the implementation reference as "the value", but that simply isn't helpful to anyone except Python's implementors (of which Jeremy and I are two, BTW). >>> def f(x): ... x[:] = [-1] * 3 >>> y = [1, 2, 3] >>> f(y) >>> y [-1, -1, -1] >>> There's no rational sense in which that can be called call-by-value. A similar program using C structs shows what call-by-value does mean: #include struct s { int x, y, z; }; void display(const char* tag, struct s s) { printf("%s %d %d %d\n", tag, s.x, s.y, s.z); } void f(struct s s) { display("inside before", s); s.x = s.y = s.z = -1; display("inside after", s); } void main() { struct s t = {1, 2, 3}; display("before", t); f(t); display("after", t); } Of course that displays: before 1 2 3 inside before 1 2 3 inside after -1 -1 -1 after 1 2 3 From aahz at pythoncraft.com Sun May 18 20:58:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 May 2003 20:58:48 -0400 Subject: __getattr__ functionality for modules? References: Message-ID: In article , Stefan Franke wrote: >On 18 May 2003 18:55:20 -0400, aahz at pythoncraft.com (Aahz) wrote: >> >>Nope, and Guido is violently opposed to making this possible. Why not >>just use a class? > >Because a namespace object behaves different when it comes to setting >attributes: There are no nested scopes. > >What I'm trying to realize is a small domain specific configuration >language: A subset of Python that consists of nothing else but > >- a couple of functions, > >- the ability to define your own functions with 'def' with correct scope nesting > >- Python's numeric expressions > >- and an (unlimited) number of builtin constants. That's what I need > the module getattr hook for > >This is absolutely trivial to learn for the users in my context. Using >objects and attributes here adds an unnecessary (and unwanted) >level of complexity. But you can import their module and attach the functions to a class object. They don't need to know that. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From bdesth at removethis.free.fr Mon May 5 16:31:04 2003 From: bdesth at removethis.free.fr (laotseu) Date: Mon, 05 May 2003 20:31:04 +0000 Subject: Should I write a book on Python Metaprogramming ? (short answer) References: Message-ID: <3EB6CA08.2050208@removethis.free.fr> David Mertz wrote: > Hi gang, > (snip) > > So here's my questions to c.l.py. Would you want a book along the below > lines at all? yes. Laotseu From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri May 30 04:45:07 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 30 May 2003 10:45:07 +0200 Subject: Time constants module - standard-library fodder? In-Reply-To: References: Message-ID: <3ed71a14$0$49099$e4fe514c@news.xs4all.nl> Ben Finney wrote: > Many programmers in many languages break the "use named constants" rule, > but one of the most egregious examples seems to be constants for number > of seconds in an hour, day, week, etc. > > Using the numeric literal '604800' instead of 'SECS_PER_WEEK' is as bad > as using '3.14159265' instead of 'math.pi', for all the same reasons: > it's prone to hard-to-find typing errors, it's not obvious to anyone > unfamiliar with the value of the constant, it gives no context as to why > this number is being used, etc. That's why I'm usually writing it as "60*60*24*7" Although giving this kind of numbers their own constant sounds reasonable. But I'm not too fond of HOURS_PER_DAY and the other 'simple' ones. Why, it's 24, this will *never* change, *everybody* knows this, and if your code isn't clear when you use the number 24 directly, I think the rest of your code has a problem, and it won't improve much when you're using the HOURS_PER_DAY constant instead. We might as well name the following constants: FIRST_INTEGER_AFTER_ZERO=1 NUMBER_OF_DIGITS_IN_BASE_TEN=10 FOUR_TIMES_PI=math.pi*4 I think these kind of constants are *too* obvious and only make your code harder to read. BUT: this depends on the situation! I always think about the readability and maintainability while writing the code. Perhaps in some parts, these 'obvious' constants are needed to improve the code, but usually they are not (my opinion). > Is there a better way? A standard module I've missed? Any improvements > to offer? Should this go into the standard library, in some form? Why > or why not? > SECS_PER_MINUTE = 60 > MINUTES_PER_HOUR = 60 > HOURS_PER_DAY = 24 > DAYS_PER_WEEK = 7 > MONTHS_PER_YEAR = 12 [...] > SECS_PER_HOUR = MINUTES_PER_HOUR * SECS_PER_MINUTE > SECS_PER_DAY = HOURS_PER_DAY * SECS_PER_HOUR > SECS_PER_WEEK = DAYS_PER_WEEK * SECS_PER_DAY Fine. But see above. > DAYS_PER_YEAR_AVG = 365.25 > DAYS_PER_MONTH_AVG = DAYS_PER_YEAR_AVG / MONTHS_PER_YEAR > WEEKS_PER_YEAR_AVG = DAYS_PER_YEAR_AVG / DAYS_PER_WEEK [...] > SECS_PER_MONTH_AVG = DAYS_PER_MONTH_AVG * SECS_PER_DAY > SECS_PER_YEAR_AVG = DAYS_PER_YEAR_AVG * SECS_PER_DAY I'm not happy with this: it's wrong. The avg. number of days per year is 365.242199. Second, there's also a Siderial year, 365.256366 days. Sometimes you need the first, sometimes the other. Perhaps you require even greater precision than 6 fractional digits. Either remove these constants or define them exactly (you probably meant the Julian year). I think you're opening a can of worms here ;-) More info at http://www.maa.mhn.de/Scholar/calendar.html --My ?0.02, Irmen de Jong From msoulier at storm.ca._nospam Sun May 25 22:42:55 2003 From: msoulier at storm.ca._nospam (Michael P. Soulier) Date: 26 May 2003 02:42:55 GMT Subject: pure aesthetic question References: <3ec7ba3c$0$26716$ba620e4c@reader1.news.skynet.be> Message-ID: On Sun, 18 May 2003 18:52:11 +0200, Helmut Jarausch wrote: > Hi > > as far as I know I have to put a Python script > into a file with suffix '.py' (e.g. BackUp.py) > and if it gets compiled there is a BackUp.pyc or > BackUp.pyo file. > Is it possible (under Linux) to get the plain name > BackUp > which executes the compiled and/or optimized script > when invoked by the shell (system) You don't need to put a python script in a file ending in .py at all. You do need to do that if you're going to import it as a library. If you want to compile your code, and run the compiled version, the main issue is telling the OS to use the python interpreter on that file. The easiest way to do this is with a wrapper script. [msoulier at tigger msoulier]$ cat foo.py #!/usr/bin/python print 'foo' [msoulier at tigger msoulier]$ python -c \ 'import py_compile; py_compile.compile("'foo.py'")' [msoulier at tigger msoulier]$ rm foo.py [msoulier at tigger msoulier]$ python foo.pyc foo So, it works just fine. You just need to wrapper it now in a bourne-shell script. [msoulier at tigger msoulier]$ cat foo #!/bin/sh /usr/bin/python $HOME/foo.pyc [msoulier at tigger msoulier]$ ./foo foo That's it. Mike -- Michael P. Soulier , GnuPG pub key: 5BC8BE08 "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix HTML Email Considered Harmful: http://expita.com/nomime.html From achrist at easystreet.com Sat May 24 12:43:47 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sat, 24 May 2003 09:43:47 -0700 Subject: [Q]:Generate Unique ID's References: <3ECE8494.5A6EA6EB@easystreet.com> Message-ID: <3ECFA143.39FBE030@easystreet.com> "Martin v. L?wis" wrote: > > Steven Taschuk wrote: > > > When you say "no exceptions", do you mean "some very small number > > of exceptions, close enough to zero for all practical purposes"? > > He meant what he said: forever unique, no exceptions. That, of course, > means that he has fallen to marketing hype. What the algorithm really > guarantees is "close enough to zero for all practical purposes". > That IETF doc that was mentioned a ways back in this thread did mention that there would be some kind of a rollower in about 1400 years, so forever isn't quite what it used to be, but it never has been. My back-of-the envelope calculations, done without any envelope, suggest that if you could generate truly random p=0.5 bits, then if you generate a trillion row database every second for a period of time equal to the current age of the universe, and give each row a 128-bit random ID, it's about even money whether or not a duplicate key error would occur once over all those databases over that time period. "close enough to zero for all practical purposes"? Al From gh at ghaering.de Sat May 24 13:18:17 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 24 May 2003 19:18:17 +0200 Subject: latin1 encoding as default? In-Reply-To: <3ecfa218$0$11134$ba620e4c@reader0.news.skynet.be> References: <3ecfa218$0$11134$ba620e4c@reader0.news.skynet.be> Message-ID: <3ECFA959.6070406@ghaering.de> Helmut Jarausch wrote: > HI, > > is there a means to configure Python such that I > can enter string constants in latin1-encoding? Yes. > I've tried to set encoding='latin1' in site.py > but it didn't accept characters like > ? - I get unsupported characters in input. First, use sitecustomize.py instead of hacking site.py for local changes :-) Then, such an approach is not recommended, as your app will then depend on local changes to run correctly. > (This is cvs python 05/24) > > Thanks for a hint, Use an encoding cookie, they're meant for exactly this purpose: http://www.python.org/peps/pep-0263.html -- Gerhard From aahz at pythoncraft.com Sun May 18 18:55:20 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 May 2003 18:55:20 -0400 Subject: __getattr__ functionality for modules? References: Message-ID: In article , Stefan Franke wrote: > >Is there a way to achieve for modules what overriding __getattr__ does >for classes? Nope, and Guido is violently opposed to making this possible. Why not just use a class? (To Alex, Stefan isn't about using getattr(), he's asking about .__getattr__()) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From duncan at NOSPAMrcp.co.uk Thu May 29 09:21:18 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 29 May 2003 13:21:18 +0000 (UTC) Subject: Array design question References: Message-ID: Peter Slizik wrote in news:bb4oom$5fc19$1 at ID-196014.news.dfncis.de: > Thanks, I know I can use a dictionary. But I think the usage of a > hash-table in the place where 'ordinary' array could be employed is at > least unaesthetical. It is also inefficient. Why do you think it is inefficient? Have you actually tried it and found either a performance problem or excessive use of memory, or are you just guessing. A dictionary is actually slower, but for this sort of use its only about 20% slower, and unless the dictionary is quite sparse there won't be any collisions when using integer indexes. C:\Python23>lib\timeit.py -s "l = [0] * 100" "l[0] += 1" "l[50] += 1" "l[99] += 1" 1000000 loops, best of 3: 1.74 usec per loop C:\Python23>lib\timeit.py -s "l = dict([(i,0) for i in range(100)])" "l[0] += 1" "l[50] += 1" "l[99] += 1" 100000 loops, best of 3: 2.11 usec per loop -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From nospam at diving.ukdiver.com Fri May 16 05:13:04 2003 From: nospam at diving.ukdiver.com (Beanie) Date: Fri, 16 May 2003 10:13:04 +0100 Subject: newbie help ? - thanks as i though crash stoopidity References: Message-ID: > comments = request.from_addr , "tried for a code but we run out.") comments = request.from_addr +"tried for a code but we run out.") > comments = "Your Discount code is:" & strDiscountCode & ".") comments = "Your Discount code is:" + strDiscountCode + ".") durr so the script works or i assume it would if zope had the open function -its been removed for security reason :( Error Type NameError Error Value global name 'open' is not defined ta beanie From martin at v.loewis.de Tue May 6 01:42:37 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 May 2003 07:42:37 +0200 Subject: writing Unicode objects to XML References: Message-ID: Steven Taschuk writes: > Our disagreement is in this last sentence. XML is not just the > infoset; it is also a syntax by which the information in the > infoset is (de)serialized. This was an endless debate in the XML community: whether the XML document is just what an XML parser reports, or whether all lexical properties also belong to it. The definition of the XML infoset was meant to end this debate, in the sense "an XML document consists just this information, and an XML processor is not required and should not be expected to return more than that". It is really unfortunate that the XML infoset spec did not end this debate, apparently. > The infoset is an abstraction layer; but XML is octets too. So you would also argue that while 1: pass and while 1: pass are different Python programs? You could do that; Python is octets, too. But it would not be helpful. Regards, Martin From imbosol at aerojockey.com Tue May 13 15:27:37 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Tue, 13 May 2003 19:27:37 GMT Subject: polymorphism References: <%a%va.2384$hX1.844@nwrdny01.gnilink.net> Message-ID: Alex wrote: > Carl Banks wrote: > >>> The longer answer is that python is not statically typed. This makes it >>> *much* more flexible than C++. If desired, polymorphism can be achieved >>> withough any inheritance at all. After a couple days, C++ will feel like >>> a straight jacket. >> >> Dude, you rule. Mind if I use this simile? > > Sure, but I can't take the credit. A professor of mine once used it to > compare Ada and C. I don't know the original source. Hmm--I wonder whether the straitjacket referred to Ada or C. It seems like it should be Ada, but I can see it both ways. -- CARL BANKS From imbosol at aerojockey.com Wed May 14 18:37:05 2003 From: imbosol at aerojockey.com (Carl Banks) Date: Wed, 14 May 2003 22:37:05 GMT Subject: Bug in CPython 2.2.1? - resend References: Message-ID: Fernando Perez wrote: > Martin v. L?wis wrote: > >> Fernando Perez writes: >> >>> Can you at least confirm it's still there with the current versions? >> >> I just tested it, and it crashes with 2.2.2, but I can't reproduce a >> crash with 2.3b1. > > Ok, then I won't file anything. Whatever it was, you guys fixed it > already. I don't know if you consider it important enough to > backport the fix. I would file it anyways. It probably got fixed as a side effect of tidying things up. And IIRC, for both 2.0 and 2.1, someone did a bugfix release after the succeeding version came out, so maybe the same will happen to 2.2? -- CARL BANKS From ohoel at earthlink.net Wed May 21 21:17:09 2003 From: ohoel at earthlink.net (Otto Hoel) Date: Thu, 22 May 2003 01:17:09 GMT Subject: IDLE not working on RedHat 9 Message-ID: Hi, Python works, but IDLE does not. Here is what I get when trying to run it: [root at costaplenty idle]# ./idle Traceback (most recent call last): File "./idle", line 5, in ? from idlelib import IdleConf ImportError: No module named idlelib [root at costaplenty idle]# ./idle.py Traceback (most recent call last): File "./idle.py", line 3, in ? import PyShell File "./PyShell.py", line 13, in ? from Tkinter import * ImportError: No module named Tkinter rpm -qa reveals, among much else, the following: tk-8.3.5-88 but no tcl of any kind. Trying to find Tkinter returns nothing. Running the package config program shows that python devloper packages are installed. What am I missing here? Any pointers greatly appreciated. Otto From haris at email.hinet.hr Sat May 10 16:54:38 2003 From: haris at email.hinet.hr (Haris Bogdanovic) Date: Sat, 10 May 2003 22:54:38 +0200 Subject: Pyrex - Cannot convert Python object argument to type 'void (*)' Message-ID: I have function: def setInputHostApiSpecificStreamInfo(self, void *streamInfo): and I get error: Cannot convert Python object argument to type 'void (*)' I don't understand what's wrong. Haris From nk at nkauer.com Mon May 5 09:56:36 2003 From: nk at nkauer.com (Nikolas Kauer) Date: 5 May 2003 06:56:36 -0700 Subject: dict.get(key, default): conditional default evaluation Message-ID: <19240914.0305050556.40aeedd6@posting.google.com> I propose to not evaluate the expression default in dict.get(key, default) if key in dict. Example: ---------------------------------- >>> class A: ... def __init__(self): ... print "Constructing A instance" ... >>> d = {1: 0} >>> d.get(0, A()) Constructing A instance <__main__.A instance at 0xa094bd8> >>> d.get(1, A()) Constructing A instance 0 ---------------------------------- I'd prefer if in the latter case A.__init__ would not be evaluated. Similar in spirit to b in (a and b) not being evaluated if a is False. From msoulier at storm.ca._nospam Fri May 30 12:07:20 2003 From: msoulier at storm.ca._nospam (Michael P. Soulier) Date: 30 May 2003 16:07:20 GMT Subject: Copy construction of class instance object References: Message-ID: On Wed, 28 May 2003 10:24:08 -0600, Steven Taschuk wrote: > Quoth Bror Johansson: >> Is there a good/recommended way to emulate the copy constructor >> classinstance creation (a la C++) in Python? > > Why do you want to? > > If memory serves (and I haven't used C++ in quite a while, so it > might not), the copy constructor is used when you do, for example, > Foo a; > Foo b = Foo("args", "to", "normal", "constructor"); > a = b; > Then a and b are different objects, the one in a having been > created by the copy constructor. C++ copy constructors are also used under the covers to pass an object by value in a method or function call, something that you don't typically want to do in Python, unless you do it explicitely. Remember, implicit bad. Explicit good. Mike -- Michael P. Soulier , GnuPG pub key: 5BC8BE08 "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix HTML Email Considered Harmful: http://expita.com/nomime.html From tjreedy at udel.edu Fri May 2 02:32:37 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 May 2003 02:32:37 -0400 Subject: Finding items not in 2 lists/dictionaries References: <95c29a5e.0305011933.289d71ca@posting.google.com> Message-ID: "Robin Siebler" wrote in message news:95c29a5e.0305011933.289d71ca at posting.google.com... > On page 15 of the Python Cookbook, it shows how to find all of the > common items in 2 dictionaries. How would I find all of the items > that are *not* in both dictionaries (or lists)? More practical than previous reply (untested, it too late here): out = dict(dict1) for k,v in dict2: if k in out: del out[k] else: out[k] = v Terrry J. Reedy From andros at no_mail.com Thu May 1 12:21:25 2003 From: andros at no_mail.com (Andros) Date: Thu, 1 May 2003 18:21:25 +0200 Subject: delete files/dirs with read-only mode Message-ID: Hello, how to delete an entire directory wich contain files or subdirs with read-only mode (windows) ? Is it possible to change the read-only mode for a file or dir ? Thanks >>> import shutil >>> shutil.rmtree('test') Traceback (most recent call last): File "", line 1, in ? shutil.rmtree('test') File "F:\Python22\lib\shutil.py", line 128, in rmtree raise exc[0], (exc[1][0], exc[1][1] + ' removing '+cmd[1]) OSError: [Errno 13] Permission denied removing test\test.py From fperez528 at yahoo.com Thu May 15 13:53:18 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 15 May 2003 11:53:18 -0600 Subject: Pyrex - Numeric demo doesn't build in 0.7.2 References: Message-ID: Greg Ewing (using news.cis.dfn.de) wrote: > Fernando Perez wrote: >> mat[k,l] = sqrt_N_inv * \ >> exp(I*(alpha*(k*k-k*l+l*l) + kap_al*sin(alpha*l))) > > The array indexing and the calls to exp and sin are all > being done as Python operations. > > For maximum speed, you need to remove all operations > involving Python objects from the inner loop. This will > involve declaring appropriate functions from the > C math library (e.g. sin) so they will be called directly, > and using the techniques from the Numeric demo to poke > data directly into the Numeric array. > > You'll also want to avoid dealing with Python complex > number objects inside the loop. This will mean using > some suitable C library for doing complex exp() etc., > or handling the real and imaginary components yourself. [snip] Thanks a lot for your tips. I was trying to probe pyrex a bit for the kind of things I typically do with weave.inline (C/C++) or f2py (Fortran). It seems that for _this_ case, pyrex may actually not be the easiest tool to use. A simple inlining with weave of the critical loop using: # This version instantiates a Complex number on each element codes['C++ std'] = """ double phi_kl; for (int k=0;k(cos(phi_kl),sin(phi_kl)); } """ # Call weave to execute the C++ code inline(codes[code_tag],['N','alpha','kap_al','mat','sqrt_N_inv','phi'], type_converters = converters.blitz, support_code = support, libraries = ['m'], ) is enough to get a factor of 50 speedup over plain python. So for this kind of situation, inlined C/C++ is really a very low pain/high gain approach. But I'll keep on exploring pyrex for other situations, as it seems to be a very interesting piece of work. Best regards, Fernando. From aahz at pythoncraft.com Sun May 11 11:57:07 2003 From: aahz at pythoncraft.com (Aahz) Date: 11 May 2003 11:57:07 -0400 Subject: Threading problems with httplib References: Message-ID: [posted & e-mailed] In article , David Fendrich wrote: > >Hypothesis: >I think that the problem is related to this: >http://mail.python.org/pipermail/python-dev/2002-September/028555.html >("mysterious hangs in socket code") >Does anybody know if that issue was ever resolved. >I think that httplib (which is used by both urllib and robotparser) is >not thread safe (because I sporadically and non-deterministically get >funny error messages from deep inside the code when I don't surround >those calls with try/except) and that it locks the GIL around code >which is idle and waiting to timeout. According to the post mentioned >above, it might be a problem specific to linux and DNS-resolution. Yup, you're probably right. Although there never was a specific fix to this problem AFAIK, there were some changes made for 2.3 due to other problems. I'd suggest trying 2.3b1, and if that doesn't fix the problem, please file a bug report on SF and post to python-dev. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From max at alcyone.com Mon May 12 21:21:49 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 12 May 2003 18:21:49 -0700 Subject: where should I look for sys.stderr output? References: <63081650.0305120617.9e29ab8@posting.google.com> <63081650.0305121652.40b30cd8@posting.google.com> Message-ID: <3EC048AD.D21C5D25@alcyone.com> Steve Canfield wrote: > I never did find where the stderr is being written to, but I did find > my problem. It probably behooves you to find this out in any case; whatever language or architecture you're using, the first place to look when things don't seem to be working right is the Web server error log, which is going to include the stderr output of any CGI scripts. It's really in your best interest to find out where that is on any host you happen to be using, since you're invariably going to need that information again at some point in the future. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I'm the woman whose / Three wishes came true \__/ Lamya Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python. From tjreedy at udel.edu Tue May 27 17:55:54 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 May 2003 17:55:54 -0400 Subject: Two-dimensional arrays References: Message-ID: <4umdne1MoplzQ06jXTWcpA@comcast.com> "monsterkodi" wrote in message news:d9608a84.0305270903.361a751f at posting.google.com... [in response to my response] > I just think that this way of constructing a multidimensional array > isn't exactly what I would call a 'very clear and intuitive syntax'. ok > Maybe a built in function > array(width,height,depth=0,value=None) > which returns a simple 2 or 3-dimensional array, internally > represented > as lists of lists (of lists) "Carl Banks" wrote in message news:u6OAa.21293$fT5.1655 at nwrdny01.gnilink.net... [also in response to me] > I think a builtin multidimensional array factory would be nice. I > suggest this: > multiarray(dims,initializer=None,func=None) > dims is a sequence of array dimensions. > initializer is an initializer value. Interesting convergence of responses. During the pydev discussion the new sum() builtin, someone suggested that it might be nice to have a simple statistics module (which is where min(), max(), and sum() would belong). If such a thing were to come to pass, an array function should certainly be included. Terry J. Reedy From aahz at pythoncraft.com Fri May 16 14:07:09 2003 From: aahz at pythoncraft.com (Aahz) Date: 16 May 2003 14:07:09 -0400 Subject: passing by refference References: <874r3vhp2m.fsf@charter.net> <87r86zaclk.fsf@charter.net> Message-ID: In article <87r86zaclk.fsf at charter.net>, Doug Quale wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article <874r3vhp2m.fsf at charter.net>, >> Doug Quale wrote: >>> >>>How do you explain assignment (binding) in Python? The values there >>>are references too, right? >> >> Actually, I don't use "value" at all when talking about Python when I >> can help it, because there's the confusion with "value of an object". > >Right, but I ask that that answer be stricken from the record as >non-responsive. Python binding does need to be explained, even if you >don't like to use the word value. How do you explain it? Here's what I usually say: In Python, names contain bindings to objects. A binding is a reference, but experienced Python programmers do not use "reference" because references are not accessible within Python programs (unlike pointers in C). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From gh at ghaering.de Sat May 31 15:23:10 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 31 May 2003 19:23:10 GMT Subject: CGI question: safe passwords possible? References: <3ED86146.F2029ADB@alcyone.com> <1054368881.10515.265.camel@lothlorien> <7x1xyfgxq6.fsf@ruckus.brouhaha.com> Message-ID: Will Stuyvesant wrote: >> > [Gerhard H?ring] >> > That's why I recommended to use digest authentication. > >> [Paul Rubin] >> Javascript has better browser coverage than digest auth, ... >> >> I really think the OP should say more about what he's doing. If his >> security requirements are bad enough that he needs to worry about >> passwords being captured, he may have much worse problems that he >> doesn't know about yet. > > [...] I am building a prototype for an application. For this > I would very much like to do CGI programming with > Python. I already have most of it figured out, with > Python and CGI, in a nice way, independent of host or > operating system etc. But the customer insists on > "security". [...] Ok. It's probably best to use secured HTTP (HTTPS), then. Getting a site hosted via HTTPS *is* more expensive than plain HTTP, but if you need it, you really need it :-) If you're concerned about performance, you could only publish some "pages" of your site via HTTPS, the rest via HTTP. The main advantage that you could also explain to your customer is that HTTPS is proven technology. If my bank uses it for online banking, it should be good enough for you ;-) Especially in the security field, I prefer to use proven technologies instead of inventing my own schemes that I think *should be* secure. > [...] Of course I would prefer Python to javascript, but I > have to deal with a hosted environment, and later on > even unknown hosts, Any hoster should offer HTTPS. > This all seems to lead to the conclusion that Python is > useless for secure CGI programming, at least for the > difficult first "authenticate and login" step, unless > you are a service provider yourself. Python is no different than any other language here. Gerhard -- http://ghaering.de/ From andrew at acooke.org Sun May 11 16:22:40 2003 From: andrew at acooke.org (andrew cooke) Date: Sun, 11 May 2003 16:22:40 -0400 (CLT) Subject: Improve this recursive code please! In-Reply-To: <20030511135925.B627@tibia.amotlpaa.bogus> References: <3EB7DF65.55A50CD4@sarcastic-horse.com> <48827.127.0.0.1.1052666979.squirrel@127.0.0.1> <20030511135925.B627@tibia.amotlpaa.bogus> Message-ID: <3305.10.2.0.2.1052684560.squirrel@127.0.0.1> i think i was calling something (a test routine?) where no bricks == no bins.... Steven Taschuk said: > Quoth andrew cooke: > [...] >> search for 1 1 2 3 5 7 11 15 22 30 42 56 77 101 135 176 231 297 385 490 >> at http://www.research.att.com/~njas/sequences/ >> (or sequence number A000041) >> >> it returns a single result - i can't work out how to link directly - and >> there's no nice simple formula (which cheered me up because i spent a >> while trying to figure one out, but couldn't). > > Ah, but that's the partition function p(n), the number of ways to > store n bricks in any number of bins, where each bin is nonempty, > and bins are not considered distinct. For example, > 4 = 3+1 = 2+2 = 2+1+1 = 1+1+1+1 > showing that p(4) = 5. This is the answer to a different problem; > in the OP's code, the bins are considered distinct, and there's a > maximum number of bins. That turns out to be more tractable; see > my other post of a few minutes ago for a closed-ish form. > > (A direct link for the above sequence: > > .) > > -- > 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) > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://www.acooke.org/andrew From dirk at gerrits.homeip.net Fri May 16 05:01:42 2003 From: dirk at gerrits.homeip.net (Dirk Gerrits) Date: Fri, 16 May 2003 11:01:42 +0200 Subject: Integrate Python in a C/C++ application In-Reply-To: References: Message-ID: Jacky Buyck wrote: > Hi all. > I'm studying solution to embed scripting langage in C/C++ application. > I'll not learn you anything if I say you that giving to an application the > power of scripting you give it a more longer life. > FOr the moment I've mainly focused my attention around Lua and Ruby. But > I want to know if I can do the same with Python ? In Lua it's really simpe. > In Ruby I'ven't make any test for the moment. I know that some game use > Python for their scripting langage so I want to know if it's simple to > control the logic of an application using Python ? Using Boost.Python (http://www.boost.org/libs/python/doc/index.html) it is relatively straightforward. Check out the embedding-part of the Boost.Python tutorial: http://www.boost.org/libs/python/doc/tutorial/doc/embedding.html We're currently working to make it even more straightforward in the future by adding a convenient interpreter class, BTW. Another option is to use the Python C/API directly. (http://www.python.org/doc/current/ext/ext.html) This has the disadvantage that you'll have to do the reference counting of Python objects manually instead of letting Boost.Python take care of that. Manual reference counting is rather error prone, especially when using C++ exceptions and/or functions with multiple return paths, so I advise you to take a look at Boost.Python. Regards, Dirk Gerrits From http Mon May 5 18:32:27 2003 From: http (Paul Rubin) Date: 05 May 2003 15:32:27 -0700 Subject: Should I write a book on Python Metaprogramming ? References: Message-ID: <7x4r49f2is.fsf@ruckus.brouhaha.com> "andrew cooke" writes: > Personally, I would be interested in something that covered the more > obscure / newer parts of Python. I understand that you can generate > bytecode dyanmically, for example. Also, what's the difference between > old + new style classes (including implementation)? What do the various > special __ methods do etc. That belongs in the Python documentation, not in some book you have to buy separately!!! From theller at python.net Fri May 30 11:57:19 2003 From: theller at python.net (Thomas Heller) Date: 30 May 2003 17:57:19 +0200 Subject: control the directory installation of files with bdist_wininst? References: <62ec7e1c.0305300446.2a2e3279@posting.google.com> Message-ID: <7k88h1gg.fsf@python.net> Gerhard H?ring writes: > Thomas Heller wrote: > > Gerhard H?ring writes: > > > > >>David wrote: > >> > >>>I've made a window installer of some files with bdist_wininst. but I > >>>didn't succeed to control the directory installation. > >>>The file created with bdist_wininst makes the installation of my files in > >>>C:\python22. > >>>I'd like to change this directory installation. > >> > >>You can't currently install stuff outside the Python root dir. Making > >>the install path user-selectable at install time has been on the TODO > >>list for some time (look into the source for the bdist_wininst for > >>this). > > I think I should remove these comments, it is not worth it IMO. > > > I disagree. I was asked several times for my DB module installers why > you can't install them. These people did have a Python 2.1, but it was > part of ZOPE. Or they had just copied the Python dir + the > python{major}{minor}.dll from another machine. > Pythonware's (or is it /F's) python distribution has the same problem, he suggests to add some registry info for the installers. > > The only workaround I could give them was to unzip the .exe using > Winzip or whatever and then move pieces where they need go be > themselves. Installation from source is another possibility, for those people without a compiler prebuild source trees could be distributed. > > This, however, is even more inconvenient than bdist_dumb. > > So I think that this feature would be worth it. Not for me, I would not use it. But anyone is 'invited' to finish this stuff and upload a patch. Most of the functionality is already there. Thomas From marcus at infa.abo.fi Tue May 13 13:29:51 2003 From: marcus at infa.abo.fi (Marcus Alanen) Date: 13 May 2003 20:29:51 +0300 Subject: Laughing at myself References: <3ebfc7f4$1_2@hpb10302.boi.hp.com> <3ebfcbcb$1_1@hpb10302.boi.hp.com> <3ec11bcf$1_2@hpb10302.boi.hp.com> Message-ID: On Tue, 13 May 2003 10:22:39 -0600, Daniel Fackrell wrote: >Okay, I think I'm slightly puzzled again. time.sleep(x) appears to behaving >differently depending on the magnitude of x. Look at the man pages of sleep(3), usleep(3) and nanosleep(2) on your Linux system. Especially in the BUGS section of nanosleep(2), the granularity of the sleeping is in 1/HZ, which is often 0.01 seconds. Thus, when sleeping for 0.001 seconds, you are actually sleeping 0.01! Naturally, this leads to a magnitude more of total sleep time. When your sleep time is low enough, the operating system (Or Python. Or the C library) may decide to implement it as a busy wait, and then the total sleep time will drop again. Note that the overhead of the actual call will take some time, which is why you still don't get around 1 second total sleep time. Similar reasoning applies to other operating systems, I guess. Be warned, however: the above is certainly not an _accurate_ description of how any operating system does it, but it's an adequate general rule. The *point* is, "don't assume that sleep() returns immediately after the time has elapsed." If you remember this, you can forget about my guesses above. ;) >Redhat 7.0 (Linux 2.2.16-22): >sleeptime: 1.0, iterations: 1, total: 0.993653059006 >sleeptime: 0.1, iterations: 10, total: 0.997701048851 >sleeptime: 0.01, iterations: 100, total: 0.998471021652 >sleeptime: 0.001, iterations: 1000, total: 9.99859297276 Here, each sleep(0.001) actually means sleep(0.01). >sleeptime: 0.0001, iterations: 10000, total: 99.9983990192 And here the same thing happens. >sleeptime: 1e-05, iterations: 99999, total: 1000.03835404 Again. >sleeptime: 1e-06, iterations: 1000000, total: 92.6922489405 Perhaps the C library decided to take a shortcut??? Regards, Marcus From eichin at metacarta.com Sun May 18 17:08:40 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 18 May 2003 17:08:40 -0400 Subject: jython and midp? Message-ID: <7gof20t12f.fsf@pikespeak.metacarta.com> Has anyone tried using Jython with MIDP? I'm actually interested in coding in python for a Siemens S55 phone, and was wondering if this is a realistic path... From bokr at oz.net Fri May 9 13:26:22 2003 From: bokr at oz.net (Bengt Richter) Date: 9 May 2003 17:26:22 GMT Subject: define References: <3EBA50CB.2040306@cs.nott.ac.uk> <7h3addxy1xe.fsf@pc150.maths.bris.ac.uk> <3EBA7E9F.80003@cs.nott.ac.uk> Message-ID: On Fri, 09 May 2003 12:22:15 GMT, Alex Martelli wrote: > > >Turhan Ozen wrote: > >> I have a long list of parameters. I want to keep them in an array in >> order to pass them to functions. But I want to use the name of each >> parameter in the formulas to make them easy to read. I can use x[index] >> in the formulas. I am trying to have another name for each x[index]. If >> I do anything to this secondary reference, the same is done to the >> corresponding x[index]. >> >> It is possible to do this in C and it looks more readable. > >It looks to me that a good solution is a "list with named items" class. >E.g., in Python 2.3 (warning, untested code): > [... the code ...] >and then you can access and/or set e.g. x[1] equivalently to >x.another. Why you would want to use indexed access as well as >named access, I don't know, but surely it's MUCH clearer and more >readable if any access on an item of x does use x.something rather >than just a bare unqualified 'something' as the name! > I can sympathize with a desire to avoid writing, e.g., x.y = (-x.b + x.sign*sqrt(x.b**2 - 4.0*x.a*x.c))/2.0*x.a in favor of something like, e.g., using y, b, sign, a, c with x: y = (-b + sign*sqrt(b**2 - 4.0*a*c))/2.0*a Or, perhaps, alternatively, with (y, b, sign, a, c) in x: y = (-b + sign*sqrt(b**2 - 4.0*a*c))/2.0*a Or, when it applies to every symbol used (same-line suite optional, of course), with x: y = (-b + sign*sqrt(b**2 - 4.0*a*c))/2.0*a Perhaps it's time to reexamine whether it could be done nicely somehow? Regards, Bengt Richter From timr at probo.com Thu May 22 01:42:06 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 21 May 2003 22:42:06 -0700 Subject: please help me understand os.system() result References: <20030520213938.28fb7e91.bravo@resourcez.org> Message-ID: Roman Suzi wrote: >On Tue, 20 May 2003, Keisuke URAGO wrote: > >> You should shift 8bits like this. >> >> >>> os.system("exit 7") >> 8 >> 7 >> >>> os.system("python -c 'import sys;sys.exit(1)'") >> 8 >> 1 >> >>> os.system("python -c 'import sys;sys.exit(2)'") >> 8 >> 2 > >Thank you, I already guessed it. >However, it's strange that os.system() behaves like this on Linux and the >other way on WinNT/2000. (This is in the docs - so ok) It's not so strange; os.system is returning exactly what the "system" standard library function would return. Windows programmers are used to their way, Unix programmers are used to their way. For those few programs that need to work on both, it only takes a couple of lines of code to handle this. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From andrew-pythonlist at puzzling.org Wed May 14 22:49:17 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 15 May 2003 12:49:17 +1000 Subject: Creating a service/deamon ?? In-Reply-To: <7fqwa.12154$b71.234507@news4.e.nsc.no> References: <7fqwa.12154$b71.234507@news4.e.nsc.no> Message-ID: <20030515024916.GA11403@frobozz> On Wed, May 14, 2003 at 02:02:08PM +0200, Thomas Weholt ( PRIVAT ) wrote: > Hi, > > I need to create a long-time running service/deamon that will monitor some > email-accounts and do certain jobs on given intervals. Preferrably it will > be able to run as a Windows2000-service, available in the service-manager You mention that you are already using Twisted; search the twisted-python mailing list archives for examples of how to run a Twisted app as an NT service. To run any python program as an NT service, you'll need the win32all package. > and as a deamon started by inetd/xinetd etc on Linunx, just like ordinary > services. I don't think inetd is what you meant here -- it doesn't start daemons. I think you meant something that runs with the usual init scripts? If you're using Twisted on Debian Linux, look at the "tap2deb" script. Moshe Zadka is also developing a "twisted-web" package for Debian that includes an init script you could possibly adapt. Your best bet here is probably to ask on the twisted-python list. > I'm working with Twisted for my web-projects so if I could use that package > for this it would be nice. A very nice-to-have feature would be to have the > service available for configuration while running using xmlrpc. If it can be > done using standard modules in the Python-distro that's even better. Twisted makes writing an XML-RPC server incredibly easy; see doc/examples/xmlrpc.py in the Twisted distribution. -Andrew. From gh at ghaering.de Sat May 10 10:04:59 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 10 May 2003 16:04:59 +0200 Subject: Need help with Python programming problem. In-Reply-To: References: Message-ID: <3EBD070B.4030508@ghaering.de> gk wrote: > Been trying to get the following problem to work. So far its been > hectic since i am very new to programming: >[...] but i don't know much syntax and therefore am stuck: It won't help you learn if we give you the complete solution. Do you have any concrete question? -- Gerhard From skip at pobox.com Wed May 21 08:54:40 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 May 2003 07:54:40 -0500 Subject: New-style string formatting In-Reply-To: <20030521084926.GA2450@nl.linux.org> References: <1053433902.3eca202e41ed0@mcherm.com> <20030520155546.GA3145@nl.linux.org> <16074.22020.811260.575419@montanaro.dyndns.org> <20030520193324.GB3665@nl.linux.org> <16074.35919.381153.504398@montanaro.dyndns.org> <20030521084926.GA2450@nl.linux.org> Message-ID: <16075.30480.536098.962846@montanaro.dyndns.org> Gerrit> So, where _does_ the % as string operator come from? Gerrit> My question was actually historic; what is the history of Gerrit> printf? Does it come from C or is it older? Don't know. >> [2] Aside: Would "..."(args) be more efficient than "..."%(args)? Gerrit> No, not at all... I was thinking that the machinery necessary to decide how to execute left % right would be avoided. "..."(args) would cause the interpreter to check the __call__ slot of the string object and call the target. Skip From guettli at thomas-guettler.de Sun May 18 06:33:18 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Sun, 18 May 2003 12:33:18 +0200 Subject: filter directory In-Reply-To: <3ec5a861$0$8986$afc38c87@news.optusnet.com.au> References: <3ec5a861$0$8986$afc38c87@news.optusnet.com.au> Message-ID: <20030518103318.GB749@thomas-guettler.de> On Sat, May 17, 2003 at 01:11:29PM +1000, Psybar Phreak wrote: > ok - does anyone know how to : > > filter the contents of a folder depending on the extension? This script lists all files ending with ".txt". Is this what you want? import os my_files=[] for file in os.listdir("."): if file.lower().endswith(".txt"): my_files.append(file) print my_files thomas -- Thomas Guettler http://www.thomas-guettler.de From Jonathan.Mackenzie at palmsource.com Thu May 22 14:02:38 2003 From: Jonathan.Mackenzie at palmsource.com (Jonathan Mackenzie) Date: 22 May 2003 11:02:38 -0700 Subject: os.popen in unbuffered mode? Message-ID: <3be0b8a4.0305221002.5465fd7f@posting.google.com> Using os.popen("command", 'r', 0) on Windows 2000 (python 2.2.1) and I get: pa = os.popen(progStr, 'r', 0) ValueError: popen() arg 3 must be -1 Can anyone please tell me how to put popen into unbuffered mode? I'm looking to get real-time returns from the subprocess, which is writing to stdout. Thanks! From tundra at tundraware.com Sun May 11 00:50:07 2003 From: tundra at tundraware.com (Tim Daneliuk) Date: 11 May 2003 04:50:07 GMT Subject: Strange Tkinter error Message-ID: <48kk9b.j0j.ln@boundary.tundraware.com> A colleague is attempting to use my 'twander' program on SUSE 8.2. 'twander' is cross-platform filesystem browser implemented in Python and Tkinter and is known to work on RH, Mandrake, FreeBSD, and Win32. However, on SUSE 8.2, it throw the following error: 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(): ?? Any ideas on what might be causing this? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/TundraWare.PGP.Keys.txt From gh at ghaering.de Sat May 31 22:11:06 2003 From: gh at ghaering.de (Gerhard Haering) Date: Sun, 1 Jun 2003 04:11:06 +0200 Subject: Request for feedback on my first Python program In-Reply-To: References: Message-ID: <20030601021106.GA7831@mephisto.ghaering.de> * Sean Legassick [2003-06-01 02:52 +0200]: > In message , Andrew > Walkingshaw writes > >def isMeaningful(line): > > if line != "" and line[0] != "#": > > return True > > else: > > return False > > Yuck! > > def isMeaningful(line): > return line != "" and line[0] != "#"; > > No offence intended, but I've seen this too often in real code not to > point out its redundancy here. No offence intended, but your code is redundant as well ;-) def isMeaningful(line): return not line.startswith("#") And omit the trailing semicolon, you filthy C/C++/Java programmer :-P Gerhard -- http://ghaering.de/ From aleax at aleax.it Thu May 1 06:49:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 01 May 2003 10:49:50 GMT Subject: Raising objects References: <453d10b2.0304290750.222fb453@posting.google.com> <%OYra.27334$3M4.759346@news1.tin.it> Message-ID: Steven Taschuk wrote: ... > Ah yes, the type/class distinction. I frequently forget that. It's gonna go away. But it will take a while. > So what then is the distinction between new-style classes and > types? (Other than that types are not quite reliably subclassable > yet, or so I hear.) There is no way to reliably draw that distinction -- we're in transition and in a mess:-). >> Moreover, if what you raise is always derived by Exception, the >> Exception base class can ensure all sort of nice error-reporting > > A good point. > > But usually in Python we do not care whether an object inherits > from a specific subclass; we only care whether it has the > attributes we need it to have. Why should the error-reporting > facilities of Exception be any different? Exception handling is one of the very few places in Python that DO care who inherits from what! A few others are marginal and explicit -- issubclass, isinstance, calling unbound methods -- but only in exception handling does inheritance play such a major role. So, I think the "usually" doesn't extent to this case. > In other words, why should we stop a programmer who *doesn't* want > those error-reporting facilities from raising some other object? > Isn't trusting the programmer pythonic? Yes, but letting the programmer make a mess in order to let him have features he doesn't need isn't. "23"+45 raises an exception -- not because we don't trust the programmer, but because the exception is more pragmatically useful here than some other silly behavior. Accessing a yet-unbound local raises an exception rather than supplying some default value such as 'None' for an entirely similar reason. I've seen confused newbies use raise 'TypeError' rather than raise TypeError and lose time tracking things down because the string exception does alas have to be accepted for backwards compatibility. I am NOT at all keen to extend the occasions for such confusions and mistakes without any good countervailing practical reason. > clause. (My excuse for forgetting this is that I always raise > instances.) > > I'd like to get rid of this; it seems conceptually wrong to me > that a class and its instances are interchangeable in this Nolo contendere, but I think backwards compatibility binds us forevermore in this respect. > respect. The identity test which makes it work made sense back > when exceptions were strings (as you explained so cogently), but > imho it's now a (minor) wart for backwards compatibility. > > So, what I'd like to see eventually is this: > > Raise anything you like. > > An except clause catches an exception e if and only if it > names a type of which e is an instance. I think you'll never see that -- you always raise instances, but most others always raise classes -- look at the standard library and you'll see just about all raise SomeClass, 'someargument' If I could raise anything I like I would expect this to raise a tuple with two items -- a class then a string:-). Some modules are even inconsistent in this, e.g. Lib/copy_reg.py: raise ValueError, "code out of range" Lib/copy_reg.py: raise ValueError("key %s is already reg... In a greenfield-designed language this might or might not make sense (I would still prefer a specific Exception type which must be the base of anything raised, for all of the advantages you previously conceded, for 'except Exception' as the best way to catch anything, etc, etc) -- but the debate is moot. Python 3000 will introduce incompatibilities but, I think, none as deep as this one would be. > This seems simpler than what you would want to see eventually: > > Raise any subclass of (New)Exception, or an instance of such > a subclass. > > An except clause catches an exception if and only if it > names either a type of which e is an instance, or an object > which is identical to e. > > (Hopefully I've correctly understood what you're saying.) Either > of these is, of course, simpler than the present rules. I would explain my desiderata differently: raising any instance of NewException raises it; raising any subclass of NewException instantiates it (optionally with the provided argument[s]) and raises the resulting instance. So, the exception that is propagating is ALWAYS an instance of NewException. An except clause catches an exception E, if and only if it names a type of which E is an instance. The backwards-compatibility hacks aren't in my "desiderata" -- and it MIGHT conceivably be possible to remove string exceptions one day and just make Exception newstyle (well, one can dream, but I DO dream of a day where classic classes have gone!). > The only disadvantage of my ideal scenario that I can see is that > it introduces a new kind of "forgot the parentheses" bug; > raise ValueError > would raise an exception which would go right past > except ValueError: > and only be caught by the very unlikely > except type: > or a bare except. That, and other errors. > To get from the present rules to my ideal scenario, the identity > test has to be removed, and while we're at it, the syntax > raise foo, bar > should go too. (Again, it made sense back when exceptions were > strings.) And perhaps sys.exc_* would have to be revised as well. If the BDFL ever Pronounces that "raise foo, bar" should eventually go, then I guess it may, but I've never seen him express any dislike of it. > The path seems straightforward: > > Step 0. Revise the Tutorial to advocate "raise ValueError(...)" > instead of "raise ValueError, ...". Mention the latter only as > an old way of doing things. But it's not -- the newest modules in the standard library use it just as freely as the older ones. > Step 1. Issue warnings when an exception is caught by the > identity test, and when the "raise foo, bar" syntax is used. > (These warnings could be phased in via __future__ if desired.) Warnings have their own ways to enable/disable. And yes, it WOULD be nice to start getting optional warnings for usage tied to string exceptions (but I doubt the 2-arguments raise will be warned about). > Step 2. Remove the identity test; catch only by the isinstance > test. Remove the "raise foo, bar" syntax. Revise sys.exc_* > if appropriate. > > Step 3. Make Exception a new-style class. > > Step 4. Allow anything to be raised. > > (I haven't thought about the e in > except ValueError, e: > yet.) I don't see how that could cause a problem. > Hm... maybe I should write a PEP. Yes, I agree you should -- nothing as major as this is gonna happen without a lot of PEPping. Alex From jamie at nospam.net Tue May 27 16:53:04 2003 From: jamie at nospam.net (Jamie) Date: Wed, 28 May 2003 08:53:04 +1200 Subject: SHGetFileInfo References: <65nx0zmw.fsf@python.net> Message-ID: Many thanks, Thomas. Jamie "Thomas Heller" wrote in message news:65nx0zmw.fsf at python.net... > "Jamie" writes: > > > Hi all, > > > > Does anyone have an example of how to make this call using either the ctypes > > module or the win32 python extensions? > > I don't find it in the win32 extensions, so here is the ctypes version, > which prints this (WinXP pro german): > > 1 > 0x40400177L > 'python.exe' > 'Anwendung' > > Thomas > ----- > from ctypes import * > > MAX_PATH = 260 > HICON = c_int > > class SHFILEINFO(Structure): > _fields_ = [("hIcon", HICON), > ("iIcon", c_int), > ("dwAttributes", c_uint), > ("szDisplayName", c_char * MAX_PATH), > ("szTypeName", c_char * 80)] > > SHGFI_ICON = 0x000000100 > SHGFI_DISPLAYNAME = 0x000000200 > SHGFI_TYPENAME = 0x000000400 > SHGFI_ATTRIBUTES = 0x000000800 > SHGFI_ICONLOCATION = 0x000001000 > SHGFI_EXETYPE = 0x000002000 > SHGFI_SYSICONINDEX = 0x000004000 > SHGFI_LINKOVERLAY = 0x000008000 > SHGFI_SELECTED = 0x000010000 > SHGFI_ATTR_SPECIFIED = 0x000020000 > SHGFI_LARGEICON = 0x000000000 > SHGFI_SMALLICON = 0x000000001 > SHGFI_OPENICON = 0x000000002 > SHGFI_SHELLICONSIZE = 0x000000004 > SHGFI_PIDL = 0x000000008 > SHGFI_USEFILEATTRIBUTES = 0x000000010 > > > shfileinfo = SHFILEINFO() > > import sys > > flags = SHGFI_DISPLAYNAME | SHGFI_TYPENAME | SHGFI_ATTRIBUTES > print windll.shell32.SHGetFileInfo(sys.executable, > 0, > byref(shfileinfo), > sizeof(shfileinfo), > flags) > > print hex(shfileinfo.dwAttributes) > print repr(shfileinfo.szDisplayName) > print repr(shfileinfo.szTypeName) > ----- From graham at rockcons.co.uk Sun May 18 23:32:39 2003 From: graham at rockcons.co.uk (Graham Nicholls) Date: Mon, 19 May 2003 04:32:39 +0100 Subject: A little disappointed so far References: <3ec8309c.15860507@news.cybermesa.com> Message-ID: Aahz wrote: > In article , > Graham Nicholls wrote: >> >>I use autoindent in vim/gvim, but reckon I may need to up the tabs to 4 >>perhaps. I've never got on with emacs, though - vi is God's own editor. >>(Now I'll really start a flame war!) > > Don't worry, you've got lots of vi[m] company here -- after all, Python > is the scripting language in vim! Now thats interesting! -- Graham Nicholls All round good guy. From tjreedy at udel.edu Mon May 5 12:33:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 May 2003 12:33:16 -0400 Subject: PEP 315: Enhanced While Loop References: <3EB33BB7.60805@pobox.com> Message-ID: "Andrew Koenig" wrote in message news:yu99isspv9mm.fsf at europa.research.att.com... > By implication, there is no obvious reason that one could not write > > while : > > and while : > > and while : > To me, this is the best alternative (to the current idiom) so far. No new keyword, no ambiguity about where block begins and ends. However, the actual execution flow is still not necessarily clear. Reading this naively, I would expect the loop to continue, and to continue to be executed, until was false. Or something like that. > which would be equivalent to > > while : > > if not (): break > > if not (): break > > > Looking at these examples, I find myself liking the "and while" idea more, > because it uses (negative) indentation to mark the possible exit points. I am beginning to like explicit breaks more. Terry J. Reedy From aleax at aleax.it Mon May 5 04:14:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 05 May 2003 08:14:44 GMT Subject: PEP263 (Specifying encoding) and bytecode strings References: Message-ID: Tony Meyer wrote: >> > Is there some way to specify that all strings are >> > bytecodes, and not encoded characters? >> Couldn't resourcepackage just insert a suitable encoding >> "declaration", which is after all a comment and thus >> innocuous for any previous release of Python -- or else emit >> non-ascii chars as escape sequences? > > I probably phrased my question poorly: what, then, is the correct > encoding for the output of zlib.compress()? I know IANA has a list [1] > of encodings, but it's not really clear which is the right one. > > [zlib.compress() returns a string of '\xXX's, where XX is from 00 to > FF.] > > I'm happy to admit that I know almost nothing about encodings. > Particularly, I don't see why '\xda' [2] is not considered ascii. It > should be an upper case U with an acute, according to rfc1345 [3] - > isn't that what ascii is? No. The A in ASCII stands for "American" (the rest of the letters stand for "Standard Code for Information Interchange). The standards body who aproved that standard is ANSI (the American National Standards Institute), and the document that currently defines it is: Standard ANSI X3.4-1986, "US-ASCII. Coded Character Set - 7-Bit American Standard Code for Information Interchange". US-ASCII is the preferred name of this encoding for MIME purposes, by the way. But almost always it's referred to as just ASCII. I suspect (but cannot be sure) that ISO 8859-1 is the encoding you want to use for your purposes. Alex From max at alcyone.com Wed May 28 15:33:14 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 28 May 2003 12:33:14 -0700 Subject: pickle, marshal, ? References: Message-ID: <3ED50EFA.A96972B0@alcyone.com> Max Khesin wrote: > pickle is introduced as very fast but version dependent can for simple > data > structures only. marshal is relatively slow but version-independent > and > supports complex data structures. I am looking for something that is > version-independent but trades off data structure complexity for speed > - it > only needs to do lists, dictionaris & strings. Sounds like you have these reversed. pickle is the one that's version-independent; marshal is the one that's explicitly documented as "Details of the format are undocumented on purpose; it may change between Python versions (although it rarely does)." -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Your theory is not right; it is not even wrong. \__/ Wolfgang Pauli From abcdebl2nonspammy at verizon.net Fri May 23 00:47:53 2003 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Fri, 23 May 2003 04:47:53 GMT Subject: Thank you everyone In-Reply-To: References: Message-ID: The people in this group are really great. Thanks everyone. This is exactly what I was looking for. David Lees From bdesth at removethis.free.fr Fri May 16 13:47:06 2003 From: bdesth at removethis.free.fr (laotseu) Date: Fri, 16 May 2003 17:47:06 +0000 Subject: language aesthetics References: Message-ID: <3EC5241A.1010508@removethis.free.fr> Sandy Norton wrote: > Hi, > > I often worry that I've become so 'comfortable' with python that I may > end turning into a language bigot not appreciating the ideas and > motivations behind other language designs. As a counter to this, I > usually take it upon myself to put some effort into learning how other > languages do it. At times this leads to wonderful and rewarding > journeys (e.g. haskell), and at other times, I run away screaming back > to pythonistan (e.g. > http://www.perl.com/pub/a/2003/04/09/synopsis.html ). > > My question is: what other languages 'fit' the common aesthetic (if it > exists) of a pythonista? IMHO, you could go for Smalltalk, Objective-C (which adds a Smalltalk-like object layer to plain old C), and Common Lisp... my 2 (euro)cents... Laotseu From hleblanc at bitstream.net Tue May 6 10:04:36 2003 From: hleblanc at bitstream.net (Harry LeBlanc) Date: Tue, 06 May 2003 09:04:36 -0500 Subject: streaming ogg vorbis Message-ID: <3eb7c063$0$79558$6536d21b@news.bitstream.net> Hi, I posted a message a couple of weeks ago about uml & ogg vorbis. Got lots of useful replies about uml, but no one spoke to the other issue. I need to stream ogg vorbis audio files from a python-driven website. Is that possible? What are the toolkits out there that support this? Thanks for your feedback. You can email me personally at hleblanc (at) bitstream (dot) net. Harry From aleax at aleax.it Mon May 19 08:33:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 19 May 2003 12:33:56 GMT Subject: Newbie question - strings References: Message-ID: mandingo wrote: > Sorry for my ignorance. > > What is the Python equivelent to VB's NthField? where in Basic you might have: somestring = "a,few,words,go,here" another = NthField(somestring, ",", 3) in Python you might have: somestring = "a,few,words,go,here" another = somestring.split(",")[2] Note that in the Python approach you're building a whole list of fields then selecting a specific one (0-based indexing like everywhere in Python) -- more often than not you'll want more than one field so you'll save the list and use it repeatedly, e.g.: somestring = "a,few,words,go,here" fields = somestring.split(",") afield = fields[0] another = fields[2] and the like. But, if you do want just one field, you can choose to create and index the list at once. Alex From tug at wilson.co.uk Thu May 22 08:42:55 2003 From: tug at wilson.co.uk (John Wilson) Date: Thu, 22 May 2003 13:42:55 +0100 Subject: [Tree] Looking for tree python library References: Message-ID: <219401c3205f$ab231190$640a0b0a@handel> ----- Original Message ----- From: "Sinclair" Newsgroups: comp.lang.python To: Sent: Thursday, May 22, 2003 1:32 PM Subject: [Tree] Looking for tree python library > Hi, > > I need a library of python tools for managing trees. Appendix B of http://www.ruraltech.org/pubs/theses/ceder/ceder_ms_thesis.pdf describes such a Python program John Wilson ;-))) The Wilson Partnership http://www.wilson.co.uk From rnd at onego.ru Tue May 20 07:17:17 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 20 May 2003 15:17:17 +0400 (MSD) Subject: please help me understand os.system() result Message-ID: Under Linux I have very strange results for exit status info: >>> os.system("exit 7") 1792 >>> os.system("python -c 'import sys;sys.exit(1)'") 256 >>> os.system("python -c 'import sys;sys.exit(2)'") 512 True for my RH 7.3 and 6.2, for Pythons 1.5.2, 2.1, 2.2.2. Any ideas? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From ta-meyer at ihug.co.nz Fri May 2 00:18:35 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 2 May 2003 16:18:35 +1200 Subject: Temporary Files In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13015F25EB@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13C8CAF4@its-xchg4.massey.ac.nz> > Well, just to interrupt this internal dialog, would it help if you > actually *did* that and then tell us what you see? ;-) Well, one problem is that the original method works fine for me, as does the copyfileobj one. I don't have a linux box to test on, and rather than go through the slow process of getting someone else to do the test, I thought maybe someone could tell me a canonically correct method of doing it. It does seem to work (although there needs to be a seek() after the flush()), but then the old way did too ;) I presume from the scarcity of replies, that there *isn't* a canonical method of doing this, and so what I've got will do. > You'll notice that like you I'm too idle to spend an hour looking for > shutil.copyfileobj() when I could do it in Python in a few lines ;-) :) And they hid the doc on it right next to shutil.copyfile(), too - why would I look *there*? ;) =Tony Meyer From bunger00 at grm.hia.no Thu May 8 14:01:48 2003 From: bunger00 at grm.hia.no (Bunger) Date: 8 May 2003 11:01:48 -0700 Subject: Problem with python script in windows Message-ID: <2ba63562.0305081001.1a962ea9@posting.google.com> Thanks for the help so far, but now I've got new problems. Please help me, what can I do to get this to work? bjorn this is the error messeges I get Encoding 'ready.avi' Traceback (most recent call last): File "C:\Documents and Settings\Bjorn\Desktop\test.py", line 47, in ? main(sys.argv[1:]) File "C:\Documents and Settings\Bjorn\Desktop\test.py", line 40, in main encode(file) File "C:\Documents and Settings\Bjorn\Desktop\test.py", line 27, in encode execPip.wait() AttributeError: 'tuple' object has no attribute 'wait' This is det code: #!/bin/env python import sys import os import popen2 INDIR = "c:\\inn" OUTDIR = "c:\\ut" FINDIR = "c:\\ferdig" ENCPATH = "C:\\Nokia\\Tools\\Nokia_Multimedia_Converter_2_0\\MMConverterCon.exe" def getInFiles(): files = os.listdir(INDIR) if len(files) == 0: return None else: fixedList = [] for file in files: fixedList.append(os.path.join(INDIR, file)) return fixedList def encode(file, store=OUTDIR): execStr = "%s -i %s -o %s" % (ENCPATH, os.path.basename(file), os.path.join(store, os.path.basename(file)[:-4] + ".3gp")) execPip = popen2.popen3(execStr) execPip.wait() os.rename(file, os.path.join(FINDIR, os.path.basename(file))) def main(args): newFiles = getInFiles() if newFiles == None: print "Ingen nye filer ? konvertere" sys.exit(1) else: for file in newFiles: print "Encoding '%s'" % os.path.basename(file) encode(file) print "Done converting %d files" % len(newFiles) sys.exit(0) if __name__=="__main__": main(sys.argv[1:]) From hemanexp at yahoo.com Sat May 24 13:01:34 2003 From: hemanexp at yahoo.com (Python-lover) Date: Sat, 24 May 2003 10:01:34 -0700 (PDT) Subject: Keypress event in canvas.......... Message-ID: <20030524170134.30951.qmail@web41901.mail.yahoo.com> Hi, iam using python and Tkinter. Is it possible to bind a keyboard event, say "Up" arrow press, to a canvas item (like rectangle)? i have created a canvas and drawn a set of rectangles one above another.Now when i press "Up" arrow key first time i expect first rectangle to get focus and second one for next keypress and so on utill you reach the last rectangle. how can i do it? My sample code is given below:***************************************from Tkinter import * class App: def __init__(self,parent): self.myparent = parent self.canvas = Canvas(self.myparent,width=600,height=500) self.canvas.pack() x1 = 100 y1 = 100 x2 = 200 y2 = 200 i = 1 while i<4: self.canvas.create_rectangle(x1,y1,x2,y2,tag='RECT',fill='red') y1 = y2 y2 = y1 + 100 i = i+1 self.canvas.tag_bind('RECT','', self.get_rect_points) def get_rect_points(): #....................... # Here i want to get rectangle points #........................ root = Tk() myapp = App(root) root.mainloop() Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vze4rx4y at verizon.net Thu May 29 03:45:33 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 29 May 2003 07:45:33 GMT Subject: string.split escaping References: Message-ID: "Dave Harrison" If I have a string > > a = 'dog;cat;big;dog' > > How do I escape the last ';' so that when I call > > string.split(a, ';') > > I get > > ['dog', 'cat', 'big;dog'] Since the split method doesn't have a builtin escape mechanism, you'll need to simulate it by: * using an escape character of your own choosing * use replace() to block out the occurrences in the string * do the split * use replace() to put back in you split character. >>> a = 'dog;cat;big_;dog' # using underscore as an escape character >>> def mysplit(s, splitchar=';', escchar='_'): escaped = escchar + splitchar marker = escchar + escchar newstr = s.replace(escaped, marker) seqn = newstr.split(splitchar) return [part.replace(marker, splitchar) for part in seqn] >>> mysplit(a) ['dog', 'cat', 'big;dog'] Raymond Hettinger From mhammond at skippinet.com.au Thu May 8 22:53:37 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 09 May 2003 02:53:37 GMT Subject: Trying to use COM... "Type mismatch" error In-Reply-To: References: Message-ID: Simon Withers wrote: > OK, I used Makepy on a third party .dll file, TGLLib.dll which is used > from VB to create/add to localized string files, for use in a game > (Bridge Commander, if anyone cares..) > > Now, I come to import TGLLib, and it turns out that things haven't > quite worked right, if the VB Code is anything to go by. The > CoClasses don't have access to the functions that they need from the > DispatchBaseClasses, and when I tinker around a little to let them get > access, it returns You should just be able to run makepy, then use win32com.client.Dispatch as normal. Evertthing should "just work" (but unfortunately doesn't for some). > com_error: (-2147352567, 'Exception occurred.', (0, 'TGLLib', 'Type > mismatch', None, 1000013, -2146828275) This means that TGLLib itself threw an exception. This often means that you passed an incorrect type. Can you post the complete interactive session, and the traceback. Also please include a "print repr(ob)" in the output, where "ob" is the COM object you are trying to call. Mark. From steve at ferg.org Mon May 5 09:33:02 2003 From: steve at ferg.org (Stephen Ferg) Date: 5 May 2003 06:33:02 -0700 Subject: Should I write a book on Python Metaprogramming ? References: Message-ID: > Would you want a book only if it focusses closely on Python? Or > would you rather have a book that addressed several languages fairly > equally, with Python just one among them? I think your description says what it should be: This book aims both to introduce readers to the general concepts of metaprogramming--in a way that applies to many programming languages--and to illustrate the use of these features in Python. Stick to a single language for illustration purposes -- that will help keep the book focussed. You will spend you time on concepts and their illustration, rather than on the quirks and syntax of many different langauges. Also, it will keep the book shorter (shorter to read, shorter to write), which makes life easier for both reader and author. From ramen at lackingtalent.com Sun May 25 17:11:54 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sun, 25 May 2003 21:11:54 -0000 Subject: can't sort References: <3ec61600$0$11142$ba620e4c@reader0.news.skynet.be> <3ecd0282$0$76090$edfadb0f@dread11.news.tele.dk> Message-ID: In article <3ecd0282$0$76090$edfadb0f at dread11.news.tele.dk>, Anders J. Munch wrote: > Suppose we added the following function to the builtins. Or at least, > to a standard module. > > def sort(sequence, cmpfunc=None, project=None): > """sort a sequence, returning a new list; > if given, cmpfunc(x,y) -> -1, 0, 1; > if given, sequence is sorted as would be [project(x) for x in sequence]""" > if cmpfunc is not None: > assert project is None > sorted = list(sequence) > sorted.sort(cmpfunc) > elif project is not None: > intermed = [(project(val), no, val) > for (no,val) in enumerate(sequence)] > intermed.sort() > return [elem[2] for elem in intermed] > else: > sorted = list(sequence) > sorted.sort() > return sorted > > This function sorts arbitrary sequences (presuming enumerate works for > unsized sequences, haven't tried out 2.3 so I don't know for sure), > and always returns a new list. > > For good measure it also implements the DSU pattern if you provide a > projection function. +1 From goodger at python.org Fri May 2 20:51:44 2003 From: goodger at python.org (David Goodger) Date: Fri, 02 May 2003 20:51:44 -0400 Subject: POD vs. reST for standalone writing? In-Reply-To: References: <7gd6j6kpq0.fsf@pikespeak.metacarta.com> <7gy91ssyrl.fsf@pikespeak.metacarta.com> <7gfznz5lld.fsf@pikespeak.metacarta.com> Message-ID: <3EB312A0.1020508@python.org> Bengt Richter wrote: > Is there a command line reST viewing utility that converts to a temp HTML > file and starts a browser to show it? (or just the file -> file conversion, > the rest would be trivial to add). A reStructuredText to HTML front-end tool is included in the Docutils package, tools/html.py. Usage: html.py input.txt output.html Use --help to see all the options. Docs are at . -- David Goodger http://starship.python.net/~goodger Programmer/sysadmin for hire: http://starship.python.net/~goodger/cv From philh at cabalamat.org Tue May 27 09:45:55 2003 From: philh at cabalamat.org (phil hunt) Date: Tue, 27 May 2003 14:45:55 +0100 Subject: A syntax idea for one-liners References: <3ED14876.C032CB0B@engcorp.com> <4017400e.0305252149.492e4fe5@posting.google.com> <3ED1B8B9.2070803@blueyonder.co.ukNOTthisBIT> Message-ID: On Mon, 26 May 2003 12:54:43 -0400, Lulu of the Lotus-Eaters wrote: >philh at cabalamat.org (phil hunt) wrote previously: >|>Now I like that idea, you could write a module with a short name that >|>when imported could read an option for the oneliner, transform then exec it. >|> >|> python -e 'import L1' -L1 'if a: if b: c;; if d: e;;; f; h' >| >|Or better, have a python1L executable allowing you to write: >| >| python1L 'if a: if b: c;; if d: e;;; f; h' > >And best still, just write an five line script called 'python1L' (or >whatever) whose first line is "#!/usr/bin/env python", and use that to >run your one liners with odd semicolon syntax. Indeed, that's what I meant. ("Executable" meant the x flag is set, it doesn't mean it contains binary machine code). -- Philip Hunt Interested in adventure holidays in Spain? Look at: From nex8 at gmx.net Tue May 13 09:21:49 2003 From: nex8 at gmx.net (Thomas) Date: 13 May 2003 06:21:49 -0700 Subject: Convert CPython library with C Code to Jython and Java References: Message-ID: Gerhard H?ring wrote in message news:... > Thomas wrote: > > Hello! > > > > I want to port a Python library that contains C code to Jython and > > Java. What is the easiest way to do that? > > > > (1) Convert C library to Java. > > (2) Somehow integrate compiled .pyd library into Jython and Java. > > (3) Any other solution? > > > > Since I don?t have enough C know-how, I would prefer not to go for > > option (1). Can you recommend me any workaround? > > Option 2): In theory, JPE is the simplest solution: > http://www.arakne.com/jpe.htm > But I think JPE is unfinished. > > If 1) is feasible and you have somebody proficient in both C and Java > (for example yourself), I think it might be the best option. > > -- Gerhard Thanks, Gerhard, I try to check out JPE! From altis at semi-retired.com Thu May 8 01:03:52 2003 From: altis at semi-retired.com (Kevin Altis) Date: Wed, 7 May 2003 22:03:52 -0700 Subject: Python used in WSH (windows scripting host) References: <3EB9D473.2133@maxinter.net> Message-ID: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65108 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65107 I think there are more in the Cookbook, but ASPN search isn't working right now, so I can't hunt them down. ka "C Chang" wrote in message news:3EB9D473.2133 at maxinter.net... I am looking some information that creates WSH using python script. Anyone know some? Thanks. C Chang From precisa at uai.com.br Mon May 19 16:41:52 2003 From: precisa at uai.com.br (Geraldo Lopes de souza) Date: Mon, 19 May 2003 17:41:52 -0300 Subject: Python and Databases Message-ID: Hi, I'm not a python programmer, but I like the language. I have read the manuals installed and played a little with wxPython (a nice library), I'm a Delphi programmer, I work making database applications. I have considered to change to python, because it's a superior language, productive, expressive, etc. From time to time I stop and try to do this, but I face one thing: The lack of multi-database library. I think that this block many people from making this change. If you're going to use just one database then ok, but if you want to use more than one, you have just one choice: the mxODBC package. It looks like a great package , it worths the price, but with java for example, I get more much more ( in library terms) for less. I don't intend to attack or be rude with the commercial package , but I have seen many discussion of the acceptance of python to make business applications. To increase this the python community needs a standard ODBC library in the language. You might say: Go for java. We are happy the way we are. For the answer I say, I like python more than java. When I get my hands in java I say : This would be a lot simpler if were done in python. You might say: Why don't you develop such library ? I haven't enough knowledge to do this, but I would test, a library like this. What I (imho) think the community needs, is an effort to make python to talk with databases in an uniform way. I know there is the DB API but we need ODBC. ODBC is the standard way of communicating with databases, if you create a database the first thing you need is an odbc driver to make the existing applications to talk with your database. What do you think, ? Please post your points. Sorry my english. Geraldo Lopes de Souza From afriere at yahoo.co.uk Thu May 8 01:04:51 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 7 May 2003 22:04:51 -0700 Subject: Help me understand... References: <3eb883c1_7@corp.newsgroups.com> Message-ID: <38ec68a6.0305072104.770557f8@posting.google.com> "Norm" wrote in message news:<3eb883c1_7 at corp.newsgroups.com>... > I'm learning this slowly... > > As I read the syntax of using split it says this in IDLE. > s.split(sep [,maxsplit]]) -> list of strings > > Now what I misunderstood out of this was that I should use [brackets] and a > ,comma such as this. > The square brackets here do not indicate a list. In describing a command and its arguments square brackets traditionally denote optional arguments as in : foo arg0 [opt_arg1 [opt_arg2]] which says foo takes the argument arg0, followed optionally by opt_arg1, followed optionally by opt_arg2 (but only if opt_arg1 was given.) When you find a comma in the square bracket, as in your example, this means that if you give the optional second argument, you must separate it from the first using a comma. > After 30 tries I got this to work > s.split("n",3) - how come the quotes weren't in the help? Because the quotes aren't necessary to the command, but only to indicate a literal. ie you could have written: foo = "n" s.split(foo, 3) From fperez528 at yahoo.com Tue May 20 18:28:06 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 20 May 2003 16:28:06 -0600 Subject: ANN: IPython 0.4.0 Message-ID: Announcing an update to IPython, an enhanced interactive Python shell. * WHAT is IPython? IPython tries to: 1. Provide an interactive shell superior to Python's default. IPython has many features for object introspection, system shell access, and its own special command system for adding functionality when working interactively. 2. Serve as an embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. 3. Offer a flexible framework which can be used as the base environment for other systems with Python as the underlying language. * WHERE to find it: http://ipython.scipy.org It's been a while (over a year) since I've announced an ipython release here. But there has been a steady stream of development, so if you haven't upgraded in a while, you should. * NEW since last public release (ChangeLog included with full details, I only give highlights here because there have been too many changes). Note that these are the changes since 0.2.14, which I did not announce here. The changes since 0.2.10, the last one announced in c.l.py are FAR more substantial, and simply too many to list (almost half the changelog). Bug Fixes --------- - Fixed many crashes caused by the auto-eval code. The new code is much safer, and free of potential side-effects. Autocalling became controllable at runtime via @autocall. This should be considered a critical fix. - Fix namespace handling in @run which could cause problems with pickle. - Fixed color handling across many terminal types. Except for MS-Windows native cmd.exe windows, all terminals seem to handle color fine now. - Fixed the installer removing many ugly distutils-related hacks/bugs. It doesn't generate spurious errors and warnings anymore. - Various fixes to the Gnuplot support (an important one in hardcopy). - Fixed crash when pdb.pm() was called. - Fixed potentially destructive change of files in ~ when ipython ran first. - Fixed crash for user-defined prompt strings with unmatched '%' in them. - Better handling of sys.excepthook to protect against spurious errors when exceptions are generated by WxWindows. - Internal workaround in case 'kinds' is not found (recently removed from Numeric's standard distribution). - Added workaround for SWIG crashes when inspecting objects. New features/enhancements ------------------------- - Optional (off by default) auto-indenting. It can be toggled at runtime. - Better support for mouse/non mouse versions of Gnuplot. - Better timing routines (under Unix) in genutils, which use getresource(). These avoid the wraparound problems inherent in time.clock(). - IPython now supports -c option, just like regular python. - IPython now has manpages (for ipython and pycolor). - RPMS are provided by me, and Debian/Fink packages are being contributed by Jack Moffitt and Andrea Riciputi (respectively). - Improved (X)Emacs integration. It now seems to work almost perfectly (using Alex Schmolck's support files, available at ipython's site). * PORTABILITY: Linux (and other unices, including Mac OSX), Windows XP/2k, Win9x (tested on 98, don't really know about 95). Note to Windows users: while I check that IPython installs and runs fine under WinXP, many of its better features are not available there. Some of this is due to the limitations of the platform, some to the fact that I simply do not use windows myself and hence can not improve it there. Some users are helping in this direction, so things may improve in the future faster than they have before. * Python version: requires 2.1 or newer. * License: LGPL (a few files from third parties carry MIT licenses). Cheers, Fernando Perez. From corey.coughlin at attbi.com Tue May 20 17:05:17 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 20 May 2003 14:05:17 -0700 Subject: language aesthetics References: Message-ID: I second the vote for Eiffel (SmallEiffel being a good implementation), but I'll have to look into some of these other suggestions too. I haven't heard of many of them. From nav at adams.patriot.net Wed May 7 11:21:44 2003 From: nav at adams.patriot.net (Nick Vargish) Date: 07 May 2003 11:21:44 -0400 Subject: bsddb185 module changes checked in References: Message-ID: Skip Montanaro writes: > I suspect others can clean it up later during the beta cycle. The > current detection code in setup.py should work for Nick on OSF/1 and > for platforms which don't require a separate db library. Hey, I see a ternary-like construct in there... :^) It won't quite work since sys.platform for OSF/1 reports osf1V5 or whatever depending on the version. Here's a diff to the setup.py as found in CVS that should take care of things: =============== CUT HERE ==================== *** setup.py Wed May 7 10:39:44 2003 --- setup.py.new Wed May 7 10:41:12 2003 *************** *** 243,248 **** --- 243,250 ---- platform = 'darwin' elif platform[:6] == 'atheos': platform = 'atheos' + elif platform[:4] == 'osf1': + platform = 'osf1' return platform =============== CUT HERE ==================== The bsddb185.so module is built and works when imported explicitly as bsddb185. However, anydbm seems to be falling back to using dbm rather than bsddb185 when creating new databases. It does use bsddb185 when opening existing hash files. Here's a little interactive exploration to show what I mean: nvargish at frwebgate2$ /usr/local/python-2.3b1/bin/python Python 2.3b1 (#1, May 7 2003, 10:53:10) [C] on osf1V5 Type "help", "copyright", "credits" or "license" for more information. >>> import anydbm >>> fdb = anydbm.open('foo.dbm', 'n') >>> fdb >>> import bsddb185 as bsddb >>> fdb2 = bsddb.open('foo2.dbm', 'n') >>> fdb2 >>> import whichdb >>> whichdb.whichdb('foo.dbm') 'dbm' >>> fdb2['a'] = 'test a' >>> fdb2.close() >>> fdb.close() >>> whichdb.whichdb('foo2.dbm') 'bsddb185' >>> fdb3 = anydbm.open('foo2.dbm') >>> fdb3 >>> fdb3['a'] 'test a' >>> fdb3.close() >>> ^D Is that the expected behavior? I can certainly survive if it is, I may just have to do a little import dance when the databases need to be created. Nick p.s I'm more conservative with the ternary-analogue, and probably would have gone for: libraries = None if platform in ['osf1']: libraries = ['db'] But they seem functionally equivalent. -- # 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 max at ford-consulting.com Thu May 29 17:39:50 2003 From: max at ford-consulting.com (Max Barry) Date: Thu, 29 May 2003 14:39:50 -0700 Subject: Passing an object from VB using Microsoft's Script Control to python Message-ID: I am trying to run Python using Microsoft's Script Control in VB and when I pass a Scripting.Dictionary as an object, I cannot access Items(), Count() or Keys(). I can't even get to a item using its key value. The following error is displayed when trying to access the dictionary: Unexpected Python Error: pywintypes.com_error:(-2147467263, 'Not implemented', None, None)(Python COM Server Internal Error) I have added some sample code below: VB6 Code: Dim mydic as Object Set mydic = CreateObject("Scripting.Dictionary") 'fill with some values. For i = 1 To 10 mydic.Add "item" & i, "object " & i Next Set mSct = New ScriptControl mSct.Language = "Python" mSct.Timeout = 20000 ' 20 seconds 'This is where the dictionary that gets passed to the python script mSct.AddObject "mdict", mydic With fso.OpenTextFile("dicttest.py") mSct.AddCode .ReadAll End With mSct.CodeObject.Initialize Set mSct = Nothing Python code (dictest.py): def Initialize(): import pywintypes from tempfile import gettempdir import os import path outfilename = "testcontrol.txt" outfilepath = path.join(gettempdir(), outfilename) filout = open(outfilepath, 'w+') filout.write("THIS IS A TEST FILE FOR SCRIPT CONTROL\n") filout.write ("Dictionary Count: " + mdict.count) # write dictionary count to testcontrol.txt in temp directory. filout.close #END OF SAMPLE Any ideas on how I can make this work? From max at cNOvSisiPonAtecMh.com Mon May 19 11:28:11 2003 From: max at cNOvSisiPonAtecMh.com (Max Khesin) Date: Mon, 19 May 2003 15:28:11 GMT Subject: IPC Message-ID: I am looking to implement a fast IPC mechanism w/python. mmap module looks ripe for the strorage part of it - can't get faster than shared memory! The missing link I am looking for here is the signaling part. Basically one of my processes works as a server and maintains a large data structure in memory. The client (a CGI script in my case) requests some info about the data structure (request being stored in shared mem) and waits for the reply. On windoze I would probably build a queue for the requests and use something like SetEvent to tell the server that the queue was updated. Then I would put the client in a waiting state via one of the WaitFor* funcs and have the server activate it via a windows event or a mutex when the result is ready. So I am looking for an equivalent (or better) way to do this in python. Also I had the impression that there is some more direct support in python for presistent-CGI-in-memory kind of stuff, maybe someone can give me a pointer? 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 johnroth at ameritech.net Wed May 28 19:18:36 2003 From: johnroth at ameritech.net (John Roth) Date: Wed, 28 May 2003 19:18:36 -0400 Subject: GUI in Windows References: Message-ID: "Gerhard H?ring" wrote in message news:mailman.1054151023.19600.python-list at python.org... > morden wrote: > > Suppose I need to do some GUI on Windows. My understanding is that > > pythonTk is flaky on Windows. > > Really? Apart from some obscure bug that happens on Win9x I haven't > heard it were flaky, yet. Obscure? Hardly. If you throw an exception, it freezes the system on attempting to exit the DOS box, and also on exiting Windows itself. That's not obscure, it's unusable. John Roth > > -- Gerhard > From cybernut at uswest.net Wed May 21 14:49:06 2003 From: cybernut at uswest.net (cybernut) Date: Wed, 21 May 2003 12:49:06 -0600 Subject: help on ultra newbie program please References: Message-ID: <0UPya.49$%s1.37437@news.uswest.net> "Gerhard H?ring" wrote in message news:mailman.1053536739.4538.python-list at python.org... > cybernut wrote: > > [Tried to solve a problem in a Python tutorial] > > Here's a solution using only "if" and "while" statements. I hope it's > somewhat enlightening. > > #v+ > # The correct password. 'Constants' are usually named all-capital. > CORRECT_PASSWORD = "unicorn" > > # Number of times the user tried entering a password. Zero at the start. > tries = 0 > > # Wether the password is entered correctly. Default to a logically false > value. > password_ok = 0 > > # Execute the loop at most three times, and only as long as the correct > # password hasn't been entered. > while tries < 3 and not password_ok: > password = raw_input("Password:") > if password == CORRECT_PASSWORD: > password_ok = 1 > tries += 1 > > if password_ok: > print "Welcome!" > else: > print "Go away!" > #v- > > Don't worry if you can't solve some problems, yet. Learning to program > is learning about patterns (think of building blocks). I'd call this one > the "count and break at certain value" building block. You'll encounter > it very often. > > These combiniations of control structures are kind of basic patterns. > Soon you'll have learnt all control structures and from then on the > major issue will be how to best organize your data :-) > > This is where OOP (object oriented programming) will eventually enter > the game. > > -- Gerhard > Gerhard, I appriciate you sharing your experience as well. Its great to see different examples to accomplish the same task. Will really help me learn it I think. Also your tip about learning to program was insightful. I hope its like learning anything new. I just need to get my brain in the mode of seeing and using patterns like you said. Memorizing the control structures (is that what the while and if commands are called?) and what they do seems like the easy part to me at least... While I'm thinking about it, would there be enough good tutorials on the net to lessen the need for a begginers book about python programming? Was thinking of picking up a book, but these days it seems like theres a lot of good resources on the net for this. Thanks From bram at nospam.sara.nl Thu May 15 10:29:22 2003 From: bram at nospam.sara.nl (Bram Stolk) Date: Thu, 15 May 2003 16:29:22 +0200 Subject: First forking and then multithreading the interpreter? Message-ID: <20030515162922.71620098.bram@nospam.sara.nl> Hello, Does anyone know what bad things could happen if you first fork python, and then create threads in one of the processes? I would assume this is possible. However, I get very weird behavior: I can run my python app in multiprocess mode. I can run this same app with multithreading. But if I combine them by doing a coarse grain multiproc, and finer grain multithreading, the app misbehaves (some tasks not performed). The forking is implemented in C code, wrapped by SWIG as a Python object. After the fork, I have 3 processes running (OpenGL|Performer processes: APP,CULL,DRAW). In the app, I create a thread to run concurrently with the main python thread -> things are not performed well. If I leave out the fork step: all is well (both in multithread and singlethread mode) If I leave out the threading step: all is well (both in multiproc and single proc mode) I don't have details on the fork step, because it is done in the OpenGL|Performer library I link against. The multithreading step is performed by the thread.start_new_thread method. Also, I have no race-conditions, and do not perform concurrent access to shared resources. I use SMP linux and python 2.2.1 thx, Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Specialist. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "I heard if you play the NT-4.0-CD backwards, you get a satanic message." "Thats nothing, if you play it forward, it installs NT-4.0" ------------------------------------------------------------------------------ From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon May 5 07:10:13 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 05 May 2003 13:10:13 +0200 Subject: include in python In-Reply-To: References: <3eb63359$0$49110$e4fe514c@news.xs4all.nl> Message-ID: <3eb64786$0$49103$e4fe514c@news.xs4all.nl> Bartek Golenko wrote: > Irmen de Jong wrote: >>from your_module import * > > # prog.py > > from xxx import * > > def hello(): > print "Hello..." > > # xxx.py > > hello() > > It will not work unless I do > > # xxx.py > import __main__ > > __main__.hello() > > Which is sth I really want to avoid ;) > You have a back-dependency here: xxx.py uses something in prog.py. If you are splitting things this way, you're doing something wrong IMHO. The parts that you split off should really be self-contained (that's what I assumed). Why do you want to split up your source in this way?? If it is a prototype, why not just let it be one big chunk, and think about proper modularization later when you write the real thing? --Irmen From mathew at bbd.co.za Fri May 23 10:42:12 2003 From: mathew at bbd.co.za (Mathew) Date: 23 May 2003 07:42:12 -0700 Subject: DCOracle2 Message-ID: <2b345e99.0305230642.2286b81e@posting.google.com> Hi, I would just like to know if I can post questions about DCOracle2 here as well. Thanks Mathew From unlearned at DELETETHIS.learn2think.org Tue May 6 12:12:20 2003 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Tue, 6 May 2003 10:12:20 -0600 Subject: PEP 315: Enhanced While Loop References: <3EB33BB7.60805@pobox.com> <3EB64B3C.6010209@pobox.com> Message-ID: <3eb7dee4$1_2@hpb10302.boi.hp.com> "Steven Taschuk" wrote in message news:mailman.1052166437.3263.python-list at python.org... > Quoth W Isaac Carroll: > > I feel that the use of break is similar to the use of goto in the past. > > Goto was necessary because of the limited control structures available > > in early languages, but as for, while, if-else, functions, and other > > powerful control structures came into use, the goto was no longer > > necessary and gradually disappeared. If we adopt loop constructs of > > sufficient power and flexibility, the break statement will also no > > longer be needed, and will disappear from use. > > Imho 'break' and 'continue' together make 'while' a "loop > construct of sufficient power and flexibility". :) Out of curiousity, supposing that the "while and while ..." syntax were accepted, are we going to start seeing requests for continue statements that can continue at any while? It wouldn't terribly surprise me, and my gut feel tell me that following that path would be a Bad Thing(tm). -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From markus_wankus at hotmail.com Fri May 16 14:30:13 2003 From: markus_wankus at hotmail.com (Markus Wankus) Date: Fri, 16 May 2003 14:30:13 -0400 Subject: MySQL and Python on Linux - Proper Method? Message-ID: Hi all, I am about to dive into my first Python/wxPython app on Linux using a MySQL database backend. I was wondering what the proper way of doing this on Linux is. I can currently see a couple of options: 1) Using mxODBC (looks to be the most promising right now...) 2) Using MySQLdb (is this dead?) and probably SQLDict to make my life easier... I'm sure there are kajillions (OK, maybe not kajillions but millions at least...) of Pythonistas doing this so I was curious as to what the accepted method of doing this is? I am finding surprisingly little information on this subject. Well, there is lots of info out there but it seems to be all over the map in terms of what the accepted method is. I will ultimately be installing my *platform-independent* application on Windows machines as well. I assume I will just be using an ODBC driver to connect to the MySQL database (running on a Linux server). Thanks for any advice. -- Markus From unlearned at DELETETHIS.learn2think.org Fri May 23 13:34:02 2003 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Fri, 23 May 2003 11:34:02 -0600 Subject: Can I get the total memory usage of Python? References: Message-ID: <3ece5b8a$1_3@hpb10302.boi.hp.com> Cameron Laird wrote: > In article , > Tim Peters wrote: >> Except that there's no standard way in C to query the platform >> malloc about how much memory it's actually using, and all mallocs >> have hidden overheads. When allocating a large number of small >> objects, malloc overhead can be more than half the story. In 2.3 >> pymalloc takes most of that out of the platform malloc's hands >> (although it still grabs *large* chunks from the platfrom malloc, >> and pymalloc still can't know how much overhead the platform malloc >> chews up for those). > > Right; it's a general principle of common OSs that > t's shockingly hairy to find out what is *really* > going on in memory. > > What I meant, although far too elliptically, was just > at the pymalloc level. No, that doesn't correspond > to real memory use, as seen "from the outside"; my own > intentions for memory introspection are satisfied by > anything which reliably enumerates my use of memory, > even if it's inaccurately quantified. It's enough > for me to have a handle on how many and which objects > I'm asking the system to juggle. I have begun work on collaborative system that will eventually allow people to edit and create code for long-lived, persistent objects in a running server (MUD-type application). For this sort of thing, it would be helpful to be able to provide the administrators with a general idea of how memory is being used with respect to time. One possible use would be to track down plugin modules that are creating disposable objects, but not destroying all references, leading to a good old-fashioned leak. Even it can't be isolated to a particular location, knowing that a leak exists is a good first step toward finding and eradicating it. A general idea of the rate of leakage is probably a close second. -- Daniel Fackrell (newsgroups.NOSPAM at dfackrell.mailshell.com) When we attempt the impossible, we can experience true growth. From mhammond at skippinet.com.au Mon May 19 20:43:35 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 20 May 2003 00:43:35 GMT Subject: Manipulating the MS Outlook-inbox ?? In-Reply-To: References: Message-ID: Thomas Weholt ( PRIVAT ) wrote: > Hi, > > Does anybody have an example on how to scan the Outlook Inbox and move > messages based on subject, senders address etc. in Python?? > > Tips appreciated. > > Best regards, > Thomas > Apart from SpamBayes, see also the win32com\demos\OutlookAddin.py demo - this is a nice skeleton of an addin without all the Bayes cruft. Also, I have a "personal" addin I use here to remove almost all virus mail, which does a pretty good job (even with very dumb heuristics.) I would be happy to share it - it grabs around 90 virus emails a day, and if we add that to the similar amount of Spam that SpamBayes grabs, my mailbox is delightfully quiet these days. Mark. From ramen at lackingtalent.com Tue May 6 15:41:58 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 06 May 2003 19:41:58 -0000 Subject: Metaclasses vs. standard Python reflection? References: <20030502044336.A980@localhost.localdomain> <2259b0e2.0305020517.67b88b00@posting.google.com> <8ef9bea6.0305041747.707b8a7d@posting.google.com> Message-ID: In article , Alex Martelli wrote: > For example, say in logger.py you only have the following code: > > def log_call(method): > def new_method(self, *args, **kwds): > print 'Entering %s...' % method > result = method(self, *args, **kwds) > print 'Exiting %s...' % method > > return new_method Just in case another reader tries this code, I should mention that I forgot a return statement in new_method. After that second print statement, there should be another line that says "return result". Otherwise, this technique will clobber all return values from methods. ;) For the cut-and-pasters: def log_call(method): def new_method(self, *args, **kwds): print 'Entering %s...' % method result = method(self, *args, **kwds) print 'Exiting %s...' % method return result return new_method > class Logger(type): > def __new__(cls, name, bases, dict): > for key in dict: > if callable(dict[key]): > dict[key] = log_call(dict[key]) > > return type.__new__(cls, name, bases, dict) > > and simple.py is unchanged (except I lowercased the filename:-). > > Now, for example: > > Python 2.3b1+ (#10, May 3 2003, 20:20:32) > [GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import logger >>>> import types >>>> simple = types.ModuleType('simple') # make a new empty module >>>> simple.__metaclass__ = logger.Logger # set its __metaclass__ >>>> execfile('simple.py', simple.__dict__) # and now populate it >>>> simple.Simple.__class__ # check we have the metacl > >>>> x = simple.Simple(23) # make an instance > Entering ... > Exiting ... >>>> x.print_x() # call its method > Entering ... > x = 23 > Exiting ... >>>> class lessimple(simple.Simple): # now let's subclass > ... def somethingelse(self): print 'boo!' > ... >>>> y = lessimple(42) # subclass instance > Entering ... > Exiting ... >>>> y.somethingelse() # and ITS method > Entering ... > boo! > Exiting ... >>>> > > > Does this help...? To use the per-module __metaclass__ in a module > that wasn't written for this, you have to use some trick such as this > one (there may be many others too). Afterwards, __metaclass__ gets > inherited. Remember to ALSO bind the name 'object' (to an empty > class with your metaclass) to get classes that are newstyle because > they inherit from object. Yes! Thank you! =) I managed to bind "object" this way - is this how you would do it?: simple.object = simple.__metaclass__('object', (), {}) > This won't work for classes that inherit from other builtin types > or declare their own __metaclass__ in their body -- THOSE you have > to fixup post facto (with some subtlety in the latter case -- you > will need to dynamically generate a suitable metaclass inheriting > from the explicitly set one AND take care about conflicts in the > intended semantics, particularly in __new__ -- indeed SOME conflicts > might possibly be insoluble). It also assumes you're only applying a single aspect, "Logger" in this case. To apply multiple aspects, it would probably be a good idea to have a single metaclass that dispatches... Well, that was very helpful. Thanks for taking the time to answer that. =) Take care, Dave From magnus.therning at wanadoo.nl Thu May 22 17:13:31 2003 From: magnus.therning at wanadoo.nl (Magnus Therning) Date: Thu, 22 May 2003 21:13:31 GMT Subject: Invoking a method by name? References: Message-ID: <%3bza.1947843$sj7.84890591@Flipper> Thanks, I expected there ought to be something like this. It works like a charm! /M Brian Quinlan wrote: >> I need to call a method of an object where I only have the name of the >> method in a string. I have found one way, but I am not sure, maybe > there >> is a more beautiful way to accomplish it? >> >> This is some example code: >> >> import inspect >> >> class test1: >> def test(self): >> print 'test' >> >> class test2(test1): >> def test(self): >> print 'extended test' >> >> >> a = test1() >> b = test2() > > getattr(a, 'test')() > getattr(b, 'test')() > > Cheers, > Brian > > -- Magnus Therning (OpenPGP: 0x6A83A7DF) People who don't make mistakes make the greatest mistake of all; they do nothing. -- Unknown From gh at ghaering.de Fri May 16 13:37:34 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 16 May 2003 19:37:34 +0200 Subject: piping an email message In-Reply-To: References: Message-ID: <3EC521DE.70709@ghaering.de> Alessio Pace wrote: > Hi, I am writing a filter for the emails, I need it to pass through stdin > and then go via stdout. > > Would this piece of code be okay to let just pass the message through the > pipe correctly? > > # file 'pipe.py' > import email > import sys > > def main(): > stdin_message = sys.stdin.read() > msg = email.message_from_string(stdin_message) > sys.stdout.write(str(msg)) > > if __name__ == '__main__': > main() The problem with this code is that it needs to read the entire message into memory. For 90 % of the messages, this should be no problem, but for the few multi-megabyte messages that you'll probably process, it will have negative impacts on the system performance. I'd rather do something like: #v+ CHUNK_SIZE = 1024 while True: chunk = sys.stdin.read(CHUNK_SIZE) if not chunk: break sys.stdout.write(chunk) #v- Now that you know how to do it properly, you can use the relevant library function in the first place :-) #v+ import shutil shutil.copyfileobj(sys.stdin, sys.stdout) #v- As you'll read strings, anyway, the explicit conversion to string using str() in your above code is superfluous, btw. -- Gerhard From bdesth at removethis.free.fr Mon May 12 18:16:55 2003 From: bdesth at removethis.free.fr (laotseu) Date: Mon, 12 May 2003 22:16:55 +0000 Subject: IDE Feature request References: <3ebe1b9e@usenet.per.paradox.net.au> Message-ID: <3EC01D57.9060200@removethis.free.fr> Andy Jewell wrote: > On Sunday 11 May 2003 10:49 am, Cameron Zemek wrote: > >>What features would you like to see in an open source IDE for Python? >> >>* Refactoring (see http://www.refactoring.com/catalog/) >>* Syntax checking >>* Integrated debugger (set debug points in the source editor) >>* Workspace support >>* Code assist (also referred to as code completion) >>* Integrated interactive shell >>* Code browser (browse by module and type) >>* Coverage analysis >>* Unit test generator Ok, plus see below >>What do you think of existing IDEs? Dont know, i'm using emacs >>Do you think that having a plugin for an existing IDE (eg. Netbeans, >>Eclipse, Visual Studio) is better then a standalone IDE? If it's Visual Studio, I could not care less... It dont run on my Mac nor on my Linux Box. >>Any other comments on an Python IDE. >> >>Implementation thoughts on IDE: >>* Use wxPython to have a cross-platform environment Definitively, yes >>* License it under the same as Python's license >>* Use the scintilla editor (not sure on this) Think it's a good choice >>* Included existing tools >>* Write complete documentation for IDE as it is implemented >>* Use mainly python as the implementation language Of course ! (snip) > > > Sounds great... > > A few thoughts about features... > > 1) Folding support, i.e. the ability to reduce the clutter in a source listing > by selectively hiding code parts, such as procedure and class definitions, > ifs and loops. Which is supported by the Scintilla text editor widget > 2) Expose the text buffer to a python command-line interpreter, so that the > user can issue commands that work on the document being edited. Likes emacs python mode > 3) Printer support, including layout customization. This one's probably the > most difficult to do... 4) use Python as the scripting language for the IDE 5) allow the embedded interactive shell to control the IDE Would that be enough ?-) You should have a look at pycrust (comes the wxPython module), which could be as basis for a Python IDE. BTW, it's author was talking, a few weeks ago, of deriving an emacs-like editor from it (google for the thread in this ng). Laotseu From robin at jessikat.fsnet.co.uk Wed May 21 04:00:53 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 21 May 2003 09:00:53 +0100 Subject: EAFP vs LBYL (was Re: A little disappointed so far) References: <3ec82283.12251706@news.cybermesa.com> <_daya.118281$3M4.2687052@news1.tin.it> <38ec68a6.0305202129.84ded31@posting.google.com> Message-ID: In article <38ec68a6.0305202129.84ded31 at posting.google.com>, Asun Friere writes >Robin Becker wrote in message news:H at jessikat.demon.co.uk>... > >> well I hope you're not flying with engineering like >> >> try: >> igniteKerosene() >> except ExplosionError: >> handleExplosionCase() >> >> :) > >As long as the engineers actually have some way of handling the >explosion, what's the problem. :p > >BTW, there's this neat device called the 'internal combustion engine' >which ... ;) well I was thinking there might be some cheaper way while flammableMixture(): sleep(1) igniteKerosene() but since, as Alex says, we can't guarantee anything we probably still need the try ie while flammableMixture(): sleep(1) try: igniteKerosene() except ExplosionError: handleExplosionCase() #call lawyers etc except FlameWentOutError: blameSuppliersEtc() except EndOfUniverseError: pray() ...... other exceptions -- Robin Becker From jjl at pobox.com Sun May 11 17:07:42 2003 From: jjl at pobox.com (John J. Lee) Date: 11 May 2003 22:07:42 +0100 Subject: [OT] developers needed References: Message-ID: <87u1c1jiox.fsf@pobox.com> Michael Anckaert writes: [...] > First of all, sorry about this post being off topic. > I'm developping a text adventure written entirely in Python. If anyone > is interested to help development or just want more information, please > contact me. I recall somebody making some kind of text adventure construction system in Python before. Search Google groups for it if you're interested. Of course, you *do* realise there are 101 text adventure-construction systems out there already to do a lot of the work for you? rec.arts.int-fiction is the group you want, IIRC. John From zhitenev at cs.vsu.ru Wed May 14 02:05:14 2003 From: zhitenev at cs.vsu.ru (Lexy Zhitenev) Date: Wed, 14 May 2003 10:05:14 +0400 Subject: How to ping a machine in a simple way? References: Message-ID: Hello, David! You wrote on Tue, 13 May 2003 21:41:46 GMT: DB> That may not be a good test, if the machine is firewalled, you'd not DB> see a responce on 139 either. NetBIOS port 139 is guaranteed to be open in my domain, yet this doesn't work. 'telnet c1r383n09 139' succeeds (if the machine is up). So, can anyone help me? With best regards, Lexy Zhitenev. E-mail: zhitenev at cs.vsu.ru From staschuk at telusplanet.net Sat May 3 00:05:46 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Fri, 2 May 2003 22:05:46 -0600 Subject: HTML Parser chokes on WordHTML... In-Reply-To: <20030502130918.A1433@tibia.amotlpaa.bogus>; from staschuk@telusplanet.net on Fri, May 02, 2003 at 01:09:18PM -0600 References: <20030502130918.A1433@tibia.amotlpaa.bogus> Message-ID: <20030502220546.A1319@tibia.amotlpaa.bogus> A couple oversights in my previous comments: Quoth I: > Quoth Harald Massa: [...] > Strictly speaking, anything inside is a comment and the > parser should ignore it. This is mostly true in XML, excepting sections (which are, however, rarely used in HTML). And as Andrew Clover pointed out, in SGML it is possible for elements to be implicitly CDATA, by virtue of a declaration to that effect in the DTD. [...] > > again, does not look great, but should be legal > > HTMl - should'nt it? > > No: isn't legal HTML, so HTMLParser quite properly > rejects it. The declaration (and inside a DTD, which is not usually present in an > HTML document). ... and for starting , and, in SGML, and , and perhaps other things I've forgotten about. But again, these are rarely used in HTML. -- 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 theller at python.net Fri May 23 02:34:11 2003 From: theller at python.net (Thomas Heller) Date: 23 May 2003 08:34:11 +0200 Subject: File version on Windows References: <0Naza.124120$3n5.74832@news2.central.cox.net> <3ecd46b3_1@corp-news.newsgroups.com> <7Nfza.427605$Si4.372466@rwcrnsc51.ops.asp.att.net> Message-ID: <1xyqnpcs.fsf@python.net> [about getting file version with GetFileVersionInfo] "Bryan" writes: > wouldn't ctypes work just as well? Sure, and it even does contain sample code for this. Thomas From evan at 4-am.com Tue May 20 15:50:01 2003 From: evan at 4-am.com (Evan Simpson) Date: Tue, 20 May 2003 14:50:01 -0500 Subject: persistant web state In-Reply-To: <20030520.091027.706043324.1320@nets.com> References: <20030520.091027.706043324.1320@nets.com> Message-ID: <3ECA86E9.6010601@4-am.com> Jay O'Connor wrote: > Others? Suggestions? If you're not prepared to go full-force with Twisted, Zope, Quixote, or one of the other servers that give you this sort of thing for free, you should *at least* try to use ZODB/ZEO. It gives you an astounding amount of state-persisting-power with very little investment. The ZEO part allows you to share state seamlessly even among processes running on different computers. Cheers, Evan @ 4-am From skip at pobox.com Fri May 9 10:57:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 9 May 2003 09:57:49 -0500 Subject: R: unicode to string conversion In-Reply-To: <000001c315fb$c31bf5f0$410100a4@utente65> References: <16058.41185.434413.777621@montanaro.dyndns.org> <000001c315fb$c31bf5f0$410100a4@utente65> Message-ID: <16059.49645.239019.147301@montanaro.dyndns.org> Skip> u = u'questa \xe8 bella' Skip> s = u.encode("iso-8859-1") Skip> print s Skip> questa ? bella Luca> maybe i have mispelled my problem .... Luca> I would like to transform the unicode string: Luca> u= u'pi?' Luca> into an usual string: Luca> s = 'pi?' Which is exactly what my answer did. There is no one best encoding when converting a unicode object into a plain string object. Try the above with the following print type(u) print type(s) You'll see that s is a plain string object. As Jeff Epler pointed out, for him encoding as utf-8 made more sense because that's what his terminal application expected. Skip From phil at riverbankcomputing.co.uk Mon May 26 04:28:21 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 26 May 2003 09:28:21 +0100 Subject: PYQT Windows Title Bar Problem In-Reply-To: References: Message-ID: <200305260928.21652.phil@riverbankcomputing.co.uk> On Sunday 25 May 2003 11:35 pm, matt wrote: > Phil Thompson wrote in message > news:... > > > On Sunday 25 May 2003 9:01 am, matt wrote: > > > On PyQT Linux, calls to setCaption() change the title of the window as > > > expected but on Windows, all title bars appear as pythonw. > > > > > > Any help would be much appreciated. > > > > Which version of Qt? > > > > Phil > > On Linux, QT 3.1. > > On Windows, QT 2.3 The non-commercial edition? I suspect setCaption() is intentionally disabled in that version. Phil From jay at jaydorsey.com Sat May 31 13:54:37 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sat, 31 May 2003 13:54:37 -0400 Subject: extract element In-Reply-To: <20030531174133.72612.qmail@web40414.mail.yahoo.com> References: <20030531174133.72612.qmail@web40414.mail.yahoo.com> Message-ID: <200305311354.37214.jay@jaydorsey.com> Darren, How about this: >>> # create a multi-line string >>> mystr = 'this:is:something\nblah:blah:blah\nhere:is:more' >>> # save it to a text file (simulates the file you already have) >>> f = file('myfile.txt', 'w').write(mystr) >>> mylist = [] # create a list to hold the items you want >>> # open the text file up >>> f = file('myfile.txt', 'r') >>> for line in f.readlines(): # go over each line ... # split on the : and grab the second element ... mylist.append(line.split(':')[1]) ... >>> mylist # see whats inside of our list at the end of the loop ['is', 'blah', 'is'] On Saturday 31 May 2003 13:41, Darren Teo wrote: > hey just wondering how do u extract every second element delimited by the > ":" on every line and put them all in a list thanx .... -- Jay Dorsey jay at jay dorsey dot com From pwatson at redlinec.com Wed May 7 23:15:41 2003 From: pwatson at redlinec.com (Paul Watson) Date: Wed, 7 May 2003 22:15:41 -0500 Subject: Why use backticks? References: <3eb81743$0$123$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Yes, but the commands module appears to be UNIX only. "Jeff Epler" wrote in message news:mailman.1052357472.17747.python-list at python.org... > On Wed, May 07, 2003 at 05:16:38PM -0500, Paul Watson wrote: > > Backticks in Python do not mean the same thing as they do in Perl. Your > > Perl friend would need to do something like: > > .. or they could use the commands module. > >>> commands.getoutput("uname -a") > 'Linux parrot 2.4.20-9 #1 Wed Apr 2 13:42:50 EST 2003 i686 i686 i386 > GNU/Linux' > > I notice this even has the last-newline-stripping feature of Perl's ``. > (I also don't see how to turn this off, in case the program's output is > binary...) > > Jeff > From zERo at nowhere.com Mon May 5 01:13:12 2003 From: zERo at nowhere.com (zERo) Date: Mon, 05 May 2003 05:13:12 GMT Subject: How to designate sys.stdout for binary output in win32? References: <3eb56a9d.1643312@news.lexicon.net> Message-ID: sjmachin at lexicon.net (John Machin) wrote in news:3eb56a9d.1643312 at news.lexicon.net: > On Sun, 04 May 2003 10:50:16 GMT, "C.M. Lim" wrote: > >>I need to print strings as-is, control/escape chars et al, to >>sys.stdout in a win32 python environment (in Unix, this would be >>trivial). >> >>I found some sample code that uses msvcrt module to explicitly set the >>BINARY mode, as follows: > [snip] >>but on my system (Python2.1.1), sys.stdout is a PyShell.PseudoFile >>instance, and does not have a fileno() method. >> > > Please let us know what piece of software you expect to act on the > escape sequences and control characters that you wish to send to > sys.stdout. > > If it is Pyshell, then you should be addressing your question to the > PyShell maintainer(s). > > If it is not PyShell, but some other gadget, like a > green-screen-terminal emulator -- similar to the good ol' ANSI.SYS > console device driver on MS-DOS -- then it seems an incredibly good > bet that you may have to run Python at the command line. > My current application uses Python to generate an image. Instead of creating a file, it could be used to send raw output. By using appropriate html headers, I could use it as a CGI app and have it display directly in a browser. Thus, the requirement of 'binary' output to sys.stdout, so the browser can act upon it. I can think of other uses this may have, an example would be akin to Unix filter apps, where the Python app would take the input and pass along modified output (albeit in 'binary' form) as stdout. After reading your post, it got me thinking. I now believe that the indication I got that sys.stdout is a Pyshell.PseudoFile instance comes from the fact that I tried to simplify it into a test-case and *WAS* checking it out in a PyShell, and hence would receive that indication. Uugggh!! back to square one... Thanks for your input. BTW, it should not matter what the receiving app is, so long as the previous stage sends data out on stdout and the receiving app receives it on stdin, right??? CM From tim.one at comcast.net Mon May 19 20:49:30 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 19 May 2003 20:49:30 -0400 Subject: 2.2 properties and subclasses In-Reply-To: Message-ID: [Tim] > If you think that's what you want (I don't recommend it), you > could, e.g., write the stuff this way instead: > > class BaseClass(object): > def __init__(self): > self._prop = "BASE" > > def get_prop(self): return self._prop > prop = property(lambda self: self.get_prop()) # the only change > > class SubClass(BaseClass): > def get_prop(self): return "SUB" > > Then the (still shared) prop dynamically looks up which > get_prop() to use on each invocation, and only get_prop needs to be > overridden in SubClass. [Miles Egan] > This is the behavior I was expecting. I guess what I really want here > is a simple way to implement properties in the base class and > intercept access to them in some cases in subclasses (lazy > initialization, etc). > > Why don't you recommend this? It seems like a pretty natural solution > to my current problem. Just because it's clearer, and more efficient at runtime, to repeat prop = property(get_prop) in both classes. For that matter, it would be clearer and more efficient still to have clients call get_prop() directly and skip the property layer, but I appreciate that may be less convenient for clients. The two ways of implementing with properties look the same to clients. From cremediakis at optusnet.com.au Sun May 4 04:44:56 2003 From: cremediakis at optusnet.com.au (Christine) Date: Sun, 4 May 2003 18:44:56 +1000 Subject: nltk.set iterators Message-ID: <3eb4d342$0$1025$afc38c87@news.optusnet.com.au> Is it possible to iterate through a nltk.set ie. c{Set} If so, how???? For now I will copy the elements into a list and traverse the copy. Cheers, Chris From boudewijn at tryllian.com Thu May 8 05:51:37 2003 From: boudewijn at tryllian.com (Boudewijn Rempt) Date: Thu, 08 May 2003 11:51:37 +0200 Subject: import guards? References: <9badaf0.0305061601.32587ad2@posting.google.com> <3EB8505E.423FD9@engcorp.com> <3eba26ab$0$26190$626a54ce@news.free.fr> Message-ID: <3eba2968$0$134$e4fe514c@dreader4.news.xs4all.nl> Littlejohn septante cinq wrote: > And how is pyQt in this regard ? Still pretty big, even if things like canvas, network, sql, xml and gl are taken out of the qt module to their own. Still, import qt help(qt) gives about 16.000 lines of help. Doesn't take more than a few seconds on my ancient laptop, though. More extensive documentation that I'd thought, too. -- Boudewijn | http://www.valdyas.org From rcs at russellsalsbury.com Fri May 2 17:14:50 2003 From: rcs at russellsalsbury.com (Russ Salsbury) Date: 2 May 2003 14:14:50 -0700 Subject: Metaclasses vs. standard Python reflection? References: <698f09f8.0305012053.123ead56@posting.google.com> <20030502044336.A980@localhost.localdomain> <2259b0e2.0305020517.67b88b00@posting.google.com> Message-ID: <3ea624c6.0305021314.40a3d8c6@posting.google.com> mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0305020517.67b88b00 at posting.google.com>... > > Some time ago, I read a paper about AOP. Maybe that paper was particularly > bad, but these were my impressions: > > 1) I couldn't manage to distinguish between the buzzwords and the actual > information; > > 2) the examples were too abstract and saying nothing to me; I've read 3 or 4 papers, so maybe I can shed some light. ;-) The AspectJ homepage is http://www.eclipse.org/aspectj/ www.aosd.net -- the AOP homepage is now password protected. Definitely unfriendly. Also AOP seems to be under the umbrella term "Adaptive Programming". The motivating idea is that while an algorithm may be easy to understand, it can be downright impenetrable when you add synchronizaion, exceprion handling, and the like. To make the code clearer and easier to implement, aspects (synchronization, eiffel contracts, ...) are separated into separate files, coded in the AspectJ extensions to Java. The AspectJ preprocessor takes the aspects and the Java and "weaves" the "tangled" code (their words :-). Chapter 2 of the the language manual on the eclipse site gives a pretty clear example. (Well maybe clear if you have thought about this style of programming before. ;-) If the Java example seems a little contrived, take a look at the C++ examples in Ch. 8 of "Generative Programming" by Czarnecki and Eisenecker. It makes AOP look like an idea whose time has come. (It's a good survey of the program generation art. If your interest lies in that direction, I recommend it.) I think part of the problem of clarity is that these are new concepts to most of us. I submit the recent discussions of metaclasses as evidence. ;-) I have been thinking about some of these things for years (even implementing them) and still my brain gets tied in knots. > 3) the part I understood, I could have implemented trivially with > Python metaclasses, without any need to go through a new programming > language such as AspectJ. AspectJ is a little more powerful, because it can be more fine grained than metaclasses. For example, you can apply guards (like synchronization) to assignment statements. But in general you are right. > 4) I had the impression they were introducing many ad hoc concepts to > solve specific problems, whereas a general purpose solution such as > a metaclass would have solved everything in a much clearer and customizable > way for the final user. I think the paper you read was on an earlier version because that was certainly true then. Worse even, because each specific problem had its own aspect language. The version at eclipse is a little more general. But again you are right; all the AOP style technologies seemed to have started as general solutions to specific problems. I believe it's Demeter that is a program generator for tree walking problems. The Visitor Pattern has its own programming language! > Of course, I only have read one paper and I could well be wrong. > My position (due the reading of that only one paper, could change > in the future) is that the problems AOP is trying to address are > important; nevertheless, that paper did not convince me that the AOP > solution was the right solution. > > There is nom doubt that metaclasses are the right solution <0.5 wink> I agree with you. I lost interest in AOP after it became Java specific (at Xerox PARC at least). The weakness that I see in AOP is that appears to be applied to specific classes (wild cards allowed). OTOH metacalsses are part of class composition like inheritance is. To be more specific: in the AOP scheme of things you could write a program using the stack class, and then at some arbitrary point in the future create a synchronization aspect, run AspectJ, and presto changeo you have a synchronized version without touching your original program. With metaclasses you would create a new syncstack class inheriting from stack and using the sync metaclass. They are certainly different ways of tackling a problem. The interesting thing about metaclasses (and python in general) is it gives us a simple way to tackle some very hairy problems. Contrast that with AOP where many reachers at a number of universities have spent nearly a decade to come up with a very elegant solution to a subset of the same problems. (Acutually there are a number of big academic solutions to the same set of problems.) I expect that as pythonistas start using metaclasses some very elegant methods for specifying metaclasses will emerge. Then someone will invent AspectP. Solve the problem, then make the solution elegant. Very Pythonish. My candidate for needs-an-elegant-solution is how to specify metaclass composition. Take a look at "Putting Metaclasses to Work" by Forman and Danforth for ideas on the use of metaclasses, although you will have to slog through C++ and an excessive need to be mathematically formal. -- Russ From quale1 at charter.net Thu May 29 18:11:18 2003 From: quale1 at charter.net (Doug Quale) Date: 29 May 2003 17:11:18 -0500 Subject: passing by refference References: <9xRw+ks/KrpJ089yn@the-wire.com> <87znlng7cf.fsf@charter.net> Message-ID: <87wug9h08p.fsf@charter.net> Jordan Krushen writes: > Am I correct in understanding that this is why Doug is calling it CBV, > and others are calling it CBR? The fact that f(x) does not send a > reference to x, but the value of x, which is itself a reference of > sorts? Actually I'm pretty sure noone says it's call-by-reference. Typically a different word is used, like call-by-sharing or call-by-object-reference. From cnetzer at mail.arc.nasa.gov Tue May 27 14:49:00 2003 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: 27 May 2003 11:49:00 -0700 Subject: Storing 'unhashable' types in dictionaries by address In-Reply-To: References: Message-ID: <1054061339.521.19.camel@sayge.arc.nasa.gov> On Sun, 2003-05-25 at 15:09, Ed Avis wrote: > "Tim Peters" writes: > >The builtin function id(x) returns the "object identity" of x, which > >you can think of as being its address. > > Thanks for telling me about this (and to the other poster who said the > same). So now I can happily associate extra information with > arbitrary objects by using their address. One thing to remember is that Python is free to reuse the object id (ie. address), after that object is deleted. You should take steps to insure that when you keep track of an object id, that the object itself is not deleted and the id possibly reused.. A simple technique, when the id() is used as a key in a dictionary, is to ensure that the corresponding value of that entry should have a reference to the object (that's the most straightforward way to do it, anyway). You can take a tuple of the stuff you want to associate with the id() key, and the object itself. ie: d = {} a = SomeObject() b = SomeDataToAssociateWithSomeObject() d[id(a)] = (b, a) instead of just d[id(a)] = b Of course, it is likely the case when keeping track of ids, that you might also have a list of the objects, or some other way to keep track of them all (otherwise, what value is the id()?). Just want to make sure this caveat is explicitly stated. For more info on reuse of ids, and an example of it happening, see the following post: http://groups.google.com/groups?q=chad+netzer+difference+in+binding&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.1052862200.26129.python-list%40python.org&rnum=1 -- Chad Netzer (any opinion expressed is my own and not NASA's or my employer's) From artyprog at wanadoo.fr Sat May 3 16:49:35 2003 From: artyprog at wanadoo.fr (Salvatore) Date: Sat, 03 May 2003 22:49:35 +0200 Subject: Syntax Coloring In-Reply-To: <87u1cbvlxw.fsf@millingtons.org> References: <87u1cbvlxw.fsf@millingtons.org> Message-ID: Glyn Millington wrote: > Well, I typed py2html into Google and got this....... > > http://www.norvig.com/python/py2html.html > > 8<------8<------8<------8<------8<------8<------8<------8<------8<------ > > #!/usr/local/bin/python > """Pretty-print Python code to colorized, hyperlinked html. > In python, do: > py2html.convert_files(['file1.py', 'file2.py', ...]) > From the shell, do: > python py2html.py *.py""" > > 8<------8<------8<------8<------8<------8<------8<------8<------8<------ > > > any use? Thanks very much Glyn, same problem it uses the '
' tag.

Regards

Salvatore









From ianb at colorstudy.com  Sun May 25 15:13:37 2003
From: ianb at colorstudy.com (Ian Bicking)
Date: 25 May 2003 14:13:37 -0500
Subject: Medusa: Reloading Python Source
In-Reply-To: <20030525060754.GB752@thomas-guettler.de>
References: <20030525060754.GB752@thomas-guettler.de>
Message-ID: <1053890017.19356.52.camel@lothlorien>

On Sun, 2003-05-25 at 01:07, Thomas Guettler wrote:
> Hi!
> 
> If you are developing applications with medusa, you need to restart it
> every time you change your source code. It would be nice if the server
> would detect changes automatically.
> 
> I tried to apply the "magic" that is done by zope's refresh, but
> failed.
> 
> Can twisted do this?

We have a technique we've been using in Webware a while, where it polls
all the loaded files (as found in sys.modules), and sees if they've
changed.  If any have, the monitor thread starts a shutdown, with exit
code 3.  The shell script that starts the AppServer does a restart if it
gets that exit code.

It works pretty well, and performs well enough for development.  The
problem with reloading that we'd probably find is stale objects that use
old class definitions.  Reloading the modules, and redefining the
classes, doesn't deal with persistent objects.  Making it do so seems
really hard (though I imagine ZODB is a help there, because the class
definitions are probably always reloaded when an object is fetched from
the database).

  Ian






From gmunger at nospam.lpiweb.com  Mon May 19 12:40:16 2003
From: gmunger at nospam.lpiweb.com (greg munger)
Date: Mon, 19 May 2003 16:40:16 GMT
Subject: search replace in Word from Python
Message-ID: 

I have a simple perl script that uses the COM interface to convert a few 
MS Word styles to html (based on word2pod.pl by Jan Dubois). I would 
rather use Python than Perl, but I can't get one thing to work in Python.

At one point I do the following (in Perl):

    my $Search = $Doc->Content->Find;
    my $Replace = $Search->Replacement;
    $Search->Clearformatting;
    $Replace->Clearformatting;
    # convert bold styles
    $Search->Font->{Bold} = 1;
    $Replace->{Text} = '^&';
    $Search->Execute({Replace => wdReplaceAll});
    # convert italic
    $Replace->Clearformatting;
    $Search->Clearformatting;
    $Search->Font->{Italic} = 1;
    $Replace->{Text} = '^&';
    $Search->Execute({Replace => wdReplaceAll});

This modifies the current document, then I read it and print it 
preserving this formatting.

I have been trying to get the equivalent code to work with Python. I did 
run the MakePy utility to generate the COM constants. In the example 
below I used a constant for the Bold replacement, and used the value for 
the italic replacement. I don't get an error, but I don't see any bold or 
italic elements either.

def fixStyles( doc):
	search = doc.Content.Find
	replace = search.Replacement
	search.ClearFormatting();
	replace.ClearFormatting();
	
	search.Font.Bold = 1
	replace.Text = "^&,"
	search.Execute( Replace = constants.wdReplaceAll)
	search.ClearFormatting();
	replace.ClearFormatting();
	
	search.Font.Italic = 1
	replace.Text = "^&,"
	search.Execute( Replace = 2)
	search.ClearFormatting();
	replace.ClearFormatting();
	

Can anyone see what I am doing wrong?

thanks,

Greg Munger



From http  Sat May 31 06:23:05 2003
From: http (Paul Rubin)
Date: 31 May 2003 03:23:05 -0700
Subject: CGI question: safe passwords possible?
References:     <3ED86146.F2029ADB@alcyone.com> 
Message-ID: <7xptlzxvna.fsf@ruckus.brouhaha.com>

Ian Bicking  writes:
> FWIW, getting access to the authentication headers yourself can be quite
> difficult.  Apache does not freely pass authentication information on to
> CGI scripts, for security reasons (particular with people who don't
> trust each other on the same domain).  If you don't have complete
> control of Apache, don't even bother trying.

Generally speaking, using HTTP auth is a pretty crude way to do
authentication.  It's simple, but has an annoying UI.  Once a person
logs in with it, they can't log out without closing their browser.  It
throws a username/password dialog box on the screen which can feel
kind of harsh for the user.  Basically it's something you do if you
want to put quick and dirty access control on some file or resource.
If you're trying to make a nice site, implement your own
authentication in your CGI and maintain session with a cookie.



From jim_938 at hotmail.com  Mon May 26 13:35:12 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Mon, 26 May 2003 23:05:12 +0530
Subject: c to python
Message-ID: 

Hi !

I have a structure in c like this

struct ab
{
        int a;
        int b;
        int *c;
       struct d *d;
} AB;


And i am using it in my program like

void XYZ(int a , AB *b)


How can this kind of structure be translated in python code?

Your suggestions are welcomed.

Regards

_________________________________________________________________
Got a wish? Make it come true. 
http://server1.msn.co.in/msnleads/citibankpersonalloan/index.asp Best 
personal loans!





From singer at chemistry.ohio-state.edu  Sun May 11 06:41:08 2003
From: singer at chemistry.ohio-state.edu (Sherwin J. Singer)
Date: Sun, 11 May 2003 06:41:08 -0400
Subject: setup.py syntax error building python-imaging
References:  
Message-ID: 

Fredrik and David:

Thanks very much for your very quick responses.  Of course, David is totally 
correct and invoking python2 gets the ball rolling.  Then I hit another 
problem: 

distutils.errors.DistutilsPlatformError: invalid Python installation: unable 
to open /usr/lib/python2.2/config/Makefile (No such file or directory)

Indeed there is no config directory in either /usr/lib/python2.2 or 
/usr/lib/python1.5.

Please let me know if there is a convenient fix.  Otherwise I'll wait until 
I upgrade from RH7.3.  (My goal is to install Sketch.  Hey, xfig is still 
OK for now.)

Thanks for your help,
   Sherwin

=============  FULL TRACEBACK ===================================
running build_ext
Traceback (most recent call last):
  File "setup.py", line 301, in ?
    ext_modules = MODULES,
  File "//usr/lib/python2.2/distutils/core.py", line 138, in setup
    dist.run_commands()
  File "//usr/lib/python2.2/distutils/dist.py", line 893, in run_commands
    self.run_command(cmd)
  File "//usr/lib/python2.2/distutils/dist.py", line 913, in run_command
    cmd_obj.run()
  File "//usr/lib/python2.2/distutils/command/build.py", line 107, in run
    self.run_command(cmd_name)
  File "//usr/lib/python2.2/distutils/cmd.py", line 330, in run_command
    self.distribution.run_command(command)
  File "//usr/lib/python2.2/distutils/dist.py", line 913, in run_command
    cmd_obj.run()
  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 139, in 
customize_compiler
    (cc, opt, ccshared, ldshared, so_ext) = \
  File "//usr/lib/python2.2/distutils/sysconfig.py", line 421, in 
get_config_vars
    func()
  File "//usr/lib/python2.2/distutils/sysconfig.py", line 326, 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)

=================================================================

> Sherwin J. Singer wrote:
> 
>> I am trying to build python-imaging on RH7.3 (so I can use Sketch). 
>> After successfully compiling libImaging.a, I get a syntax error trying to
>> execute the setup.py program:
>>
>> > python setup.py build
>>   File "setup.py", line 191
>>     for fw in 'Tcl', 'Tk'
>>       ^
>> SyntaxError: invalid syntax
> 
> there's a list comprehension in the mac os x build fork that
> wasn't supposed to be there.
> 
> workarounds:
> 
> - make sure you're building with Python 2.1 or later (see
>   David's reply)
> 
> - edit setup.py, and replace the code inside the
>    clause with a single
>   "pass"
> 
> - downgrade to PIL 1.1.3
> 
> - change "Python 2.0" to "Python 2.1" in PIL's README file
> 
> I'll fix this in 1.1.5.
> 
> thanks /F

-- 

Sherwin Singer
Department of Chemistry
Ohio State University
100 W. 18th Ave.
Columbus, OH 43210
614-292-8909
614-292-1685 (fax)



From cjw at sympatico.ca  Thu May  1 17:30:47 2003
From: cjw at sympatico.ca (Colin J. Williams)
Date: Thu, 01 May 2003 17:30:47 -0400
Subject: Endorsement of list comprehensions
References: 
Message-ID: <3EB19207.99710A77@sympatico.ca>

Michael Chermside wrote:

> Carsten Gehling writes:
> > Okay I understand everyting except this contruct:
> >
> > keys = [d[0] for d in cursor.description]
> >
> > Let me guess: it loops through cursor.description (obvious), for each of the
> > items (which are tuples) it "outputs" element 0. The output is then
> > automatically formatted in a way, that conforms to the list creation syntax.
> >
> > Or something like that. Kind of neat - haven't seen that in any other
> > language, that I've used.
>
> YES! Exactly!
>
> This is a feature called "list comprehensions", and it works just like
> you describe. You type out:
>
>     [ func_using_var for var in some_list if condition_using_var ]
>
> and Python makes that into the following loop:
>
>     aList = []
>     for var in some_list:
>         if condition_using_var:
>             aList.append( func_using_var )
>     return aList
>
> (except, of course, that there's no "aList" variable... python just
> uses the list that would be generated that way).
>
> The original idea comes from "Haskell", another cool programming
> language, and the strongest argument I've EVER heard for why this
> is a good feature is the little "stream-of-consciousness" description
> you just gave which seems to show that as a new-to-python programmer,
> it took you only a few moments to figure it out (correctly!) on your
> own!
>
> Thanks for endorsing one of my favorite Python features!
>
> -- Michael Chermside

You wrote:
   [ func_using_var for var in some_list if condition_using_var ]

It might be slightly more generally be expressed as:
   [expr_using_var for var in some_list if condition_using_var ]

Colin W.








From jacek.generowicz at cern.ch  Tue May  6 07:32:14 2003
From: jacek.generowicz at cern.ch (Jacek Generowicz)
Date: 06 May 2003 13:32:14 +0200
Subject: Should I write a book on Python Metaprogramming ?
References: 
Message-ID: 

"andrew cooke"  writes:

> PS i guess i want "on lisp" rather than sicp, if you get my drift...
> 
> PPS http://mitpress.mit.edu/sicp/ <- sicp

PPPS http://www.paulgraham.com/onlisptext.html  <- On Lisp



From andrew-pythonlist at puzzling.org  Sat May 24 21:34:08 2003
From: andrew-pythonlist at puzzling.org (Andrew Bennetts)
Date: Sun, 25 May 2003 11:34:08 +1000
Subject: python IRC & Command line
In-Reply-To: 
References: 
Message-ID: <20030525013407.GE11368@frobozz>

On Sat, May 24, 2003 at 07:30:10PM -0400, enk0d wrote:
> Hello everyone, 
> 
>                  I was wondering if this was actually possible or if
> someone tried it already but seeing how alot of us are linux,BSD, unix
> users i was wondering how hard would it be to make my own irc client that
> can run from the commmand line of linux. 
> 
> I would like your opinions in this matter please. Thank you 

It's certainly possible.  There's a proof-of-concept built with Twisted
using the standard curses module.  You can get Twisted from
http://twistedmatrix.com/.  The simple curses IRC client can be found in
doc/examples/cursesclient.py inside the Twisted distribution.

Of course, there are other modules for Python that implement the IRC
protocol... although most people seem to use Python to write bots rather
than IRC clients for users.  :)

-Andrew.





From charleshixsn at earthlink.net  Tue May  6 16:22:28 2003
From: charleshixsn at earthlink.net (Charles Hixson)
Date: Tue, 06 May 2003 13:22:28 -0700
Subject: Looking for a basic GUI tutorial
In-Reply-To: 
References: 
Message-ID: 

Russ Schmidt wrote:
> ...
> Thanks for your help.
> 
> Russ
Similarly, is there a good tutorial for Python + Gtk that goes beyond 
dialogs?  I'm currently trying to piece something together from the 
PythonCAD source code, but that's pretty heavy in gtkimage and appears 
light on everything else.  (I say appears... it's over 500 pages long, 
so I don't really know just what all it's doing.  But it's a silly way 
to have to learn the API.)
... all I wanted was to piece together a simple little rogue-like game 
as a study project, but the more I try to figure out how, the less 
simple it looks!  (I suppose I could use ncurses, but it's so *ugly*!)

-- 
-- Charles Hixson
Gnu software that is free,
The best is yet to be.




From tim.one at comcast.net  Fri May 23 00:05:08 2003
From: tim.one at comcast.net (Tim Peters)
Date: Fri, 23 May 2003 00:05:08 -0400
Subject: Slow Ref cleanup in 2.2.1 with 100K+ objects on Linux. - or SAP
 DBAPI problem?
In-Reply-To: 
Message-ID: 

[Brad Clements]
> ...
> So .. 230K+ records have been copied, and during this process it
> probably pulled in 200K+ other related parent records and is keeping
> all of those in RAM (duh, bad design).
>
> But interestingly, the copy subroutine has finished, and is
> "returning" to it's parent, however the process seems hung. I thought
> I had read somewhere about a problem cleaning up ref's (There aren't
> any cycles in this case), but I can't recall exactly.
>
> This is python 2.2.1 on RH 9
> ...
> Anyone seen a condition like this before?

Reports of C's free() taking time quadratic in the # of small objects
allocated have been seen before on Linux.  pymalloc in 2.3 cures it.  As an
experiment, you could trying rebuilding 2.2.1 with pymalloc enabled and see
if it makes things better.  pymalloc can't be recommended in 2.2 because of
a security hole, and also because it wasn't properly tuned for the changes
in Python's typical memory usage between the time pymalloc was first written
and when 2.2 came out.  Fixing all this for 2.3 was a miserable amount of
work, and won't get backported to the 2.2 line (well, not unless a
masochistic volunteer appears).  Trying your program under 2.3b1 would be an
even more interesting experiment (pymalloc is on by default in 2.3, the
security hole was plugged, and it's properly tuned for 2.3's typical memory
usage patterns).





From anti-spam.dbroadwell at mindspring.com  Tue May 13 13:16:46 2003
From: anti-spam.dbroadwell at mindspring.com (David Broadwell)
Date: Tue, 13 May 2003 17:16:46 GMT
Subject: [OT] developers needed
References: 
Message-ID: <2M9wa.4594$oy.964@nwrddc04.gnilink.net>

"Simon Wittber (Maptek)" wrote
> There is also VWS, which I submitted to useless python a while ago.
> It's distinguishing feature is user programmability and the fact that it
> is multi-user.
Sounds like a MUD.

--

David Broadwell





From noah at noah.org  Fri May  9 14:31:16 2003
From: noah at noah.org (Noah)
Date: 9 May 2003 11:31:16 -0700
Subject: PythonCOM: Finding a COM ProgID name?
Message-ID: 

I am trying to script adobe illustrator 10 with Python.
I ran the COM Makepy utility on the Abobe Illustrator Type Library.

I'm having trouble finding the ProgID name of a COM object
that I registered with MakePy. How do get the ProgID or CLSID?
In general, how do I get the names of the interfaces that 
I can dispatch from a Type Library? 

There seems to be a gap between running MakePy; selecting a Type Library;
and then access the TLB interface by name.
MakePy only gives the descriptive names, not the ProgID name
necessary to Dispatch the COM interface.

I guessed and came up with this -- which works:
    win32com.client.Dispatch("Illustrator.Application")
But guessing seemed like a dumb answer.

Then I tried using gencache (as generated with 'makepy.py -i' option):
    from win32com.client import gencache
    tlb = gencache.EnsureModule('{14937A4C-9A34-48a9-853A-DA92323E3587}', 0, 1, 0)
And now I am able to use Python to inspect the methods of tlb.
This is fine, but is there a more direct way? I feel like I missed
something obvious.

Yours,
Noah



From aleax at aleax.it  Wed May 14 06:00:34 2003
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 14 May 2003 10:00:34 GMT
Subject: Just good advice? = WAS("Re: getting system date")
References: <3ebd15c2$0$8986$afc38c87@news.optusnet.com.au> <87znlusu5s.fsf@mrbun.watterson> <3ebd1adf$0$16254$afc38c87@news.optusnet.com.au>       <5w1wa.86060$3M4.2013073@news1.tin.it> 
Message-ID: <6towa.92298$3M4.2117815@news1.tin.it>



David Broadwell wrote:
   ...
>> any other stray type -- few types would have append and sort methods
>> unless in a deliberate attempt to mimic lists, after all.
> And if it's trying to mimic a list then treating it like a list isn't an
> end of the world thing ...

Exactly: indeed, it's what SHOULD happen whenever feasible.


>> amateurish stints at sysadm'ing and marveled at the way a REAL sysadm
>> would often zero in on the root of a weird, "impossible" problem (on
>> the basis of their experience, clever paranoia, etc)
> That's called troubeshooting, and instinct and 'feel' are part of that
> data to troubshoot with.

Right.  For some reason it doesn't surprise me when e.g. a good auto
mechanic does it with my car (because I wouldn't know even where to
START doing the same thing myself;-), but it does, pleasantly, when
a good sysadm does it with my system or network (because I do have a
vague idea and amateur-level experience doing that sort of thing:-).


> I like the style, but have found a 'core refrence' to be very usefull too
> if something isn't in the nutshell. And then, with python you have a nice
> code base installed to grope (er, grep on windows).

grep on windows?  with cygwin or an add-on I guess;-).  But yes, the
Python online docs AND the Tools and Demo directories are a crucial
resource -- the Nutshell is necessarily selective and strives to give
you what you need 90%+ of the time, but there WILL be some percent of
the time when you need to go to the full Python reference or sources.

BTW, I heartily recommend getting the Python source distribution even
if you have zero interest in installing from it, just for the educational
value -- it includes more demos and tools, all precious examples, than
the binary installer does.  And THAT point is one I make in the Nutshell,
too, because most Windows users cannot know what they're missing when
they only get the binary installer...


> In any case, Thank Alex.

And again, you're welcome!


> (Correct if I'm wrong, but I hadn't realized that you were a writer ...
> suppose I should have.)

Heh, well, I guess you could take this up with my editor -- I suspect
there were many times when SHE had substantial trouble realizing I'm
a writer, too;-} (considering the amount of editing, correcting, and even
rewriting that she had to perform on my text -- a good editor's
contribution to a book should be emphasized much more than it often is!!!).


Alex




From max at alcyone.com  Fri May  9 17:15:31 2003
From: max at alcyone.com (Erik Max Francis)
Date: Fri, 09 May 2003 14:15:31 -0700
Subject: String += time trials. (was: Re: Speeding up: s += "string")
References: 
Message-ID: <3EBC1A73.4CBB3D0C@alcyone.com>

Francis Avila wrote:

> Is it the best solution?

My point was that naive string concatenation inside a loop brings out
the worst behavior (O(n^2)), and was suggesting a solution that has
better scaling (amortized O(n)).  StringIO/cStringIO would also be an
example of a way to get this superior behavior.

As for the specific merits of building a list and then using S.join vs.
StringIO, that really depends on the specifics of the situation.  I
don't know how helpful your comparison here is, since you're dealing
with such tiny strings.

My point would simply be to pick the behavior that has the right big-O
complexity.  In a language like Python, you're not looking to optimize
every last cycle out of your program -- otherwise you wouldn't be using
Python -- but you _do_ want to make sure that your program uses the
proper algorithms to prevent complexity explosions.  Repeated string
concatenation is bad.  The other solutions are good.  The relative
goodness of the superior solutions is something I wouldn't worry about
too much.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The critical period in matrimony is breakfast-time.
\__/ A.P. Herbert
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.



From fredrik at pythonware.com  Thu May 15 14:03:59 2003
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Thu, 15 May 2003 20:03:59 +0200
Subject: passing by refference
References:     
Message-ID: 

Aahz wrote:

> >I don't think we disagree about semantics, only terminology.
>
> Terminology *is* about semantics, to a certain extent; if we don't have
> shared vocabulary, we can't communicate meaning.

no, but everyone can be 100% right all the time ;-)

(and who cares about what a bunch of renowned computer scientists came
up with some 30 years ago; nobody's using CLU anyway these days...)









From g2h5dqi002 at sneakemail.com  Mon May 19 21:09:09 2003
From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de))
Date: Tue, 20 May 2003 13:09:09 +1200
Subject: Python Style Question
In-Reply-To: 
References: <6ee58e07.0305191003.395d1b3a@posting.google.com> 
Message-ID: 

Greg Fortune wrote:
> Looks like the coder expected a performance improvement.  If it gets 
> executed the way I expect, the second example requires a lookup through the 
> dialog module each time the class is instantiated.

It's certainly *not* executed that way. The base class
expression is only evaluated once, when the class is
defined.

Are the XXX_Parent things used anywhere else? Maybe
they're being used for inherited method calls, and the
author wanted to insulate such calls from changes to
the base class in future versions.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




From g2h5dqi002 at sneakemail.com  Wed May 28 02:30:34 2003
From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de))
Date: Wed, 28 May 2003 18:30:34 +1200
Subject: A Standard
In-Reply-To: 
References: <000001c32310$65d0af90$cd0620cc@LUISLAPTOP>   <3ED16485.169B4417@alcyone.com>  <3ED194E0.303C432B@alcyone.com>   
Message-ID: 

Andrew Koenig wrote:
> Greg> And in Python, every sequence (i.e. something that
> Greg> implements __getitem__) can be iterated over
> 
> You mean it is impossible for a user-defined type to implement
> __getitem__ without also implementing __iter__?

No, but if the object doesn't implement __iter__,
the iter() function supplies a default iterator that
uses __getitem__ to access the object.

 > Python iterators are much closer to C++ input iterators
> than they are to forward iterators.

Consider my table updated appropriately, then (I'm not
very familiar with STL terminology).

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




From domma at procoders.net  Tue May 20 10:03:53 2003
From: domma at procoders.net (Achim Domma)
Date: Tue, 20 May 2003 16:03:53 +0200
Subject: Image editing in Python
References: 
Message-ID: 

"Amit Keney"  wrote in message
news:ae0a3e50.0305200359.42037a39 at posting.google.com...
>     can anyone please tell me a python library by which i can edit
> images through my python prorams.

As the author of PythonMagick, I would direct you to
http://www.procoders.net/pythonmagick. It's a wrapper around
http://www.graphicsmagick.org which should run on your Unix system. It
depends on boost.python which should also support your OS. PythonMagick is
still not complete and a bit complicated to install, but I would be glad to
help, if you have problems. Just have a look, to see if it suits your needs.

regards,
Achim





From dave at nullcube.com  Thu May  8 17:42:02 2003
From: dave at nullcube.com (Dave Harrison)
Date: Fri, 9 May 2003 07:42:02 +1000
Subject: curiosa RE 1.5.2 and socket.error
Message-ID: <20030508214202.GA1935@dave@alana.ucc.usyd.edu.au>

the other day I came across a strange problem with an exception in 1.5.2.

When socket.error was raised it returned either :
- A single tuple of a string (error description)
- A two tuple (string, error number)

However as far as the documentation read, if I was going to just get the first return value, it should simply be a string object.
To get to this single object however, I had to grab that arg value of the exception, and reference the first element of the one tuple (not what the doco described, or at least that's not how I read it).

Does anyone know what I missed ? Or was it an anomoly of 1.5.2 ??




From eppstein at ics.uci.edu  Fri May 23 11:01:11 2003
From: eppstein at ics.uci.edu (David Eppstein)
Date: Fri, 23 May 2003 08:01:11 -0700
Subject: python code into LaTeX...
References: 
Message-ID: 

In article ,
 Alessio Pace  wrote:

> Hi, as you can see from the subject, I need to put some python code into a
> latex document. Which is the preferable way to do it and possibly under
> Linux? I tried a couple of softwares but I don't like them very much...

What's wrong with

\begin{verbatim}
...your code here
\end{verbatim}

?

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science



From peter at engcorp.com  Tue May  6 18:38:06 2003
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 06 May 2003 18:38:06 -0400
Subject: Gui Advice Needed: wxPython or PyQT ?
References: <8d3e714e.0305051833.65da42bc@posting.google.com>   <3EB7B189.2691E394@engcorp.com>  <3EB7EBBD.516620FF@engcorp.com> <3eb82fb8$0$2242$e4fe514c@dreader6.news.xs4all.nl>
Message-ID: <3EB8394E.780246@engcorp.com>

Boudewijn Rempt wrote:
> 
> Peter Hansen wrote:
> 
> >
> > Very brief experimentation, *and* a look at the demo apps (to note
> > Riccardo's point), were all it took to make me feel this way, and
> > I would actually recommend that *regardless* of the advice of the
> > experts (their accuracy and thoroughness notwithstanding), a new
> > user should still try out both wxPython and PyQT before settling on
> > either.
> 
> Trying out is a good idea -- I tried out literally everything, up to and
> including Amulet -- when I was looking for a toolkit before settling on
> PyQt. However, I must say that it can be quite hard to get the toolkits
> themselves up and running. I still haven't managed to get a working
> wxPython installation on my SuSE systems; even though PyGTK on OS X was a
> breeze (thanks to Fink). PyQt can be a bit of a nut to crack before it
> runs, unless you buy BlackAdder. And even Tkinter isn't always as easy to
> get running.

Sadly, I suppose that is true on some non-Windows systems.  Thankfully
for us luser Windows users :-), the Win32 installers for Python, wxPython,
and most other packages (presumably even PyQT) are effectively capable
of being used by someone without a working brain (like me, some days).
(Huge heaps of kudos here to Mark Hudson, Robin Dunn, and no doubt
some others.)

I recall being quite pleasantly surprised by how I could install wxPython,
click on the Demo icon, and see the huge expanse of available power from
the framework, all running (nearly) flawlessly on my machine.

-Peter



From mwh at python.net  Thu May  1 08:21:33 2003
From: mwh at python.net (Michael Hudson)
Date: Thu, 1 May 2003 12:21:33 GMT
Subject: fcntl in windows
References:    <7h33cjz51y0.fsf@pc150.maths.bris.ac.uk> 
Message-ID: <7h3vfwu3ljt.fsf@pc150.maths.bris.ac.uk>

Afanasiy  writes:

> On Wed, 30 Apr 2003 17:29:46 GMT, Michael Hudson  wrote:
> 
> >Alex Martelli  writes:
> >
> >> Jp Calderone wrote:
> >> 
> >> > On Wed, Apr 30, 2003 at 03:26:29PM +0000, Afanasiy wrote:
> >> >> Is there an fcntl in Windows? A stub, a wrapper, etc?
> 
> >Indeed, it would seem to me that implementing a version of fcntl on
> >Windows would be flat out insane -- surely the sensible thing to do
> >would be provide two implementations of whatever it is you need, the
> >unix one of which calls fcntl.
> 
> Insane? I strongly disagree.
> 
> Sensible thing? I strongly disagree.
> 
> The sensible thing would provide the functionality
> in a well designed platform independent module.

That's what I was trying (muddily, I concede) to suggest :-)

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 arnaud at tribu.ch  Thu May  1 08:40:35 2003
From: arnaud at tribu.ch (Arnal)
Date: Thu, 01 May 2003 14:40:35 +0200
Subject: Three questions about Tkinter
References:  
Message-ID: 

In b8on3n$8au$1 at news-reader13.wanadoo.fr,  "Eric Brunel"
 wrote?:

>> resize it on the fly (the width and height properties are measured in
>> characters and lines, not in pixels). My current workaround is to make the
>> window not resizable but it would be nice to do it.
> 
> I don't exactly understand what you're trying to do here. What's the problem?
> Can you post a piece of code showing it?

I have found an answer, thanks anyway.

> The most common way to do it is via a lambda function. If you don't know what
> it 
> is, look at:
> http://www.python.org/doc/current/tut/node6.html#SECTION006740000000000000000
> 
> Practically, you'd write what you want to do like follows:
> 
> MRecents.insert_command(0, label=GetFileName(file),
>                           accelerator=acc,
>                           command=lambda i=i: OpenRecent(i))
> 
> There are more sophisticated solutions but this one should be enough for you.

Indeed, at least for the begining.

> HTH

Thank you!




From tim.one at comcast.net  Thu May 15 19:13:12 2003
From: tim.one at comcast.net (Tim Peters)
Date: Thu, 15 May 2003 19:13:12 -0400
Subject: passing by refference
In-Reply-To: <87isscgcmz.fsf@charter.net>
Message-ID: 

[Doug Quale]
> ...
> I should have let this pass in this newsgroup, but I was mildly annoyed
> when Aahz repeatedly told Joshua that he was wrong when Joshua correctly
> pointed out that Python is call-by-value.  Even Guido's Python Tutorial
> correctly states that Python is cbv.

And corrected it with a footnote because, as you haven't yet picked up,
calling Python cbv isn't *helpful*.  I'll repeat a msg from 2 years ago:

    http://mail.python.org/pipermail/python-list/2001-June/048702.html

    I usually say Python does "call by object".  Then people go "hmm,
    what's that?".  If you say "call by XXX" instead, then the inevitable
    outcome is a tedious demonstration that it's not what *they* mean by
    XXX.  Instead I get to hear impassioned arguments that "by object"
    is what any normal person means by YYY .

I'll note now that you (and Joshua, and so far) fit into the last sentence
of that, with YYY == "call by value".  You're not the first .

    BTW, I believe Barbara Liskov first coined "call by object" to
    describe argument-passing in CLU.

A primary difference between you and Joshua and responders (including me,
Aahz, Jeremy, Fredrik and Terry), is that we've been explaining Python to
newcomers for many years.  The idea that "call by value" has One True
Objective Meaning is simply silly, as actually doing the literature search I
suggested at the start would have shown you.  It's used to mean several
distinct things, depending on the programming culture using it.  Even so, in
no case does it have enough explanatory power to answer most practical
questions about the semantics of calls in Python.  Therefore it's useless as
a pedagogical device here.  In contrast, Liskov's description of "call by
object reference" explains just about everything, and applies almost
verbatim to CLU, Smalltalk, Python, and-- with a little bit of squinting to
exempt special forms and macro calls --a majority of Lisp variants.

So I don't care what you (or Joshua) want to insist "call by value" means --
no matter what it means to you, it doesn't *help* here.  If you care to
learn something new, I recommend Henry Baker's "Equal Rights for Functional
Objects", which argues the issue in detail in the context of Lisp:

    http://home.pipeline.com/~hbaker1/ObjectIdentity.html

I'll just quote the start of section 7 ("Call-by-reference versus
call-by-value") here:

    Despite the thirty years that the problem of "call-by-reference"
    versus "call-by-value" in argument-passing semantics of Algol-like
    programming languages has been discussed, it has never been clearly
    resolved.  While many undergraduate texts [Aho86,s.7.5] and language
    manuals give a definition of each policy, there has always been a
    nagging feeling that these definitions for Algol-60, Fortran and Ada
    are too ad hoc and too implementation-oriented.

    ...

    We claim that the only argument-passing model that is consistent
    in non-functional languages is call-by-object-reference, i.e.,
    passing object identities.

He goes on to explain why it's incorrect to call Lisp "call-by-value", and I
agree -- provided that by "call-by-value", you mean the One True Objective
Meaning it had when I was your age .

If thinking of Python as being cbv helps you to understand it, I certainly
don't object to that.  The evidence of the last decade is that it actively
hinders understanding for most newcomers, but that explaining call-by-object
actively helps.

stick-around-and-you'll-eventually-agree-ly y'rs  - tim





From anton at vredegoor.doge.nl  Thu May 22 10:46:52 2003
From: anton at vredegoor.doge.nl (Anton Vredegoor)
Date: Thu, 22 May 2003 16:46:52 +0200
Subject: Python-2.3b1.exe install error on W98se
References: 
Message-ID: 

anton at vredegoor.doge.nl (Anton Vredegoor) wrote:

>A message box popups almost immediately:
>
>
>Install
>
>Could not initialize installation. File size expected=1972043840, size
>returned=9096924. The parameter is incorrect.
>
>		OK
>

I finally traced the problem to an infection with the virus
W95.spaces. As Cruyff might have said, there was an advantage to the
virus, because the error message it produces for certain installer
executables contains a very distinctive number. This post is probably
the first google hit for this number that connects it to the virus.

The virus is said to corrupt the master boot record every first of
June each year, so anyone intrigued by this number in the same way as
I have been in the past few weeks should take the necessary steps
soon.

For example:

	To detect it: http://www.free-av.com/ave.htm

	To remove it: http://www.viruskiller.nl/avx (also
        desinfects all exe's, might not be what you want)


Anyway, the problem is solved now, I downloaded and installed
Python-2.3b1.exe. Thanks to everyone who tried to help me with this.
Now to the subject of writing anti virus tools in Python ...

Anton



From oktaysafak at ixir.com  Fri May 30 16:17:58 2003
From: oktaysafak at ixir.com (Oktay Safak)
Date: 30 May 2003 13:17:58 -0700
Subject: Bug in 2.3b1?
References: <722261f9.0305251147.37ef5291@posting.google.com>  <722261f9.0305281346.43fde7a3@posting.google.com> 
Message-ID: <722261f9.0305301217.cf19752@posting.google.com>

I filed a bug report on SF. No:746304

https://sourceforge.net/tracker/index.php?func=detail&aid=746304&group_id=5470&atid=105470

Oktay



From martin at v.loewis.de  Fri May  2 11:17:24 2003
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Fri, 02 May 2003 17:17:24 +0200
Subject: socketpair() missing ?
In-Reply-To: 
References:  
Message-ID: 

Dave Brueck wrote:

> Maybe it isn't supported on enough platforms, it varies too much by
> platform, or maybe you're just the first person to want it. :) 

The latter (actually it is requested as python.org/sf/567969)

> You could
> submit a patch to SourceForge if nobody here pipes up with a good reason
> for it not being in the socket module already.

One may think that it belongs to the posix module, being a POSIX 
function. But that is a matter of taste, of course.

Regards,
Martin




From skip at pobox.com  Thu May  8 06:48:39 2003
From: skip at pobox.com (Skip Montanaro)
Date: Thu, 8 May 2003 05:48:39 -0500
Subject: Why use backticks?
In-Reply-To: 
References: <3eb81743$0$123$e4fe514c@dreader4.news.xs4all.nl>
        
        
Message-ID: <16058.13831.452375.815053@montanaro.dyndns.org>

    Francis> Of course, maybe we should just use 'x = %s' % 1.  But anyway,
    Francis> I see backticks a lot, and I use them quite a bit, too.  Are
    Francis> they really slated for removal?

I don't believe they are removal candidates, at least not until Python 3.
In any case, they are too widely used to remove during the 2.x series, and
they are convenient to use during interactive sessions when you want to see
the precise content of strings.  "Discouraged" might be a more apt
description of their status.

    Francis> Seems kinda drastic.  I for one never got them confused with
    Francis> the shell syntax, and I'd be sad to see them go. Surely
    Francis> converting a value to a string is a common enough operation to
    Francis> deserve its own terse special syntax?

The confusion isn't with the shell syntax, it's do they mean str() or
repr()?  If repr() deserves a shortcut syntax, why not str()?  Finally,
backticks are very small, easily hidden, bits of punctuation which can
fairly easily be overlooked or confused with single quotes.

Skip




From ramen at lackingtalent.com  Mon May 26 03:18:37 2003
From: ramen at lackingtalent.com (Dave Benjamin)
Date: Mon, 26 May 2003 07:18:37 -0000
Subject: Sorted associative container in Python?
References: 
Message-ID: 

In article , Roy Smith wrote:
> C++ STL's map is a sorted associative container, with the following 
> properties:
> 
> 1) You can iterate over the entries in key-sorted order in linear time.
> 2) You can access any given key in log time.
> 3) Keys can be arbitrary type values.
> 
> What's the best way to do that in Python?  A dictionary gives you #2 (or 
> maybe even constant time?) and #3, but fails #1.  A list fails #3.

See my "odict" recipe at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747

Please note that there are a couple of bugs that readers have discovered and
I have not yet fixed them in the example. It extends UserDict (I wrote it
before I started using Python 2.2) and uses a list to keep track of keys. I
tried to be thorough about the interface.

HTH,
Dave



From sholden at holdenweb.com  Fri May  2 16:05:35 2003
From: sholden at holdenweb.com (Steve Holden)
Date: Fri, 02 May 2003 20:05:35 GMT
Subject: It never fails (bsddb retirement in 2.3)
References:   <7x1xziibnz.fsf@ruckus.brouhaha.com>      
Message-ID: 

"Nick Vargish"